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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f951c5c79458ef2d1710cdbd8b15a7b97821fa6c | Ruby | sails-simulator/ruby-sailsd | /lib/sailsd.rb | UTF-8 | 904 | 3.09375 | 3 | [] | no_license | require 'json'
require 'socket'
class Sailsd
attr_reader :latitude
attr_reader :longitude
attr_reader :heading
attr_reader :rudder_angle
attr_reader :sail_angle
attr_reader :speed
def initialize()
@socket = nil
end
def connect()
@socket = TCPSocket.open('localhost', 3333)
end
def send_bytes(msg)
@socket.puts(msg)
return @socket.gets
end
def send_hash(hash)
bytes = JSON.generate(hash)
ret = send_bytes(bytes)
return JSON.parse(ret)
end
def update()
connect()
r = send_hash({
:request => [
'latitude',
'longitude',
'heading',
'rudder-angle',
'sail-angle',
'speed'
]
})
@latitude = r['latitude']
@longitude = r['longitude']
@heading = r['heading']
@rudder_angle = r['rudder-angle']
@sail_angle = r['sail-angle']
@speed = r['speed']
end
end
| true |
ef541829a14586149bf07455502b05a4b8d9f7e0 | Ruby | tamepenguin/netbak | /bs.rb | UTF-8 | 355 | 2.875 | 3 | [] | no_license | #/usr/bin/env ruby -w
require 'socket'
port = "19165"
hostname = '127.0.0.1'
file = "/tmp/f"
outfile = open(file, "w")
socket = TCPServer.open(port)
puts "Server started"
data = ""
client = socket.accept
puts "The connection is now in place"
data = client.read
outfile.write(data)
client.close
socket.close
outfile.close
puts "Server ended" | true |
bb3b6714987f91d02b688247e13ccc8fe84a8145 | Ruby | leusonmario/TravisAnalysis | /build_conflicts_analysis/CausesExtractor/IndividualExtractor/AlternativeStatement.rb | UTF-8 | 821 | 2.625 | 3 | [] | no_license | class AlternativeStatement
def initialize()
end
def extractionFilesInfo(buildLog)
filesInformation = []
begin
information = buildLog.to_enum(:scan, /\[ERROR\] Alternative [a-zA-Z0-9\.]* is a subclass of alternative [a-zA-Z0-9\.]*/).map { Regexp.last_match }
count = 0
while(count < information.size)
classFile = information[count].to_s.match(/\[ERROR\] Alternative [a-zA-Z0-9\.]*/).to_s.split("\.").last
secondClass = information[count].to_s.match(/is a subclass of alternative [a-zA-Z0-9\.]*/).to_s.split("\.").last
count += 1
filesInformation.push(["alternativeStatement", classFile, secondClass])
end
return "alternativeStatement", filesInformation, information.size
rescue
return "alternativeStatement", [], 0
end
end
end | true |
6b47d877ddeecb50b3106938480e3c869d96ff9e | Ruby | alejandracampero/ruby-advanced-class-methods-lab-v-000 | /lib/song.rb | UTF-8 | 1,178 | 3.296875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
class Song
attr_accessor :name, :artist_name
@@all = []
def self.all
@@all
end
def save
self.class.all << self
end
def self.create
song = Song.new
song.save
song
end
def self.new_by_name (song_name)
song = self.new
song.name = song_name
song
end
def self.create_by_name (song_name)
song = self.create
song.name = song_name
song
end
def self.find_by_name(song_name)
@@all.detect {|song| song.name == song_name}
end
def self.find_or_create_by_name(song_name)
self.find_by_name(song_name) || self.create_by_name(song_name)
end
def self.alphabetical
@@all.sort_by {|song| song.name}
end
def self.new_from_filename(file_data)
data = file_data.split (" - ")
artist_name = data[0]
name = data[1][/[^.]+/]
song = self.new
song.name = name
song.artist_name = artist_name
song
end
def self.create_from_filename(file_data)
data = file_data.split(" - ")
artist_name = data[0]
song_name = data[1][/[^.]+/]
song = self.create
song.name = song_name
song.artist_name = artist_name
song
end
def self.destroy_all
self.all.clear
end
end
| true |
1ef092add7f5679a6244e02486e24f7ab182d93f | Ruby | hopegiometti/oo-my-pets-dumbo-web-100719 | /lib/owner.rb | UTF-8 | 1,484 | 3.609375 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
class Owner
attr_reader :name, :species
@@all = []
def initialize(name)
@name = name
@species = "human"
@@all << self
end
def say_species
p "I am a #{@species}."
#ask why puts won't work here
end
def self.all
@@all
end
def self.count
@@all.size
end
def self.reset_all
@@all.clear
end
def cats
Cat.all.select do |kitty_witty|
kitty_witty.owner == self
end
end
def dogs
Dog.all.select do |doggy_woggy|
doggy_woggy.owner == self
end
end
def buy_cat(name)
new_cat = Cat.new(name, self)
end
def buy_dog(name)
new_dog = Dog.new(name, self)
end
def walk_dogs
dogs.map do |doogy_woggy|
doogy_woggy.mood = "happy"
end
end
def feed_cats
cats.map do |kitty_witty|
kitty_witty.mood = "happy"
end
end
def sell_pets
cats.map do |kitty_witty|
kitty_witty.owner = nil
kitty_witty.mood = "nervous"
# binding.pry
end
dogs.map do |doggy_woggy|
doggy_woggy.owner = nil
doggy_woggy.mood = "nervous"
end
end
def list_pets
num_cats = Cat.all.select do |kitty_witty|
kitty_witty.owner == self
end
num_dogs = Dog.all.select do |doggy_woggy|
doggy_woggy.owner == self
end
p "I have #{num_dogs.count} dog(s), and #{num_cats.count} cat(s)."
# binding.pry
# p "I have #{@owner.dogs.count} dog(s), and #{@owner.cats.count} cat(s)."
end
end
| true |
fa4bbf10bc4ddf05c22ff4620230eee0222cbe9c | Ruby | marcbey/thomeli-webapp | /app/managers/token_generator.rb | UTF-8 | 728 | 3.296875 | 3 | [
"MIT"
] | permissive | module TokenGenerator
extend self
CHARS = ('a'..'z').to_a
VOWELS = %w( a e i o u )
CONSONANT = CHARS - VOWELS
BLOCKS = 5
BLOCK_LENGTH = 4 # must be divisible by 2
SEPERATOR = '-'
PREFIX_REGEX = /^([A-Z0-9]{2})([0-9])([A-Z])$/i
def unique_token( unicator )
begin
token = generate
end while not unicator.call( token )
return token
end
private
def generate
code = []
BLOCKS.times do
code << generate_block
end
return code.join( SEPERATOR ).upcase
end
def generate_block
block = ''
( BLOCK_LENGTH / 2 ).times do
block << CONSONANT[rand( CONSONANT.length )]
block << VOWELS[rand( VOWELS.length )]
end
return block
end
end
| true |
8b9799672050d560bc8685e1c8500c5ed8ae714e | Ruby | LelnaG/Ruby_LL | /RubyBlanks_Challenge.rb | UTF-8 | 680 | 4.03125 | 4 | [] | no_license | #!/usr/bin/env ruby
#Ruby Blanks: fill in the blank (Mad Libs)
#"I decided to ____ a ______ party for my _____ ______"
# ----decide if the blank should be a verb, adjective, noun, etc
#place word types into an array
#i.e blanks = ['verb', 'adjective', 'adjective, 'noun']
#ask user for words
#output final resulting sentence
blanks = ['verb', 'adjective', 'adjective', 'noun']
vowels = ['a', 'e', 'i', 'o', 'u']
#prompt user
blanks.map! do |word|
article = vowels.include?(word[0]? 'an' : 'a')
print "Give #{article} #{word}: "
response = gets.chomp
end
finalSentence = "I decided to #{blanks[0]} a #{blanks[1]} party for my #{blanks[2]} #{blanks[3]}"
puts finalSentence | true |
fd36bcc017ca5ab3eeb7a3dea2f0a16e6d296ef6 | Ruby | CSheesley/backend_prework | /day_6/exercises/dog.rb | UTF-8 | 799 | 4.5625 | 5 | [] | no_license | # In the dog class below, add a (play)? method that, when called, will result in
# the dog being hungry. Call that method below the class, and print the dog's
# hunger status.
class Dog
attr_reader :breed, :name, :age
def initialize(breed, name, age)
@breed = breed
@name = name
@age = age
@hungry = true
end
def bark
p "woof!"
end
def eat
@hungry = false
p "Time for #{name} to eat."
end
def play
@hungry = true
p "#{name} has played a lot, and is now hungry!"
end
def hungry
if @hungry == true
"#{name} is hungry."
else
"#{name} is now full, and not currently hungry."
end
end
end
fido = Dog.new("Bernese", "Fido", 4)
p fido.breed
p fido.name
p fido.age
fido.play
p fido.hungry
fido.eat
p fido.hungry
| true |
d2a2d7de395d631f59444374c68ab3fafe55cf15 | Ruby | jneen/plans | /app/models/theme.rb | UTF-8 | 1,260 | 2.765625 | 3 | [] | no_license | module Theme
def self.wrap(thing)
case thing
when Theme
thing
else
create(thing)
end
end
def self.create(name)
name ||= 'default'
klass = (name !~ /\W/) ? LocalTheme : ExternalTheme
klass.new(name)
end
def self.local
DIR.entries.map(&:to_s).grep(/\.css$/).map { |entry|
create(entry.chomp('.css'))
}
end
DIR = Rails.root.join('public/stylesheets/themes')
class Base
attr_reader :name
def initialize(name)
@name = name
end
def external?
!local?
end
def valid?
true
end
def url
raise "plz define url"
end
def pretty_name
raise "plz define pretty_name"
end
def ==(other)
name == other.name
end
end
class LocalTheme < Base
def local?
true
end
def pretty_name
name.split('_').map(&:capitalize).join(' ')
end
def valid?
DIR.join("#{name}.css").readable?
end
def url
local_name = valid? ? name : 'default'
"/stylesheets/themes/#{local_name}.css"
end
end
class ExternalTheme < Base
def local?
false
end
def url
name
end
def pretty_name
"Custom Stylesheet <#{name}>"
end
end
end
| true |
7b52fcf84d4e4dfb1f0074616fb9bcfcc3cf88ad | Ruby | sevos/git-pp | /bin/git-pp | UTF-8 | 1,467 | 3.09375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# encoding: utf-8
require 'yaml'
CONFIG_FILE_PATH="#{ENV['HOME']}/.git-pp.yml"
module Git
module Pp
module Activable
def activate
`git config user.name '#{name}'`
`git config user.email '#{email}'`
end
end
end
end
Person = Struct.new(:name, :email) do
include Git::Pp::Activable
end
class Pair < Struct.new(:left, :right)
include Git::Pp::Activable
def name
"Pairing #{left.name} + #{right.name}"
end
def email
"#{left.email}, #{right.email}"
end
end
def setup
unless File.exists?(CONFIG_FILE_PATH)
File.open(CONFIG_FILE_PATH, 'w') do |file|
file << <<-TEMPLATE
me:
name: #{`git config user.name`.strip}
email: #{`git config user.email`.strip}
buddies:
matt:
name: Matt Doe
email: matt@example.com
TEMPLATE
end
puts "#{CONFIG_FILE_PATH} created."
puts "Press ENTER key to edit config..."
STDIN.getc
`#{ENV['EDITOR']} #{CONFIG_FILE_PATH}`
end
end
def switch(mate_name)
config = begin
YAML.load(File.read(CONFIG_FILE_PATH))
rescue
STDERR.puts "Config file does not exist, creating..."
setup
exit 1
end
me = Person.new(config['me']['name'], config['me']['email'])
pairs = {}
config['buddies'].each do |pair_name, c|
pairs[pair_name] = Pair.new(Person.new(c['name'], c['email']), me)
end
person = pairs[mate_name.to_s.downcase] || me
puts "Activating: #{person.name}"
person.activate
end
switch ARGV[0]
| true |
6de6487f9e3430f472ba1a5f9700ef5198300bb9 | Ruby | eSilvac/To-Do-List_Sinatra | /EdicionVariables.rb | UTF-8 | 516 | 2.859375 | 3 | [] | no_license | require 'make_todo'
tareas = Tarea.all
class Edit
attr_accessor :posi, :nuevo, :arr, :temp, :cont
def initialize(pos,ne)
@arr = Tarea.all
@posi = pos + 1
@cont = pos
@nuevo = ne
todo
end
def todo
@arr.shift
i = 1
@arr.each do |actual|
if @cont == i
Tarea.destroy(actual["id"])
Tarea.create(@nuevo)
else
if actual["done"] != true
id = actual["id"]
nombre = actual["title"]
Tarea.destroy(id)
Tarea.create(nombre)
end
end
i+=1
end
end
end
| true |
bc2e7e7d813a839ce947cfb5d427b38031d4f88d | Ruby | rawswift/ruby-collections | /class/basic/person.rb | UTF-8 | 971 | 4.34375 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
class Person
# constructor
def initialize(name = '', email = '', address = '')
@name = name
@email = email
@address = address
end
#
# setter methods
#
def set_name(name = '')
@name = name
end
def set_email(email = '')
@email = email
end
def set_address(address = '')
@address = address
end
#
# getter methods
#
def get_name
@name
end
def get_email
@email
end
def get_address
@address
end
end
#
# Use class
#
person = Person.new
person.set_name('John Doe')
person.set_email('johndoe@example.com')
person.set_address('Somewhere out there')
puts "Name: " + person.get_name
puts "Email: " + person.get_email
puts "Address: " + person.get_address
#
# Another example, using constructor to set values
#
puts # spacer
peter = Person.new('Peter Pan', 'peterpan@example.com', 'Neverland')
puts "Name: " + peter.get_name
puts "Email: " + peter.get_email
puts "Address: " + peter.get_address
| true |
a32697dc7f4c2c950da99baaba92e357cc55d3fe | Ruby | yuzhiyuan413/fish | /app/models/pass/permission.rb | UTF-8 | 1,867 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | class Pass::Permission < Pass::Base
self.table_name = "permissions"
serialize :operates, Array
#添加
ADD_CODE = "0"
#查看
SHOW_CODE = "1"
#删除
DELETE_CODE = "2"
#修改
EDIT_CODE = "3"
OPERATE_CODES = [ADD_CODE, SHOW_CODE, DELETE_CODE, EDIT_CODE]
#状态 允许
STATUS_YES = 1
#状态 禁止
STATUS_NO = 0
ALLOW = 'allow'
NOT_ALLOW = 'not allow'
DO_NOT_KNOW = "do not know"
def function
@function ||= Pass::System.functions.find { |f| f.id == function_id }
end
def subsystem
@subsystem ||= Pass::System.subsystems.find { |f| f.id == subsystem_id }
end
#是否有权限
def pass controller, operate
return DO_NOT_KNOW unless any_controller?(controller)
return DO_NOT_KNOW unless any_operate?(operate)
return ALLOW if self.status == STATUS_YES
return NOT_ALLOW if self.status == STATUS_NO
return DO_NOT_KNOW
end
def all_operate?
return true if operates.nil? or operates.length == 0
return true if OPERATE_CODES.all?{ |o| operates.include?(o)}
return false
end
def self.find_all_by_link_type_and_link_id link_type, link_id
where({link_type: link_type, link_id: link_id}).order("sort")
end
#这条权限信息是否包含这个操作
def any_operate? operate
return false if operate.nil?
return true if operates.nil? or operates.length == 0
operates.any? { |o| o.to_i == operate.to_i }
end
private
#这条权限信息是否包含这个controller
def any_controller? controller
if subsystem and function
return function.controllers.any? { |c| c.name == controller }
elsif subsystem_id == 0 and function_id == 0
return true
elsif subsystem and function_id == 0
return subsystem.functions.any? { |f| f.controllers.any? { |c| c.name == controller }}
else
return false
end
end
end
| true |
362ba1474a0cfb3febf8648841aa01bc7db925c4 | Ruby | jonpiffle/projectEuler | /euler4.rb | UTF-8 | 214 | 3.5625 | 4 | [] | no_license | def is_palendrome(i)
i.to_s == i.to_s.reverse
end
max = 0
999.downto(1).each do |i|
999.downto(1).each do |j|
if is_palendrome(i*j)
puts i*j
max = i*j if i*j > max
end
end
end
puts max
| true |
8b663b8cf924cabdd5c5aad8374ee39a9061aee7 | Ruby | Pas-byNumbers/deli-counter-london-web-051319 | /deli_counter.rb | UTF-8 | 622 | 3.90625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def line(queue)
if queue.size == 0
puts "The line is currently empty."
else
message = "The line is currently:"
queue.each_with_index do |name, index|
message += " #{index.to_i+1}. #{name}"
end
puts "#{message}"
end
end
def take_a_number(queue, name)
queue.push(name)
position = queue.index(name)
puts "Welcome, #{name}. You are number #{queue.index(name)+1} in line."
return name, position
end
def now_serving(queue)
if queue.empty?
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{queue[0]}."
queue.shift
end
end | true |
a298d0ef124e99d0f1784b51728dd9d2881f6021 | Ruby | lightmotive/ls-exercises-ruby-basics | /debugging/08_colorful_things.rb | UTF-8 | 1,129 | 3.78125 | 4 | [] | no_license | # frozen_string_literal: true
# The following code throws an error. Find out what is wrong and think about how you would fix it.
colors = ['red', 'yellow', 'purple', 'green', 'dark blue', 'turquoise', 'silver', 'black', 'sapphire blue']
things = ['pen', 'mouse pad', 'coffee mug', 'sofa', 'surf board', 'training mat', 'notebook', 'keyboard']
colors.shuffle!
things.shuffle!
i = 0
shortest_length = [colors.length, things.length].min
loop do
break if i == shortest_length # This was a great Launch School suggestion!
puts "#{i.zero? ? 'I have a ' : 'And a '}#{colors[i]} #{things[i]}."
i += 1
end
# The problem: things has one item less than colors, so it throws an error with the last colors entry.
# Main fix: break if i == colors.length (missed that while looking at other issues!)
# Possible fixes:
# - Explicitly call to_s on each array query.
# - Replace string concatenation (+) with string interpolation, which implicitly calls to_s on each entry.
# - Ensure that each array has the same length.
# - Stop looping after reaching the shortest array's length. That was a great Launch School suggestion!
| true |
ecb2978a4b1fd7b66ce456459110f6ea0587bd9c | Ruby | eregon/adventofcode | /2017/18b.rb | UTF-8 | 1,893 | 2.921875 | 3 | [] | no_license | input = File.read("18.txt")
class Program
REG = /[a-z]/
OP = /(?:#{REG}|-?\d+)/
attr_writer :other
attr_reader :queue, :sends
def initialize(input, pid)
@pid = pid
@registers = Hash.new(0)
@registers['p'] = pid
@queue = Queue.new
@sends = 0
parse(input)
end
def val(str)
if REG =~ str
r = str
-> { @registers[r] }
else
v = Integer(str)
-> { v }
end
end
def parse(input)
@code = input.strip.lines.map { |line|
case line
when /^set (#{REG}) (#{OP})$/
r, v = $1, val($2)
-> { @registers[r] = v.call }
when /^add (#{REG}) (#{OP})$/
r, v = $1, val($2)
-> { @registers[r] += v.call }
when /^mul (#{REG}) (#{OP})$/
r, v = $1, val($2)
-> { @registers[r] *= v.call }
when /^mod (#{REG}) (#{OP})$/
r, v = $1, val($2)
-> { @registers[r] %= v.call }
when /^snd (#{OP})$/
v = val($1)
-> {
@sends += 1
@other.queue << v.call
Fiber.yield :send
}
when /^rcv (#{REG})$/
r = $1
-> {
Fiber.yield :waiting while @queue.empty?
@registers[r] = @queue.pop
}
when /^jgz (#{OP}) (#{OP})$/
v, off = val($1), val($2)
-> pc { pc + (v.call > 0 ? off.call : 1) }
else
raise line
end
}
end
def run
loop {
pc = 0
while instr = @code[pc]
if instr.arity == 0
instr.call
pc += 1
else
pc = instr.call(pc)
end
end
}
end
end
a, b = Program.new(input, 0), Program.new(input, 1)
a.other, b.other = b, a
progs = [a, b].map { |prog| Fiber.new { prog.run } }.cycle
last = :send
loop do
result = progs.next.resume
if result == :waiting and last == :waiting
p b.sends
break
end
last = result
end
| true |
25770d7be280f8fa1fb18a970a7b24b48c111878 | Ruby | example-apps/palindrome | /tatum/spec/palindrome_spec.rb | UTF-8 | 901 | 2.984375 | 3 | [] | no_license | require 'spec_helper'
describe "#palindrome?" do
it "should handle empty Strings" do
expect(''.palindrome?).to be_false
end
it "returns false with an in-valid palidrome" do
expect('baseball'.palindrome?).to be_false
end
it "returns true with an valid palidrome" do
expect('racecar'.palindrome?).to be_true
end
it 'return true even with capital letters' do
expect('RacEcaR'.palindrome?).to be_true
end
it 'returns true even with special characters' do
expect("!No 'x' in 'Nixon".palindrome?).to be_true
end
it 'returns false for invalid words' do
expect('@#$%^&*()'.palindrome?).to be_false
end
context 'when passing numbers' do
it 'return true with a valid palindrome' do
expect(3883.palindrome?).to be_true
end
it 'returns false with an in-valid palindrome' do
expect(1337.palindrome?).to be_false
end
end
end
| true |
a1d8595e130f4ba4710b159556f9313a8d282510 | Ruby | Maria-L/Programme | /Aufgabe6/lib/hash.rb | UTF-8 | 1,126 | 2.703125 | 3 | [] | no_license | $LOAD_PATH.unshift File.join(File.dirname(__FILE__),'../..','Extensions')
#require'test/unit'
require_relative '../Extensions/ext_pr1_v4'
#Proove if self is equal to aHash
#
#equals_ ::= (aHash) :: Hash -> Bool
#
#Test{ (Hash["a" =>1],Hash["a" =>1]) => true, (Hash["a" =>1,"b" =>2],Hash["a" =>1])=> false,
# (Hash["a" =>1],Hash["a" =>2])=> false, (Hash["a" =>1,"b" =>2],Array[1,2])=> false}
class Hash
def equals_ aHash
if not aHash.hash? then false
else self.keys.all? {|a| self[a] == aHash[a]} and aHash.keys.all? {|a| self[a] == aHash[a]}
end
end
#Add the Values of the keys of both hashes
#
#add_counts_::= (a_hash) :: Hash -> Hash
#
#Test{ (Hash["a" =>1],Hash["a" =>1]) => Hash["a" => 2], (Hash["a" =>1, "b" => 2],Hash["a" =>1]) => Hash["a" => 2, "b" => 2],
# (Hash["a" =>1, "b" => 2], Hash["c" => 3]) => Hash["a" => 1, "b" => 2, "c" => 3]
# (Hash["a" =>1],"a") => Err}
def add_counts_ a_hash
check_pre(a_hash.hash?)
self.each_key {|a|
if a_hash.include?(a) then a_hash[a] = a_hash[a] + self[a]
else a_hash[a] = self[a]
end
}
a_hash
end
end
| true |
13b28f2af9627a1a0dd83c1a7b96903bf6f6c39e | Ruby | microsoftgraph/msgraph-sdk-ruby | /lib/models/learning_course_activity.rb | UTF-8 | 8,956 | 2.546875 | 3 | [
"MIT"
] | permissive | require 'date'
require 'microsoft_kiota_abstractions'
require_relative '../microsoft_graph'
require_relative './models'
module MicrosoftGraph
module Models
class LearningCourseActivity < MicrosoftGraph::Models::Entity
include MicrosoftKiotaAbstractions::Parsable
##
# Date and time when the assignment was completed. Optional.
@completed_date_time
##
# The percentage completion value of the course activity. Optional.
@completion_percentage
##
# A course activity ID generated by the provider. Optional.
@externalcourse_activity_id
##
# The user ID of the learner to whom the activity is assigned. Required.
@learner_user_id
##
# The ID of the learning content created in Viva Learning. Required.
@learning_content_id
##
# The registration ID of the provider. Required.
@learning_provider_id
##
# The status of the course activity. Possible values are: notStarted, inProgress, completed. Required.
@status
##
## Gets the completedDateTime property value. Date and time when the assignment was completed. Optional.
## @return a date_time
##
def completed_date_time
return @completed_date_time
end
##
## Sets the completedDateTime property value. Date and time when the assignment was completed. Optional.
## @param value Value to set for the completedDateTime property.
## @return a void
##
def completed_date_time=(value)
@completed_date_time = value
end
##
## Gets the completionPercentage property value. The percentage completion value of the course activity. Optional.
## @return a integer
##
def completion_percentage
return @completion_percentage
end
##
## Sets the completionPercentage property value. The percentage completion value of the course activity. Optional.
## @param value Value to set for the completionPercentage property.
## @return a void
##
def completion_percentage=(value)
@completion_percentage = value
end
##
## Instantiates a new learningCourseActivity and sets the default values.
## @return a void
##
def initialize()
super
end
##
## Creates a new instance of the appropriate class based on discriminator value
## @param parse_node The parse node to use to read the discriminator value and create the object
## @return a learning_course_activity
##
def self.create_from_discriminator_value(parse_node)
raise StandardError, 'parse_node cannot be null' if parse_node.nil?
mapping_value_node = parse_node.get_child_node("@odata.type")
unless mapping_value_node.nil? then
mapping_value = mapping_value_node.get_string_value
case mapping_value
when "#microsoft.graph.learningAssignment"
return LearningAssignment.new
when "#microsoft.graph.learningSelfInitiatedCourse"
return LearningSelfInitiatedCourse.new
end
end
return LearningCourseActivity.new
end
##
## Gets the externalcourseActivityId property value. A course activity ID generated by the provider. Optional.
## @return a string
##
def externalcourse_activity_id
return @externalcourse_activity_id
end
##
## Sets the externalcourseActivityId property value. A course activity ID generated by the provider. Optional.
## @param value Value to set for the externalcourseActivityId property.
## @return a void
##
def externalcourse_activity_id=(value)
@externalcourse_activity_id = value
end
##
## The deserialization information for the current model
## @return a i_dictionary
##
def get_field_deserializers()
return super.merge({
"completedDateTime" => lambda {|n| @completed_date_time = n.get_date_time_value() },
"completionPercentage" => lambda {|n| @completion_percentage = n.get_number_value() },
"externalcourseActivityId" => lambda {|n| @externalcourse_activity_id = n.get_string_value() },
"learnerUserId" => lambda {|n| @learner_user_id = n.get_string_value() },
"learningContentId" => lambda {|n| @learning_content_id = n.get_string_value() },
"learningProviderId" => lambda {|n| @learning_provider_id = n.get_string_value() },
"status" => lambda {|n| @status = n.get_enum_value(MicrosoftGraph::Models::CourseStatus) },
})
end
##
## Gets the learnerUserId property value. The user ID of the learner to whom the activity is assigned. Required.
## @return a string
##
def learner_user_id
return @learner_user_id
end
##
## Sets the learnerUserId property value. The user ID of the learner to whom the activity is assigned. Required.
## @param value Value to set for the learnerUserId property.
## @return a void
##
def learner_user_id=(value)
@learner_user_id = value
end
##
## Gets the learningContentId property value. The ID of the learning content created in Viva Learning. Required.
## @return a string
##
def learning_content_id
return @learning_content_id
end
##
## Sets the learningContentId property value. The ID of the learning content created in Viva Learning. Required.
## @param value Value to set for the learningContentId property.
## @return a void
##
def learning_content_id=(value)
@learning_content_id = value
end
##
## Gets the learningProviderId property value. The registration ID of the provider. Required.
## @return a string
##
def learning_provider_id
return @learning_provider_id
end
##
## Sets the learningProviderId property value. The registration ID of the provider. Required.
## @param value Value to set for the learningProviderId property.
## @return a void
##
def learning_provider_id=(value)
@learning_provider_id = value
end
##
## Serializes information the current object
## @param writer Serialization writer to use to serialize this model
## @return a void
##
def serialize(writer)
raise StandardError, 'writer cannot be null' if writer.nil?
super
writer.write_date_time_value("completedDateTime", @completed_date_time)
writer.write_number_value("completionPercentage", @completion_percentage)
writer.write_string_value("externalcourseActivityId", @externalcourse_activity_id)
writer.write_string_value("learnerUserId", @learner_user_id)
writer.write_string_value("learningContentId", @learning_content_id)
writer.write_string_value("learningProviderId", @learning_provider_id)
writer.write_enum_value("status", @status)
end
##
## Gets the status property value. The status of the course activity. Possible values are: notStarted, inProgress, completed. Required.
## @return a course_status
##
def status
return @status
end
##
## Sets the status property value. The status of the course activity. Possible values are: notStarted, inProgress, completed. Required.
## @param value Value to set for the status property.
## @return a void
##
def status=(value)
@status = value
end
end
end
end
| true |
d615ef7fd16e5c54e2dc1c4e28129bcc26ab2226 | Ruby | ODINAKACHUKWU/ruby-tutorials | /codes/f2cio.rb | UTF-8 | 320 | 3.375 | 3 | [] | no_license | puts "Reading Fahrenheit temperature value from data file..."
num = File.read("temp.dat")
fahrenheit = num.to_i
celsius = (5 * fahrenheit - 160) / 9
puts "Saving result to output file 'temp.out'..."
fh = File.new("temp.out", "w")
fh.puts celsius
fh.close
puts "Please check file 'temp.out' for the Celsius equivalence!"
| true |
da8b7a1844ce938ebaae12847a7242aa948f58ba | Ruby | Hyan18/OOD-encapsulation | /spec/secret_diary_spec.rb | UTF-8 | 2,076 | 3.078125 | 3 | [] | no_license | require 'secret_diary'
describe SecretDiary do
describe '#add_entry' do
it "should throw an error when the diary is locked" do
secret_diary = SecretDiary.new
expect(secret_diary.add_entry("text")).to eq("Diary is locked")
end
it "should add an entry whilst the diary is unlocked" do
secret_diary = SecretDiary.new
secret_diary.unlock
expect(secret_diary.add_entry("text")).to eq(["text"])
end
it "should throw an error when the diary is unlocked then locked again" do
secret_diary = SecretDiary.new
secret_diary.unlock
secret_diary.lock
expect(secret_diary.add_entry("text")).to eq("Diary is locked")
end
end
describe '#get_entries' do
it "should throw an error when the diary is locked" do
secret_diary = SecretDiary.new
expect(secret_diary.get_entries).to eq("Diary is locked")
end
it "should display an entry when the diary is unlocked" do
secret_diary = SecretDiary.new
secret_diary.unlock
secret_diary.add_entry("first entry")
expect{secret_diary.get_entries}.to output("first entry\n").to_stdout
end
it "should display multiple entries on new lines when the diary is unlocked" do
secret_diary = SecretDiary.new
secret_diary.unlock
secret_diary.add_entry("first entry")
secret_diary.add_entry("second entry")
expect{secret_diary.get_entries}.to output("first entry\nsecond entry\n").to_stdout
end
it "should throw an error when the diary is unlocked then locked again" do
secret_diary = SecretDiary.new
secret_diary.unlock
secret_diary.lock
expect(secret_diary.get_entries).to eq("Diary is locked")
end
end
describe '#unlock' do
it "should unlock the diary" do
secret_diary = SecretDiary.new
expect(secret_diary.unlock).to eq("Diary has been unlocked")
end
end
describe '#lock' do
it "should lock the diary" do
secret_diary = SecretDiary.new
expect(secret_diary.lock).to eq("Diary has been locked")
end
end
end
| true |
9921c76655c3715d89313de313706817c034e8b2 | Ruby | techthumb/http_stub | /spec/lib/http_stub/models/stub_parameters_spec.rb | UTF-8 | 2,478 | 2.5625 | 3 | [] | no_license | describe HttpStub::Models::StubParameters do
let(:request_parameters) { double("RequestParameters") }
let(:request) { double("HttpRequest", params: request_parameters) }
let(:stubbed_parameters) { { "key1" => "value1", "key2" => "value2", "key3" => "value3" } }
let(:regexpable_stubbed_paremeters) { double(HttpStub::Models::HashWithStringValueMatchers).as_null_object }
let(:stub_parameters) { HttpStub::Models::StubParameters.new(stubbed_parameters) }
describe "when stubbed parameters are provided" do
it "creates a regexpable representation of the stubbed parameters" do
expect(HttpStub::Models::HashWithStringValueMatchers).to receive(:new).with(stubbed_parameters)
stub_parameters
end
end
describe "when the stubbed parameters are nil" do
let(:stubbed_parameters) { nil }
it "creates a regexpable representation of an empty hash" do
expect(HttpStub::Models::HashWithStringValueMatchers).to receive(:new).with({})
stub_parameters
end
end
describe "#match?" do
it "delegates to the regexpable representation of the stubbed parameters to determine a match" do
allow(HttpStub::Models::HashWithStringValueMatchers).to receive(:new).and_return(regexpable_stubbed_paremeters)
expect(regexpable_stubbed_paremeters).to receive(:match?).with(request_parameters).and_return(true)
expect(stub_parameters.match?(request)).to be(true)
end
end
describe "#to_s" do
describe "when multiple parameters are provided" do
let(:stubbed_parameters) { { "key1" => "value1", "key2" => "value2", "key3" => "value3" } }
it "returns a string containing each parameter formatted as a conventional request parameter" do
result = stub_parameters.to_s
stubbed_parameters.each { |key, value| expect(result).to match(/#{key}=#{value}/) }
end
it "separates each parameter with the conventional request parameter delimiter" do
expect(stub_parameters.to_s).to match(/key\d.value\d\&key\d.value\d\&key\d.value\d/)
end
end
describe "when empty parameters are provided" do
let(:stubbed_parameters) { {} }
it "returns an empty string" do
expect(stub_parameters.to_s).to eql("")
end
end
describe "when nil parameters are provided" do
let(:stubbed_parameters) { nil }
it "returns an empty string" do
expect(stub_parameters.to_s).to eql("")
end
end
end
end
| true |
a5ca30becacb89f82e36d7662b2ae2a9577616bf | Ruby | breeshiaturner/Inventory | /wednesday_morning.rb | UTF-8 | 224 | 3.71875 | 4 | [] | no_license | def greeting
message = "Hello #{@user_name}, it is very #{@weather} this morning."
return message
end
puts "What is your name?"
@user_name = gets.chomp
puts "How is the weather today?"
@weather = gets.chomp
puts greeting | true |
a442cf2f3954039449fb0c0ee8c8a3a1c44df225 | Ruby | afas/cr | /app/models/remote_type.rb | UTF-8 | 687 | 3.03125 | 3 | [] | no_license | # encoding: utf-8
class RemoteType
attr_accessor :name
attr_accessor :cut
attr_accessor :code
def self.collection
[
RemoteType.new(:name => 'Пешком', :cut => 0, :code => "п"),
RemoteType.new(:name => 'Общественным транспортом', :cut => 1, :code => "т")
]
end
def initialize(hash)
self.name = hash[:name]
self.cut = hash[:cut]
self.code = hash[:code]
end
def self.by_id(id)
collection.each do |value|
return value.name if value.cut == id
end
false
end
def self.by_code(code)
collection.each do |value|
return value.cut if value.code == code
end
false
end
end | true |
025d8cac970b09fddd737f74f349a0ff36ad8725 | Ruby | tryppr/web_app | /app/models/tryppr_route.rb | UTF-8 | 1,862 | 2.84375 | 3 | [] | no_license | class TrypprRoute
attr_accessor :start_location, :end_location, :places
def puzzle_route
schedule = facilitate_places
morning_points = get_route(schedule[:morning_places], start_location, schedule[:midday_places][0].position)['routes'][0]['overview_polyline']['points']
midday_points = get_route(schedule[:midday_places].shift, schedule[:midday_places][0].position, schedule[:evening_places][0].position)['routes'][0]['overview_polyline']['points']
if schedule[:evening_places].length > 1
evening_points = get_route(schedule[:evening_places].shift, schedule[:evening_places][0].position, end_location)['routes'][0]['overview_polyline']['points']
else
evening_points = ''
end
[morning_points, midday_points, evening_points]
end
def get_route(places = self.places, start, finish)
if places.is_a?(Array)
places_positions = places.map{|p| p.position}.join('|')
else
places_positions = places.position
end
GoogleApi.get_google_route(start, finish, places_positions)
end
def facilitate_places
places = self.places
morning_places = TrypprRoute.order_places(180, places.select{|p| p.visiting_time.morning})
places -= morning_places
midday_places = TrypprRoute.order_places(300, places.select{|p| p.visiting_time.midday})
places -= midday_places
evening_places = TrypprRoute.order_places(500, places.select{|p| p.visiting_time.evening || p.visiting_time.night})
{
morning_places: morning_places,
midday_places: midday_places,
evening_places: evening_places,
}
end
private
def self.order_places(time, places)
result = []
places.sort { |a, b| b.duration <=> a.duration }.each do |place|
if time - place.duration >= 0
result.push(place)
time -= place.duration
end
end
result
end
end
| true |
4192da339f896c6de248838603d7ff3837fa7abe | Ruby | JeremyOttley/ruby-learn | /do-every.rb | UTF-8 | 102 | 3.171875 | 3 | [] | no_license | def interval(seconds)
loop do
sleep(seconds)
yield
end
end
interval(2) { puts "Hello!" }
| true |
3fa82083a7f4b906a79f1b98660dbdd86fa717e0 | Ruby | crayray/forms-and-basic-associations-rails-lab-austin-web-102819 | /app/controllers/songs_controller.rb | UTF-8 | 1,852 | 2.578125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class SongsController < ApplicationController
def index
@songs = Song.all
end
def show
@song = Song.find(params[:id])
end
def new
@song = Song.new
# Build 3 "empty" notes that are automatically set up with the correct
# parameter names to be used by accepts_nested_attributes_for
# See:
# https://api.rubyonrails.org/v5.2.3/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
2.times { @song.notes.build }
end
def create
# Create a local variable and set it equal to
# look for an artist that is entered into the song params with the :artist_name key
# If one exists, set it equal to artist
# If none exists, create it and set it equal to artist
artist= Artist.find_or_create_by(name: song_params[:artist_name])
# Create an instance variable and set it equal to
# build (not create: we're not saving to the DB yet) a new Song object
# and save the artist_id (above) to the song, using the parameters
@song = artist.songs.build(song_params)
# byebug
# if an exception is not thrown when we save @song to the db, redirect to the @song path
if @song.save
redirect_to @song
else
#otherwise, re-render the form
render :new
end
end
def edit
@song = Song.find(params[:id])
end
def update
@song = Song.find(params[:id])
@song.update(song_params)
if @song.save
redirect_to @song
else
render :edit
end
end
def destroy
@song = Song.find(params[:id])
@song.destroy
flash[:notice] = "Song deleted."
redirect_to songs_path
end
private
def song_params
params.require(:song).permit(:title, :artist_name, :genre_id, :notes, notes_attributes: [:content] )
# notes_attributes is used with fields_for to nest the data
end
end
| true |
ba45c6091277f250ff5e2b63c2e0e24f074cadc6 | Ruby | Duncan-Britt/Merge-Sort | /lib/main.rb | UTF-8 | 635 | 3.640625 | 4 | [] | no_license | def merge(arr1, arr2)
new = []
i = 0
j = 0
while i < arr1.length && j < arr2.length
if arr1[i] < arr2[j]
new << arr1[i]
i += 1
else
new << arr2[j]
j += 1
end
break if arr1[i].nil? || arr2[j].nil?
end
if i < arr1.length
until i == arr1.length
new << arr1[i]
i += 1
end
else
until j == arr2.length
new << arr2[j]
j += 1
end
end
new
end
def merge_sort(arr)
return arr if arr.size == 1
mid = arr.length / 2
left = arr[0..(mid-1)]
right = arr[mid..-1]
left = merge_sort(left)
right = merge_sort(right)
merge(left, right)
end
| true |
da730d5b593c65d4b34a9b06adc92932127b16e1 | Ruby | HackGT/catalyst2018-website | /.travis.d/pr_autodeploy.rb | UTF-8 | 3,293 | 2.53125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'git'
require 'octokit'
TR_PR_BRANCH = ENV['TRAVIS_PULL_REQUEST_BRANCH']
GH_TOKEN = ENV['GH_TOKEN']
ORG_NAME = ENV['ORG_NAME'] || 'HackGT'
GIT_NAME = ENV['GIT_NAME'] || 'HackGBot'
GIT_EMAIL = ENV['GIT_EMAIL'] || 'thehackgt@gmail.com'
def commit_to_biodomes
path = Dir.mktmpdir
git = Git.clone("https://github.com/#{ORG_NAME}/biodomes.git",
'biodomes',
path: path,
depth: 1)
# Configure git
git.config('user.name', GIT_NAME)
git.config('user.email', GIT_EMAIL)
# Change origin
git.remote('origin').remove
git.add_remote('origin',
"https://#{GH_TOKEN}@github.com/#{ORG_NAME}/biodomes.git",
fetch: false)
# do whatever work you want
message = nil
Dir.chdir(File.join(path, 'biodomes')) { || message = yield }
# commit & push
git.add(all: true)
begin
git.commit(message)
rescue
puts 'Nothing to commit, skipping...'
return
end
git.push
end
def git_branch
return TR_PR_BRANCH unless TR_PR_BRANCH.nil?
return ENV['TRAVIS_BRANCH'] unless ENV['TRAVIS_BRANCH'].nil?
`git rev-parse --abbrev-ref HEAD`.strip
end
def git_remote
remotes = `git remote -v`.match %r{#{ORG_NAME}/(.*?)\.git }i
remotes[1]
end
def git_branch_id(branch)
branch.gsub(/[^0-9a-zA-Z-]/, '-')
end
def pr_id(branch)
"#{git_remote}-#{git_branch_id branch}"
end
def create_biodome_file(branch)
remote = git_remote
data = <<~EOF
git:
remote: "https://github.com/#{ORG_NAME}/#{remote}.git"
branch: "#{branch}"
secrets-source: git-#{ORG_NAME}-#{remote}-secrets
deployment:
replicas: 1
strategy:
type: Recreate
EOF
["pr/#{pr_id branch}.yaml", data.downcase]
end
def create_message(branch)
<<~EOF
Hey y'all! A deployment of this PR can be found here:
https://#{pr_id branch}.pr.hack.gt
EOF
end
def pr_digest(github, slug)
github.pulls(slug)
.select { |p| p.state == 'open' }
.map do |p|
{
branch: p.head.ref,
number: p.number
}
end
.uniq
end
def main
github = Octokit::Client.new(access_token: GH_TOKEN)
remote = git_remote
slug = "#{ORG_NAME}/#{remote}"
digest = pr_digest(github, slug)
open_branches = digest.map { |pr| pr[:branch] }
files = open_branches.map { |branch| create_biodome_file(branch) }
# commit all the right files to biodomes
commit_to_biodomes do
FileUtils.rm_rf(Dir["./pr/#{remote}-*"])
files.each do |(path, data)|
FileUtils.mkdir_p(File.dirname(path))
File.write(path, data)
end
puts `git status`
puts `git diff`
"Automatic #{remote} PR deploys of #{open_branches.join(', ')}."
end
# Check if this is part of a PR build
current_branch = git_branch
current_pr = digest.find { |pr| pr[:branch] == current_branch }
return if current_pr.nil?
# Check if a message has already been written
message = create_message current_branch
comment_written =
github
.issue_comments(slug, current_pr[:number])
.find { |comment| comment.body.gsub(/\s+/, '') == message.gsub(/\s+/, '') }
return unless comment_written.nil?
# Write a message
github.add_comment(slug, current_pr[:number], message)
end
main
| true |
a027ff76f236df6462d1b6ecf39380af7a6d9010 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/gigasecond/3cd88e4c921142ebb0d90b70ac94feab.rb | UTF-8 | 230 | 2.921875 | 3 | [] | no_license | require 'date'
require 'time'
class Gigasecond
def self.from(begin_date)
#convert to datetime
begin_datetime = Time.new(begin_date.year, begin_date.month, begin_date.day)
return (begin_datetime + (10**9)).to_date
end
end
| true |
45dfec89b9f0a8365980bc368c2bf27722d35640 | Ruby | iulia-chitan/bitmap-editor | /cell_spec.rb | UTF-8 | 1,481 | 3.1875 | 3 | [] | no_license | require 'rspec'
require_relative 'cell'
require_relative 'image'
describe Cell do
(1..5).each do |k|
it 'should raise error if param string is not correct' do
expect{ Cell.new(k)}.to raise_error(RuntimeError, 'Please insert correct value for this cell')
end
end
('A'..'Z').each do |k|
it 'should initialize a new cell in the matrix' do
expect(Cell.new(k).value).to eq(k)
end
end
it 'should initialize a new cell in the matrix' do
expect(Cell.new().value).to eq('O')
end
[1, 5, 0, 45, 37, '/'].each do |k|
it 'should raise error if color char is not correct' do
cell = Cell.new
expect{ cell.color(k)}.to raise_error(RuntimeError, 'Please provide a valid cell color')
end
end
['A','D','W','Z','M'].each do |k|
it 'should color the cell' do
cell = Cell.new
cell.color(k)
expect(cell.value).to eq(k)
end
end
it 'should return correct neighbors' do
@image = Image.new(3,3)
@cell = @image.get_cell(1,2)
@cell.color('Z')
@neighbors = @cell.get_neighbors(@image)
expect(@neighbors.map{|c| @image.get_cell_coordinates(c)}).to eq([[1,1], [1,3], [2,2]])
end
it 'should return correct region cells' do
@image = Image.new(2,2)
@cell = @image.get_cell(2,2)
@cell2 = @image.get_cell(1,2)
@cell.color('Z')
@cell2.color 'Z'
@reg = @cell.get_region_cells(@image, @cell.value, [], [])
expect(@reg).to eq([@cell, @cell2])
end
end | true |
e5e923733e113883f96349f4a5e042efb29fea79 | Ruby | LaunchPadLab/decanter | /spec/decanter/parser/pass_parser_spec.rb | UTF-8 | 786 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe 'PassParser' do
let(:name) { :foo }
let(:parser) { Decanter::Parser::PassParser }
describe '#parse' do
it 'lets anything through' do
expect(parser.parse(name, '(12)2-21/19.90')).to match({name =>'(12)2-21/19.90'})
end
context 'with empty string' do
it 'returns nil' do
expect(parser.parse(name, '')).to match({name => nil})
end
end
context 'with nil' do
it 'returns nil' do
expect(parser.parse(name, nil)).to match({name => nil})
end
end
context 'with array value' do
it 'returns the array value' do
expect(parser.parse(name, ['123'])).to match({name => ['123']})
expect(parser.parse(name, [])).to match({name => []})
end
end
end
end
| true |
1161fd5f2432641560f43516ccae2740e8db00b5 | Ruby | minad/rack-contrib | /lib/rack/contrib/rewrite.rb | UTF-8 | 1,680 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'cgi'
module Rack
# Rack::Rewrite rewrites absolute paths to another base.
# If you have an application for / which you want to install under /~user/app
# then you can use this middleware.
# You have to specify the base as option.
class Rewrite
def initialize(app, options={})
raise ArgumentError, 'Base option is missing' if !options[:base]
@app = app
@base = options[:base]
@base.gsub!(%r{^/+|/+$}, '')
end
def call(env)
if env['PATH_INFO'] =~ %r{^/#{@base}$|^/#{@base}/}
env['PATH_INFO'] = env['PATH_INFO'].to_s.sub(%r{^/#{@base}/?}, '/')
env['REQUEST_URI'] = env['REQUEST_URI'].to_s.sub(%r{^/#{@base}/?}, '/')
status, header, body = @app.call(env)
if [301, 302, 303, 307].include?(status)
header['Location'] = '/' + @base + header['Location'] if header['Location'][0..0] == '/'
elsif ![204, 304].include?(status) && html?(header)
tmp = ''
body.each {|data| tmp << data}
body = tmp
body.gsub!(/(<(a|img|link|script|input|area|form)\s[^>]*(src|href|action)=["'])\/([^"']*["'])/m, "\\1/#{@base}/\\4")
header['Content-Length'] = body.length.to_s
end
[status, header, body]
else
response = Response.new
response.write "Webserver is not configured correctly. <a href=\"/#{@base}\">Application is available under /#{@base}</a><p>#{CGI::escapeHTML env.inspect}</p>"
response.finish
end
end
private
def html?(header)
%w(application/xhtml+xml text/html).any? do |type|
header['Content-Type'].to_s.include?(type)
end
end
end
end
| true |
228f51ce2dfc59c42d0772939813f6b36b6e0481 | Ruby | whatalnk/cpsubmissions | /atcoder/ruby/arc004/arc004_1/2120036.rb | UTF-8 | 580 | 3.328125 | 3 | [] | no_license | # Contest ID: arc004
# Problem ID: arc004_1 ( https://atcoder.jp/contests/arc004/tasks/arc004_1 )
# Title: A. 2点間距離の最大値 ( The longest distance )
# Language: Ruby (2.3.3)
# Submitted: 2018-02-21 07:43:04 +0000 UTC ( https://atcoder.jp/contests/arc004/submissions/2120036 )
N = gets.chomp.to_i
points = []
N.times do
x, y = gets.chomp.split(" ").map(&:to_i)
points << [x, y]
end
ans = 0
(0...N).each do |i|
a = points[i]
(i...N).each do |j|
b = points[j]
d = (b[0] - a[0])**2 + (b[1] - a[1])**2
ans = [ans, d].max
end
end
puts Math.sqrt(ans)
| true |
980848522a836ad841a8fc0887f2e27a78e75fea | Ruby | the-guitarman/brunch_finden | /app/models/forwarding.rb | UTF-8 | 3,531 | 2.875 | 3 | [] | no_license | class Forwarding < ActiveRecord::Base
@@update_last_use_at_on_find_enabled = true
# VALIDATIONS ----------------------------------------------------------------
validates_presence_of :source_url, :destination_url
validates_uniqueness_of :source_url
# CALLBACKS ------------------------------------------------------------------
def before_create
self.last_use_at = Time.now
end
def before_save
# Update source_url to destination_url example:
# Computer category/product/... forwards to Hardware.
# - Computer => Hardware
# Hardware will be deleted und forwarded to Electronics.
# - Hardware => Electronics
# Former forwardings to Hardware have to be updated to Electronics too.
# - so update: Comuter => Electronics
self.class.update_all(
"destination_url = '#{self.destination_url}'", # update
"destination_url = '#{self.source_url}'" # conditions
)
end
# PUBLIC METHODS -------------------------------------------------------------
def validate
if self.source_url == self.destination_url
self.errors.add(:source_url, "can't be equal to the destination url. ")
self.errors.add(:destination_url, "can't be equal to the source url. ")
end
end
# CLASS METHODS --------------------------------------------------------------
# Extends Forwarding.find, so that all Forwardings found by
# a given source_url (this should be one in each case only), will be
# updated with last_use_at = Time.now.
def self.find(*args)
result = super
if @@update_last_use_at_on_find_enabled
unless result.blank?
# url forwarding(s) found
options = args.extract_options!
# Are there find conditions given ...
unless options[:conditions].blank?
# ... and the field 'source_url' is in the conditions?
sql = self.sanitize_sql(options[:conditions])
unless sql.index('source_url').blank?
# update last_use_at to Time.now
# for all url forwarding(s), they are contained in the result
case result.class.name
when "Array"
result.each do |url_forwarding|
url_forwarding.update_attributes({:last_use_at => Time.now})
end
when name
result.update_attributes({:last_use_at => Time.now})
end
end
end
end
end
return result
end
# Returns @@update_last_use_at_on_find_enabled
def self.update_last_use_at_on_find_enabled
@@update_last_use_at_on_find_enabled
end
# Note: If you set this to false, a url forwarding will not update its
# attribute last_use_at, if it's found by Forwarding.find.
def self.update_last_use_at_on_find_enabled=(true_or_false)
@@update_last_use_at_on_find_enabled = true_or_false
end
# Cleans up not used url forwardings (default is older than one year).
def self.cleaner(options={})
show_messages = options[:show_messages].nil? ? true : options[:show_messages]
last_use_before = options[:last_use_before].nil? ? (Time.now - 1.year) : options[:last_use_before]
if show_messages
puts; print "Clean up forwardings before #{last_use_before.strftime('%d.%m.%Y')} ..."
count = 0
end
count = self.delete_all(["last_use_at < ?", last_use_before])
if show_messages
puts "done! (deleted #{count})"
nil
end
end
# PRIVATE METHODS ------------------------------------------------------------
private
end | true |
a4f988b3ce07cac58ee39b1fb72823b805a60c14 | Ruby | vtomyev/learn-ruby-the-hard-way | /ex22.rb | UTF-8 | 579 | 3.671875 | 4 | [] | no_license | # - is called hash and is used to comment or can be used in #{} to evaluate an expression in a string
+ used to add
= used to assign variables
- subtract
* multiply
/ divide
% modulus
return - returns output from a function
def - define function
end - ends function
puts - prints out a string on a new line
print - prinst out a string on the same line
\ - escape character ex. "I want \"this to print out within this string\" but also be in double quotes"
"" - string literal
'' - same as above
ARGV - takes a command argument as input
open - opens a file
gets - takes an input
| true |
6ed9348aeebc108fe7dbab58acb220b88ea7e97c | Ruby | davidruizrodri/code_kata | /spec/integration/chop.rb | UTF-8 | 1,604 | 2.84375 | 3 | [] | no_license | require 'spec_helper'
describe Chop::Base do
subject { Chop::Base }
context 'with an empty sorted array' do
it 'indicates item not found' do
expect( subject.recursive_find(1, []) ).to be -1
expect( subject.iterative_find(1, []) ).to be -1
end
end
context 'with search target in the middle of the array' do
it 'provides the index of the located item' do
expect( subject.recursive_find(20, [5, 10, 20, 30, 50]) ).to be 2
expect( subject.iterative_find(20, [5, 10, 20, 30, 50]) ).to be 2
end
end
context 'with search target as first item in the array' do
it 'provides an index of 0' do
expect( subject.recursive_find(20, [20, 30, 40, 50, 60]) ).to be 0
expect( subject.iterative_find(20, [20, 30, 40, 50, 60]) ).to be 0
end
end
context 'with search target as last item in the array' do
it 'provides an index for the last item' do
expect( subject.recursive_find(20, [5, 10, 15, 20]) ).to be 3
expect( subject.iterative_find(20, [5, 10, 15, 20]) ).to be 3
end
end
context 'with search target not in the array' do
it 'indicates item not found' do
expect( subject.recursive_find(20, [5, 15, 45, 135]) ).to be -1
expect( subject.iterative_find(20, [5, 15, 45, 135]) ).to be -1
end
end
context 'with a large array and a locatable search target' do
it 'provides the index of the found item' do
large_array = Array(0..900)
expect( subject.recursive_find(100, large_array) ).to be 100
expect( subject.iterative_find(100, large_array) ).to be 100
end
end
end | true |
a568384e12629773bcaa50b6a4baafd102540817 | Ruby | Ramoin/exos | /exo_16.rb | UTF-8 | 120 | 3.1875 | 3 | [] | no_license | puts "Quel age as-tu ?"
print ">"
age = gets.chomp.to_i
age.times do |i|
puts "Il y a #{i}ans, tu avais #{age-i}"
end
| true |
59b84d5c6c230b69e1729b9edbf1feee79ce3efa | Ruby | jackrobbins1/the-bachelor-todo-chicago-web-career-040119 | /lib/bachelor.rb | UTF-8 | 1,453 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require "pry"
js_hash = JSON.parse(File.read('spec/fixtures/contestants.json'))
def get_first_name_of_season_winner(data, season)
data.each { |seazon, contests|
if seazon == season
contests.each { |contest|
name = contest["name"].split(" ")
return name[0]
}
else
next
end
}
end
def get_contestant_name(data, occupation)
data.each { |seazon, contests|
contests.each { |contest|
if contest["occupation"] == occupation
return contest["name"]
else
next
end
}
}
end
def count_contestants_by_hometown(data, hometown)
townz = {}
data.each {|seazon, contests|
contests.each {|contest|
if townz.has_key?(contest["hometown"])
city = contest["hometown"]
townz[city] += 1
else
city = contest["hometown"]
townz[city] = 1
end
}
}
townz[hometown]
end
def get_occupation(data, hometown)
data.each {|seazon, contests|
contests.each {|contest|
if contest["hometown"] == hometown
return contest["occupation"]
else
next
end
}
}
end
def get_average_age_for_season(data, season)
ages = []
data.each { |seazon, contests|
if seazon == season
contests.each { |contest|
ages << contest["age"].to_f
}
else
next
end
}
averagez = ages.sum / ages.size
averagez.round
end
get_average_age_for_season(js_hash, "season 10")
| true |
b491bf55a555f5d28efa05a4b6ba3a5836b5d4fa | Ruby | vidoseaver/black_thursday | /lib/invoice_item_repository.rb | UTF-8 | 983 | 2.90625 | 3 | [] | no_license | require_relative "../lib/invoice_item"
require "csv"
require 'pry'
class InvoiceItemRepository
attr_reader :all
def initialize(data_path, sales_engine = nil)
@sales_engine = sales_engine
@all = []
csv_loader(data_path)
item_maker
end
def csv_loader(data_path)
@csv = CSV.open data_path, headers:true, header_converters: :symbol
end
def item_maker
@all = @csv.map do |row|
InvoiceItem.new(row, self)
end
end
def find_by_id(id_input)
@all.find do |instance|
instance.id == id_input.to_i
end
end
def find_all_by_price(price)
@all.find_all do |instance|
instance.unit_price == (price)
end
end
def find_all_by_item_id(item_id_input)
@all.find_all do |instance|
instance.item_id == item_id_input.to_i
end
end
def find_all_by_invoice_id(invoice_id_input)
@all.find_all do |instance|
instance.invoice_id == invoice_id_input.to_i
end
end
def inspect
end
end
| true |
91c47253ce8d9bb22406c4e3325bc45868635bf0 | Ruby | shwe-yuji/atcoder | /keyence2020.rb | UTF-8 | 453 | 3.46875 | 3 | [] | no_license | # #問題1
# h = gets.to_i
# w = gets.to_i
# n = gets.to_i
# if n % [h, w].max > 0
# puts n / [h, w].max + 1
# else
# puts n / [h, w].max
# end
# #問題2
# n = gets.to_i
# range = []
# for i in 1..n
# rob = gets.split(" ").map(&:to_i)
# r = [rob[0] - rob[1], rob[0] + rob[1]]
# range << r
# end
# range.sort!
# ctn = n
# i = 0
# while i <= range.length-2
# if range[i][1] > range[i+1][0]
# ctn -= 1
# end
# i += 1
# end
# puts ctn | true |
500687b9a426fc64f0d2aa6f2ec80927896cada4 | Ruby | orta/ortacasts | /tests.rb | UTF-8 | 863 | 2.84375 | 3 | [] | no_license | require File.dirname(__FILE__) + '/data'
require 'cgi'
require 'uri'
require 'net/http'
get_items()
links = []
@items.each do |cast|
# I want to know all the attributes are set
attrs = %w( title sub link description date length)
attrs.each do | attribute |
puts "no #{attribute} on #{ CGI.unescapeHTML(cast[:title]) }" unless cast[attribute.to_sym]
end
# # I want to check the file exists
# uri = URI.parse( @server + cast[:link] )
# http = Net::HTTP::new(uri.host, uri.port)
# response = http.request_head( cast[:link] )
# puts "location doenst exist on #{ CGI.unescapeHTML(cast[:title]) }" unless response.is_a? Net::HTTPSuccess
# I want to check that there' no duplication on the feeds
if( links.index(cast[:link]) )
puts "duped location on #{ CGI.unescapeHTML(cast[:title]) }"
end
links.push cast[:link]
end
| true |
a2c66ba456e6e7a1bbf7352735d14b82d7700fd6 | Ruby | rednblack99/bank_tech_test | /spec/transaction_spec.rb | UTF-8 | 788 | 2.890625 | 3 | [] | no_license | require 'transaction.rb'
describe Transaction do
context 'can read the' do
subject(:transaction) { described_class.new("01/01/2001", 1000, nil, 1000) }
it 'date' do
expect(transaction.date).to eq "01/01/2001"
end
it 'credit' do
expect(transaction.credit).to eq 1000
end
it 'debit' do
expect(transaction.debit).to eq nil
end
it 'balance' do
expect(transaction.balance).to eq 1000
end
end
it 'knows transaction is a deposit' do
transaction = Transaction.new("01/01/2001", nil, 1000, 1000)
expect(transaction.debit?).to eq "1000.00 "
end
it 'knows transaction is a withdrawal' do
transaction = Transaction.new("01/01/2001", 1000, nil, 1000)
expect(transaction.credit?).to eq "1000.00 "
end
end
| true |
942152597d1f1148355fac821285a52b13b21bbb | Ruby | ngeballe/ls120-lesson2 | /election/forecast.rb | UTF-8 | 1,185 | 3.765625 | 4 | [] | no_license | class State
attr_accessor :name, :clinton, :trump, :lead, :electoral_votes
def initialize(row_data)
@name = row_data[/[a-z\s]+/i].strip
@clinton, @trump, @lead, @electoral_votes = row_data.gsub(name, "").strip.split
self.electoral_votes = electoral_votes.to_i
# self.clinton = (clinton.to_f) / 100
# self.trump = (trump.to_f) / 100
self.lead = (lead.to_f) / 100
end
def winner
if @lead > 0
"Clinton"
elsif @lead < 0
"Trump"
end
end
end
class Clinton
end
class Trump
end
class Forecast
attr_accessor :states
def initialize(filename)
@data = File.readlines(filename)
@states = []
end
def generate_state_data
@data[1..-1].each do |line|
@states << State.new(line)
end
end
def tally_vote_forecast
generate_state_data
clinton_ev = 0
trump_ev = 0
# see who wins each state
@states.each do |state|
if state.winner == "Clinton"
clinton_ev += state.electoral_votes
elsif state.winner == "Trump"
trump_ev += state.electoral_votes
end
end
puts clinton_ev
puts trump_ev
end
end
f = Forecast.new('data.txt').tally_vote_forecast
| true |
df35f0ec9cf3c8c6e85a1e11d8c9eaffba74a280 | Ruby | meisyal/sastrawi-ruby | /spec/stop_word_remover/stop_word_remover_spec.rb | UTF-8 | 811 | 2.640625 | 3 | [
"MIT",
"CC-BY-NC-SA-3.0"
] | permissive | require 'spec_helper'
require 'sastrawi/dictionary/array_dictionary'
require 'sastrawi/stop_word_remover/stop_word_remover'
module Sastrawi
module StopWordRemover
describe StopWordRemover do
let :words do
%w[di ke]
end
let :array_dictionary do
Sastrawi::Dictionary::ArrayDictionary.new(words)
end
let :stop_word_remover do
Sastrawi::StopWordRemover::StopWordRemover.new(array_dictionary)
end
it 'should get dictionary' do
expect(stop_word_remover.dictionary).to be(array_dictionary)
end
it 'should remove stop words' do
expect(stop_word_remover.remove('pergi ke sekolah')).to eq('pergi sekolah')
expect(stop_word_remover.remove('makan di rumah')).to eq('makan rumah')
end
end
end
end
| true |
b0f80c3f904270023273b72cc709c43595dcc6c5 | Ruby | Gifts/cracklord | /build/travis-before_deploy.rb | UTF-8 | 1,723 | 2.71875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# This script goes through the current packages on packagecloud and deletes the older ones
# if there are more that 2 for a distro. Note that packagecloud differentiates between
# the queue and resource server, so that should give us a total of 4 packages per distro.
require 'json'
require 'pp'
require 'rest-client'
require 'time'
# Takes the name of a package and distribution and determines if we have too many. If so
# it deletes them.
def processPackage(distName, pkgName)
url = BASE_URL + "/package/deb/#{distName}/#{pkgName}/amd64/versions.json"
begin
versions = RestClient.get(url)
rescue StandardError => msg
puts msg
return
end
parsed_versions = JSON.parse(versions)
sorted_versions = parsed_versions.sort_by { |x| Time.parse(x["created_at"]) }
puts "[*] #{distName} - #{pkgName} - #{sorted_versions.size} existing packages."
if sorted_versions.size >= LIMIT
to_yank = sorted_versions.first
distro_version = to_yank["distro_version"]
filename = to_yank["filename"]
yank_url = "/#{distro_version}/#{filename}"
url = BASE_URL + yank_url
result = RestClient.delete(url)
if result == {}
puts "[!] Successfully yanked #{filename} to make room for new deployment."
end
end
end
# Get our environment variables all set.
API_TOKEN=ENV["PACKAGECLOUD_TOKEN"]
USER = 'emperorcow'
REPOSITORY = 'cracklord'
LIMIT = 2
BASE_URL = "https://#{API_TOKEN}:@packagecloud.io/api/v1/repos/#{USER}/#{REPOSITORY}"
DISTROS = [
'ubuntu/trusty',
'ubuntu/xenial',
'debian/jessie'
]
PACKAGES = [
'cracklord-queued',
'cracklord-resourced'
]
DISTROS.each { |dist|
PACKAGES.each { |pkg|
processPackage(dist, pkg)
}
}
| true |
d736a427ac6de18148da1cdfe57be317bb6b6c8f | Ruby | maurogs/ironhack | /week6/manderley_cast/app/models/vote.rb | UTF-8 | 646 | 2.65625 | 3 | [] | no_license | class Vote < ActiveRecord::Base
belongs_to :movie
belongs_to :user
enum rating: {disliked: -1, liked: 1, not_voted: 0}
scope :likes, ->() { liked }
scope :dislikes, ->() { disliked }
scope :user, ->(user) { where user: user}
scope :movie, ->(movie) { where movie: movie}
def liked
self.rating = :liked
end
def disliked
self.rating = :disliked
end
# Estos ya no se usan por el enum
# def liked!
# liked
# save
# end
# def disliked!
# disliked
# save
# end
#Estos 2 metodos son para tests
# def liked?
# amount == 1
# end
# def disliked?
# amount == -1
# end
end
| true |
56fec619a53434f43616d8616c4f6c09995cbc7d | Ruby | luisguzman02/body-mass | /app/interactors/body_mass_index.rb | UTF-8 | 1,151 | 3 | 3 | [] | no_license | class BodyMassIndex
include Interactor
before :valid_params?
CATEGORIES = {
0...15 => 'Very severely underweight',
15...16 => 'Severely underweight',
16...18.5 => 'Underweight',
18.5...25 => 'Normal (healthy weight)',
25...30 => 'Overweight',
30...35 => 'Obese Class I (Moderately obese)',
35...40 => 'Obese Class II (Severely obese)',
40 => 'Obese Class III (Very severely obese)'
}.freeze
def call
calculate_index
find_category
end
def calculate_index
idx = context.weight.to_f / (context.height.to_f * context.height.to_f)
context.index = (format '%.1f', idx).to_f
end
def find_category
context.category = CATEGORIES.detect do |k, _v|
if k.is_a?(Integer)
context.index >= k
else
k.include? context.index
end
end.last
end
private
def valid_params?
%w[weight height].each do |param|
context.fail!(error: "#{param} is required", status: :bad_request) if !context[param] || context[param].blank?
context.fail!(error: "#{param} must be a number", status: :bad_request) if context[param].to_f.zero?
end
end
end
| true |
0e721c7445c6e0e8db2e2903b9c89d88e25aa466 | Ruby | ctoneal/cs_sln_graph | /lib/vsfile_reader.rb | UTF-8 | 1,585 | 2.703125 | 3 | [
"MIT"
] | permissive | require File.expand_path(File.join(File.dirname(__FILE__), "project.rb"))
require 'rexml/document'
class VSFile_Reader
# get a list of projects from the solution file
def self.read_sln(path)
lines = []
projects = []
file = File.open(path) { |f| f.read }
file.each_line do |line|
match_data = line.match(/^\s*Project\s*\(\s*\"\{[A-F0-9\-]{36}\}\"\s*\)\s*=\s*\"(\S+)\"\s*,\s*\"(.*\.(vcproj|csproj))\"\s*,\s*\"\{([A-F0-9\-]{36})\}\"\s*$/i)
if not match_data.nil?
proj = Project.new(match_data[4], match_data[1], File.join(File.dirname(path), match_data[2]))
projects << proj
end
end
if projects.empty?
raise "No projects found."
end
return projects
end
# get a list of dependencies for the given project
def self.read_proj(path)
dependencies = []
begin
file = File.open(path) { |f| f.read }
rescue
return dependencies
end
document = REXML::Document.new(file)
# find external dependencies
document.elements.each('//Project/ItemGroup/Reference') do |element|
include = element.attributes["Include"]
items = include.split(',')
dependencies << items[0]
end
# find project dependencies
document.elements.each('//Project/ItemGroup/ProjectReference') do |element|
dep_path = File.absolute_path(File.join(File.dirname(path), element.attributes["Include"]))
name = ""
element.elements.each('Name') do |e|
name = e.text
end
id = ""
element.elements.each('Project') do |e|
id = e.text
end
proj = Project.new(id, name, dep_path)
dependencies << proj
end
return dependencies
end
end | true |
0e2b12a0ba8175bfe903032121d2da72b15d3c5a | Ruby | Andrz16/programacion_ruby_1 | /examen_final/ejercicio_01.rb | UTF-8 | 1,292 | 4.28125 | 4 | [] | no_license | #Pregunta 1
#Escriba una clase llamada Proceso, que contenga un método que haga lo siguiente:
#El método recibirá una cadena. Suponga que "#" es como un retroceso en la cadena.
#Esto significa que la cadena "a#bc#d#" en realidad es "bd". Su tarea es procesar la cadena con símbolos "#"
#Ejemplos:
#"abc#d#d##c" ==> "ac"
#"abc##d######" ==> ""
#"######" ==> ""
#"" ==> ""
#Test:
#analyze_string("abc#d#d##c")
#analyze_string("abc##d######")
#analyze_string("##dd####c")
#analyze_string("######")
class Proceso
def analyze_string(string)
i = 0
string.each_char do
puts "---- Iteración #{i} ----"
puts "Entrada: #{string[0,i+1]}"
if string[0] =="#"
puts "Eliminar: #{string[0]}"
string.sub!(string[0], "")
puts "Salida: ''"
elsif string[i] == "#"
puts "Eliminar: #{string[i-1,2]}"
string.sub!(string[i-1,2], "")
i -= 2
puts "Salida: #{string[0,i+1]}"
else
puts "Eliminar: Sin acción"
puts "Salida: #{string[0,i+1]}"
end
i+=1
end
puts "-------------------------"
puts "Salida final: '#{string}'"
end
end
obj_class = Proceso.new
puts "Ingrese una cadena: "
obj_class.analyze_string(string = gets.chomp)
| true |
4fc0e507a6cd3db4dae42f773ec56d5ac91272b5 | Ruby | rob4lderman/ruby-euler | /PrimeSet.rb | UTF-8 | 3,504 | 3.953125 | 4 | [] | no_license |
#
#
# Methods for calculating, caching, and iterating thru prime numbers.
#
# Note: not thread safe.
#
#
class PrimeSet
@@primes = [2, 3, 5, 7, 11, 13, 17, 19]
def initialize
@i = 0
end
def doUntil(max)
p = nextPrime
while (p <= max)
yield(p)
p = nextPrime
end
end
#
#
#
def nextPrime
if (@i >= @@primes.length)
@@primes.push( PrimeSet.computeNextPrime( @@primes.last ) )
end
@i += 1 # for the next go around
return @@primes[ @i - 1 ]
end
#
# given prime number x, compute next prime
#
def PrimeSet.computeNextPrime(x)
if (x <= 2)
return x+1
else
#brute force, check all subsequent numbers of the form 6k +- 1
k = (x + 7) / 6 # x could be of the form 6k-1, so move ahead 7 to guarantee we don't retry x
while true
a = 6*k - 1
return a if isPrime(a)
a = 6*k + 1
return a if isPrime(a)
k += 1
end
end
end
#
# http://en.wikipedia.org/wiki/Primality_test
#
def PrimeSet.isPrime(x)
if (x < 2)
return false
elsif (x == 2)
return true
end
# only need to check ints up to the sqrt of the number.
max = Math.sqrt(x).ceil
# first check all the primes we know about.
# Note: the first prime we divide with is 2, which is equivalent to a quick isEven check
@@primes.each do |p|
return true if (x == p)
return false if (x % p == 0)
end
# If the last prime we know about is still less than max,
# then check all odd numbers until we get to max
# There's a more efficient way to do this. All primes
# are of the form 6k +- 1 (except 2,3), so instead of checking all odds
# we need only check all numbers 6k +- 1, k=1..n, where 6k + 1 <= max.
# This saves us a single odd number check (worth it?)
if (@@primes.last < max)
starting_k = @@primes.last / 6
ending_k = max / 6
(starting_k..ending_k).each { |k| return false if ( (x % (6*k-1) == 0) || (x % (6*k+1) == 0) ) }
# (@@primes.last..max).step(2) { |n| return false if (x % n == 0) }
end
return true
end
def to_s
puts "PrimeSet:@@primes:#{@@primes}"
end
# -rx- #
# -rx- # @return the next permutation, or nil if none remain
# -rx- #
# -rx- def next
# -rx- k = find_k
# -rx- return nil if (k < 0)
# -rx- l = find_l(k)
# -rx- @digits.swap!(k,l)
# -rx- @digits.reverse_part!(k+1,@digits.length-1)
# -rx- return @digits
# -rx- end
#
# Yields each successive prime to the given block. If no block
# is given, returns a lazy Enumerator.
#
# Usage: primeEnum = PrimeSet.new.each
# primeEnum.next
# primeEnum.next
#
def each
if block_given?
loop do
yield nextPrime
end
else
#
# TODO: i don't really understand how this works...
Enumerator.new do |yielder|
loop do
yielder.yield nextPrime
end
end
end
end
private :nextPrime
end
| true |
6d41297b34ea6b52964d982bb108710f4be56e6c | Ruby | devdame/craigslist-jr | /app/helpers/helper.rb | UTF-8 | 59 | 2.921875 | 3 | [] | no_license | def to_money(cents)
"$" << cents.to_s.insert(-3, '.')
end | true |
f045bc5fe9ac725512a718775eef9aa8b0bf4969 | Ruby | ericovinicosta/pdti-ruby-respostas-exercicio05 | /resposta08.rb | UTF-8 | 324 | 3.859375 | 4 | [] | no_license | =begin
Faça uma função que informe a quantidade de dígitos de um determinado número inteiro informado.
=end
def quantidade_digitos (numero)
valor_numero = numero.to_s
valor_numero.length
end
print "Entre com um numero inteiro: "
numeros = gets.to_i
puts "A quantidade de digitos é: #{quantidade_digitos numeros}" | true |
7ba3acdede6a0d495194ee62c6e25b3f223a5a87 | Ruby | nyc-cicadas-2015/zip | /source/deck.rb | UTF-8 | 277 | 2.90625 | 3 | [] | no_license | require_relative 'card'
require_relative 'parser'
class Deck
attr_reader :deck
def initialize(deck)
@deck = []
# @still_left_in_deck = deck
end
def shuffle
flash_deck = @deck.shuffle!
flash_deck.pop
end
def empty?
@deck.empty?
end
end
| true |
8bf866159e6dfc14aa8d3c13e60784340e9cb8fa | Ruby | MayccSuarez/Ruby | /plural.rb | UTF-8 | 170 | 3.5 | 4 | [] | no_license | def plural palabra
"#{palabra}s"
end
plural "carro"
# agregar un método a una clase de ruby
class String
def mi_plural
"#{self}s"
end
end
puts "carro".mi_plural
| true |
63174175508dc452ca61c0f20ee5e2d44bd1e895 | Ruby | noidontdig/nyu-cs-prototype | /scripts/table_p.rb | UTF-8 | 938 | 2.859375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rubygems'
File.open("/Users/Ali/Desktop/table.txt", "r") do |file|
linetype = 1;
file.lines.each do |line|
fixed_line = line.strip;
if line.strip[0..2] != "<tr" and line.strip[0..3] != "</tr"
if linetype == 8
linetype = 1
end
case linetype
when 7
fixed_line = fixed_line.insert(3, " class=\"room\"")
when 1
fixed_line = fixed_line.insert(3, " class=\"number\"")
when 2
fixed_line = fixed_line.insert(3, " class=\"call-number\"")
when 3
fixed_line = fixed_line.insert(3, " class=\"name\"")
when 4
fixed_line = fixed_line.insert(3, " class=\"professor\"")
when 5
fixed_line = fixed_line.insert(3, " class=\"days\"")
when 6
fixed_line = fixed_line.insert(3, " class=\"time\"")
end
linetype = linetype + 1
end
puts line.split("<")[0] + fixed_line
end
end | true |
278f23ba7b89913c9e2df9ca96f875e04c32e37e | Ruby | ROCHAAL/Take_a_ten_minute_walk- | /spec/take_a_ten_minute_walk_spec.rb | UTF-8 | 1,059 | 3.1875 | 3 | [] | no_license | require 'take_a_ten_minute_walk'
describe 'ten_minute_walk' do
it 'takes an assortment of directions with the letters n, s, e, or w and return false if there are less than 10 minutes walk.'do
walk = ten_minute_walk?(['w', 's'])
expect(walk).to eq(false)
end
it 'takes an assortment of directions with the letters n, s, e, or w randomly and return true'do
walk = ten_minute_walk?(['w', 's', 'e', 'e', 'n', 'n', 'e', 's', 'w', 'w'])
expect(walk).to eq(true)
end
it 'takes the directions letters n, s, e, or w and return false if do not return to the starting point'do
walk = ten_minute_walk?(['w', 's', 'e', 's', 's', 'e', 's', 'w', 'n', 'n'])
expect(walk).to eq(false)
end
it 'takes the directions letters n, s, e, or w and return false if return an empty array'do
walk = ten_minute_walk?([])
expect(walk).to eq(false)
end
it 'takes the directions letters n, s, e, or w and return false if return to early'do
walk = ten_minute_walk?(['w', 's', 'e'])
expect(walk).to eq(false)
end
end
| true |
c7159b89153a2bd0f072e8456bbd2b3a71eb1a20 | Ruby | BrunaRosa/udemy-Ruby_studies | /ruby_basico/12-hashes.rb | UTF-8 | 440 | 3.5 | 4 | [] | no_license | # frozen_string_literal: true
# Hashes - informo a chave e o valor
h = { 'a' => '123', 'b' => '456' }
puts h['b']
# ou vc pode usar da forma de baixo
h = { a: '123', b: '456' }
puts h[:b]
# Simbolos são strings estaticas, o object_id não muda
puts 'string'.object_id # vem com valor diferente
puts 'string'.object_id # vem com valor diferente
puts :symbol.object_id # vem com valor igual
puts :symbol.object_id # vem com valor igual
| true |
9992711ccf6597a305cbf4e90afee45c00e57372 | Ruby | toxic2302/railsHoursAccounting | /app/helpers/workdays_helper.rb | UTF-8 | 353 | 3.109375 | 3 | [
"MIT"
] | permissive | module WorkdaysHelper
# get the working hours for an workday in hh:mm
def get_working_hours workday
workday.workingHours/60/60/24
end
# get the total working hours per month
def get_total_working_hours workdays
result = 0
workdays.each do |workday|
result = result + get_working_hours(workday)
end
result
end
end
| true |
ebc93fb1ed830a5f64ef073a09e885a4e137bff9 | Ruby | BaxmypkaVlad/Baxmypka | /Exampleprivateclass.rb | UTF-8 | 466 | 3.6875 | 4 | [] | no_license | class Animal
def initialize name
@name=name
end
def jump
puts "#{@name.capitalize} jumping"
end
def run
eat
10.times do
sleep 1
print "."
end
puts "\n#{@name.capitalize} is running"
end
private ##тут приватные методы которые вызвать нельзя отдельно
def eat
puts "#{@name.capitalize} eating"
end
end
cat=Animal.new "cat"
puts "#{cat.run}" | true |
b354b4a604aa9024666f489c2142e4b57f0f2b7c | Ruby | aghos7/batch_geocode | /batch_geocode.rb | UTF-8 | 13,092 | 2.625 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'csv'
require 'date'
require 'yaml'
require 'geocoder'
# require 'byebug'
require 'optparse'
require 'active_support/all'
require_relative 'wiw'
SEPARATOR = ","
# helper functions
def header(hash)
hash.keys.join SEPARATOR
end
def to_csv(hash)
hash.values.map do |value|
escape value unless value.nil?
end.join SEPARATOR
end
def score_results(results, line, opts = {})
results.each do |result|
# Score based on lat/lng
if result.latitude.present? && result.longitude.present?
lat = result.latitude.try(:to_f).try(:round, opts[:lat_lng_scale])
lng = result.longitude.try(:to_f).try(:round, opts[:lat_lng_scale])
if [lat, lng] == [line[:using_latitude], line[:using_longitude]]
result.score += 1000
result.scored_by << :lat_lng
end
if line[:using_latitude].present? && line[:using_longitude].present?
# Penalize lat/lng score based on distance, farther away decreases score
result.score -= Geocoder::Calculations.distance_between(
result.coordinates,
[line[:using_latitude], line[:using_longitude]])
result.scored_by << :lat_lng_distance
end
end
# Score based on Company
if result.data['name'].try(:present?) && result.data['name'].try(:downcase) == line[:using_company].try(:downcase)
result.score += 1500
result.scored_by << :company
end
# Score based on Street Address
if result.address_result.street_address == result.street_address
result.score += (result.lookup == :google ? 800 : 1500)
result.scored_by << :street_address
end
# Score based on City
if result.address_result.city == result.city
result.score += (result.lookup == :google ? 250 : 500)
result.scored_by << :city
end
# Score based on State
if result.address_result.state_code == result.state_code
result.score += 750
result.scored_by << :state
end
# Score based on Postal Code
if result.address_result.postal_code == result.postal_code
result.score += 250
result.scored_by << :postal
end
# Score based on Country
if result.address_result.country_code == result.country_code
result.score += 100
result.scored_by << :country
end
# Score types
if ((result.types || []) & [opts[:limit_types]].flatten).any?
result.score += 1500
result.scored_by << :place_type
end
# Score table_place_id
if result.place_id.present? && result.place_id == line[:table_place_id]
result.score += (result.lookup == :google ? 500 : 500000)
result.scored_by << :table_place_id
end
# Score places_place_id
if result.place_id.present? && result.place_id == line[:places_place_id]
result.score += (result.lookup == :google ? 1500 : 1000000)
result.scored_by << :places_place_id
end
# Penalize google maps results
if result.lookup == :google
result.scored_by << :google_maps_penalty
end
end
end
def search(query, opts={})
results = Geocoder.search(query, opts)
sleep (opts[:sleep] || @options[:sleep]) # ick
results
end
def line_defaults(line, opts={})
line[:using_place_id] ||= ""
line[:using_latitude] ||= ""
line[:using_longitude] ||= ""
line[:using_company] ||= ""
line[:using_address] ||= ""
line[:geocoded_company] ||= ""
line[:geocoded_place_id] ||= ""
line[:geocoded_latitude] ||= ""
line[:geocoded_longitude] ||= ""
line[:geocoded_address] ||= ""
line[:geocoded_street_address] ||= ""
line[:geocoded_city] ||= ""
line[:geocoded_state] ||= ""
line[:geocoded_sub_state] ||= ""
line[:geocoded_postal_code] ||= ""
line[:geocoded_country] ||= ""
line[:geocoded_types] ||= ""
line[:geocoded_wiw_industry] ||= ""
line[:geocoded_score] ||= ""
line[:geocoded_scored_by] ||= ""
line[:geocoded_lookup] ||= ""
line[:possible_issues] ||= ""
line[:geocoded_status] ||= ""
end
def log_line(line, opts={})
puts "--------------------------------------------------------------------------------"
puts "#{line[:table]}:#{line[:table_id]}:#{line[:account_id]}"
puts "using company: #{line[:using_company]}"
puts "using address: #{line[:using_address]}"
puts "using place_id: #{line[:using_place_id]}"
puts "geo company: #{line[:geocoded_company]}"
puts "geo address: #{line[:geocoded_address]}"
puts "geo place_id #{line[:geocoded_place_id]}"
puts "lookup: #{line[:geocoded_lookup]}"
puts "score: #{line[:geocoded_score]}"
puts "scored by: #{line[:geocoded_scored_by]}"
puts "industry: #{line[:geocoded_wiw_industry]}"
puts "issues: #{line[:possible_issues]}"
puts "status: #{line[:geocoded_status]}"
end
def possible_issues(line, result, opts={})
issues = []
if line[:using_latitude].present? && line[:using_longitude].present?
if [line[:geocoded_latitude], line[:geocoded_longitude]] != [line[:using_latitude], line[:using_longitude]]
issues << :lat_lng_mismatch
end
else
issues << :missing_lat_lng
end
if line[:using_place_id].present?
if line[:geocoded_place_id].to_s != line[:using_place_id].to_s
issues << :place_id_mismatch
end
else
issues << :missing_place_id
end
if line[:geocoded_company].present? && line[:geocoded_company] != line[:using_company]
issues << :company_mismatch
end
if result.try(:street_address).present? && result.street_address != result.address_result.try(:street_address)
issues << :street_address_mismatch
end
if result.try(:city).present? && result.city != result.address_result.try(:city)
issues << :city_mismatch
end
if result.try(:state_code).present? && result.state_code != result.address_result.try(:state_code)
issues << :state_mismatch
end
if result.try(:postal_code).present? && result.postal_code != result.address_result.try(:postal_code)
issues << :postal_mismatch
end
if result.try(:country_code).present? && result.country_code != result.address_result.try(:country_code)
issues << :country_mismatch
end
issues
end
@options = {}
# Load config
begin
yaml = YAML.load_file("config.yml")
@options[:input_file] = yaml['input_file'] || 'input.csv'
@options[:output_file] = yaml['output_file'] || 'output.csv'
@options[:geocoder_api_key] = yaml['geocoder_api_key']
@options[:lat_lng_scale] = yaml['lat_lng_scale'].try(:to_i) || 8
@options[:sleep] = yaml[:sleep].try(:to_f) || 0
@options[:line_sleep] = yaml[:line_sleep].try(:to_f) || 1
@options[:always_raise] = yaml[:always_raise] || :all
@options[:skip_status] = yaml[:skip_status].try(:split, ',') || nil
@options[:exclude_skipped] = yaml[:exclude_skipped] == "true" || false
rescue Errno::ENOENT
puts "config file not found"
end
# read command line options
OptionParser.new do |opt|
opt.on('-i input_file', '--input_file input_file', 'Input file') { |o| @options[:input_file] = o }
opt.on('-o output_file', '--output_file output_file', 'Output file') { |o| @options[:output_file] = o }
opt.on('-k api_key', '--api_key api_key', 'Geocoder API Key') { |o| @options[:geocoder_api_key] = o }
opt.on('-s skip_status', '--skip_status skip_status', 'Statuses to skip') { |o| @options[:skip_status] = o.try(:split, ',') }
opt.on('-e exclude_skipped', '--exclude_skipped exclude_skipped', 'Exclude skipped from output - true/false') do |o|
@options[:exclude_skipped] = (o == "true")
end
end.parse!
# config geocoder
Geocoder.configure(
use_https: true,
# to use an API key:
api_key: @options[:geocoder_api_key],
timeout: 10,
always_raise: @options[:always_raise]
)
# read each line of input file, geocode and output results
puts "reading address file"
# write to CSV
CSV.open(@options[:output_file], "wb") do |csv|
line_number = 0
CSV.foreach(@options[:input_file], headers: true, header_converters: :symbol) do |line|
begin
result = nil
line_defaults(line)
if line_number == 0
csv << line.headers
end
line_number += 1
if @options[:skip_status].present? && @options[:skip_status].include?(line[:geocoded_status])
csv << line unless @options[:exclude_skipped]
puts "skipping status: #{line[:geocoded_status]}"
next
end
match_options = {}
query_params = {}
if line[:table] == 'accounts'
match_options[:limit_types] = 'establishment'
query_params[:types] = 'establishment'
end
match_options[:match_place_id] = true
line[:using_place_id] = (line[:places_place_id] || line[:table_place_id]).to_s
line[:using_latitude] = (line[:places_latitude] || line[:table_latitude]).try(:to_f).try(:round, @options[:lat_lng_scale])
line[:using_longitude] = (line[:places_longitude] || line[:table_longitude]).try(:to_f).try(:round, @options[:lat_lng_scale])
results = []
[line[:address], line[:account_address]].compact.uniq.each do |address|
search("#{address}", lookup: :google).each do |address_result|
[line[:company], line[:account_company]].compact.uniq.each do |company|
queries = []
queries << {
name: :company_address,
text: "#{company}, #{address}",
score: 2000 }
queries << {
name: :company_postal,
text: "#{company}, #{address_result.postal_code}",
score: 1000 }
queries << {
name: :company_city_state,
text: "#{company}, #{address_result.city} #{address_result.state_code}",
score: 500 }
queries << {
name: :company,
text: "#{company}",
score: 100 }
queries << {
name: :address,
text: "#{address}",
score: 100 }
queries.each do |query|
search(query[:text], lookup: :google_places_autocomplete, params: query_params).each do |autocomplete_result|
results += search(autocomplete_result.place_id, lookup: :google_places_details).each do |result|
class << result
attr_accessor :lookup
end
result.lookup = :google_places_autocomplete
end
end
results += search(query[:text], lookup: :google, params: query_params).each do |result|
class << result
attr_accessor :lookup
end
result.lookup = :google
end
results.each do |result|
class << result
attr_accessor :using_company
attr_accessor :using_address
attr_accessor :address_result
attr_accessor :scored_by
attr_accessor :query
attr_accessor :score
end
result.using_company = company
result.using_address = address
result.address_result = address_result
result.scored_by = [query[:name]]
result.query = query
result.score = query[:score]
end
end
end
end
end
results.uniq!{ |result| result.place_id }
score_results(results, line, @options.merge(match_options))
results.sort_by!{ |result| -result.score }
result = results.first
line[:using_company] = result.try(:using_company)
line[:using_address] = result.try(:using_address)
line[:geocoded_company] = result.try(:data).try(:[], 'name')
line[:geocoded_place_id] = result.try(:place_id)
line[:geocoded_latitude] = result.try(:latitude).try(:to_f).try(:round, @options[:lat_lng_scale])
line[:geocoded_longitude] = result.try(:longitude).try(:to_f).try(:round, @options[:lat_lng_scale])
line[:geocoded_address] = result.try(:address)
line[:geocoded_street_address] = result.try(:street_address)
line[:geocoded_city] = result.try(:city)
line[:geocoded_state] = result.try(:state_code)
line[:geocoded_sub_state] = result.try(:sub_state)
line[:geocoded_postal_code] = result.try(:postal_code)
line[:geocoded_country] = result.try(:country_code)
line[:geocoded_types] = result.try(:types).try(:join, ',')
line[:geocoded_wiw_industry] = Wiw::google_place_types_to_industry_ids(result.try(:types)).first || Wiw::INDUSTRIES['Other']
line[:geocoded_score] = result.try(:score)
line[:geocoded_scored_by] = result.try(:scored_by).try(:join, ',')
line[:geocoded_lookup] = result.try(:lookup)
line[:possible_issues] = possible_issues(line, result).compact.join(',')
line[:geocoded_status] = result.present? ? :success : :geocode_failed
log_line(line)
csv << line
rescue Geocoder::Error => e
line[:geocoded_status] = e.to_s
log_line(line)
csv << line
rescue => e
puts "processing error #{e.to_s}"
puts line.inspect
end
sleep @options[:line_sleep]
end
end
puts "done"
nil
| true |
5241e4dd88d833ade366db8e128c52e2631efdcf | Ruby | amhursh/black_thursday | /test/item_test.rb | UTF-8 | 4,094 | 2.71875 | 3 | [] | no_license | require_relative 'test_helper'
require_relative '../lib/item'
require_relative '../lib/sales_engine'
class ItemTest < Minitest::Test
def test_item_exists
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
assert_instance_of Item, item
end
def test_item_has_id
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
id = item.id
assert_equal 263399187, id
end
def test_item_has_name
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
name = item.name
assert_equal "Spalted Maple Heart Box", name
end
def test_item_has_description
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
descrip = item.description
assert_equal "spalted maple wood USA, handmade", descrip
end
def test_item_has_unit_price
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
unit_price = item.unit_price
assert_instance_of BigDecimal, unit_price
assert_equal 48.0, unit_price.to_f
end
def test_item_has_merchant_id
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
merch_id = item.merchant_id
assert_equal 12334365, merch_id
end
def test_item_has_created_at_date
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
create_date = item.created_at
assert_instance_of Time, create_date
end
def test_item_has_updated_at_date
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
update_date = item.updated_at
assert_instance_of Time, update_date
end
def test_unit_price_dollar_conversion
item = Item.new({:id => 263399187, :name => "Spalted Maple Heart Box",
:description => "spalted maple wood USA, handmade", :unit_price => 4800,
:merchant_id => 12334365, :created_at => "2016-01-11 11:59:38 UTC",
:updated_at => "1988-01-23 17:26:28 UTC"}, self)
unit_price_in_cents = 1200
unit_price = item.unit_price_in_dollars(unit_price_in_cents)
assert_equal 12.00, unit_price
end
def test_item_can_get_merchant
se = SalesEngine.from_csv({
:items => "./data/items.csv",
:merchants => "./data/merchants.csv",
:invoices => "./data/invoices.csv"
})
items = se.items
item = items.find_all_by_merchant_id(12335119)[0]
merchant = item.merchant
assert_instance_of Merchant, merchant
end
end
| true |
062bdd89c9982fb38894fff831041ebe416646fd | Ruby | FHG-IMW/epo-ops | /test/epo_ops/util_test.rb | UTF-8 | 1,062 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
module EpoOps
class UtilTest < Minitest::Test
# dig
def test_traverse_the_path_and_return_a_single_result
data = {foo: {bar: {baz: 'foobarbaz'}}}
assert_equal 'foobarbaz', EpoOps::Util.dig(data,:foo,:bar,:baz)
end
def test_return_nil_if_path_does_not_exist
data = {foo: {bar: [{baz: 'foobarbaz'}]}}
assert_nil EpoOps::Util.dig(data,:foo,:bar,:baz)
end
#flat_dig
def test_traverse_a_nested_hash
data = {foo: {bar: {baz: 'foobarbaz'}}}
assert_equal ['foobarbaz'], EpoOps::Util.flat_dig(data,:foo,:bar,:baz)
end
def test_traverse_mixed_nested_hashs_and_arrays
data = {foo: {bar: [ {baz: '1'}, {baz: '2'} ] }}
assert_equal ['1','2'], EpoOps::Util.flat_dig(data,:foo,:bar,:baz)
end
def test_ignore_empty_paths_in_mixed_nested_hash_and_array
data = {
foo: [
{bar: {baz: 1}},
{bar: 2},
3
]
}
assert [1], EpoOps::Util.flat_dig(data,:foo,:bar,:baz)
end
end
end
| true |
f2d84384fec61a11b39823509e5e8ddca23bdde2 | Ruby | Madao-3/LeetCode_Madao | /500. Keyboard Row .rb | UTF-8 | 144 | 3.046875 | 3 | [] | no_license | # @param {String[]} words
# @return {String[]}
def find_words(words)
words.select { |w| w =~ /^([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$/i }
end | true |
e2db8e7e45d2eb458c65363afef6e5510d2c10c3 | Ruby | games-directory/steam-api | /lib/steam-api/steam/user.rb | UTF-8 | 3,673 | 2.65625 | 3 | [
"MIT"
] | permissive | # -*- encoding: utf-8 -*-
module Steam
# A Ruby DSL for communicating with the Steam::User Web API.
# @see https://developer.valvesoftware.com/wiki/Steam_Web_API
# @since 1.0.0
module User
# Get User's Friend List
# @param [String] steamid
# @param [String] relationship Relationship filter.
# Possibles values: all, friend.
# @return [Hash] A hash object resulting from the API call; should
# returns the friend list of any Steam user, provided their Steam
# Community profile visibility is set to "Public".
# @see http://wiki.teamfortress.com/wiki/WebAPI/GetFriendList
def self.friends(steamid, relationship: :all)
response = client.get 'GetFriendList/v1/',
params: { steamid: steamid,
relationship: relationship }
response = response.parse_key('friendslist')
.parse_key('friends')
response
end
# Get Multiple Player Bans
# @param [Array] steamids Array of SteamIDs
# @return [Hash] A hash containing the API response
# @see http://wiki.teamfortress.com/wiki/WebAPI/GetPlayerBans
def self.bans(steamids)
steamids = [steamids] unless steamids.is_a?(Array)
response = client.get 'GetPlayerBans/v1/',
params: { steamids: steamids.join(',') }
response
end
# Get Player Summaries
# @option params [Array] :steamids List of player's steamids
# @return [Hash] The hash object resulting from the API call. Some data
# associated with a Steam account may be hidden if the user has their
# profile visibility set to "Friends Only" or "Private". In that case,
# only public data will be returned.
# @see http://wiki.teamfortress.com/wiki/WebAPI/GetPlayerSummaries
def self.summary(steamid)
summaries([steamid]).first
end
# Get Player Summaries
# @param [Array] steamids List of player's steamids
# @return [Hash] The hash object resulting from the API call. Some data
# associated with a Steam account may be hidden if the user has their
# profile visibility set to "Friends Only" or "Private". In that case,
# only public data will be returned.
# @see http://wiki.teamfortress.com/wiki/WebAPI/GetPlayerSummaries
def self.summaries(steamids)
response = client.get 'GetPlayerSummaries/v2/',
params: { steamids: steamids.join(',') }
response.parse_key('response')
.parse_key('players')
end
# Get User Groups
# @param [Fixnum] steamid 64bit Steam ID to return friend list.
# @return [Hash] A hash containing the API response
# @see http://wiki.teamfortress.com/wiki/WebAPI/GetUserGroupList
def self.groups(steamid)
response = client.get 'GetUserGroupList/v1', params: { steamid: steamid }
response = response.parse_key('response')
response.check_success
response.parse_key('groups')
end
# Resolve Vanity URL
# @param [String] vanityurl The vanity URL part of a user's Steam
# profile URL. This is the basename of http://steamcommunity.com/id/ URLs
# @return [Hash] A hash containing the API response
# @see http://wiki.teamfortress.com/wiki/WebAPI/ResolveVanityURL
def self.vanity_to_steamid(vanityurl)
response = client.get 'ResolveVanityURL/v1',
params: { vanityurl: vanityurl }
response = response.parse_key('response')
response.check_success(success_condition: 1)
response.parse_key('steamid')
end
def self.client
build_client 'ISteamUser'
end
end
end
| true |
b4749773eae725097e9b1e60057f4c3c7e10ca31 | Ruby | taw/project-euler | /euler_57.rb | UTF-8 | 175 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env ruby1.9
require 'mathn'
a = 2
c = 0
999.times{|i|
b = 1+1/a
a = 2+1/a
if b.numerator.to_s.size > b.denominator.to_s.size
c += 1
p b
end
}
p c
| true |
35b0b59a41effb233278e30051199fc8dd4a928b | Ruby | wowonrails/csv-file-manager | /lib/csv_file_manager.rb | UTF-8 | 694 | 2.546875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require "csv"
require "csv_file_manager/file_manager"
require "csv_file_manager/file_redactor"
require "csv_file_manager/instance_properties"
require "csv_file_manager/base_methods"
# Dir[File.dirname(__FILE__).concat('/**/*.rb')].each { |path| require path }
module CsvFileManager
def self.create_file(class_name)
FileManager.create(class_name)
end
def self.destroy_file(class_name)
FileManager.destroy(class_name)
end
class Base
extend CsvFileManager::FileRedactor
include CsvFileManager::InstanceProperties
include CsvFileManager::BaseMethods
end
end
class Post < CsvFileManager::Base
my_properties :title, :content
end
| true |
0afe2bb5d5a5f10a6bb879a71acd9ec300e69580 | Ruby | CJStadler/state_machine_checker | /spec/machines/simple_machine.rb | UTF-8 | 476 | 3.03125 | 3 | [
"MIT"
] | permissive | require "state_machines"
require "./lib/state_machine_checker/finite_state_machine.rb"
require "./lib/state_machine_checker/transition.rb"
class SimpleMachine
# Our internal representation of the state machine.
def self.finite_state_machine
StateMachineChecker::FiniteStateMachine.new(
:one,
[StateMachineChecker::Transition.new(:one, :two, :go)]
)
end
state_machine initial: :one do
event :go do
transition one: :two
end
end
end
| true |
8817d7c538bced6f7a0c11c93ce1da3a234c98bb | Ruby | hiimchinh/rb101 | /easy_4/convert_a_string_to_a_signed_number.rb | UTF-8 | 663 | 3.96875 | 4 | [] | no_license | DIGITS = {
'0' => 0,
'1' => 1,
'2' => 2,
'3' => 3,
'4' => 4,
'5' => 5,
'6' => 6,
'7' => 7,
'8' => 8,
'9' => 9
}
def string_to_integer(string)
digits = string.chars.map { |char| DIGITS[char] }
total = 0
index = 1
string.chars.reverse.each do |char|
number = DIGITS[char]
total += number * index
index *= 10
end
total
end
def string_to_signed_integer(string)
multiply_by = string.include?('-') ? -1 : 1
string = string.delete('+-')
string_to_integer(string) * multiply_by
end
puts string_to_signed_integer('4321') == 4321
puts string_to_signed_integer('-570') == -570
puts string_to_signed_integer('+100') == 100 | true |
87e9fc67957d90f465a958bfa90059830ed700e9 | Ruby | security-prince/websitesVulnerableToSSTI | /ruby/ERB/src/web.rb | UTF-8 | 763 | 2.796875 | 3 | [
"Apache-2.0"
] | permissive | require "sinatra"
require 'erb'
set :port,5081
set :bind, '0.0.0.0'
def getHTML(name)
correct_form = <<-slim
<html>
head
title Example
<body>
<p><%= name %></p>
</body>
</html>
slim
text = '<!DOCTYPE html><html><body>
<form action="/" method="post">
First name:<br>
<input type="text" name="name" value="">
<input type="submit" value="Submit">
</form><h2>Hello '+name+'</h2></body></html>'
template = ERB.new(text)
return template.result(binding)
end
get "/" do
name =""
if(params["name"]!= nil)
name =params['name']
end
getHTML(name)
end
post "/" do
name =""
if(params["name"]!= nil)
name =params['name']
end
getHTML(name)
end | true |
3803d97869665bbf59d4af1179b33860fd2a1129 | Ruby | kbkbqiang/reverse_adoc | /lib/reverse_adoc/converters/h.rb | UTF-8 | 1,001 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | module ReverseAdoc
module Converters
class H < Base
def convert(node, state = {})
id = node['id']
anchor = id ? "[[#{id}]]" : ""
internal_anchor = treat_children_anchors(node, state) || ""
anchor.empty? and anchor = internal_anchor
anchor.empty? or anchor += "\n"
prefix = '=' * (node.name[/\d/].to_i + 1)
["\n", anchor, prefix, ' ', treat_children_no_anchors(node, state), "\n"].join
end
def treat_children_no_anchors(node, state)
node.children.reject { |a| a.name == "a" }.inject('') do |memo, child|
memo << treat(child, state)
end
end
def treat_children_anchors(node, state)
node.children.select { |a| a.name == "a" }.inject('') do |memo, child|
memo << treat(child, state)
end
end
end
register :h1, H.new
register :h2, H.new
register :h3, H.new
register :h4, H.new
register :h5, H.new
register :h6, H.new
end
end
| true |
42ba40e25392a45e2f6e545fcbeb15823668bdef | Ruby | derailed/wewoo | /spec/wewoo/edge_spec.rb | UTF-8 | 946 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
module Wewoo
describe Vertex do
before :all do
@g = Graph.new(:test_graph)
build_test_graph( @g )
end
context 'equality' do
it 'validates two egdes are the same' do
expect( @v1.outE(:love) == @v1.outE(:love) ).to eq true
end
it 'validates two egdes are different' do
e1, e2 = @v1.outE(:friend).first, @v1.outE(:friend).last
expect( e1 == e2 ).to eq false
end
it 'validates anything against null' do
expect( @v1.outE(:love) == nil ).to be false
end
end
context 'vertices' do
it "fetches edge head correctly" do
expect( @e1.in ).to eq @v2
end
it "fetches edge tail correctly" do
expect( @e1.out ).to eq @v1
end
it 'deletes an edge correctly' do
before = @g.E.count()
@e1.destroy
expect( @g.E.count() ).to eq before-1
end
end
end
end
| true |
ea34363beb98729c34a2f928bd7aec1685273af1 | Ruby | wilkerlucio/dragonfly | /spec/dragonfly/extended_temp_object_spec.rb | UTF-8 | 3,037 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require File.dirname(__FILE__) + '/../spec_helper'
describe Dragonfly::ExtendedTempObject do
it "should raise an error if not configured with an app" do
temp_object = Dragonfly::ExtendedTempObject.new('asdf')
lambda{
temp_object.process(:dummy)
}.should raise_error(Dragonfly::ExtendedTempObject::NotConfiguredError)
end
describe "when configured correctly" do
before(:each) do
@analyser = mock('analyser', :has_callable_method? => false)
@analyser.stub!(:has_callable_method?).with(:width).and_return(true)
@processor = mock('processor')
@encoder = mock('encoder')
@app = mock('app', :analysers => @analyser, :processors => @processor, :encoders => @encoder)
@klass = Class.new(Dragonfly::ExtendedTempObject)
@klass.app = @app
end
describe "analysis" do
before(:each) do
@object = @klass.new('asdf')
end
it "should respond to something that the analyser responds to" do
@analyser.should_receive(:has_callable_method?).with(:some_method).and_return(true)
@object.should respond_to(:some_method)
end
it "should not respond to something that the analyser doesn't respond to" do
@analyser.should_receive(:has_callable_method?).with(:some_method).and_return(false)
@object.should_not respond_to(:some_method)
end
it "should delegate the analysis to the analyser" do
@analyser.should_receive(:width).with(@object).and_return(4)
@object.width.should == 4
end
it "should cache the result so that it doesn't call it a second time" do
@analyser.should_receive(:width).with(@object).and_return(4)
@object.width.should == 4
@analyser.should_not_receive(:width)
@object.width.should == 4
end
it "should do the analysis again when it has been modified" do
@analyser.should_receive(:width).with(@object).and_return(4)
@object.width.should == 4
@object.modify_self!('hellothisisnew')
@analyser.should_receive(:width).with(@object).and_return(17)
@object.width.should == 17
@analyser.should_not_receive(:width)
@object.width.should == 17
end
end
describe "encoding" do
before(:each) do
@temp_object = @klass.new('abcde')
end
it "should encode the data and return the new temp object" do
@encoder.should_receive(:encode).with(@temp_object, :some_format, :some => 'option').and_return('ABCDE')
new_temp_object = @temp_object.encode(:some_format, :some => 'option')
new_temp_object.data.should == 'ABCDE'
end
it "should encode its own data" do
@encoder.should_receive(:encode).with(@temp_object, :some_format, :some => 'option').and_return('ABCDE')
@temp_object.encode!(:some_format, :some => 'option')
@temp_object.data.should == 'ABCDE'
end
end
end
end | true |
6c5628c655d4b99a0ecd9f026709a3bf59fc6f38 | Ruby | nyc-island-foxes-2016/apartments-live-code | /rentable.rb | UTF-8 | 235 | 2.8125 | 3 | [] | no_license | module Rentable
def rent
(self.number_of_bedrooms * 250) + (self.number_of_bathrooms * 100) + (self.square_feet * 75)
end
def book_occupant
self.rented = true
end
def evict_occupant
self.rented = false
end
end | true |
0b6083a003a90f49f8df7d6af534e40d603d88d5 | Ruby | Razultull/cpsc415 | /CrossFit/db/seeds.rb | UTF-8 | 1,444 | 2.5625 | 3 | [] | no_license | #---
# Excerpted from "Agile Web Development with Rails",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
#---
# Excerpted from "Agile Web Development with Rails, 4rd Ed.",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
#---
# encoding: utf-8
#:name, :number_of_days_per_week, :number_of_exercises, :workout_length
Workout.delete_all
Workout.create(:name => "Elliptical Burn",
:number_of_days_per_week => 7,
:number_of_exercises => 5,
:workout_length => "1 hour")
# . . .
Workout.create(:name => "Fat Burner",
:number_of_days_per_week => 5,
:number_of_exercises => 5,
:workout_length => "90 Minutes")
# . . .
Workout.create(:name => "Mega Man Abs",
:number_of_days_per_week => 3,
:number_of_exercises => 12,
:workout_length => "35 Minutes")
| true |
21dae5f8a23a4d6d8f2a97dd7c1a1e837076ed27 | Ruby | CoopTang/battleship | /test/board_test.rb | UTF-8 | 4,442 | 3.484375 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/ship'
require './lib/cell'
require './lib/board'
class BoardTest < MiniTest::Test
def setup
@cell_A1 = Cell.new("A1")
@cell_A2 = Cell.new("A2")
@cell_A3 = Cell.new("A3")
@cell_A4 = Cell.new("A4")
@cell_B1 = Cell.new("B1")
@cell_B2 = Cell.new("B2")
@cell_B3 = Cell.new("B3")
@cell_B4 = Cell.new("B4")
@cell_C1 = Cell.new("C1")
@cell_C2 = Cell.new("C2")
@cell_C3 = Cell.new("C3")
@cell_C4 = Cell.new("C4")
@cell_D1 = Cell.new("D1")
@cell_D2 = Cell.new("D2")
@cell_D3 = Cell.new("D3")
@cell_D4 = Cell.new("D4")
@cells = {
"A1" => @cell_A1,
"A2" => @cell_A2,
"A3" => @cell_A3,
"A4" => @cell_A4,
"B1" => @cell_B1,
"B2" => @cell_B2,
"B3" => @cell_B3,
"B4" => @cell_B4,
"C1" => @cell_C1,
"C2" => @cell_C2,
"C3" => @cell_C3,
"C4" => @cell_C4,
"D1" => @cell_D1,
"D2" => @cell_D2,
"D3" => @cell_D3,
"D4" => @cell_D4
}
@board = Board.new
@cruiser = Ship.new("Cruiser", 3)
@submarine = Ship.new("Submarine", 2)
end
def test_it_exists
assert_instance_of Board, @board
end
def test_it_makes_a_board
@board.cells.each do |key,value|
assert_equal true, value == @cells[key]
end
end
def test_makes_alphabetical_coordinate
assert_equal "A", @board.calculate_alphabetical_coordinate(1)
assert_equal "B", @board.calculate_alphabetical_coordinate(2)
assert_equal "C", @board.calculate_alphabetical_coordinate(3)
assert_equal "D", @board.calculate_alphabetical_coordinate(4)
assert_equal "Z", @board.calculate_alphabetical_coordinate(26)
assert_equal "AA", @board.calculate_alphabetical_coordinate(27)
assert_equal "AZ", @board.calculate_alphabetical_coordinate(52)
assert_equal "BA", @board.calculate_alphabetical_coordinate(53)
assert_equal "CC", @board.calculate_alphabetical_coordinate(81)
assert_equal "AAA", @board.calculate_alphabetical_coordinate(703)
assert_equal "AAAB", @board.calculate_alphabetical_coordinate(18280)
end
def test_it_has_cells_hash
assert_instance_of Hash, @board.cells
end
def test_valid_coordinate?
assert_equal true, @board.valid_coordinate?("A1")
assert_equal false, @board.valid_coordinate?("E1")
end
def test_valid_placement?
assert_equal true, @board.valid_placement?(@submarine, ["A1", "B1"])
assert_equal true, @board.valid_placement?(@cruiser, ["A1", "A2", "A3"])
assert_equal true, @board.valid_placement?(@submarine, ["D3", "D4"])
assert_equal true, @board.valid_placement?(@submarine, ["C3", "D3"])
@board.cells["D2"].place_ship(@submarine)
assert_equal false, @board.valid_placement?(@cruiser, ["A1", "A3", "A2"])
assert_equal false, @board.valid_placement?(@cruiser, ["A3", "A2", "A1"])
assert_equal false, @board.valid_placement?(@cruiser, ["B2", "C2", "D2"])
end
def test_place
@board.place(@cruiser,["A1", "A2", "A3"])
assert_equal @cruiser, @board.cells["A1"].ship
assert_equal @cruiser, @board.cells["A2"].ship
assert_equal @cruiser, @board.cells["A3"].ship
@board.place(@submarine,["A1", "A2"])
assert_equal @cruiser, @board.cells["A1"].ship
assert_equal @cruiser, @board.cells["A2"].ship
assert_equal @cruiser, @board.cells["A3"].ship
end
def test_render
@board.place(@cruiser, ["A1","A2","A3"])
assert_equal " 1 2 3 4 \nA . . . . \nB . . . . \nC . . . . \nD . . . . \n", @board.render
assert_equal " 1 2 3 4 \nA S S S . \nB . . . . \nC . . . . \nD . . . . \n", @board.render(true)
@board.cells["A1"].fire_upon
assert_equal " 1 2 3 4 \nA H S S . \nB . . . . \nC . . . . \nD . . . . \n", @board.render(true)
@board.cells["B2"].fire_upon
assert_equal " 1 2 3 4 \nA H S S . \nB . M . . \nC . . . . \nD . . . . \n", @board.render(true)
@board.cells["A2"].fire_upon
assert_equal " 1 2 3 4 \nA H H S . \nB . M . . \nC . . . . \nD . . . . \n", @board.render(true)
@board.cells["A3"].fire_upon
assert_equal " 1 2 3 4 \nA X X X . \nB . M . . \nC . . . . \nD . . . . \n", @board.render(true)
@board.place(@submarine, ["C2", "D2"])
assert_equal " 1 2 3 4 \nA X X X . \nB . M . . \nC . . . . \nD . . . . \n", @board.render
assert_equal " 1 2 3 4 \nA X X X . \nB . M . . \nC . S . . \nD . S . . \n", @board.render(true)
end
end
| true |
40c6c7fab10962dcd2263b1df32294bfa7ee5cdb | Ruby | dupjpr/ruby | /module.rb | UTF-8 | 543 | 3.546875 | 4 | [] | no_license | module TextAnalyzer
def num_words
@body ? @body.split.size : 0
end
def num_chars
@body ? @body.chars.size : 0
end
end
class Article
attr_reader :body
include TextAnalyzer
def initialize(body)
@body = body
end
end
class Comment
attr_reader :body
include TextAnalyzer
def initialize(body)
@body = body
end
end
a1 = Article.new("Este es el cuerpo del artículo")
puts a1.num_words
puts a1.num_chars | true |
20a10e6589395aa5f7e3c9bb1c8296707dabac02 | Ruby | rleber/bun | /lib/bun/bots/main/same_task.rb | UTF-8 | 2,421 | 2.609375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# -*- encoding: us-ascii -*-
desc "same [OPTIONS] TRAITS... FILES...", "Group files which match on a certain criterion"
option 'asis', :aliases=>'-a', :type=>'boolean', :desc=>"Do not attempt to decode files"
option 'case', :aliases=>'-c', :type=>'boolean', :desc=>"Case insensitive"
option 'format', :aliases=>'-F', :type=>'string', :desc=>"Use other formats", :default=>'text'
option 'inspect', :aliases=>'-I', :type=>'boolean', :desc=>"Just echo back the value of the traits as received"
option 'justify', :aliases=>'-j', :type=>'boolean', :desc=>"Justify the rows"
option 'min', :aliases=>'-m', :type=>'numeric', :desc=>"For counting traits: minimum count"
option 'text', :aliases=>'-x', :type=>'boolean', :desc=>"Based on the text in the file"
option 'usage', :aliases=>'-u', :type=>'boolean', :desc=>"List usage information"
option 'value', :aliases=>'-v', :type=>'string', :desc=>"Set the return code based on whether the" +
" result matches this value"
long_desc <<-EOT
Group files which match on certain criteria.
Available traits include all file fields, arbitrary Ruby expressions, and the following traits:\x5
#{String::Trait.trait_definition_table.freeze_for_thor}
If you are using more than one trait, separate the traits from the files with the --in parameter.
See the bun help show for more details on traits.
EOT
def same(*args)
# Check for separator ('--in') between traits and files
traits, files = split_arguments_at_separator('--in', *args, assumed_before: 1)
check_for_unknown_options(*traits, *files)
if options[:usage]
puts String::Trait.usage
exit
end
if options[:inspect]
puts traits
exit
end
case traits.size
when 0
stop "!First argument should be an trait expression"
when 1
trait = traits.first
else
trait = '[' + traits.join(',') + ']'
end
stop "!Must provide at least one file " unless files.size > 0
opts = options.dup # Weird behavior of options here
asis = opts.delete(:asis)
options = opts.merge(promote: !asis)
# TODO DRY this up (same logic in map_task)
# TODO Allow shard specifiers
dups = Archive.duplicates(trait, files, options)
last_key = nil
dups.keys.sort.each do |key|
puts "" if last_key
dups[key].each {|dup| puts ([key] + [dup]).flatten.join(' ')}
last_key = key
end
end
| true |
b96bd1c7c7e75c88416c6b913eba22441085262a | Ruby | trizen/sidef | /scripts/RosettaCode/factors_of_an_integers.sf | UTF-8 | 256 | 3.125 | 3 | [
"Artistic-2.0"
] | permissive | #!/usr/bin/ruby
#
## http://rosettacode.org/wiki/Factors_of_an_integer
#
func factors(n) {
gather {
{ |d|
take(d, n//d) if d.divides(n)
} << 1..n.isqrt
}.sort.uniq
}
for n [53, 64, 32766] {
say "factors(#{n}): #{factors(n)}"
}
| true |
5938cd2226761de0e93e9b871a9dd4d536575bce | Ruby | wenchonglai/leetcode-practice | /202103/20210312-986-interval-list-intersections.rb | UTF-8 | 328 | 3.140625 | 3 | [] | no_license | def interval_intersection(first_list, second_list)
arr = []
until first_list.empty? || second_list.empty?
s = [first_list[0][0], second_list[0][0]].max
e = [first_list[0][1], second_list[0][1]].min
(e == first_list[0][1] ? first_list : second_list).shift
arr << [s, e] if s <= e
end
arr
end
| true |
1854c2d08cc63af8e6914cc2534a534ee2d55551 | Ruby | manonthemat/RubyRace | /race_spec.rb | UTF-8 | 1,513 | 3.53125 | 4 | [] | no_license | require './race.rb'
describe 'puzzle 1' do
it 'should return the second to last word of a decoded base64 string' do
expect(first_puzzle('dGhhbmsgeW91IGZvciBhbGwgdGhlIGdyZWVuIGJlYW5pbmc=')).to eq('green')
expect(first_puzzle('V2VubiBtYW4ga2VpbmUgQWhudW5nIGhhdCwgZWluZmFjaCBtYWwgZGllIEZyZXNzZSBoYWx0ZW4uLi4=')).to eq('Fresse')
end
end
describe 'puzzle 2' do
it 'should zip two arrays of integers, if all elements are divisible by 5' do
expect(second_puzzle([5, 10, 15, 20], [20, 15, 10, 5])).to eq([[5, 20], [10, 15], [15, 10], [20, 5]])
end
it 'should return a string' do
expect(second_puzzle([1, 2, 3, 4, 5], [50, 30, 20, 25, 5])).to eq("You don't have 5 on it!")
end
end
describe 'puzzle 3' do
it 'should return the sum of the addition of the first 1000 prime numbers' do
expect(third_puzzle(1000, '+')).to eq(3682913)
end
it 'should return the product of the multiplication of the first 23 prime numbers' do
expect(third_puzzle(23, '*')).to eq(267064515689275851355624017992790)
end
end
describe 'puzzle 4' do
it 'should add a $ in front of each element of an array of numbers' do
expect(fourth_puzzle([1, 5, 6.87, 234.32])).to eq(["$1", "$5", "$6.87", "$234.32"])
end
end
describe 'puzzle 5' do
it 'should add 2 to a number' do
expect(fifth_puzzle(5)).to eq(7)
end
it 'should handle all exceptions classy' do
expect(fifth_puzzle('so long and thanks for all the fish')).to eq("I don't always catch exceptions, but when I do: 42")
end
end
| true |
210f988a6d1c6d09f3ffb1483002bb6b4c0cb34a | Ruby | AngusGMorrison/data-structures | /ruby/linked_lists/doubly-linked-list/doubly_linked_list.rb | UTF-8 | 2,434 | 3.6875 | 4 | [] | no_license | require_relative './node'
require_relative './doubly_linked_list_errors'
class DoublyLinkedList
include DoublyLinkedListErrors
attr_reader :head, :tail, :length
def initialize
@head = nil
@tail = nil
@length = 0
end
def insert(data)
# O(1)
node = Node.new(data)
if @head
node.prev = @tail
@tail.next = node
else
@head = node
end
@tail = node
@length += 1
node
end
def delete(node)
# Ordinarily an O(1) operation, but the need to verify that the node is part
# of the list makes it an O(n) operation
raise NodeNotFound unless find { |existing_node| existing_node == node }
node == @head ? delete_head : delete_from_body(node)
@length -= 1
rescue NodeNotFound => message
puts message
end
private def delete_head
if @head.next
@head = @head.next
else
@head = @tail = nil
end
end
private def delete_from_body(node)
preceding_node = node.prev
next_node = node.next
preceding_node.next = next_node
next_node.prev = preceding_node if next_node
end
def concat(list)
# O(1)
unless list.is_a?(DoublyLinkedList)
raise ArgumentError.new("Expected a linked list, received #{list.class.name}")
end
@tail.next = list.head
list.head.prev = @tail
@tail = list.tail
@length += list.length
end
def clear
# O(n)
while @length > 0
delete(head)
end
end
def find(&predicate)
# O(n)
current = @head
while current
return current if yield(current)
current = current.next
end
end
def find_last(&predicate)
# O(n)
current = @tail
while current
return current if yield(current)
current = current.prev
end
end
def each(&block)
# O(n)
current = @head
while current
yield(current)
current = current.next
end
self
end
def reverse_each(&block)
# O(n)
current = @tail
while current
yield(current)
current = current.prev
end
self
end
def to_a
# O(n)
array = []
each { |node| array << node.data }
array
end
def map(reverse: false, &block)
# O(n)
mapped = DoublyLinkedList.new
mapper = Proc.new do |node|
value = block_given? ? yield(node.data) : node.data
mapped.insert(value)
end
reverse ? reverse_each(&mapper) : each(&mapper)
mapped
end
end
| true |
0ab0cd1fc267f448c87348656092113e99ce3079 | Ruby | dexterfgo/bcap_bake_my_day | /lib/bake_my_day.rb | UTF-8 | 912 | 3.375 | 3 | [
"MIT"
] | permissive | require_relative "bake_my_day/version"
require_relative "bake_my_day/item"
require_relative "bake_my_day/order"
require_relative "bake_my_day/menu"
require_relative "bake_my_day/tracer"
require_relative "bake_my_day/input"
module BakeMyDay
Tracer.create(!ARGV.empty?)
Tracer.info "Bake My Day v" + BakeMyDay::VERSION + " Populating Menu... \n"
# Display menu at least once
Menu.instance.setup
Menu.instance.display_menu
# maybe move this down?
order = Order.new
# Endlessly request for input unless an exit is requested
loop do
begin
Tracer.prompt "\n[Quantity]<space>[Item Code] >> "
terminal = STDIN.gets
rescue Interrupt
terminal = "exit"
break
end
# If exit is typed, end simulation.
break if terminal =~ /^\s*exit\s+/
# Not "exit"? Parse input.
input = Input.new(terminal.strip.upcase)
order.add_item_to_order(input)
end
Tracer.info "\nEnd Simulation."
end
| true |
8c7888fa31b3c333a6e29c6272e2bbdba028a8ec | Ruby | zwaarty/project_euler | /ruby/problem_065.rb | UTF-8 | 389 | 3.34375 | 3 | [] | no_license |
def e_fraction nth
seq = [2]
n = 2
k = 1
loop do
break if n > nth
seq << 1
n += 1
break if n > nth
seq << 2 * k
n += 1
k += 1
break if n > nth
seq << 1
n += 1
end
den = seq.reverse
t = den.shift.to_r
until den.empty?
t = den.shift.to_r + 1 / t
end
t
end
p e_fraction(100).numerator.to_s.chars.collect(&:to_i).inject(:+)
| true |
027fc64e9bc01db9852381e77185b9a76b2a56c3 | Ruby | parterburn/dabble.me | /app/helpers/application_helper.rb | UTF-8 | 1,288 | 2.609375 | 3 | [
"MIT"
] | permissive | module ApplicationHelper
def title(page_title)
content_for(:title) { page_title.to_s }
end
def yield_or_default(section, default = '')
content_for?(section) ? content_for(section) : default
end
def tag_relative_date(tag_date, entry_date)
return "Today" if tag_date == entry_date
a = []
a << distance_of_time_in_words(tag_date, entry_date)
if tag_date > entry_date
a << "from"
else
a << "since"
end
# a << tag_date.strftime('%b %-d, %Y')
a << "entry"
a.join(" ")
end
def distance_of_time_in_words(earlier_date, later_date)
Jekyll::Timeago.timeago(earlier_date, later_date, depth: 2, threshold: 0.05).gsub(" ago", "").gsub("in ", "").gsub("tomorrow", "1 day")
end
def format_number(number)
return number unless number.present?
number = trim(number) if number.is_a?(String)
rounded_number = number.to_i > 100 ? number.round(0) : number.round(2)
number_with_delimiter(rounded_number, delimiter: ",")
end
def elapsed_days_in_year(year)
today = Date.today
if today.year == year.to_i
start_of_year = Date.new(year.to_i, 1, 1)
elapsed_days = (today - start_of_year).to_i
return elapsed_days
else
return Date.leap?(year.to_i) ? 366 : 365
end
end
end
| true |
daf2bbc754cb4bcfecfd93708194a4686e1e4670 | Ruby | markshawtoronto/Cracking_the_Coding_Interview | /ruby/app/services/miscellaneous/palindrome.rb | UTF-8 | 337 | 3.90625 | 4 | [] | no_license | # Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".
module Miscellaneous
module Palindrome
def self.first_palindrome(words)
words.each do |w|
if w == w.reverse
return w
end
end
""
end
end
end | true |
e88b401a110d05b3fed133ba69bf291ac1f42270 | Ruby | karaebrahim/jfisch | /app/helpers/survivor_entries_helper.rb | UTF-8 | 20,241 | 2.796875 | 3 | [] | no_license | module SurvivorEntriesHelper
# Displays the currently selected entries for the specified game_type, as well as allows the user
# to update the number of selected entries, if the season has not yet begun.
def entries_selector(game_type, type_to_entry_map, span_size, before_season)
entries_html = "<div class='span" + span_size.to_s + " survivorspan center'>
<h4>" + link_to(SurvivorEntry.game_type_title(game_type),
"/" + game_type.to_s,
class: 'btn-link-black') + "</h4>"
# Show existing entries
current_entries = type_to_entry_map[game_type]
if !current_entries.nil?
entries_html << "<div class='row-fluid'>"
span_size = get_span_size(current_entries.size, SurvivorEntry::MAX_ENTRIES_MAP[game_type])
offset_size = get_offset_size(current_entries.size, span_size)
entry_count = 0
current_entries.each do |current_entry|
entry_count += 1
entries_html << "<div class='survivorspan span" + span_size.to_s
if (offset_size > 0)
entries_html << " offset" + offset_size.to_s
offset_size = 0
end
entries_html << "'><h5>" +
link_to(SurvivorEntry.game_type_abbreviation(game_type) + " #" +
current_entry.entry_number.to_s,
"/survivor_entries/" + current_entry.id.to_s,
class: 'btn-link-black') +
"</h5>"
# TODO Allow user to change picks in bulk
entries_html << "</div>"
end
entries_html << "</div>"
else
entry_count = 0
end
# If season has not begun, allow user to update count of entries
if before_season
entries_html << "<p><strong>Entry count:</strong>
<select name='game_" + game_type.to_s + "' class='input-mini'>"
0.upto(SurvivorEntry::MAX_ENTRIES_MAP[game_type]) { |num_games|
entries_html << " <option value=" + num_games.to_s
if num_games == entry_count
entries_html << " selected"
end
entries_html << ">" + num_games.to_s + "</option>"
}
entries_html << " </select>
</p>"
end
entries_html << "</div>"
return entries_html.html_safe
end
# displays the buttons at the bottom of the my_entries page
def entries_buttons(before_season)
buttons_html = "<p class='center'>"
if before_season
buttons_html << "<button class='btn btn-primary' name='save'>Update Entry Counts</button>
  "
end
# TODO add button to update bets in bulk
buttons_html << "<button class='btn' name='cancel'>Cancel</button></p>"
return buttons_html.html_safe
end
# Displays all bets for all entries for a specific game type
def entries_bet_display(game_type, type_to_entry_map, entry_to_bets_map, span_size)
entries_html = "<div class='span" + span_size.to_s + " center survivorspan'>
<h4>" + link_to(SurvivorEntry.game_type_title(game_type),
"/" + game_type.to_s,
class: 'btn-link-black') +
"</h4>"
# Show all bets, separated by entries
current_entries = type_to_entry_map[game_type]
if !current_entries.nil?
entries_html << "<div class='row-fluid'>"
span_size = get_span_size(current_entries.size, SurvivorEntry::MAX_ENTRIES_MAP[game_type])
offset_size = get_offset_size(current_entries.size, span_size)
entry_count = 0
current_entries.each do |current_entry|
entry_count += 1
entries_html << "<div class='survivorspan span" + span_size.to_s
if (offset_size > 0)
entries_html << " offset" + offset_size.to_s
offset_size = 0
end
if !current_entry.is_alive
entries_html << " dead"
end
entries_html << "'><h5>" +
link_to(SurvivorEntry.game_type_abbreviation(game_type) + " #" +
current_entry.entry_number.to_s,
"/survivor_entries/" + current_entry.id.to_s,
class: 'btn-link-black') +
"</h5>"
# Show all bets for the entry
entries_html <<
"<table class='" + ApplicationHelper::TABLE_STRIPED_CLASS + " table-dashboard'>
<thead><tr>
<th>Week</th>
<th>Team</th>
</tr></thead>"
has_knockout_bet = current_entry.is_alive
if entry_to_bets_map.has_key?(current_entry.id)
entry_to_bets_map[current_entry.id].each { |bet|
entries_html << "<tr"
if !bet.is_correct.nil? &&
(current_entry.is_alive || bet.week <= current_entry.knockout_week)
entries_html << " class='" + (bet.is_correct ? "green-row" : "red-row") + "'"
elsif !current_entry.is_alive
entries_html << " class='dead-row'"
end
entries_html << ">
<td>" + bet.nfl_game.week.to_s + "</td>
<td"
if !bet.is_correct.nil?
entries_html << " title='" + bet.game_result + "'"
end
entries_html << ">" + bet.nfl_team.abbreviation + "</td>
</tr>"
if !has_knockout_bet && bet.week == current_entry.knockout_week
has_knockout_bet = true
end
}
end
if !has_knockout_bet
entries_html << "<tr class='red-row'>
<td>" + current_entry.knockout_week.to_s + "</td>
<td>--</td>
</tr>"
end
entries_html << "</table></div>"
end
entries_html << "</div>"
else
entry_count = 0
end
entries_html << "</div>"
return entries_html.html_safe
end
# returns the size of the span elements based on the number of existing entries and the max number
# allowed
def get_span_size(num_entries, max_entries)
if max_entries == 2
return 6
elsif max_entries == 4
return (num_entries < 4) ? 4 : 3
end
end
# returns the size of the initial offset number of existing entries and the span size
def get_offset_size(num_entries, span_size)
if span_size == 3
return 0
elsif span_size == 4
return (num_entries == 1) ? 4 : ((num_entries == 2) ? 2 : 0)
elsif span_size == 6
return (num_entries == 1) ? 3 : 0
end
end
# returns the number of entries allowed to be created for the specified survivor entry game type
def entries_remaining(game_type, type_to_entry_map)
num_entries = type_to_entry_map.has_key?(game_type) ? type_to_entry_map[game_type].length : 0
return SurvivorEntry::MAX_ENTRIES_MAP[game_type] - num_entries
end
# shows the table of the specified array of bets, allowing the user to change only those which
# haven't been locked yet.
def entry_bets_table(survivor_entry, selector_to_bet_map, week_team_to_game_map, nfl_teams_map,
week_to_start_time_map)
entry_html = "<table class='" + ApplicationHelper::TABLE_STRIPED_CLASS + "'>
<thead><tr>
<th>Week</th>
<th>Selected Team</th>
<th>Opponent</th>
<th>Result</th>
</tr></thead>"
game_type = survivor_entry.get_game_type
1.upto(SurvivorEntry::MAX_WEEKS_MAP[game_type]) { |week|
1.upto(SurvivorEntry.bets_in_week(game_type, week)) { |bet_number|
entry_html << "<tr"
existing_bet = selector_to_bet_map[SurvivorBet.bet_selector(week, bet_number)]
if !existing_bet.nil?
if !existing_bet.is_correct.nil? &&
(survivor_entry.is_alive || existing_bet.week <= survivor_entry.knockout_week)
entry_html << " class='" + (existing_bet.is_correct ? "green-row" : "red-row") + "'"
elsif !survivor_entry.is_alive
entry_html << " class='dead-row'"
end
elsif !survivor_entry.is_alive
if survivor_entry.knockout_week == week
entry_html << " class='red-row dead-row'"
else
entry_html << " class='dead-row'"
end
end
entry_html << ">
<td>" + week.to_s + "</td>"
# if pick is locked for this week [game has already started or week start time has already
# passed], show as read-only
pick_locked = false
if (DateTime.now > week_to_start_time_map[week]) ||
(!existing_bet.nil? && (DateTime.now > existing_bet.nfl_game.start_time))
pick_locked = true
end
# If bet exists & game is complete, show result; otherwise, show dropdown with available
# teams
if !existing_bet.nil? &&
(!existing_bet.is_correct.nil? || !survivor_entry.is_alive || pick_locked)
entry_html << "<td>" + existing_bet.nfl_team.full_name + "</td>"
elsif !survivor_entry.is_alive || pick_locked
if !survivor_entry.is_alive && survivor_entry.knockout_week == week
entry_html << "<td>--</td>"
else
entry_html << "<td></td>"
end
else
entry_html << get_team_select(week, bet_number, existing_bet, nfl_teams_map,
week_team_to_game_map, selector_to_bet_map)
end
# If bet already exists, show opponent
entry_html << "<td>"
if !existing_bet.nil?
game = week_team_to_game_map[NflSchedule.game_selector(week, existing_bet.nfl_team_id)]
if !game.nil?
opponent_team_id = game.opponent_team_id(existing_bet.nfl_team_id)
opponent_team = nfl_teams_map[opponent_team_id]
entry_html << game.matchup_string(opponent_team)
end
end
entry_html << "</td>
<td>"
# If bet already exists and game is complete, show result
if !existing_bet.nil? && !existing_bet.is_correct.nil?
entry_html << existing_bet.game_result
end
entry_html << "</td>
</tr>"
}
}
entry_html << "</table>"
return entry_html.html_safe
end
# returns the select tag with all of the available nfl teams to select from, marking the team
# from the specified existing bet as selected, if it exists
def get_team_select(week, bet_number, existing_bet, nfl_teams_map, week_team_to_game_map,
selector_to_bet_map)
select_html = "<td class='tdselect'>
<select name='" + SurvivorBet.bet_selector(week, bet_number) + "'>
<option value=0></option>"
selected_team_ids = selector_to_bet_map.values.map { |bet| bet.nfl_team_id }
nfl_teams_map.values.each { |nfl_team|
# Only allow team to be selected if it has a game during that week, which hasn't yet started,
# and it has not already been selected in a different week.
team_game = week_team_to_game_map[NflSchedule.game_selector(week, nfl_team.id)]
if !team_game.nil? && DateTime.now < team_game.start_time
is_selected_team = !existing_bet.nil? && (existing_bet.nfl_team_id == nfl_team.id)
if is_selected_team || !selected_team_ids.include?(nfl_team.id)
select_html << "<option "
# show bet is selected if bet already exists
if is_selected_team
select_html << "selected "
end
# dropdown shows name of NFL team
select_html << "value=" + nfl_team.id.to_s + ">" + nfl_team.full_name + "</option>"
end
end
}
select_html << "</select></td>"
return select_html
end
# displays the update picks buttons if the specified entry is still alive
def display_update_picks_buttons(survivor_entry)
button_html = ""
if survivor_entry.is_alive
button_html <<
"<p class='center'>
<button class='btn btn-primary' name='save'>Update Picks</button>
<button class='btn' name='cancel'>Cancel</button>
</p>"
end
return button_html.html_safe
end
# shows the table of all bets for all users, for the specified game type
def all_bets_table(game_type, entries_by_type, entry_to_bets_map, logged_in_user, current_week,
game_week)
bets_html = "<h4>Entry Breakdown</h4>
<table class='" + ApplicationHelper::TABLE_CLASS + "'>
<thead>
<tr>
<th rowspan='2'>Entry</th>"
max_week = [current_week, game_week].max
if max_week > 0
bets_html << "<th colspan='" + SurvivorEntry::MAX_BETS_MAP[game_type].to_s + "'>Weeks</th>"
end
bets_html << "</tr>
<tr>"
# Show bets for all weeks up to the current week.
1.upto(max_week) { |week|
bets_html << "<th colspan='" + SurvivorEntry.bets_in_week(game_type, week).to_s + "'>" +
week.to_s + "</th>"
}
bets_html << "</tr>
</thead>"
entries_by_type.each { |entry|
bets_html << "<tr class='"
# highlight logged-in user's entries
if entry.user_id == logged_in_user.id
bets_html << "my-row"
end
bets_html << "'>
<td class='rightborderme "
# if entry is dead, cross out entry name
if !entry.is_alive
bets_html << "dead-cell red-cell"
end
bets_html << "'>"
if entry.user_id == logged_in_user.id
bets_html << link_to((entry.user.full_name + " " + entry.entry_number.to_s),
"/survivor_entries/" + entry.id.to_s)
else
bets_html << entry.user.full_name + " " + entry.entry_number.to_s
end
bets_html << "</td>"
bets = entry_to_bets_map[entry.id]
1.upto(max_week) { |week|
1.upto(SurvivorEntry.bets_in_week(game_type, week)) { |bet_number|
# Show selected team, marking correct/incorrect, if game is complete.
bets_html << "<td"
if !bets.nil?
bet = bets[SurvivorBet.bet_selector(week, bet_number)]
if !bet.nil?
if entry.is_alive || week <= entry.knockout_week
if !bet.is_correct.nil?
bets_html << " class='" + (bet.is_correct ? "green-cell" : "red-cell").to_s + "'
title='" + bet.game_result + "'"
end
bets_html << ">"
# only show bet if it's marked as correct/incorrect or the game has already started
if !bet.is_correct.nil? || DateTime.now > bet.nfl_game.start_time
bets_html << bet.nfl_team.abbreviation
end
else
bets_html << ">"
end
elsif entry.knockout_week == week
# no bets were made during week & entry was knocked out
bets_html << " class='red-cell'>--"
else
bets_html << ">"
end
elsif entry.knockout_week == week
# no bets were made, but entry was knocked out in week 1
bets_html << " class='red-cell'>--"
else
bets_html << ">"
end
bets_html << "</td>"
}
}
bets_html << "</tr>"
}
bets_html << "</table>"
return bets_html.html_safe
end
# returns a table of stats for the specified game_type, including the total alive, eliminated
# and remaining entries in each week.
def entry_stats_table(game_type, week_to_entry_stats_map, current_week)
stats_html = "<h4>Entry Stats</h4>
<table class='" + ApplicationHelper::TABLE_CLASS + "'>
<thead>
<tr>
<th rowspan=2>Stat</th>"
if current_week > 0
stats_html << "<th colspan='" + SurvivorEntry::MAX_BETS_MAP[game_type].to_s + "'>Weeks</th>"
end
stats_html << "</tr><tr>"
1.upto(current_week) { |week|
stats_html << "<th>" + week.to_s + "</th>"
}
stats_html << "</thead>"
stats_html << "<tr><td class='rightborderme'>Total Entries</td>"
1.upto(current_week) { |week|
stats_html << "<td>" + week_to_entry_stats_map[week]["alive"].to_s + "</td>"
}
stats_html << "</tr>
<tr><td class='rightborderme'>Eliminated Entries</td>"
1.upto(current_week) { |week|
stats_html << "<td>" + week_to_entry_stats_map[week]["elim"].to_s + "</td>"
}
stats_html << "</tr>
<tr><td class='rightborderme'>Remaining Entries</td>"
1.upto(current_week) { |week|
stats_html << "<td>" + (week_to_entry_stats_map[week]["alive"] -
week_to_entry_stats_map[week]["elim"]).to_s + "</td>"
}
stats_html << "</tr></table>"
return stats_html.html_safe
end
# displays the all entries table, including number of entries for all the specified users
def all_entries_table(users, user_to_entries_count_map)
all_entries_html = "<table class='" + ApplicationHelper::TABLE_CLASS + "'>
<thead><tr>
<th rowspan=2>User</th>
<th colspan=2>Survivor</th>
<th colspan=2>Anti-Survivor</th>
<th colspan=2>High-Roller</th>
</tr>
<tr>
<th>Total</th><th>Alive</th>
<th>Total</th><th>Alive</th>
<th>Total</th><th>Alive</th>
</tr></thead>"
# number of (total & alive) entries per user
users.each { |user|
all_entries_html << "<tr><td>" + user.full_name + "</td>"
if user_to_entries_count_map.has_key?(user.id)
[:survivor, :anti_survivor, :high_roller].each { |game_type|
0.upto(1) { |idx|
all_entries_html << "<td"
all_entries_html << " class='leftborderme'" if idx == 0
all_entries_html << ">" + user_to_entries_count_map[user.id][game_type][idx].to_s +
"</td>"
}
}
else
0.upto(5) { |idx|
all_entries_html << "<td"
all_entries_html << " class='leftborderme'" if idx.even?
all_entries_html << ">0</td>"
}
end
all_entries_html << "</tr>"
}
# total entries for all users
all_entries_html << "<tr class='bold-row'><td class='topborderme'>Totals</td>"
[:survivor, :anti_survivor, :high_roller].each { |game_type|
0.upto(1) { |idx|
all_entries_html << "<td class='topborderme"
all_entries_html << " leftborderme" if idx.even?
all_entries_html << "'>" + user_to_entries_count_map[0][game_type][idx].to_s + "</td>"
}
}
all_entries_html << "</tr></table>"
return all_entries_html.html_safe
end
# returns a table of the specified entries, indicating username, game type & whether the entry is
# alive
def kill_entries_table(entries_without_bets)
kill_html = "<table class='" + ApplicationHelper::TABLE_CLASS + "'>
<thead><tr>
<th>Entry</th>
<th>Game Type</th>
<th>Status</th>
</tr></thead>"
entries_without_bets.each { |entry|
kill_html << "<tr>
<td>" + entry.user.full_name + " " + entry.entry_number.to_s + "</td>
<td>" + entry.type_title + "</td>
<td>" + (entry.is_alive ? "Alive" : "Dead") + "</td>
</tr>"
}
kill_html << "</table>"
return kill_html.html_safe
end
end
| true |
7137aaa44fbff00d1799e34d9fafc4ecbf5c28c5 | Ruby | benj2240/euler | /Ruby/euler034_tests.rb | UTF-8 | 199 | 2.515625 | 3 | [] | no_license | require_relative "euler034.rb"
require "test/unit"
class Euler034Tests < Test::Unit::TestCase
def test_actual
expected = 40730
result = euler034
assert_equal expected, result
end
end | true |
fa93475df6eff4e29681d251de1f5a09df1a0dac | Ruby | roryokane/cs283-final-project | /lib/converting.rb | UTF-8 | 2,132 | 3.09375 | 3 | [
"MIT"
] | permissive | def convert_bc_to_c(better_c)
dumb_implementation(better_c)
end
def test_implementation(better_c)
better_c.chomp.reverse
end
def dumb_implementation(better_c)
lines = better_c.split("\n", -1)
# negative second parameter indicates to keep trailing blank lines
# add parens around conditionals
original_lines = lines.dup
original_lines.each_with_index do |line, index|
paren_keywords = ["if", "while", "for"]
paren_keywords.each do |keyword|
if line.match(/\s*#{keyword}/)
lines[index] = lines[index].sub("#{keyword} ", keyword + " (")
lines[index] += ")"
end
end
end
# add {} from indents
# only works with tab indents right now
prev_indent_level = 0
original_lines = lines.dup
original_lines.each_with_index do |line, index|
this_indent_level = (line.match(/\t*/)[0]).size
if this_indent_level > prev_indent_level
indent_increase = this_indent_level - prev_indent_level
# in actual programs, indent should never double-increase,
# but handling it seems better than ignoring it
indent_increase.times do
lines[index - 1] = lines[index - 1] + " {"
end
elsif this_indent_level < prev_indent_level
closing_brace_lines = []
(prev_indent_level - 1).step(this_indent_level, -1).each do |closing_indent_level|
indents = "\t" * closing_indent_level
closing_brace_lines.push(indents + "}")
end
lines = lines.insert(index, *closing_brace_lines)
end
prev_indent_level = this_indent_level
end
# add semicolons
lines = lines.map do |line|
line_needs_semicolon = true
starting_cancels = ['#']
ending_cancels = %w[{ } ; , + - \\]
regex_cancels = [/^\s*$/, /^\s*\/\//]
cancels_and_test_methods = {
starting_cancels => :start_with?,
ending_cancels => :end_with?,
regex_cancels => :match,
}
cancels_and_test_methods.each do |cancels, test_method|
cancels.each do |cancel|
if line.send(test_method, cancel)
line_needs_semicolon = false
end
end
end
if line_needs_semicolon
line + ";"
else
line
end
end
return lines.join("\n")
end
def parsing_implementation(better_c)
# not written yet
end
| true |
213f4be1e16ba5ec8846b87095416f203fd4fe66 | Ruby | OndrejKucera/university-assignments | /dpo/dpo1/lib/world.rb | UTF-8 | 1,757 | 2.796875 | 3 | [] | no_license | require_relative 'build_world'
class World
attr_accessor :variables_environment, :hash_rooms
def initialize(model)
@model = model
@hash_rooms = {} # ({'jeskyne' => Room.new('Jeskyně'), 'vychod_jeskyne' => Room.new()})
@variables_environment = {} # ({'presvedcil_jsem_jiz_kneze_aby_mi_otevrel_branu' => false})
end
def build_all
@build_world = Build_world.new(@model)
room1 = @build_world.build_room("Predsin")
room2 = @build_world.build_room("Kuchyn")
room3 = @build_world.build_room("Obyvaci_pokoj")
room4 = @build_world.build_room("Pracovna")
zapalovac = @build_world.build_item_in_room(room1, "zapalovac")
door_1_2 = @build_world.build_door_in_room(room1, room2) #Hash['able_pass_door' => true])
door_1_3 = @build_world.build_door_in_room(room1, room3)
trouba = @build_world.build_item_in_room(room2, "Trouba")
kucharka = @build_world.build_person_in_room(room2, "kucharka", "Utika plyn!!!")
door_2_1 = @build_world.build_door_in_room(room2, room1)
door_2_3 = @build_world.build_door_in_room(room2, room3)
klic = @build_world.build_item_in_room(room3, "klic")
@build_world.build_condition(klic, 'able_use', room3)
door_3_1 = @build_world.build_door_in_room(room3, room1)
door_3_2 = @build_world.build_door_in_room(room3, room2)
door_3_4 = @build_world.build_door_in_room(room3, room4)
@build_world.build_condition(door_3_4, 'able_pass_door', klic)
hasici_pris = @build_world.build_item_in_room(room4, "hasici pristroj")
door_4_3 = @build_world.build_door_in_room(room4, room3)
@hash_rooms["Predsin"] = room1
@hash_rooms["Kuchyn"] = room2
@hash_rooms["Pokoj"] = room3
@hash_rooms["Pracovna"] = room4
end
end | true |
fd886de49691b6e079379ddd2d9b5d665aa39a59 | Ruby | 12ew/alphabetize-in-esperanto-dumbo-web-042318 | /lib/alphabetize.rb | UTF-8 | 354 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def alphabetize(arr)
alphabet = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz".chars # makes arr of characters
# binding.pry
arr.sort_by do |sentence| #iterate over arr of sentences
sentence.chars.map do |character| alphabet.index(character) # iterate over
# each sentence and index ever letter
# binding.pry
end
end
end
| true |
2f0015aa8e1461ef10687468088f0a2b2f03158c | Ruby | elvamuyi/black_jack | /src/Game.rb | UTF-8 | 6,549 | 3.828125 | 4 | [] | no_license | # /src/Game.rb
# This file defines the class for a blackjack game.
# Usage example:
# my_game = Game.new
# mygame.get_bet
# mygame.round
require File.dirname(__FILE__) + "/" + "Dealer.rb"
require File.dirname(__FILE__) + "/" + "Player.rb"
class Game
# Initializing a game.
def initialize
puts "Welcome to Yining's BlackJack Game!"
puts "\nHow many players are at the table (integer)?"
@num_player = gets.chomp.to_i
until @num_player > 0
puts "Invalid input. Please enter again:"
@num_player = gets.chomp.to_i
end
puts "How many decks do you want to use (integer 4 ~ 8)?"
@num_decks = gets.chomp.to_i
until @num_decks >= 4 && @num_decks <= 8
puts "Invalid input. Please enter again:"
@num_decks = gets.chomp.to_i
end
puts "\n------"
puts "Game starting...\n"
# Initializing some objects needed in game.
@mydecks = Decks.new(@num_decks)
@myaction = Action.new
@mydealer = Dealer.new(@mydecks)
@myplayers = []
@num_player.times do |i|
@myplayers << Player.new(i+1)
end
puts @myplayers
end
# Getting bets for a round from existing players
def get_bet
@myplayers.each do |one_player|
helper_hand = Hand.new # Helper hand used in Player.add_bet(bet, hand)
puts "\n------"
puts "Player " + one_player.get_number.to_s + \
": Please enter your bet (integer 1 ~ " + one_player.get_money.to_s + ")."
bet = gets.chomp.to_i
until one_player.add_bet(bet, helper_hand)
puts "Invalid input. Please enter again:"
bet = gets.chomp.to_i
end
end
end
# Input: player, hand, bet
# When a player enters an action, his hands and bets change upon the action.
def play(player, hand, bet)
# A flag implying if the player should keep playing with the current hand.
keep_playing = !hand.is_21
while keep_playing
puts "Please choose:\n 1(hit) 2(stand) 3(double down) 4(split)"
choice = gets.chomp
until ["1","2","3","4"].include?(choice)
puts "Invalid input. Please enter again:"
choice = gets.chomp
end
# Different actions.
case choice
# Hit
when "1"
if @myaction.hit(hand, @mydecks)
puts "Your cards are: " + hand.to_s
keep_playing = !hand.is_bust && !hand.is_21
end
# Stand
when "2"
if @myaction.stand
puts "Your cards are: " + hand.to_s
keep_playing = false
end
# double_down
when "3"
if !player.double_bet(player.get_hand_index(hand))
puts "Money not enough for double_down."
puts "Your cards are: " + hand.to_s
keep_playing = true
elsif !@myaction.double_down(hand, @mydecks)
puts "Your cards are: " + hand.to_s
keep_playing = true
else
puts "Your cards are: " + hand.to_s
keep_playing = false
end
# split
when "4"
newhands = @myaction.split(hand, @mydecks)
if newhands != hand && player.add_bet(bet,newhands[1])
hand.hand_change(newhands[0])
newhands.each do |newhand|
puts "\nYour cards are: " + newhand.to_s
play(player, newhand, bet)
end
keep_playing = false
elsif newhands == hand
puts "Your cards are: " + hand.to_s
keep_playing = true
else
puts "Money not enough for splitting."
puts "Your cards are: " + hand.to_s
keep_playing = true
end
end # end of case choice
end # end of while keep_playing
end # end of def play
# Returns the ratio of bet that a player should win back.
def win_back(player_hand, dealer_hand)
if player_hand.is_bust
return 0
elsif player_hand.is_blackjack
return 1 if dealer_hand.is_blackjack
return 2.5
else
return 2 if dealer_hand.is_bust ||
(player_hand.hand_score.max > dealer_hand.hand_score.max)
return 0 if dealer_hand.is_blackjack ||
(player_hand.hand_score.max < dealer_hand.hand_score.max)
return 1
end
end
# A round of game.
def round
puts "\n------"
puts "Dealing cards..."
puts "Dealer's cards: *, " + @mydealer.initial_status.to_s
# Dealing 2 cards for each current player.
@myplayers.each do |one_player|
2.times do
@myaction.hit(one_player.get_hand(0), @mydecks)
end
puts "\n------"
puts one_player.to_s
puts "Your cards are: " + one_player.get_hand(0).to_s
play(one_player, one_player.get_hand(0), one_player.get_bet(0))
end
puts "\n------"
puts "\nEnd of Playing. Here are results:"
puts "Dealer's hand: " + @mydealer.final_status.to_s
index_list = [] # Array of index of the player that should quit the game.
delete_list = [] # Array of player that should quit the game.
# Output the results for each player.
@myplayers.each_with_index do |one_player, i|
puts "\n--- Player " + one_player.get_number.to_s + " ---"
puts "Your hand(s) are: \n"
# Output the results for each hand of the player.
one_player.get_hands.each_with_index do |one_hand, j|
puts one_hand.to_s
# Calculate the money that a player should win back and update the money
money_back = win_back(one_hand, @mydealer.final_status) * one_player.get_bet(j)
if one_player.add_money(money_back)
puts "Money getting back: " + money_back.to_s
end
end
puts one_player.to_s
# Check if a player should quit the game and update the index array.
if one_player.get_money <= 0
index_list << i
puts "You don't have enough money to continue. Bye!"
else
one_player.restart
end
end
puts "\n------"
puts "Round ends."
@mydecks.renew_decks
@mydealer = Dealer.new(@mydecks)
# Delete players with no money from current players
index_list.each {|i| delete_list << @myplayers[i]}
@myplayers = @myplayers - delete_list
end
# Returns current players
def get_players
return @myplayers
end
end | true |
bd4512564bd6cb1f508a964393bbf19960353573 | Ruby | joeainsworth/programming_exercises | /Tealeaf Academy - Ruby Exercises Workbook/Advanced/exercise_1.rb | UTF-8 | 191 | 3.484375 | 3 | [] | no_license | # What do you expect to happen when the greeting variable is referenced in the
# last line of the code below?
# A. greeting will return nil
if false
greeting = "hello world"
end
greeting
| true |
0ccad3567fe71d519405696510728ef4379230da | Ruby | educhin/square_array-online-web-sp-000 | /square_array.rb | UTF-8 | 85 | 3.21875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
arr = []
array.each{|num| arr.push(num * num)}
arr
end
| true |
b627d4e2fafd343633aa3a1480dd78051a94b785 | Ruby | doantuancanh/ruby-exercises | /basic/pt_bac1.rb | UTF-8 | 252 | 3.59375 | 4 | [] | no_license | def nhap(ten)
puts "Nhap #{ten}"
a = gets.chomp.to_i
a
end
def pt_bac1(a, b)
if a == 0
puts "Phuong trinh vo so nghiem"
else
x = -b.to_f / a
puts "Phuong trinh co nghiem la: #{x}"
end
end
a = nhap('a')
b = nhap('b')
pt_bac1(a, b) | true |
23bfb466bb8ef11cfdb5026231800ec5cbdccb65 | Ruby | helena-bond/sequelize-1 | /lib/sequelize/migrator/naming.rb | UTF-8 | 2,850 | 2.75 | 3 | [
"MIT"
] | permissive | require 'sequel/model/inflections'
module Sequelize
class Migrator
class Naming
include Sequel::Inflections
ACTION_REGEXP = /^(create|add|drop|remove|rename|change)_(.*)/.freeze
TABLE_DIV_REGEXP = /_(to|from|in)_/.freeze
COLUMN_DIV_REGEXP = /_and_/.freeze
VIEW_REGEXP = /(.*)_view$/.freeze
INDEX_REGEXP = /(.*)_index$/.freeze
##
# Returns: {String} table name
#
attr_reader :table_name
##
# Returns: {String} new table name
#
attr_reader :table_rename
##
# Returns: {Set} column names list
#
attr_reader :columns
##
# Returns: {Hash} hash of column renames
#
attr_reader :column_changes
##
# Returns: {Set} index names list
#
attr_reader :indexes
def use_change?
end
def table_action
end
def column_action
end
def index_action
end
private
def initialize(name)
@rest = underscore(name)
@name = @rest.freeze
@renames = {}
tokenize
end
def tokenize
get_action
get_table
get_columns
if @action == 'rename'
set_column_renames
set_table_renames
end
end
##
# Private: Extract action name from name
#
def get_action
match = ACTION_REGEXP.match(@name)
@rest = match[2]
@action = match[1]
end
##
# Private: Extract table name and detect
# if table is view
#
def get_table
parts = @rest.split(TABLE_DIV_REGEXP)
@table_name = parts.pop
if match = VIEW_REGEXP.match(table_name)
@view = true
@table_name = match[1]
end
parts.pop
@rest = parts.join('_')
end
##
# Private: Extract column and index names
#
def get_columns
columns = @rest.split(COLUMN_DIV_REGEXP)
@columns = Set.new
@indexes = Set.new
columns.each do |col|
if match = INDEX_REGEXP.match(col)
@indexes << match[1]
else
@columns << col
end
end
end
##
# Private: Create hash where key is old column name
# and values is new column name
#
def set_column_renames
@renames = @columns.each_with_object({}) do |column, renames|
if column.include?('_to_')
cols = column.split('_to_')
renames[cols.first] = cols.last
end
end
@columns = @renames.keys.to_set
end
##
# Private: Set table new name
#
def set_table_renames
@table_name, @table_rename = @rest, @table_name if @renames.empty?
end
end
end
end
| true |
6ec7e605a9e91fe5bfe52c90719ad20b5898ca15 | Ruby | hammackj/dissector | /lib/dissector/hex_window.rb | UTF-8 | 9,673 | 3.109375 | 3 | [] | no_license | # require 'colour_chooser'
# require 'field'
# require 'hex'
# require 'structure'
# require 'ncurses'
class HexWindow
attr_reader :window
def initialize(y, x, data, display_only)
@hex = Hex.new(data)
@y = y
@x = x
@data = data
@display_only = display_only
@current_type = 0
@current_endian = 0
@key_callbacks = {}
@fields = {}
@y_offset = @display_only ? 1 : 3
@x_offset = 1 # For the border
@rows = Ncurses.stdscr.getmaxy - y # @hex.lines + (@display_only ? 4 : 10)
@cols = 80 - x
@window = Ncurses.newwin(@rows, @cols, y, x)
Ncurses.keypad(@window, true)
end
def add_key_callback(key, callback)
@key_callbacks[key] = callback
end
def draw()
@window.move(0, 0)
# Do the title
@window.printw("\n") # The border
if(!@display_only)
@window.printw(" Press <backspace> or <escape> to go back\n\n")
end
# Print the hex
@hex.get_str.split("\n").each do |line|
@window.printw(' ' + line.gsub('%', '%%') + "\n")
end
@window.printw("\n")
if(!@display_only)
# @window.clrtobot()
# # Print the type and endianness values
# @window.printw(" Type: ")
# @window.attron(Ncurses::A_BOLD)
# @window.printw("%s " % Field::TYPE_NAMES[@current_type])
# @window.attroff(Ncurses::A_BOLD)
# @window.printw("(tab/home/end to change)\n")
#
# @window.printw(" Endian: ")
# @window.attron(Ncurses::A_BOLD)
# @window.printw("%s " % Field::ENDIAN_NAMES[@current_endian])
# @window.attroff(Ncurses::A_BOLD)
# @window.printw("(pgup/pgdown to change)\n")
# @window.printw("\n")
#
# # Get the value
# value = Field.get_preview_value(@data, @current_type, Field::ENDIANS[@current_endian], @hex.pos)
# #@window.printw("\n");
# if(value.nil?)
# @window.printw(" Value: %s\n" % '<invalid value>');
# else
# @window.printw(" Value: %s\n" % Field.value_to_string(value, Field::TYPES[@current_type]).gsub('%', '%%'));
# end
# If we're sitting on a defined field, display the information
field = get_current_field()
if(!field.nil?)
@window.printw(" Selected field:\n")
@window.printw(" Name: %s\n" % field[:name])
@window.printw(" Pos: %s\n" % field[:position])
@window.printw(" Size: %s\n" % field[:size]) # TODO: Make this a 'pretty' string representation
else
@window.printw(" Selected field:\n")
@window.printw(" n/a\n")
@window.printw("\n")
@window.printw("\n")
end
end
# Print all the fields we know of (TODO: get a proper value somehow)
@window.printw("\n")
@window.printw(" Fields:\n")
@fields.each_pair do |name, field|
@window.printw(" %s => pos: %s, size: %s\n" % [name, field[:position], field[:size]])
end
# Remove any highlighting
0.upto(@data.size) do |i|
hex_y, hex_x = Hex.get_hex_coordinates(i)
ascii_y, ascii_x = Hex.get_ascii_coordinates(i)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_OK, nil)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset + 1, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_OK, nil)
@window.mvchgat(ascii_y + @y_offset, ascii_x + @x_offset, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_OK, nil)
end
# Mark all defined fields (this should happen before highlighting)
@fields.each() do |name, field|
field[:position].upto(field[:position] + field[:size] - 1) do |i|
hex_y, hex_x = Hex.get_hex_coordinates(i)
ascii_y, ascii_x = Hex.get_ascii_coordinates(i)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset, 1, Ncurses::A_NORMAL, field[:colour], nil)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset + 1, 1, Ncurses::A_NORMAL, field[:colour], nil)
@window.mvchgat(ascii_y + @y_offset, ascii_x + @x_offset, 1, Ncurses::A_NORMAL, field[:colour], nil)
end
end
# Find any overlapping sections and mark them as errors
overlaps = get_overlapping_indexes()
overlaps.each do |i|
hex_y, hex_x = Hex.get_hex_coordinates(i)
ascii_y, ascii_x = Hex.get_ascii_coordinates(i)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_ERROR, nil)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset + 1, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_ERROR, nil)
@window.mvchgat(ascii_y + @y_offset, ascii_x + @x_offset, 1, Ncurses::A_NORMAL, ColourChooser::COLOUR_ERROR, nil)
end
if(!@display_only)
field = get_current_field()
highlight_start = 0
highlight_length = 0
if(field) # Highlight the full field
highlight_start = field[:position]
highlight_length = field[:size]
colour = field[:colour] || ColourChooser::COLOUR_OK
else # Only highlight the current position
highlight_start = @hex.pos
highlight_length = 1
colour = ColourChooser::COLOUR_OK
end
highlight_start.upto(highlight_start + highlight_length - 1) do |i|
if(i < @data.size)
hex_y, hex_x = Hex.get_hex_coordinates(i)
ascii_y, ascii_x = Hex.get_ascii_coordinates(i)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset, 1, Ncurses::A_REVERSE, colour, nil)
@window.mvchgat(hex_y + @y_offset, hex_x + @x_offset + 1, 1, Ncurses::A_REVERSE, colour, nil)
@window.mvchgat(ascii_y + @y_offset, ascii_x + @x_offset, 1, Ncurses::A_REVERSE, colour, nil)
end
end
end
# This adds the border
Ncurses.box(@window, 0, 0)
@window.refresh
end
# Add a field to the hex window so it can be highlighted. This will have
# no actual information about the field, and should be considered 'dumb'.
def add_field(name, position, size, colour)
@fields[name] = { :name => name, :position => position, :size => size, :colour => colour }
end
def clear_fields()
@fields = {}
end
def get_field_at(pos)
@fields.each_value() do |field|
if(pos >= field[:position] && pos < field[:position] + field[:size])
return field
end
end
return nil
end
def get_current_field()
return get_field_at(@hex.pos)
end
def get_previous_field()
return get_field_at(@hex.old_pos)
end
# Return a list of all indexes in data that have two or more fields
def get_overlapping_indexes()
indexes = {}
@fields.each_pair do |name, field|
field[:position].upto(field[:position] + field[:size] - 1) do |i|
indexes[i] = (indexes[i].nil?) ? 1 : (indexes[i] + 1)
end
end
overlaps = []
indexes.each_pair() do |i, v|
if(v > 1)
overlaps << i
end
end
return overlaps
end
def get_input
if(@display_only)
throw :you_cant_call_that
end
loop do
Ncurses.curs_set(0)
draw()
ch = @window.getch
case ch
when Ncurses::KEY_LEFT
begin
@hex.go_left
new_field = get_current_field()
old_field = get_previous_field()
end while((new_field == old_field && !new_field.nil? && !old_field.nil?) && @hex.old_pos != @hex.pos)
when Ncurses::KEY_RIGHT
begin
@hex.go_right
new_field = get_current_field()
old_field = get_previous_field()
end while((new_field == old_field && !new_field.nil? && !old_field.nil?) && @hex.old_pos != @hex.pos)
when Ncurses::KEY_UP
@hex.go_up
when Ncurses::KEY_DOWN
@hex.go_down
when Ncurses::KEY_NPAGE
@current_endian = (@current_endian - 1) % Field::ENDIANS.length
when Ncurses::KEY_PPAGE
@current_endian = (@current_endian + 1) % Field::ENDIANS.length
when Ncurses::KEY_HOME
@current_type = (@current_type - 1) % Field::TYPES.length
when Ncurses::KEY_END, Ncurses::KEY_TAB, ?\t
@current_type = (@current_type + 1) % Field::TYPES.length
when Ncurses::KEY_BACKSPACE, Ncurses::KEY_ESCAPE
return nil
when ?d, ?D
field = @structure.get_field_at(@data, @hex.pos)
if(!field.nil?)
children = @structure.get_children(field)
if(children.size == 0)
@structure.delete_field(@structure.get_field_at(@data, @hex.pos))
else
MessageBox.new("Can't delete #{field.name}; the following fields depend on it:\n#{children.join("\n")}", "Error!").go()
end
end
when ?e, ?E
@structure.choose_edit_field(@data)
when ?r, ?R
field = @structure.get_field_at(@data, @hex.pos)
if(field.nil?)
Ncurses.beep
else
old_name = String.new(field.name)
new_name = Textbox.new(field.name).prompt("Please enter the name --> ")
if(!new_name.nil?)
@structure.rename_field(old_name, new_name)
end
end
when Ncurses::KEY_ENTER, ?\r, ?\n
if(Field.too_long(@data, @hex.pos, Field.estimate_field_size(@data, @current_type, @hex.pos)))
Ncurses.beep
else
return [@hex.pos, @current_type, @current_endian]
end
else
if(@key_callbacks.nil? || @key_callbacks[ch].nil?)
Ncurses.beep
else
@key_callbacks[ch].call()
end
end # switch
end
end
def closeWindow
@window.delwin();
end
end
| true |
b7ebd332f1b612c01ab77e8227eb7ee60ee24705 | Ruby | coinbase/geoengineer | /lib/geoengineer/utils/has_lifecycle.rb | UTF-8 | 1,710 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | ########################################################################
# HasLifecycle provides methods to enable lifecycle hooks
########################################################################
module HasLifecycle
def self.included(base)
base.extend(ClassMethods)
end
# ClassMethods
module ClassMethods
def _init_validation_hash
{
after: {},
before: {}
}
end
def lifecycle_actions(stage, step)
all = []
# inherit lifecycle_actions
sclazz = self.superclass
all.concat(sclazz.lifecycle_actions(stage, step)) if sclazz.respond_to?(:lifecycle_actions)
# Add this lifecycle actions
la_exists = @_actions && @_actions[stage] && @_actions[stage][step]
all.concat(@_actions[stage][step]) if la_exists
all
end
# Currently only supporting after(:initialize)
def after(lifecycle_step, method_name_or_proc)
@_actions = _init_validation_hash unless @_actions
@_actions[:after][lifecycle_step] = [] unless @_actions[:after][lifecycle_step]
@_actions[:after][lifecycle_step] << method_name_or_proc
end
def before(lifecycle_step, method_name_or_proc)
@_actions = _init_validation_hash unless @_actions
@_actions[:before][lifecycle_step] = [] unless @_actions[:before][lifecycle_step]
@_actions[:before][lifecycle_step] << method_name_or_proc
end
end
# This method will return a list of errors if not valid, or nil
def execute_lifecycle(stage, step)
self.class.lifecycle_actions(stage, step).each do |actions|
if actions.is_a? Proc
self.instance_exec(&actions)
else
self.send(actions)
end
end
end
end
| true |
0526b7693879ca03c2a0467d137a6f2e5b177c2f | Ruby | Anis4300/mini_jeu_POO_anis | /lib/player.rb | UTF-8 | 1,846 | 3.71875 | 4 | [] | no_license | class Player
attr_accessor :name, :life_points #read & write
def initialize(name)
@name = name
@life_points = 10
end
def show_state
puts "#{@name} a #{life_points} points de vie." #Etat des PV des joueurs
end
def gets_damage (damages)
@life_points = @life_points - damages #dommages subis
if @life_points < 1
puts "#{@name} is DEAD !"
end
end
def attacks (player)
puts "#{@name} attaque #{player.name}"
strengh = compute_damage
puts "Il lui inflige #{strengh} points de dommages"
player.gets_damage(strengh)
end
def compute_damage
return rand(1..6)
end
end
class HumanPlayer < Player
attr_accessor :weapon_level
def initialize (name)
super(name)
@life_points = 100
@weapon_level = 1
end
def show_state
puts "#{name} a #{@life_points} points de vie et une arme de niveau #{@weapon_level}."
end
def compute_damage
rand(1..6) * @weapon_level
end
def search_weapon
new_weapon_level = rand(1..6)
puts "Tu as trouvé une nouvelle arme de niveau #{new_weapon_level} !"
if new_weapon_level > @weapon_level
@weapon_level = new_weapon_level
puts "L'arme trouvée est meilleure que l'arme actuelle, tu la prends !!"
else
@weapon_level = @weapon_level
puts "C'est de la merde, tu garde ton arme actuelle !"
end
end
def search_health_pack
health_pack = rand(1..6)
if health_pack == 1
puts "Tu n'as rien trouvé, sorry !"
elsif health_pack >= 2 and health_pack <= 5
puts "Bravo tu as trouvé un pack de +50 HP !"
if @life_points > 49
@life_points = 100
else
@life_points = @life_points + 50
end
else puts "Waouuu, tu as trouvé un pack de +80 HP !!!"
if @life_points > 19
@life_points = 100
else
@life_points = @life_points + 80
end
end
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.