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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
fe09584a9b704fc4eba877c28b8492077371961b
|
Ruby
|
ensallee/green_grocer-nyc-web-042318
|
/grocer.rb
|
UTF-8
| 1,608
| 3.359375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
def consolidate_cart(cart)
new_hash={}
cart.each do |list|
list.each do |item, qualities|
if new_hash[item]
qualities[:count] += 1
else
qualities[:count] = 1
new_hash[item] = qualities
end
end
end
new_hash
end
def apply_coupons(cart, coupons)
new_cart = {}
cart.each do |item, qualities|
new_cart[item] = qualities
coupons.each do |deal|
if new_cart[item][:count] >= deal[:num]
deal.each do |key, value|
if value == item
new_cart["#{item} W/COUPON"] ||= {}
new_cart["#{item} W/COUPON"][:price] ||= deal[:cost]
new_cart["#{item} W/COUPON"][:clearance] ||= cart[item][:clearance]
if new_cart["#{item} W/COUPON"][:count]
new_cart["#{item} W/COUPON"][:count] += 1
else
new_cart["#{item} W/COUPON"][:count] = 1
end
new_cart[item][:count]=new_cart[item][:count] - deal[:num]
end
end
end
end
end
new_cart
end
def apply_clearance(cart)
cart.each do |item, qualities|
if(qualities[:clearance])
qualities[:price]=qualities[:price]*0.80
qualities[:price]=qualities[:price].round(2)
end
end
cart
end
def checkout(cart, coupons)
new_cart = consolidate_cart(cart)
new_cart_coupons=apply_coupons(new_cart, coupons)
coupons_and_clearance=apply_clearance(new_cart_coupons)
total=0
coupons_and_clearance.each do |item, qualities|
total += qualities[:price] * qualities[:count]
end
if total > 100
total= total*0.90
end
total
end
| true
|
fcd37199b53932cff489fdfba48af38e9fd0019d
|
Ruby
|
tanphan313/leet_works
|
/problems/hash_table/top_k_frequent_words.rb
|
UTF-8
| 1,074
| 3.921875
| 4
|
[] |
no_license
|
<<-Doc
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their
lexicographical order.
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Dùng hash thì dễ implement nhưng chạy chậm => Dùng heap tree
HASH TABLE
Doc
# @param {String[]} words
# @param {Integer} k
# @return {String[]}
def top_k_frequent(words, k)
# reverse để sort words theo alphabet
# words.each_with_object(Hash.new(0)) {|w, hash| hash[w] -= 1 }.map(&:reverse).sort.first(k).map(&:last)
h = Hash.new 0
words.each { |w| h[w] += 1 }
# sort theo -value để lấy số lần xuất hiện lớn nhất, sau đó sort theo key để theo alphabet
h.sort_by { |key, value| [-value, key] }[0..k-1].map(&:first)
end
p top_k_frequent %w[i love leetcode i love coding], 3
| true
|
4bd4c6d411b979ba2b68cc5a8801edb3de4b4292
|
Ruby
|
scmwalsh/learn_ruby
|
/02_calculator/calculator.rb
|
UTF-8
| 130
| 3.15625
| 3
|
[] |
no_license
|
def add( a, b)
a + b
end
def subtract(a, b)
a - b
end
def sum ( a )
sum = 0
a.each { |number| sum += number }
sum
end
| true
|
aa1d8c145fdee089fc7be5ef61cf93a2695d4604
|
Ruby
|
tinomen/metric_fu
|
/lib/metric_fu/flog_reporter/page.rb
|
UTF-8
| 805
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
module MetricFu::FlogReporter
class Page
attr_accessor :score, :scanned_methods
def initialize(score, scanned_methods = [])
@score = score.to_f
@scanned_methods = scanned_methods
end
def to_html
output = "<html><head><style>"
output << Base.load_css
output << "</style></head><body>"
output << "Score: #{score}\n"
scanned_methods.each do |sm|
output << sm.to_html
end
output << "</body></html>"
output
end
def average_score
sum = 0
scanned_methods.each do |m|
sum += m.score
end
sum / scanned_methods.length
end
def highest_score
scanned_methods.inject(0) do |highest, m|
m.score > highest ? m.score : highest
end
end
end
end
| true
|
fd9540e28156edc5e208631ed4c25463d501c13d
|
Ruby
|
Vicky099/two_factor_application
|
/lib/json_web_token.rb
|
UTF-8
| 317
| 2.609375
| 3
|
[] |
no_license
|
class JsonWebToken
SECRET_KEY = Rails.application.secrets.secret_key_base.to_s
def self.encode(payload, exp = 24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, SECRET_KEY)
end
def self.decode(token)
decoded = JWT.decode(token, SECRET_KEY)[0]
HashWithIndifferentAccess.new decoded
end
end
| true
|
cb6fa3a91f85381ea4974843e138d7117ae9b702
|
Ruby
|
davis-campbell/ruby
|
/con4/spec/connect_four_spec.rb
|
UTF-8
| 4,206
| 3.515625
| 4
|
[] |
no_license
|
require_relative '../connect_four'
describe Game do
before :all do
@game = Game.new
end
describe '#new' do
it 'generates a Board' do
expect(@game.board).to be_an_instance_of Game::Board
end
it 'gives Player 1 the first turn' do
expect(@game.player1.is_turn).to be true
expect(@game.player2.is_turn).to be false
end
end
describe '#gg?' do
let (:gameover) { game = Game.new
game.board.each { |column| column.each { |space| space.mark('Dave') } }
return game
}
let (:davewins) { game = Game.new
4.times do
game.player1.claim(1)
end
return game
}
it 'returns false when there are empty spaces and there is no winner' do
expect(@game.gg?).to be false
end
it 'returns true when all spaces are filled' do
expect(gameover.gg?).to be true
end
before { @newgame = davewins}
it 'returns player object when a player has a winning combination' do
expect(@newgame.gg?).to eq(@newgame.player1)
end
end
describe '#active_player' do
it 'recognizes whose turn it is' do
expect(@game.active_player).to eq(@game.player1)
end
end
describe Game::Player do
describe '#claim' do
before :all do
@game.player1.claim(1)
end
it 'lets player mark a valid space' do
expect(@game.board[0][0].marked).to eq(@game.player1)
end
it "includes that space in an array of the player's spaces" do
expect(@game.player1.spaces).to eq([@game.board[0][0]])
end
before { @game.board[0].each { |space| space.mark(@game.player1) } }
it 'claim a space in a full column' do
expect{ @game.player1.claim(1) }.to raise_exception(RuntimeError)
end
it 'raises an exception if the player chooses a non-existent column' do
expect{ @game.player1.claim(0) }.to raise_exception(RangeError)
end
end
end
describe Game::Board do
it 'inherits from Array' do
expect(Game::Board.superclass).to eq(Array)
end
before :all do
@board = Game::Board.new
end
describe '#new' do
it 'creates a new Board object' do
expect(@board).to be_an_instance_of Game::Board
end
it 'makes an array with 7 arrays of 6 instances of Space' do
expect(@board[0]).to be_an_instance_of Array
expect(@board[6]).to be_an_instance_of Array
expect(@board[0][0]).to be_an_instance_of Game::Space
expect(@board[6][5]).to be_an_instance_of Game::Space
end
end
describe '#display' do
it 'prints the board to the screen' do
end
end
end
describe Game::Space do
before :all do
@space = Game::Space.new
end
before :all do
@board = Game::Board.new
@board[0][0].mark('Dave')
end
describe '#new' do
it 'creates a new Space' do
expect(@space).to be_an_instance_of Game::Space
end
it 'creates unmarked Space objects' do
expect(@space).not_to be_marked
end
end
describe '#mark' do
before :each do
@space.mark('Dave')
end
it 'marks a Space' do
expect(@space).to be_marked
end
it 'claims Space for player' do
expect(@space.marked).to eq('Dave')
end
end
describe '#below' do
it 'returns the Space beneath it on the Board' do
expect(@board[0][1].below).to eq(@board[0][0])
end
it 'returns nil when there is no Space beneath it' do
expect(@board[0][0].below).to be_nil
end
end
describe '#valid?' do
it 'returns true when the space is unmarked and has no unmarked spaces beneath it' do
expect(@board[0][1]).to be_valid
expect(@board[1][0]).to be_valid
end
it 'returns false when the space is marked' do
expect(@board[0][0]).not_to be_valid
end
it 'returns false when there is an unmarked space below it' do
expect(@board[0][5]).not_to be_valid
end
end
end
end
| true
|
384c72cde445e7512c70b637f9450b612358b09c
|
Ruby
|
fect11/ttt-7-valid-move-ruby-intro-000
|
/lib/valid_move.rb
|
UTF-8
| 329
| 3.375
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# code your #valid_move? method here
def valid_move?(board, index)
board[index] == "" || board[index] == " "
# user_input = gets.strip
# input = user_input.to_i.
# index = input - 1
# index.between?(1,9)
end
def position_taken?(board, index)
!(board[index].nil? || board[index] == " "|| board[index] == "")
end
| true
|
9b5d4dff796ac2821ffbac114f21eb8211fe5f0a
|
Ruby
|
HeyNeek/phase-3-running-ruby-code
|
/app.rb
|
UTF-8
| 333
| 3.546875
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#puts "Hello World"
#print "Hello World"
#print "Hello World"
#print "Hello World"
#p [1, 2, 3]
#pp [{ id: 1, hello: "World" }, { id: 2, hello: "Ruby" }, { id: 3, hello: "Moon" }, { id: 4, hello: "Learner" }]
#different ways to print out different types of data in Ruby
puts "Hello World!"
print "Pass this test, please."
p [1,2,3]
| true
|
332c5376c18ecd0359bee7d035851bf6a3deff95
|
Ruby
|
AlexandrePerdomo/rails-longest-word-game
|
/app/controllers/game_controller.rb
|
UTF-8
| 1,236
| 2.96875
| 3
|
[] |
no_license
|
class GameController < ApplicationController
def game
@length = params[:length] ? params[:length].to_i : 8
@grid = generate_grid(@length)
@start_time = Time.now
session["start"] = @start_time
session["grid"] = @grid
end
def score
@grid = session["grid"]
@start_time = Time.parse(session["start"])
@attempt = params[:attempt]
@end_time = Time.now
@results = run_game(@attempt, @grid, @start_time, @end_time)
end
private
def generate_grid(grid_size)
alphabet = "a b c d e f g h i j k l m n o p q r s t u v w x y z"
array_alphabet = alphabet.upcase.split
grid = []
grid_size.times do
grid << array_alphabet.sample
end
return grid
end
def run_game(attempt, grid, start_time, end_time)
array = []
attempt.each_char { |x| array << x.upcase }
y = array.all? { |letter| array.count(letter) <= grid.count(letter) }
# y = array.sort <=> grid.sort[0...array.length]
h = { time: end_time - start_time, translation: "", score: 0, message: "not in the grid" } if y == false
h = { time: end_time - start_time, translation: "", score: attempt.length / (end_time - start_time), message: "well done" } if y == true
return h
end
end
| true
|
d2ce393762c675c923e984fc9aec18a245303f95
|
Ruby
|
dmytro/ATTIC
|
/aws_deploy/lib/awsdeploy/cli/store.rb
|
UTF-8
| 1,115
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
module AWSDeploy
class CLI
include Mixlib::CLI
option :reset,
:description => "Forget instance, remove data about specific instance from local memory",
:short => "-r BRANCH", :long => "--reset BRANCH", :exit => 0 ,
:on => :head,
:proc => Proc.new { |br|
AWSDeploy::Marshal.new.forget(br)
}
option :forget,
:description => "Forget all data about deployed instances from local memory",
:short => "-f", :long => "--forget", :exit => 0 ,
:on => :head,
:proc => Proc.new {
AWSDeploy::Marshal.new.forget
}
option :list, :description => "List instances in store",
:short => '-l', :long => '--list', :exit => 0,
:on => :head,
:proc => Proc.new {
data = AWSDeploy::Marshal.new.data.keys
if data.empty?
print "No instances found"
else
pp data
end
}
option :show, :description => "Show data for an instance in store",
:short => '-s BRANCH', :long => '--show BRANCH', :exit => 0,
:on => :head,
:proc => Proc.new { |br|
pp AWSDeploy::Marshal.new.data[br]
}
end
end
| true
|
7ada145aad9e9e1cc7ff2048bf1d7079666b3a6e
|
Ruby
|
conbu/conbu-api-server
|
/location/tokyo_rubykaigi11.rb
|
UTF-8
| 270
| 2.78125
| 3
|
[] |
no_license
|
@location = {}
@location[:floor_2] = [
:"2-1",
:"2-2",
:"2-3",
:"2-4",
:"2-5",
:"2-6",
:"2-7",
]
@location[:floor_5] = [
:"5-1",
:"5-2",
:"5-3",
]
@location[:all] = @location[:floor_2] + @location[:floor_5]
@location[:all] = @location[:all].sort
| true
|
c928284204f668170b042bbadfd3c1ec56c35010
|
Ruby
|
seanliu93/ttt-with-ai-project-v-000
|
/lib/players/computer.rb
|
UTF-8
| 2,345
| 3.875
| 4
|
[] |
no_license
|
require 'pry'
class Computer < Player
WIN_COMBINATIONS = [
[0,1,2], # top row
[3,4,5], # middle row
[6,7,8], # bottom row
[0,3,6], # left column
[1,4,7], # mid column
[2,5,8], # right column
[0,4,8], # diag 1
[6,4,2] # diag 2
]
def move(board)
WIN_COMBINATIONS.each do |combo|
count = 0
enemycount = 0
combo.each do |pos|
if board.cells[pos] == token
count += 1
# if i have 2 in a row, win the game
if count == 2
if board.cells[combo[2]] == " "
return makeMove(combo[2])
elsif board.cells[combo[2]] == self.token
if board.cells[combo[1]] == " "
return makeMove(combo[1])
end
end
end
end
end
end
WIN_COMBINATIONS.each do|combo|
count = 0
enemycount = 0
combo.each do |pos|
if board.cells[pos] == other_token
enemycount += 1
# if enemy has 2 in a row, block his win
if enemycount == 2
if board.cells[combo[2]] == " "
return makeMove(combo[2])
elsif board.cells[combo[2]] == other_token
if board.cells[combo[1]] == " "
return makeMove(combo[1])
end
end
end
end
end
end
if openCorner(board) != nil
# prioritize corners
makeMove(openCorner(board))
elsif board.cells[4] == " "
# place in middle if not taken
makeMove(4)
else
# place wherever
makeMove(wherever(board))
end
end
def makeMove(index)
(index+1).to_s
end
def openCorner(board)
# prioritize opposite corner if enemy placed in middle
# if board.cells[4] == other_token
# if board.cells[0] == token
# return 8
# elsif board.cells[2] == token
# return 6
# elsif board.cells[6] == token
# return 2
# elsif board.cells[8] == token
# return 0
# end
# end
if board.cells[0] == " "
0
elsif board.cells[2] == " "
2
elsif board.cells[6] == " "
6
elsif board.cells[8] == " "
8
else
nil
end
end
def wherever(board)
for i in 0..8
if board.cells[i] == " "
return i
end
end
end
end
| true
|
3e13e630fdfc4bb666b5c2756f0d3a643406e19b
|
Ruby
|
codetriage-readme-bot/carver
|
/lib/carver/presenter.rb
|
UTF-8
| 1,302
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Carver
class Presenter
BYTES_TO_MB_CONSTANT = 1024**2
def initialize(results, path, action, parent)
@results = results
@path = path
@action = action
@parent = parent
end
def log
Rails.logger.info(
"[Carver] source=#{entry_info[:name]} type=#{entry_info[:type]} total_allocated_memsize=#{allocated_memory} " \
"total_retained_memsize=#{retained_memory}"
)
end
def add_to_results
Carver.add_to_results(
entry_info[:name],
{ total_allocated_memsize: allocated_memory, total_retained_memsize: retained_memory }.freeze
)
end
private
def allocated_memory
(@results.total_allocated_memsize.to_f / BYTES_TO_MB_CONSTANT).round(5)
end
def retained_memory
(@results.total_retained_memsize.to_f / BYTES_TO_MB_CONSTANT).round(5)
end
def controller?
@parent.downcase.include?('controller')
end
def entry_info
@entry ||= entry
end
def entry
if controller?
{ name: "#{@path.split('/').map(&:titleize).join('::').delete(' ')}Controller##{@action}", type: 'controller' }.freeze
else
{ name: "#{@path}##{@action}", type: 'job' }.freeze
end
end
end
end
| true
|
c5ab97c13d0c44957a7ecba0baa00ad378a37edd
|
Ruby
|
somethinrother/bitmaker_lessons
|
/ruby_fundamentals2/ruby_fundamentals2_e5.rb
|
UTF-8
| 152
| 3.546875
| 4
|
[] |
no_license
|
def greet_backwards
puts "What is your name?"
user_name = gets.chomp.reverse
puts "Hello, #{user_name}! Welcome home."
end
puts greet_backwards
| true
|
9a8e3e61979328f904af99142f4f96b0d5927ff9
|
Ruby
|
Kevintudiep/solar_system
|
/galaxy.rb
|
UTF-8
| 286
| 3.265625
| 3
|
[] |
no_license
|
class System
def initialize
@bodies = []
end
def bodies
@bodies
end
def add(body)
@bodies << body
end
def total_mass
return @bodies.sum
end
end
# milky = System.new
# puts milky.bodies
# puts '---'
#
#
#
# milky.add('jupiter')
# puts milky.inspect
| true
|
e0501b2b6dd9cd37314a0dcd8a4d4570e5ba7afa
|
Ruby
|
grumoz/Chris-Pine-Learn-to-Program-Ruby
|
/5.6/better_favorite_number.rb
|
UTF-8
| 104
| 3.5625
| 4
|
[] |
no_license
|
puts "Your favorite number:"
num = gets.chomp.to_i + 1
puts num.to_s + " is a bigger and better number"
| true
|
17acf7fa5db577560f767404ae742ba23f433007
|
Ruby
|
mainangethe/learn-to-code-w-ruby-bp
|
/old_sections/parallel_variable_assignment.rb
|
UTF-8
| 322
| 4.34375
| 4
|
[] |
no_license
|
# parallel variable assignment - variables are assigned at the same line
a = 10
b = 20
c = 30
#shorter syntax (just use ',' to concatenate multiple prints)
print a, b, c
#multiple assignment (same thing, use ",")
a, b, c = 10, 20, 30
puts
puts a, b,c
#swapping variables
a, b = 1,2
puts a,b
a,b = b,a
print a,b
| true
|
5e73d1db1dff244dc24516b499d1dd30d5f6d348
|
Ruby
|
itggot-markus-moen/Popen-Generator
|
/v.1/you_are.rb
|
UTF-8
| 1,501
| 3.53125
| 4
|
[] |
no_license
|
require_relative "alignment.rb"
require_relative "attributes.rb"
require_relative "background.rb"
require_relative "class.rb"
require_relative "equipment.rb"
require_relative "race.rb"
require_relative "sex.rb"
require_relative "spells.rb"
def you_are()#alignment, attributes, background, class, equipment, race, sex, spells)
race = races()
clasarr = classes()
clas = clasarr[1]
subclas = clasarr[0]
classnum = clasarr[2]
back = background()
if subclas != "GOD OF SOME MOTHA FUCKING DRAGONS!!!"
subclasclas = subclas + " " + clas
else subclasclas = subclas
end
#$character = alignments(race), sex(), race, subclasclas, back, "\n", attributes($racenum, $subracenum), equipment(clasarr, back), "\n", spell_select(classnum)
$character = "\n" + alignments(race) + "\n" + sex() + "\n" + race + "\n" + subclas + " " + clas +
"\n" + back + "\n" + "\n" + attributes($racenum, $subracenum).to_s + "\n" + equipment(clasarr, back).to_s + "\n" "\n" + spell_select(classnum).to_s
return $character
end
puts you_are
puts "\nDo you want to save this character (yes or no)?"
save_yn = gets.chomp #save_yn står för "save: yes or no"
def save(save_yn)
if save_yn == "yes"
if Dir.exists?("characters") != true
Dir.mkdir "characters"
end
Dir.chdir("characters")
puts "Name your new character"
name = gets.chomp
File.write("#{name}.txt", $character)
end
end
puts save(save_yn)
| true
|
c7758f03bacc9aa7ec52bae8f85bdb447f29c3be
|
Ruby
|
BCoulange/evadesWebSite
|
/lib/mailing_importer.rb
|
UTF-8
| 252
| 2.671875
| 3
|
[] |
no_license
|
# encoding: utf-8
class MailingImporter
require 'csv'
# Import des adresses CSV
def self.importemails(csv_text)
emails = []
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
emails << row[14]
end
return emails
end
end
| true
|
d7a586ffcb81cf8e83bb0936956321ae88e4dc0b
|
Ruby
|
awenkoff/MFA
|
/MFA_part2.rb
|
UTF-8
| 699
| 3.453125
| 3
|
[] |
no_license
|
require 'json'
puts "What is your email?"
email = gets.chomp
f = File.new("./randomemails.txt","r")
json_data = f.read
f.close
ruby_data = JSON.parse(json_data)
record = ruby_data[email]
if record == nil
puts "Email cant be found"
else
puts "What is your Password?"
password = gets.chomp
require 'digest/md5'
hashed_password = Digest::MD5.hexdigest(password)
if record["password"] == hashed_password
array_record = record.to_a
array_record.shift
question = array_record.sample[0]
puts "What is your " + question + "?"
answer = gets.chomp
if answer == record[question]
puts "Correct!"
else
puts "Wrong Answer"
exit
end
end
end
| true
|
d7c902dddf4bc6d8c8b4391d3bda1dd402bf7370
|
Ruby
|
pombreda/measure-everything
|
/code/demo.rb
|
UTF-8
| 545
| 2.671875
| 3
|
[] |
no_license
|
require 'statsd'
$statsd = Statsd.new('82.196.8.168')
def authentication(status = :success, count = 1)
key = "events.password.#{status}"
puts "sending #{count} x #{key} to statsd"
$statsd.count key, count
end
def random_authentication(status = :success, factor = 5)
count = 1000
while count > 0
rand_count = (rand * factor).to_i
count -= rand_count
authentication(status, rand_count)
sleep rand
end
end
def measure_authentication
$statsd.time('authentication') do
authentication
end
end
binding.pry
| true
|
00617357089b6c2abf933eedeaf3f9c9a52e5d55
|
Ruby
|
JoriPeterson/sweater_weather
|
/app/services/unsplash_service.rb
|
UTF-8
| 477
| 2.59375
| 3
|
[] |
no_license
|
class UnsplashService
def initialize(location)
@location = location
end
def get_background
get_json("/search/photos?")
end
private
def conn
Faraday.new('https://api.unsplash.com') do |f|
f.params['client_id'] = ENV["UNSPLASH_API_KEY"]
f.params['query'] = "#{@location}"
f.adapter Faraday.default_adapter
end
end
def get_json(url)
response = conn.get(url)
JSON.parse(response.body, symbolize_names: true)
end
end
| true
|
ceb22a4ddaf5e8796b8717338ebda35519b52e78
|
Ruby
|
FunabashiKousuke/EnjoyRuby
|
/第6章/for.rb
|
UTF-8
| 184
| 3.734375
| 4
|
[] |
no_license
|
sum = 0
for i in 1..5 do
sum = sum + i
end
puts sum
# 出力結果: 15
# for文構文:
# for 変数 開始時の数値..終了時の数値 do
# 繰り返したい処理
# end
| true
|
e6c4532be1831c85e3c0ed755d00b38b121fe629
|
Ruby
|
Redvanisation/tic-tac-toe-ruby
|
/bin/main.rb
|
UTF-8
| 924
| 3.734375
| 4
|
[] |
no_license
|
require_relative '../lib/game'
require_relative '../lib/player'
require_relative '../lib/board'
puts
puts
puts "Welcome to Tictactoe game "
puts
puts "The following is a table showing the slots numbers"
puts
puts " ******************* "
puts " 1 2 3 "
puts " 4 5 6 "
puts " 7 8 9 "
puts " ******************* "
puts
player_1_name = ""
player_2_name = ""
while player_1_name.empty?
print "Please enter the name of first player(1) : "
player_1_name = gets.chomp
player_1 = Player.new(player_1_name, 'X')
end
while player_2_name.empty?
print "Please enter the name of second player(2) : "
player_2_name = gets.chomp
player_2 = Player.new(player_2_name, 'O')
end
puts
puts "Player 1: #{player_1.name}, Color: #{player_1.color} | Player 2: #{player_2.name}, Color: #{player_2.color}"
puts
game = Game.new(player_1, player_2)
game.play
| true
|
6d5b6c17fa1df65b80e0e0ccc4e4daf79a85b337
|
Ruby
|
reactormonk/usher
|
/lib/usher/node.rb
|
UTF-8
| 6,030
| 2.796875
| 3
|
[] |
no_license
|
require File.join('usher', 'node', 'root')
require File.join('usher', 'node', 'root_ignoring_trailing_delimiters')
require File.join('usher', 'node', 'response')
class Usher
# The node class used to walk the tree looking for a matching route. The node has three different things that it looks for.
# ## Normal
# The normal hash is used to normally find matching parts. As well, the reserved key, `nil` is used to denote a variable match.
# ## Greedy
# The greedy hash is used when you want to match on the entire path. This match can trancend delimiters (unlike the normal match)
# and match as much of the path as needed.
# ## Request
# The request hash is used to find request method restrictions after the entire path has been consumed.
#
# Once the node finishes looking for matches, it looks for a `terminates` on the node that is usable. If it finds one, it wraps it into a {Node::Response}
# and returns that. All actual matching though should normally be done off of {Node::Root#lookup}
# @see Root
class Node
attr_reader :normal, :greedy, :request
attr_accessor :terminates, :request_method_type, :parent, :value, :request_methods
def initialize(parent, value)
@parent, @value = parent, value
end
def inspect
out = ''
out << " " * depth
out << "#{terminates? ? '* ' : ''}#{depth}: #{value.inspect}\n"
[:normal, :greedy, :request].each do |node_type|
send(node_type).each do |k,v|
out << (" " * (depth + 1)) << "#{node_type.to_s[0].chr} #{k.inspect} ==> \n" << v.inspect
end if send(node_type)
end
out
end
protected
def depth
@depth ||= parent.is_a?(Node) ? parent.depth + 1 : 0
end
def terminates?
@terminates && @terminates.route.recognizable?
end
def ancestors
unless @ancestors
@ancestors = []
node = self
while (node.respond_to?(:parent))
@ancestors << node
node = node.parent
end
end
@ancestors
end
def root
@root ||= ancestors.last
end
def route_set
@route_set ||= root.route_set
end
def find(request_object, original_path, path, params = [])
# terminates or is partial
if terminates? && (path.empty? || terminates.route.partial_match?)
response = terminates.route.partial_match? ?
Response.new(terminates, params, path.join, original_path[0, original_path.size - path.join.size]) :
Response.new(terminates, params, nil, original_path)
# terminates or is partial
elsif !path.empty? and greedy and match_with_result_output = greedy.match_with_result(whole_path = path.join)
child_node, matched_part = match_with_result_output
whole_path.slice!(0, matched_part.size)
params << matched_part if child_node.value.is_a?(Route::Variable)
child_node.find(request_object, original_path, whole_path.empty? ? whole_path : route_set.splitter.split(whole_path), params)
elsif !path.empty? and normal and child_node = normal[path.first] || normal[nil]
part = path.shift
case child_node.value
when String
when Route::Variable::Single
variable = child_node.value # get the variable
variable.valid!(part) # do a validity check
until path.empty? || (variable.look_ahead === path.first) # variables have a look ahead notion,
next_path_part = path.shift # and until they are satified,
part << next_path_part
end if variable.look_ahead
params << part # because its a variable, we need to add it to the params array
when Route::Variable::Glob
params << []
loop do
if (child_node.value.look_ahead === part || (!route_set.delimiters.unescaped.include?(part) && child_node.value.regex_matcher && !child_node.value.regex_matcher.match(part)))
path.unshift(part)
path.unshift(child_node.parent.value) if route_set.delimiters.unescaped.include?(child_node.parent.value)
break
elsif !route_set.delimiters.unescaped.include?(part)
child_node.value.valid!(part)
params.last << part
end
unless part = path.shift
break
end
end
end
child_node.find(request_object, original_path, path, params)
elsif request_method_type
if route_set.priority_lookups?
route_candidates = []
if specific_node = request[request_object.send(request_method_type)] and ret = specific_node.find(request_object, original_path, path.dup, params && params.dup)
route_candidates << ret
end
if general_node = request[nil] and ret = general_node.find(request_object, original_path, path.dup, params && params.dup)
route_candidates << ret
end
route_candidates.sort!{|r1, r2| r1.path.route.priority <=> r2.path.route.priority}
route_candidates.last
else
if specific_node = request[request_object.send(request_method_type)] and ret = specific_node.find(request_object, original_path, path.dup, params && params.dup)
ret
elsif general_node = request[nil] and ret = general_node.find(request_object, original_path, path.dup, params && params.dup)
ret
end
end
else
nil
end
end
def activate_normal!
@normal ||= {}
end
def activate_greedy!
@greedy ||= {}
end
def activate_request!
@request ||= {}
end
def upgrade_normal!
@normal = FuzzyHash.new(@normal)
end
def upgrade_greedy!
@greedy = FuzzyHash.new(@greedy)
end
def upgrade_request!
@request = FuzzyHash.new(@request)
end
end
end
| true
|
8a4913d4c38b1c2365bd0f318eb0c64229b9e306
|
Ruby
|
szrharrison/prime-ruby-web-031317
|
/prime.rb
|
UTF-8
| 292
| 3.125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Add code here!
def prime?(n)
n = n
if ( n <= 1 )
is_p = false
elsif ( n == 2 || n == 3 )
is_p = true
else
for d in 2..Math.sqrt( n )
if ( n % d == 0 )
break is_p = false
else
is_p = true
end
end
end
return is_p
end
prime?(40)
| true
|
84dd968ade05c23e89b12cd2a1befb94fe1e516e
|
Ruby
|
Nevens-fr/Projet_L3_Info
|
/Editeur/Ecran_jeu.rb
|
UTF-8
| 1,281
| 3.296875
| 3
|
[] |
no_license
|
load "Grille.rb"
##
# Représentation d'un écran de jeu, une partie de fill a pix
##
# * +win+ La fenêtre graphique du programme
# * +boite+ Gtk::box qui contiendra le plateau de jeu et les différents boutons
# * +grille+ Une instance de la classe Grille_jeu représentant le plateau de jeu
# * +quit+ Gtk::Button qui permet de fermer le jeu
class Ecran_jeu
def Ecran_jeu.creer(win, nbLignes, nbColonnes)
new(win, nbLignes, nbColonnes)
end
private_class_method :new
def initialize(win, nbLignes, nbColonnes)
@win = win
@boite = Gtk::Box.new(:vertical, 5)
@grille = Grille_jeu.new(nbLignes, nbColonnes)
@quit = Gtk::Button.new(:label => "Quitter")
@boite.add(@grille.grille)
@save = Gtk::Button.new(:label => "Sauvegarder")
@save.signal_connect("clicked"){
sauvegarder()
}
@boite.add(@save)
@boite.add(@quit)
@quit.signal_connect("clicked"){
vers_menu()
}
@win.add(@boite)
@win.show_all
end
##
# Permet de passer à l'écran du menu
def vers_menu()
@win.remove(@boite)
Ecran_menu.creer(@win)
end
def sauvegarder()
@grille.save()
end
end
| true
|
9ecf3979700226542cba81340f7eebcdb6a2707d
|
Ruby
|
Visiona/learn_ruby
|
/10_temperature_object/temperature.rb
|
UTF-8
| 636
| 4.03125
| 4
|
[] |
no_license
|
class Temperature
def initialize(attrs={})
@f = attrs[:f]
@c = attrs[:c]
end
def ftoc (temp)
(temp - 32.0 ) * 5.0 / 9.0
end
def ctof (temp)
temp * 9.0 / 5.0 + 32.0
end
def in_celsius
return @c if @c
return ftoc(@f) if @f
end
def in_fahrenheit
return @f if @f
return ctof(@c) if @c
end
def self.from_celsius(c)
Temperature.new(:c => c)
end
def self.from_fahrenheit(f)
Temperature.new(:f => f)
end
end
class Celsius < Temperature
def initialize(temp)
@c = temp
end
end
class Fahrenheit < Temperature
def initialize(temp)
@f = temp
end
end
| true
|
23ad0b1fc769580e36019e84700114d3e8d35f3c
|
Ruby
|
kitz99/curiosity
|
/exceptions/invalid_instruction.rb
|
UTF-8
| 145
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
class InvalidInstruction < StandardError
def initialize(message)
@message = message
end
def to_s
"#{@message} #{super}"
end
end
| true
|
d956943fb4a5475911a39ddae71e865717376e6f
|
Ruby
|
jamesjtong/oo-tictactoe
|
/void_location.rb
|
UTF-8
| 187
| 2.609375
| 3
|
[] |
no_license
|
class VoidLocation
attr_accessor :symbol
attr_reader :top, :top_left, :top_right, :left, :right, :bottom, :bottom_left, :bottom_right
def initialize
self.symbol = "V"
end
end
| true
|
c53185c81ee66f59663e883f8fb73e6dff91629f
|
Ruby
|
iskodirajga/retrodot
|
/lib/chat_ops/command.rb
|
UTF-8
| 2,396
| 2.828125
| 3
|
[
"ISC"
] |
permissive
|
module ChatOps
class CommandSetup
attr_reader :config
def initialize
@config = {}
end
def match(m)
@config[:regex] = m
end
def help(h)
@config[:help] = h
end
def incident_optional(value=true)
@config[:incident_optional] = value
end
end
class Command
class << self
attr_reader :regex
# Ruby calls this function when a class is declared that inherits from this
# class. We then register it with the ChatOps module.
def inherited(klass)
ChatOps.register(klass)
end
def process(user, message)
new(user, message).process
end
# Outsiders should call process() instead.
private :new
def incident_optional?
@incident_optional
end
def help
[Config.chatops_prefix, @help].compact.join(' ')
end
private
def setup(&block)
s = CommandSetup.new
s.instance_eval &block
s.config.each do |name, value|
instance_variable_set "@#{name}", value
end
end
end
def initialize(user, message)
@user = user
@message = message
end
def process
return unless @match = self.class.regex.match(@message)
if @match.names.include? "incident_id"
@incident = determine_incident(@match[:incident_id])
if !self.class.incident_optional?
return unknown_incident_warning if !@incident
return old_incident_warning if @match[:incident_id].nil? and @incident.old?
end
end
run
end
# Implement run() in the subclass. It should return a hash describing the
# response. The hash may contain the following keys:
#
# message: (optional) text to reply back with
# subject: (optional) a subject line for an extended message, e.g. Slack's
# "attachments"
# reaction: (optional) name of an emoji to add as a reaction to the user's
# message
#
# Return nil to indicate that we don't actually want to process the command
# after all.
def run
raise NotImplementedError
end
# LIBRARY FUNCTIONS
#
# These utility functions are used by chatops commands.
include ChatOps::MentionHelpers
include ChatOps::TimeStampHelpers
include ChatOps::MessageHelpers
include ChatOps::IncidentHelpers
end
end
| true
|
8483bdd07b5ee304f37ce3b7859b19a42f9713f4
|
Ruby
|
zhoujz10/biotcm
|
/lib/biotcm/modules/utility.rb
|
UTF-8
| 1,139
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
require 'net/http'
module BioTCM
module Modules
# Provide utility functions
module Utility
# A useful method for diverse purposes
# @overload get(url)
# Get an url
# @param url [String]
# @return [String] if success, the content
# @return [nil] if cannot recognize the scheme
# @raise RuntimeError if return status is not 200
# @overload get(:stamp)
# Get a stamp string containing time and thread_id
# @return [String]
# @example
# BioTCM::Modules::Utility.get(:stamp) # => "20140314_011353_1bbfd18"
def get(obj)
case obj
when String
uri = URI(obj)
case uri.scheme
when 'http'
res = Net::HTTP.get_response(uri)
fail "HTTP status #{res.code} returned when #{uri} sent" unless res.is_a?(Net::HTTPOK)
return res.body
end
when :stamp
return Time.now.to_s.split(' ')[0..1]
.push((Thread.current.object_id << 1).to_s(16))
.join('_').gsub(/-|:/, '')
end
nil
end
end
end
end
| true
|
8aff1368080740cc9ffc5a26226c5facc229770e
|
Ruby
|
peterc/author
|
/data/n.rb
|
UTF-8
| 94
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
File.open("names2.txt", "w") { |f| f.puts File.readlines("names.txt").map(&:downcase).join }
| true
|
e0af7bc998bb9a11e4ae1ffe2507cd531dad7a35
|
Ruby
|
evheny0/bsuir-labs
|
/model/lab1/main.rb
|
UTF-8
| 1,325
| 3.09375
| 3
|
[] |
no_license
|
require './magic_rand.rb'
require './rand_analyzer'
require 'gnuplot'
def print_histogram(array, size)
array.each do |_k, v|
puts('*' * (v * 1000 / size))
end
end
def new_rand
new_rand = MagicRand.new
printf 'Enter new params? (y/n): '
if gets.chomp == 'y'
printf 'Enter M: '
new_rand.m = gets.to_i
printf 'Enter A: '
new_rand.a = gets.to_i
printf 'Enter seed: '
new_rand.seed = gets.to_i
else
puts 'Using default params...'
end
new_rand
end
analyzer = RandAnalyzer.new(new_rand)
hist = analyzer.histogram
puts " ** EXPECTATION: #{analyzer.expectation}"
puts " ** DISPERSION: #{analyzer.dispersion}"
puts " ** STANDARD DEVIATION: #{analyzer.standard_deviation}"
puts " ** VALUES IN CIRCLE: #{analyzer.check_uniformity} ~= #{Math::PI / 4}"
puts " ** PERIOD: #{analyzer.period}\n\n"
puts '================================================='
hist = hist.sort_by { |a, _| a }.to_h
x = hist.keys.map { |i| i.round 4 }
y = hist.values.map { |i| i.to_f / analyzer.size }
Gnuplot.open do |gp|
Gnuplot::Plot.new(gp) do |plot|
plot.title 'Histogram'
plot.style 'data histograms'
plot.xtics 'nomirror rotate by -45'
plot.yrange '[0.045:0.055]'
plot.data << Gnuplot::DataSet.new([x, y]) do |ds|
ds.using = '2:xtic(1)'
ds.title = '1'
end
end
end
| true
|
3e6bcdd1c1ae838e1d90ca0138c4a1c3dc8b50b7
|
Ruby
|
fur0ut0/filmarks-exporter
|
/app.rb
|
UTF-8
| 1,348
| 2.796875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'net/http'
require 'optparse'
require 'uri'
require_relative 'filmarks_exporter/filmarks_extracter'
# main application
class App
def initialize(args)
@url, @options = parse_args(args)
end
def run
html = if @url =~ /^http.*/
Net::HTTP.get(URI.parse(@url))
else
File.open(@url).read
end
File.open(@options[:serialize], 'w') { |f| f.write(html) } if @options[:serialize]
extracter = FilmarksExporter::FilmarksExtracter.new
info = extracter.extract(html)
# TODO: make print order customizable
print_as_row(info)
end
OPT_PARSER = OptionParser.new do |p|
p.banner = "usage: #{File.basename($PROGRAM_NAME)} URL"
p.on('-s FILE', '--serialize FILE', 'serialize HTML content into file')
end.freeze
def parse_args(args)
options = {}
pos_args = OPT_PARSER.parse(args, into: options)
url = pos_args.shift
raise 'No URL specified' unless url
[url, options]
end
def print_as_row(info)
puts [
info[:title],
info[:original],
info[:duration],
info[:release_date],
info[:genres].join('、'),
info[:prime_info]
].join("\t")
end
end
App.new(ARGV).run if $PROGRAM_NAME == __FILE__
| true
|
c1a068d89bbe9a427f3b67013f0da38e29acb2f1
|
Ruby
|
hoshi-sano/digyukko
|
/managers/story_manager.rb
|
UTF-8
| 8,477
| 2.546875
| 3
|
[
"Zlib"
] |
permissive
|
module DigYukko
module StoryManager
include HelperMethods
CUSTOM_STORY_DIR = File.join(DigYukko.app_root, 'customize', 'stories')
STORY_DIR = File.join(DigYukko.app_root, 'data', 'stories')
class << self
def init(story_type, next_scene_class, next_scene_args = [])
@slides = load_story(story_type)
@slide_idx = 0
@next_scene_class = next_scene_class
@next_scene_args = next_scene_args
@skip_message = SkipMessage.new
end
def update_components
@slides[@slide_idx].update
if @slides[@slide_idx].finished?
if @slides[@slide_idx + 1]
@slide_idx += 1
else
unless ApplicationManager.scene_changing?
ApplicationManager.change_scene(@next_scene_class.new(*@next_scene_args))
end
end
end
@skip_message.update
end
def draw_components
@slides[@slide_idx].draw
@skip_message.draw if @slides[@slide_idx].skip?
end
def check_keys
return if ApplicationManager.scene_changing?
if KEY.pushed_keys.any? && @slides[@slide_idx].skip?
ApplicationManager.change_scene(@next_scene_class.new(*@next_scene_args))
end
end
def load_story(story_type)
prev_info = {}
load_yaml([CUSTOM_STORY_DIR, STORY_DIR], story_type).map do |slide_info|
slide = Slide.new(slide_info, prev_info)
prev_info = slide.info
slide
end
end
end
class Slide
include HelperMethods
ALPHA_MIN = 0
ALPHA_MAX = 255
class Event
attr_reader :message
def initialize(info)
@message = info[:message]
@procs = []
if info[:bgm_start]
bgm_name = info[:bgm_start]
BGM.add(bgm_name)
@procs << Proc.new { BGM.play(bgm_name) }
end
@procs << Proc.new { BGM.stop } if info[:bgm_stop]
if info[:sound_effect]
se_name = info[:sound_effect]
SE.add(se_name)
@procs << Proc.new { SE.play(se_name) }
end
end
def exec_actions
@procs.each(&:call)
end
end
# 以下指定可能な値の一覧。
# image_file_name以外は指定しない場合は前のスライドの値を継続する。
# カッコ内はデフォルト値。(最初のスライドで指定しなかった場合に利用される)
#
# * image_file_name: スライド画像のファイル名 (なし)
# * skip: ボタン押下によるスキップを許容するか否か (nil)
# * fade_in: スライド表示開始時にフェードインするか否か (nil)
# * fade_out: スライド表示終了時にフェードインするか否か (nil)
# * alpha_diff: フェードイン・フェードアウトする際の速さ(3)
# * image_x: スライド画像の表示位置のx座標 (画像が中央にくるx座標)
# * image_y: スライド画像の表示位置のy座標 (画像が中央にくるy座標)
# * message_x: 文章の表示位置のx座標 (画像のx座標)
# * message_y: 文章の表示位置のy座標 (画像の下端+20pixel)
# * message_speed: 文章の表示速度 (5)
# * keep_duration: 表示し終えたスライドの表示継続時間 (message_speed * 30)
#
def initialize(info, prev_info = {})
if info[:image_file_name]
@image = load_image(info[:image_file_name])
else
@image = ::DXRuby::Image.new(1, 1)
end
@events = Array(info[:events]).map { |event_info| Event.new(event_info) }
@event_idx = 0
@skip = info.key?(:skip) ? info[:skip] : prev_info[:skip]
@fade_in = info.key?(:fade_in) ? info[:fade_in] : prev_info[:fade_in]
@fade_out = info.key?(:fade_out) ? info[:fade_out] : prev_info[:fade_out]
@state = @fade_in ? :fade_in : :appeared
@alpha = @fade_in ? ALPHA_MIN : ALPHA_MAX
@alpha_diff = info[:alpha_diff] || prev_info[:alpha_diff] || 3
@r_target = ::DXRuby::RenderTarget
.new(Config['window.width'],
Config['window.height'])
@image_x = info[:image_x] || prev_info[:image_x] || @r_target.width / 2 - @image.width / 2
@image_y = info[:image_y] || prev_info[:image_y] || @r_target.height / 2 - @image.height / 2
@message_x = info[:message_x] || prev_info[:message_x] || @image_x
@message_y = info[:message_y] || prev_info[:message_y] || @image_y + @image.height + 20
@message_speed = info[:message_speed] || prev_info[:message_speed] || 5
@keep_duration = info[:keep_duration] || prev_info[:keep_duration] || @message_speed * 30
@display_message = ''
@display_message_counter = 0
@keep_counter = 0
end
def info
{
skip: @skip,
fade_in: @fade_in,
fade_out: @fade_out,
alpha_diff: @alpha_diff,
image_x: @image_x,
image_y: @image_y,
message_x: @message_x,
message_y: @message_y,
message_speed: @message_speed,
keep_duration: @keep_duration,
}
end
def skip?
@skip
end
def hidden?
@alpha <= ALPHA_MIN
end
def showed?
@alpha >= ALPHA_MAX
end
def finished?
@state == :finished
end
def current_event
@events[@event_idx]
end
def current_message
return nil if current_event.nil?
current_event.message
end
def update
case @state
when :fade_in
@alpha += @alpha_diff
if showed?
@alpha = ALPHA_MAX
@state = :appeared
end
when :fade_out
@alpha -= @alpha_diff
if hidden?
@alpha = ALPHA_MIN
@state = :finished
end
when :appeared
@state = current_event ? :exec_event : :keep
when :exec_event
# 最初の1回だけEvent#exec_actionsを呼ぶ
current_event.exec_actions if current_event && @display_message_counter.zero?
# 表示するメッセージが無かったり、メッセージを表示しきった場合は
# keep状態に移行する
if !current_message || !current_message[@display_message.length]
@state = :keep
@keep_counter = 0
return
end
# 表示する文言を徐々に増やしてメッセージ送りを表現する
if (@display_message_counter % @message_speed).zero?
@display_message.concat(current_message[@display_message.length])
end
@display_message_counter += 1
when :keep
# @keep_durationに負の数を指定した場合は
# キー押下によるskipが行われるまでスライドを表示し続ける
return if @keep_duration < 0
# 画像やメッセージを表示しきった状態で、一定時間表示したのちに
# 次のスライドへ遷移する
@keep_counter += 1
if (@keep_counter % @keep_duration).zero?
@display_message = ''
@display_message_counter = 0
@event_idx += 1
if current_event
@state = :exec_event
else
@event_idx = 0
@state = @fade_out ? :fade_out : :finished
end
end
end
end
def draw
@r_target.draw(@image_x, @image_y, @image)
@r_target.draw_font(@message_x, @message_y, @display_message, FONT[:regular])
::DXRuby::Window.draw_ex(0, 0, @r_target, alpha: @alpha)
end
end
class SkipMessage
MESSAGE = 'PUSH ANY BUTTON'
TOGGLE_INTERVAL = 45
def initialize
@show = true
@counter = 0
@font = FONT[:small]
@x = (Config['window.width'] / 2) - (@font.get_width(MESSAGE) / 2)
end
def update
@counter += 1
if (@counter % TOGGLE_INTERVAL).zero?
@show = !@show
@counter = 0
end
end
def draw
::DXRuby::Window.draw_font(@x, 0, MESSAGE, @font) if @show
end
end
end
end
| true
|
a97e8e61078770e737cb048ccae180fd1d7e817b
|
Ruby
|
jk1dd/daily-practice
|
/solved_to_review/driver_license.rb
|
UTF-8
| 2,975
| 3.5
| 4
|
[] |
no_license
|
# 1–5: The first five characters of the surname (padded with 9s if less than 5 characters)
#
# 6: The decade digit from the year of birth (e.g. for 1987 it would be 8)
#
# 7–8: The month of birth (7th character incremented by 5 if driver is female i.e. 51–62 instead of 01–12)
#
# 9–10: The date within the month of birth
#
# 11: The year digit from the year of birth (e.g. for 1987 it would be 7)
#
# 12–13: The first two initials of the first name and middle name, padded with a 9 if no middle name
#
# 14: Arbitrary digit – usually 9, but decremented to differentiate drivers with the first 13 characters in common. We will always use 9
#
# 15–16: Two computer check digits. We will always use "AA"
# data = ["John","James","Smith","01-Jan-2000","M"]
# Where the elements are as follows
#
# 0 = Forename
#
# 1 = Middle Name (if any)
#
# 2 = Surname
#
# 3 = Date of Birth (In the format Day Month Year, this could include the full Month name or just shorthand ie September or Sep)
#
# 4 = M-Male or F-Female
require 'date'
def driver(data)
first = data[2][0..4].upcase.ljust(5, '9')
second = data[3].split('-')[2][2]
# Date.parse(data[3]).month.to_s
if data[4] == "M"
third = Date.parse(data[3]).month.to_s.rjust(2, '0')
else
if Date.parse(data[3]).month >= 10
third = "6" + Date.parse(data[3]).month.to_s[1]
else
third = Date.parse(data[3]).month.to_s.rjust(2, '5') # account for adding 5 to female driver first digit
end
end
fourth = Date.parse(data[3]).day.to_s.rjust(2, '0')
fifth = data[3].split('-')[2][-1]
if data[1] == ""
sixth = data[0][0] + '9'
else
# require 'pry'; binding.pry
sixth = data[0][0] + data[1][0]
end
seventh = '9'
eigth = 'AA'
constructed_license_number = first + second + third + fourth + fifth + sixth + seventh + eigth
end
# data = ["John","James","Smith","01-Jan-2000","M"]
# data = ["Johanna","","Gibbs","13-Dec-1981","F"]
data = ["Johanna","","Johnson","13-Dec-1981","F"]
p driver(data)
# how to refactor this
# require 'date'
#
# def driver(data)
# surname(data[2]) +
# birth_decade(data[3]) +
# birth_month(data[3], data[4]) +
# birth_day_in_month(data[3]) +
# birth_year_digit(data[3]) +
# initials(data[0], data[1]) +
# arbitrary() +
# checkdigits()
# end
#
# def surname(name)
# name[0..4].upcase.ljust(5, '9')
# end
#
# def birth_decade(birthday)
# birthday[-2]
# end
#
# def birth_month(birthday, gender)
# month = Date::ABBR_MONTHNAMES
# .index(birthday[3..5])
# .to_s
# .rjust(2, '0')
# if gender == 'F'
# return (month[0].to_i + 5).to_s + month[1]
# end
# return month
# end
#
# def birth_day_in_month(birthday)
# birthday[0..1]
# end
#
# def birth_year_digit(birthday)
# birthday[-1]
# end
#
# def initials(forename, middlename)
# forename[0] + middlename[0..0].rjust(1, '9')
# end
#
# def arbitrary()
# '9'
# end
#
# def checkdigits()
# 'AA'
# end
| true
|
293d8cb3d7d870550c334ec9c63d1cde3f85f40b
|
Ruby
|
silentrob/hydraproject
|
/lib/make-torrent.rb
|
UTF-8
| 1,783
| 2.734375
| 3
|
[] |
no_license
|
require 'digest/sha1'
require 'rubytorrent'
class MakeTorrent
def initialize(file_path, tracker_url, file_url=nil)
@file_path = file_path
@file_url = file_url
@file_size = File.size(@file_path)
@tracker = tracker_url
[64, 128, 256, 512].each do |size|
@num_pieces = (@file_size.to_f / size / 1024.0).ceil
tsize = @num_pieces.to_f * 20.0 + 100
@piece_size = size * 1024
break if tsize < 10240
end
end
def pieces
mii_pieces = ""
read_pieces(@file_path, @piece_size) do |piece|
mii_pieces += Digest::SHA1.digest(piece)
end
mii_pieces
end
def write(path)
File.open(path, 'wb') do |f|
f.write(torrent.to_bencoding)
end
end
def read_pieces(file, length)
buf = ""
File.open(file) do |fh|
begin
read = fh.read(length - buf.length)
if (buf.length + read.length) == length
yield(buf + read)
buf = ""
else
buf += read
end
end until fh.eof?
end
yield buf
end
def file_name
File.basename(@file_path)
end
def info
@info ||= { 'pieces' => pieces,
'piece length' => @piece_size,
'name' => file_name,
'files' => [{'path' => [file_name], 'length' => @file_size}] }
end
def torrent
return @torrent_data unless @torrent_data.nil?
torrent = RubyTorrent::MetaInfo.new({'announce_list' => [@tracker],
'announce' => @tracker,
'url-list' => @file_url,
'info' => info,
'creation date' => Time.now})
@torrent_data = torrent
end
end
| true
|
caa47a6b49ce49e9927f2d38292c1501c0af56bd
|
Ruby
|
dbbrandt/zype-cli
|
/lib/zype/commands/video.rb
|
UTF-8
| 4,516
| 2.5625
| 3
|
[] |
no_license
|
require 'thor'
require 'zype/progress_bar'
require 'zype/uploader'
module Zype
class Commands < Thor
desc 'video:list', 'List videos'
method_option 'query', desc: 'Video search terms',
aliases: 'q', type: :string
method_option 'type', desc: 'Show videos of the specified type',
aliases: 't', type: :string, enum: ['zype','hulu','youtube']
method_option 'category', desc: 'Video category filters',
aliases: 'c', type: :hash
method_option 'active', desc: 'Show active, inactive or all videos',
aliases: 'a', type: :string, default: 'true', enum: ['true','false','all']
method_option 'page', desc: 'The page of videos to return',
aliases: 'p', type: :numeric, default: 0
method_option 'per_page', desc: 'The number of videos to return',
aliases: 's', type: :numeric, default: 25
define_method 'video:list' do
init_client
videos = @zype.videos.all(
:q => options[:query],
:type => options[:type],
:category => options[:category],
:active => options[:active],
:page => options[:page],
:per_page => options[:per_page]
)
print_videos(videos)
end
desc 'video:update', 'Update a video'
method_option 'id', aliases: 'i', type: :string, required: true, desc: 'Video ID'
method_option 'active', aliases: 'a', type: :boolean, desc: 'Video active status'
method_option 'featured', aliases: 'f', type: :boolean, desc: 'Video featured status'
method_option 'title', aliases: 't', type: :string, desc: 'Video title'
method_option 'description', aliases: 'd', type: :string, desc: 'Video description'
method_option 'keywords', aliases: 'k', type: :array, desc: 'Video keywords'
define_method 'video:update' do
init_client
if video = @zype.videos.find(options[:id])
video.title = options[:title] unless options[:title].nil?
video.keywords = options[:keywords] unless options[:keywords].nil?
video.active = options[:active] unless options[:active].nil?
video.featured = options[:featured] unless options[:featured].nil?
video.description = options[:description] unless options[:description].nil?
video.save
print_videos([video])
end
puts ''
end
desc 'video:upload', 'Upload a video'
method_option 'title', aliases: 't', type: :string, required: false, desc: 'Video title'
method_option 'keywords', aliases: 'k', type: :array, desc: 'Video keywords'
method_option 'filename', aliases: 'f', type: :string, required: false, desc: 'File path to upload'
method_option 'directory', aliases: 'd', type: :string, required: false, desc: 'Directory to upload'
define_method 'video:upload' do
init_client
filenames = []
if filename = options[:filename]
filenames << filename
end
if directory = options[:directory]
directory = directory.chomp('/')
filenames += Dir.glob(directory + '/*').reject{|f| f =~ /(^\.\.)|(^\.)/}
end
filenames.each do |filename|
upload_and_transcode_video(filename, options)
end
end
no_commands do
def print_videos(videos)
puts Hirb::Helpers::Table.render(videos, :fields=>[:_id, :title, :description, :filename, :duration, :status, :active])
end
def upload_and_transcode_video(filename,options)
upload = upload_video(filename)
if upload.status == 'complete'
transcode_video(upload, title: options[:title] || upload.filename, keywords: options[:keywords])
end
end
def transcode_video(upload,options={})
@zype.videos.create(options.merge(upload_id: upload._id))
end
def upload_video(filename)
file = File.open(filename)
basename = File.basename(filename)
upload = @zype.uploads.create(filename: basename, filesize: file.size)
begin
uploader = Zype::Uploader.new(@zype)
uploader.process(upload,file)
upload.progress = 100
upload.status = 'complete'
rescue Interrupt => e
puts 'Upload Cancelled'
upload.status = 'cancelled'
rescue Exception => e
upload.status = 'error'
upload.message = "Error: ##{e.message}"
raise
ensure
upload.save
end
puts ''
upload
end
end
end
end
| true
|
beb28972b0a084e0694856e74b26016166f16049
|
Ruby
|
codepedia/ruby_utils
|
/ruby1.rb
|
UTF-8
| 145
| 3.1875
| 3
|
[] |
no_license
|
1#!/usr/bin/env ruby
name = ["fred" , "Bob" , "jim" , "zeyad"]
name.each do |x|
puts "My name is : #{x}"
puts "my new name is $x"
end
| true
|
41fd61baaf0e0a3509a985d89518773f3a5c3b44
|
Ruby
|
ohishikaito/cherry_book
|
/before_lessons/8.rb
|
UTF-8
| 5,317
| 2.625
| 3
|
[] |
no_license
|
# # # # # # # # module Loggable
# # # # # # # # # private
# # # # # # # # # protected
# # # # # # # # def log(text)
# # # # # # # # puts "log: #{text}"
# # # # # # # # end
# # # # # # # # def pr
# # # # # # # # puts price
# # # # # # # # end
# # # # # # # # end
# # # # # # # # a = "a"
# # # # # # # # # a.log('hoge')
# # # # # # # # a.extend(Loggable)
# # # # # # # # a.log('hoge')
# # # # # # # # # # # # class Product
# # # # # # # # # # # # include Loggable
# # # # # # # # # # # # extend Loggable
# # # # # # # # # # # # def title
# # # # # # # # # # # # log('product-title')
# # # # # # # # # # # # 'title'
# # # # # # # # # # # # end
# # # # # # # # # # # # def price
# # # # # # # # # # # # 1000
# # # # # # # # # # # # end
# # # # # # # # # # # # def self.extends
# # # # # # # # # # # # log('self.extends')
# # # # # # # # # # # # end
# # # # # # # # # # # # end
# # # # # # # # # # # # a = Product.new
# # # # # # # # # # # # a.pr
# # # # # # # # # # # # # Product.log('a')
# # # # # # # # # # # # # class User
# # # # # # # # # # # # # include Loggable
# # # # # # # # # # # # # def name
# # # # # # # # # # # # # log('user-name')
# # # # # # # # # # # # # 'title'
# # # # # # # # # # # # # end
# # # # # # # # # # # # # end
# # # # # # # # # # # # # a=Product.new
# # # # # # # # # # # # # Product.extends
# # # # # # # # # # # # # Product.log('fuga')
# # # # # # # # # # # # # p a.title
# # # # # # # # # # # # # b=User.new
# # # # # # # # # # # # # p b.name
# # # # # # # # # # # # # b.log('hoge')
# # # # # # # # # # # # # p Product.ancestors
# # # # # # # # # # # p 11 <=> 2
# # # # # # # # # # # p 1 <=> 2
# # # # # # # # # # class Tempo
# # # # # # # # # # include Comparable
# # # # # # # # # # attr_reader :bpm
# # # # # # # # # # def initialize(bpm)
# # # # # # # # # # @bpm = bpm
# # # # # # # # # # end
# # # # # # # # # # def <=>(other)
# # # # # # # # # # bpm <=> other.bpm if other.is_a?(Tempo)
# # # # # # # # # # end
# # # # # # # # # # def inspect
# # # # # # # # # # "#{bpm}bpm"
# # # # # # # # # # end
# # # # # # # # # # end
# # # # # # # # # # # t_120 = Tempo.new(120)
# # # # # # # # # # # t_180 = Tempo.new(180)
# # # # # # # # # # # p t_120 > t_180
# # # # # # # # # # tinpos = [Tempo.new(100), Tempo.new(2), Tempo.new(1)]
# # # # # # # # # # p tinpos
# # # # # # # # # # p tinpos.sort
# # # # # # # # # p Object.include?(Kernel)
# # # # # # # # # p Kernel.methods.sort
# # # # # # # # # p Object.included_modules
# # # # # # # # # p self
# # # # # # # class Second
# # # # # # # def initialize(play, uni)
# # # # # # # @play = play
# # # # # # # @uni = uni
# # # # # # # end
# # # # # # # end
# # # # # # # module Clock
# # # # # # # class Second
# # # # # # # def initialize(_play)
# # # # # # # # @play = play
# # # # # # # @bs = ::Second.new(1, 2)
# # # # # # # puts @bs
# # # # # # # puts "bb-second"
# # # # # # # p self
# # # # # # # end
# # # # # # # end
# # # # # # # end
# # # # # # # Clock::Second.new('a')
# # # # # # module Loggable
# # # # # # def self_log
# # # # # # puts "logggg"
# # # # # # end
# # # # # # def log(text)
# # # # # # puts "self.log:#{text}"
# # # # # # end
# # # # # # module_function :log
# # # # # # AAA='A'.freeze
# # # # # # end
# # # # # # p Loggable::AAA
# # # # # # # Loggable.log('hi')
# # # # # # # class Product
# # # # # # # # include Loggable
# # # # # # # extend Loggable
# # # # # # # def hi
# # # # # # # log('aaa')
# # # # # # # end
# # # # # # # end
# # # # # # # a=Product.new
# # # # # # # a.hi
# # # # # # # # a.log
# # # # # # # a.self_log
# # # # # # # Product.self_log
# # # # # # p Math.sqrt(73)
# # # # # class Cal
# # # # # include Math
# # # # # def calc(n)
# # # # # sqrt(n)
# # # # # end
# # # # # end
# # # # class Test
# # # # include Kernel
# # # # extend Kernel
# # # # def self.extend(p)
# # # # puts(p)
# # # # end
# # # # def include(p)
# # # # puts(p)
# # # # end
# # # # end
# # # # include1=Test.new
# # # # include1.include('include')
# # # # Test.extend('extend')
# # # # # p a.calc(2)
# # # # # Kernel.puts 'hi'
# # # # # p('hi')
# # # require 'singleton'
# # # class Conf
# # # include Singleton
# # # attr_accessor :base_url
# # # def initialize
# # # @base_url
# # # end
# # # end
# # # # conf = Conf.new
# # # conf = Conf.instance
# # # p conf
# # # conf.base_url = "unko"
# # # p conf
# # module A
# # def to_s
# # "moduleA:#{super}"
# # end
# # end
# # class Pro
# # prepend A
# # # include A
# # def to_s
# # "classPro: #{super}"
# # end
# # end
# # a =Pro.new
# # p a.to_s
# # p Pro.ancestors
# module NameDecorator
# def name
# "module-name:#{super}"
# end
# end
# class Pro
# p self.ancestors
# prepend(NameDecorator)
# p self.ancestors
# def name
# "pro-name"
# end
# end
# # Pro.prepend NameDecorator
# a = Pro.new
# p a.name
module SS
refine String do
def shuffle
chars.shuffle.join
end
end
end
class User
using SS
def initialize(name)
@name = name
end
def shuffled_name
@name.shuffle
end
end
a = User.new('hoge')
p a::shuffled_name
a = String.new('fuga')
# p a.chars.shuffle.join(' ')
| true
|
23af5ae936779f4581b6d4d89c1baa6059a2ed52
|
Ruby
|
andlogic/hackerrank
|
/ruby/warmup/the-time-in-words.rb
|
UTF-8
| 889
| 3.78125
| 4
|
[
"MIT"
] |
permissive
|
words = { 1 => 'one', 2 => 'two', 3 => 'three' , 4 => 'four', 5 => 'five' , 6 => 'six', 7 => 'seven', 8 => 'eight', 9 => 'nine', 10 => 'ten', 11 => 'eleven' , 12 => 'twelve', 13 => 'thirteen', 14 => 'fourteen', 15 => 'quarter', 30 => 'half' }
def to_w(h,m,w,words)
if m == 0
puts words[h] + ' o\' clock'
elsif m == 1
puts words[m] + " minute #{w} " + words[h]
elsif m > 1 and m <= 14
puts words[m] + " minutes #{w} " + words[h]
elsif m == 15 || m == 30
puts words[m] + " #{w} " + words[h]
elsif m > 15 and m <= 29
n = m.to_s.split("").map { |x| x.to_i }
if n[0] == 1
puts words[n[1]] + "teen minutes #{w} " + words[h]
else
puts 'twenty' + if words[n[1]] then " "+words[n[1]] else '' end + " minutes #{w} " + words[h]
end
end
end
h = gets.to_i
m = gets.to_i
if m < 31
to_w(h,m,'past',words)
else
to_w(h+1,60-m,'to',words)
end
| true
|
093cd0b7d51eee2bdf1702de1e226735a6c0cd75
|
Ruby
|
rmullig2/playlister-sinatra-v-000
|
/app/models/genre.rb
|
UTF-8
| 460
| 2.8125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Genre < ActiveRecord::Base
has_many :song_genres
has_many :songs, through: :song_genres
has_many :artists, through: :songs
def slug
self.name.downcase.split.join("-")
end
def self.find_by_slug(slug)
#no_slug = slug.split("-").map(&:capitalize).join(" ")
no_slug = slug.split("-").join(" ")
#Genre.find_by name: no_slug
genre = Genre.select do |genre|
genre.name.downcase == no_slug
end
genre[0]
end
end
| true
|
c0a5a127deffebade9b3129296f6ffe5c446ade0
|
Ruby
|
conanite/phonefu
|
/spec/parse_spec.rb
|
UTF-8
| 4,607
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'phonefu'
describe Phonefu do
def self.expect_number input, assume_country, expected_country, expected_digits, mob
it "returns #{expected_digits.inspect} in #{expected_country.inspect} for #{input.inspect} assuming country #{assume_country.inspect}" do
tn = Phonefu.parse input, assume_country
if expected_country
expect(tn.country.iso2).to eq expected_country
expect(tn.format nil).to eq expected_digits
expect(tn.mobile?).to(mob ? be_truthy : be_falsy)
else
expect(tn.country).to be_nil
expect(tn.to_s).to eq expected_digits
end
end
end
describe "#mobile?" do
it "detects french mobile numbers" do
tn = Phonefu.parse "06 60 62 31 84", "33"
expect(tn.mobile?).to be_truthy
tn = Phonefu.parse "07 60 62 31 84", "33"
expect(tn.mobile?).to be_truthy
tn = Phonefu.parse "0146477453", "33"
expect(tn.mobile?).to be_falsy
end
end
describe 'normalise' do
expect_number "(33) 4 66 92 01 99" , "49" , "FR", "04 66 92 01 99" , false
expect_number "(33) 6 76 99 07 59" , nil , "FR", "06 76 99 07 59" , true
expect_number "+33466920199", nil , "FR", "04 66 92 01 99" , false
expect_number "(262) 99.42.00", nil , nil , "(262) 99.42.00" , false
expect_number "(1) 508 349 6820", nil , nil , "(1) 508 349 6820", false
expect_number "+33 6 77 88 99 00", nil , "FR", "06 77 88 99 00" , true
expect_number "+32.473.36.50.21", nil , "BE", "0473 36 50 21" , true
expect_number "0652520059", "33" , "FR", "06 52 52 00 59" , true
expect_number "06 85 30 18 36", "33" , "FR", "06 85 30 18 36" , true
expect_number "06-23-88-51-11", "33" , "FR", "06 23 88 51 11" , true
expect_number "09/16/22/33/44", "33" , "FR", "09 16 22 33 44" , false
expect_number "+44 7564111999", "33" , "UK", "0756 411 1999" , true
expect_number "0156 4111 999", "44" , "UK", "0156 411 1999" , false
expect_number "+1 917 214 1234", nil , nil , "+1 917 214 1234" , false
expect_number "(49) 9133767589", "33" , "DE", "0913 376 7589" , false
expect_number "030 3376 7589", "49" , "DE", "030 3376 7589" , false
expect_number "015 3376 7589", "49" , "DE", "0153 3767589" , true
expect_number "(49) 33 203 679 952", "353", "DE", "033203 67 9952" , false
expect_number "( 32) 85 23 57 99" , "49" , "BE", "085 23 57 99" , false
expect_number "(0041) 79 209 26 99", "49" , "CH", "0792092699" , false
# expect_number " 06 92 87 94 99 ", "+33692879499"
# expect_number "(0590) 841444", "+33590841444"
# expect_number "00617-420999185", "+617420999185"
# expect_number "0687964650 ET 0143583599", nil
# expect_number "06141111110/0760754726", nil
# expect_number "() 05 037 70 38", nil
# expect_number "Non encore connu", nil
# expect_number "", nil
# expect_number " ", nil
# expect_number nil, nil
end
describe "format" do
it "formats with country code" do
tn = Phonefu.parse "06 60 62 31 84", "33"
expect(tn.format true).to eq "+33 6 60 62 31 84"
end
it "formats without country code" do
tn = Phonefu.parse "06 60 62 31 84", "33"
expect(tn.format false).to eq "06 60 62 31 84"
end
it "formats without country code when requested" do
tn = Phonefu.parse "06 60 62 31 84", "33"
expect(tn.format "FR").to eq "06 60 62 31 84"
expect(tn.format "DE").to eq "+33 6 60 62 31 84"
end
it "formats without country code when requested" do
tn = Phonefu.parse "+353 87 88 99 007", nil
expect(tn.format true).to eq "+353 87 889 9007"
expect(tn.format "FR").to eq "+353 87 889 9007"
expect(tn.format "DE").to eq "+353 87 889 9007"
expect(tn.format "IE").to eq "087 889 9007"
expect(tn.format "iE").to eq "087 889 9007"
expect(tn.format "ie").to eq "087 889 9007"
expect(tn.format :ie).to eq "087 889 9007"
expect(tn.format :IE).to eq "087 889 9007"
expect(tn.format false).to eq "087 889 9007"
end
it "just returns the number if the country is unknown" do
tn = Phonefu.parse "not a number"
expect(tn.format "FR" ).to eq "not a number"
expect(tn.format "DE" ).to eq "not a number"
expect(tn.format true ).to eq "not a number"
expect(tn.format false).to eq "not a number"
end
end
end
| true
|
34a4406137c46e5ef0718341bc6f57e95636316e
|
Ruby
|
GetlinN/JumpStart
|
/candy_machine.rb
|
UTF-8
| 1,689
| 4
| 4
|
[] |
no_license
|
# Candy machine assignment
# https://github.com/Ada-Developers-Academy/jump-start/tree/master/learning-to-code/programming-expressions#candy-machine-assignment
candy_options = ["mars", "snickers", "twix", "bounty", "almond joy"]
candy_price_list = { A: "0.65", B: "0.50", C: "0.75", D: "1.00", E: "0.40" }
puts "\nWelcome to Computer Candy Machine!
(Not single candy was hurt during this assignment implementation.)\n\n"
# !add input validation
print "How much money would you like to spend on the candies? -> $"
money_to_spend_on_candies = gets.chomp.to_f
# Finds the minimal price of candy. Look for optimal solution
price_array = []
for i in (0..4)
price_array[i] = candy_price_list.values[i].to_f
end
min_price = price_array.min
if money_to_spend_on_candies < min_price
puts "\nSorry, you can't afford any candy today.\n"
else
puts "\nOK. Great! So, you have $#{money_to_spend_on_candies}.\nHere are the candy options we have for you: \n\n"
for i in (0..4)
puts "#{candy_price_list.keys[i]}: $#{candy_price_list.values[i]} #{candy_options[i]}"
end
end
print "\nWhat would you like to have today? Choose option from A to E -> "
choice = gets.chomp.capitalize
puts " "
if choice == "A" || choice == "B" || choice == "C" || choice == "D" || choice == "E"
change = money_to_spend_on_candies - candy_price_list[:"#{choice}"].to_f
if change >= 0
puts "You have chosen option #{choice}. Great choice! Please, take your candy. Your charge is $#{change}.\n"
else
puts "You don't have enough money to finish a purchase. Come back again later. \n\n"
end
else
puts "Wrong input. No such a choice. Come back again."
end
| true
|
d02273a7eea2e603242c7e4f347ba979c7fa83a6
|
Ruby
|
daianef/desafio-dev-umbler
|
/api/lib/domain_information.rb
|
UTF-8
| 2,202
| 3.59375
| 4
|
[] |
no_license
|
#
# Organiza as informacoes para facilitar
# a manipulacao delas como listas e hashes.
#
class DomainInformation
TITLE = 'title'
SECTION = 'section_values'
UNIQUE = 'unique_values'
MULTIPLE = 'multiple_values'
RAW = 'raw'
def initialize(domain_informations, info_config)
@infos = domain_informations
@config = info_config
end
#
# Retorna a saida do comando whois.
#
def get_raw_information
@infos[RAW]
end
#
# Retorna as informacoes organizadas em arrays e hashes.
#
def get_informations
infos = []
@config.keys.each do |key|
section = get_section(key)
infos << section unless section[SECTION].empty?
end
infos
end
#
# Retorna as informacoes, de uma secao, organizadas em hash.
#
def get_section(key)
return {} unless @config.has_key? key
section = @config[key]
infos = {}
infos[TITLE] = get_title(section)
infos[SECTION] = get_unique_values(section)
infos[SECTION].merge!(get_multiple_values(section))
infos
end
private
def get_title(section)
(section.has_key? TITLE)? section[TITLE] : ""
end
def get_unique_values(section)
return {} unless section.has_key? UNIQUE
values = {}
section[UNIQUE].each do |key|
if @infos.has_key? key
hash = (@infos[key].respond_to? :keys)? @infos[key] : @infos[key].first
name, value = hash.keys.first, hash.values.first
values[name] = value
end
end
values
end
def get_multiple_values(section)
return {} unless section.has_key? MULTIPLE
values = {}
section[MULTIPLE].each do |key|
if @infos.has_key? key
if @infos[key].respond_to? :keys
name, value = @infos[key].keys.first, @infos[key].values.first
values[name] = value
else
name = @infos[key].first.keys.first
values[name] = get_values(@infos[key], name)
end
end
end
values
end
def get_values(infos, key)
values = []
infos.each do |hash|
value = hash.values.first
selected = values.select {|v| !v.match(/#{value}/i).nil? }
values << value if selected.empty?
end
values
end
end
| true
|
1dcd3f605d45d09f510bc2125777c599d2b7566d
|
Ruby
|
tuxfight3r/rake_demo
|
/Rakefile
|
UTF-8
| 3,169
| 2.71875
| 3
|
[] |
no_license
|
require 'yaml'
require 'pp'
#Global tasks
desc "default task"
task :default =>[:test]
task :test do
puts "default task"
end
desc "list files from ~"
task :list do
files = Dir["file*"].sort
puts files
end
desc "Restart WebServer"
task :restart do
touch "restart.txt"
end
#namespaces to contain tasks
namespace :server do
desc "start webserver"
task :start do
puts "starting webserver"
end
desc "stop webserver"
task :stop do
puts "stop webserver"
end
desc "status webserver"
task :status do
puts "status info"
end
#single dependency
desc "detailed status webserver"
task :dstatus => :status do
puts "detailed info status"
end
#multiple dependency
desc "Restart webserver"
task :restart => [:stop, :start] do
puts "restarting web server"
end
end
#second name space define
namespace :blog do
desc "set_title"
task :set_title do
title = ENV['TITLE'] || "Blog"
puts "Setting the Title: #{title}"
end
end
#rake with arguments
desc "rake task with arguments"
task :name, [:first_name, :last_name] do |t, args|
puts "First name is #{args.first_name}"
puts "Last name is #{args.last_name}"
end
#creating task for list of hosts
HOSTS = File.join(".", "hosts.txt") # List of all hosts
hosts=File.foreach(ENV["HOSTS"] || HOSTS).map { |line| line.strip }
#puts hosts.class()
#for i in {1..10}; do echo "Content from file${i}" > file${i};done
namespace :check do
namespace :host do
desc "Run test on all hosts "
task :all => hosts.map { |h| :"#{h}" }
# Per server tasks
hosts.each do |host_name|
desc "Run test on hosts #{host_name}"
task "#{host_name}" do
puts "checking server #{host_name}"
file_no="#{host_name}".match(/host(\d+)/)[1]
sh "cat file#{file_no}"
end
end
end
end
#loop through a yaml file
properties=YAML.load_file('properties.yml')
desc "loop through yaml and print"
task :yaml do
if properties.key?('env')
properties['env'].each do |pversion|
_,peversion=pversion.split("=")
puts "PUPPET VERSION: #{peversion}"
end
puts ""
end
end
#file operations in rake
desc "rename settings.yaml to settings.yml"
file ':settings.yaml' do
mv 'settings.yaml', 'settings.yml'
end
#file operations with pandoc and markdown rendering
namespace :renderblog do
desc "renders markdown to create blog index"
task :default => 'blog.html'
articles = ['article1', 'article2']
articles.each do |article|
file "#{article}.html" => "#{article}.md" do
sh "pandoc -s #{article}.md -o #{article}.html"
end
end
file 'blog.html' => articles.map { |a| "#{a}.html" } do
File.open('blog.html', 'w') do |f|
article_links = articles.map do |article|
<<-EOS
<a href='#{article}.html'>
Article #{article.match(/\d+$/)}
</a>
EOS
end
html = <<-EOS
<!DOCTYPE html>
<html>
<head>
<title>Rake essential</title>
</head>
<body>
#{article_links.join('<br />')}
</body>
</html>
EOS
f.write(html)
end
end
end
# vim: set ts=4 sw=2 tw=0 sts=2 noet :
| true
|
7b9803d04e741f0ebc4c2193e47d2345e0a072b4
|
Ruby
|
jvogt/chef-custom-resource-flags-example
|
/cookbooks/testing/resources/foo.rb
|
UTF-8
| 1,559
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
# Define your list of props that will be used as command line flags
flag_props = [
{name: :some_string, type: String, default: 'somevalue'},
{name: :some_bool, type: [TrueClass, FalseClass], default: false},
]
# Iterate over above list to generate properties
flag_props.each do |prop|
property prop[:name], prop[:type], default: prop[:default]
end
# Define other props that won't be used as command line flags
property :debug, [TrueClass, FalseClass], default: false
# Define 'create' action
action :create do
# First iterate over flag_props to create array of flags
flags = []
flag_props.each do |prop|
flag_name = prop[:name].to_s
# Get the compiled value for this property
compiled_val = new_resource.instance_variable_get('@' + flag_name)
# Handle different types by generating different flags
case compiled_val
when TrueClass, FalseClass
if compiled_val == true
flag = '--' + flag_name
end
when String
flag = '--' + flag_name + '=' + compiled_val
end
# Add generated flag to array of flags
flags.push(flag)
end
# # NOTE: you can use this to step into a pry session (does not work in test kitchen)
# require 'pry'; binding.pry
# Convert array of flags to string
flags = flags.join(' ')
# Quick example of using above non-flag property
if new_resource.debug
Chef::Log.warn("Debug output: generated flags: #{flags}")
end
# Do work with the generated flags string
execute 'run my command' do
command "/bin/echo '#{flags}'"
end
end
| true
|
9cd49f8ae62f6e6dad3b50ee1ce522f6a016883a
|
Ruby
|
awanderson8/Pine-Practice
|
/mix1.rb
|
UTF-8
| 334
| 4.1875
| 4
|
[] |
no_license
|
puts "What's your first name?"
name1 = gets.chomp
name1 = name1.downcase.capitalize
puts ""
puts "What's your middle name?"
name2 = gets.chomp
name2 = name2.downcase.capitalize
puts ""
puts "What's your last name?"
name3 = gets.chomp
name3 = name3.downcase.capitalize
puts ""
puts "Hello #{name1} #{name2} #{name3}!"
| true
|
18f2c4722b8afcb0072e1bd8cddc573f88315fd0
|
Ruby
|
mullr/patterns_presentation
|
/observer.rb
|
UTF-8
| 354
| 3.4375
| 3
|
[] |
no_license
|
class AModel
def initialize()
@a = 1
@observers = []
end
def a
@a
end
def a=(val)
@a = val
@observers.each do |observer|
observer.call(val)
end
end
def observe_a_with(proc)
@observers.push(proc)
end
end
test = AModel.new
test.observe_a_with ->(val) { puts "The value of a is #{val}" }
test.a = 42
| true
|
b0e60dc5f1b2a2df5eb47b50e05d9774766f9bee
|
Ruby
|
sunhuachuang/study-demo
|
/ruby/class_methods.rb
|
UTF-8
| 3,871
| 3.609375
| 4
|
[] |
no_license
|
class Dog
attr :name
def speck
puts self.name
end
def initialize name
@name = name
end
end
(Dog.new 'Tom').speck
# puts Dog.new.methods.inspect
class Test
def self.self_method
puts 'self method'
end
def default_method
puts 'default method'
end
def get_default_method
self.default_method
end
def get_default_method_not_self
default_method
end
def get_self_method
# self_method, self.self_method wrong
Test.self_method
end
end
Test.self_method
#Test.new.self_method wrong
#Test.default_method wrong
Test.new.default_method
Test.new.get_default_method
Test.new.get_default_method_not_self
Test.new.get_self_method
#inheritance
class Animals
attr :name, :age
def self.class_method
puts 'this is class method'
end
def Animals.static_method
puts 'this is static method'
end
def breathe
puts 'breathe...'
end
def speck
puts "#{@name} here is super speck"
end
def initialize name, age
@name = name
@age = age + 1
end
end
class Cat < Animals
def speck
#puts (Animals.methods.include? :speck) ? super : 'super no speck'
begin
super
rescue NoMethodError
puts 'super no speck method'
else
puts '-----super ok--------'
end
puts "name is #{@name}, age is #{@age}"
end
def initialize name, age=1
@name = name
@age = age
super #call parent same name method
puts super
end
def fail_say
fail 'I am not say' #TODO fail vs raise
end
end
(Cat.new 'Jerry', 10).speck
(Cat.new 'Jerry').breathe
#(Cat.new 'Jerry').fail_say
Cat.class_method
Cat.static_method
def test
end
puts test.class #TODO test.class vs NilClass 参数接收
class Access
def get_private_method name
puts "name is #{private_method name}"
end
def get_protected_method name
puts "name is #{protected_method name}"
end
def public_method name
puts "--public name: #{name}---"
end
private
def private_method name
"--private name: #{name}---"
end
protected
def protected_method name
"--protected name: #{name}---"
end
end
class AccessChild < Access
end
Access.new.get_private_method 'Tom'
Access.new.get_protected_method 'Tom'
AccessChild.new.get_private_method 'Child'
AccessChild.new.get_protected_method 'Child'
AccessChild.new.public_method 'Child'
#TODO protected vs private
puts '------------------'
a = Access.new
# puts a.protected_method NoMethodError
# singleton method
def a.get_protected_method_out sub
puts sub.protected_method 'out'
end
def a.get_private_method_out sub
puts sub.privated_method 'out'
end
def get_protected_method_out_a a
puts a.protected_method 'out'
end
#get_protected_method_out_a a protected
#同一个类的其他对象可以调用该对象的protected方法
a.get_protected_method_out a
#a.get_private_method_out a NoMethodError
puts '---------------------'
# accessor
class Test
def inspect
'hello this is inspect'
end
def to_s
'this is to_s'
end
end
t = Test.new # irb(main):444:0> t
# => hello this is inspect
puts t #this is to_s
# attr == attr_reader
# attr_reader :v def v; @v; end
# attr_writer :v def v=(value); @v=value; end
# attr_accessor :v attr_reader :v; attr_writer :v
# attr_accessor :v, :w attr_accessor :v; attr_accessor :w
class Test
attr :a
attr_reader :reader
attr_writer :writer
attr_accessor :accessor, :accessor2
# 不支持函数重载, 使用默认参数方式实现
# def test_overload name
# puts name
# end
def test_overload name, age=1
puts name, age
end
end
t = Test.new
t.test_overload 'name'
t.test_overload 'name', 22
a = 'asdafdsasdf\
asdfasdfasdf'
puts a # asdafdsasdf\
# asdfasdfasdf
a = "asdafdsasdf\
asdfasdfasdf"
puts a #asdafdsasdfasdfasdfasdf
a = '
abc
def
ghi
'
puts a
# comments
=begin
this is big comment
=end
| true
|
2a2e4bd1fd2a7145ab2c7e45222ef68940d299c5
|
Ruby
|
renecasco/super_sports_games
|
/lib/event.rb
|
UTF-8
| 629
| 3.625
| 4
|
[] |
no_license
|
class Event
attr_reader :name,
:ages
def initialize(name, ages)
@name = name
@ages = ages
end
def max_age
ages.max(1)
end
def min_age
ages.min(1)
end
def average_age
(ages.sum.to_f / ages.count).round(2)
end
def standard_deviation_age
sum_of_integers = ages.sum
number_of_integers = ages.count
mean = average_age
calculations = ages.map{ |age| (age -= mean) ** 2}
sum_of_calculations = calculations.sum
final_division = sum_of_calculations/number_of_integers
standard_deviation = Math.sqrt(final_division).round(2)
end
end
| true
|
eda4a5b73a0360a282fbcaac5b535033436c5048
|
Ruby
|
robinst/taglib-ruby
|
/docs/taglib/base.rb
|
UTF-8
| 7,911
| 3.078125
| 3
|
[
"MIT",
"LGPL-2.1-only",
"MPL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later"
] |
permissive
|
# This is the top-level module of taglib-ruby.
#
# Where to find what:
#
# * Reading/writing basic tag and audio properties without having to
# know the tagging format: {TagLib::FileRef}
# * Reading properties of MPEG files: {TagLib::MPEG::File}
# * Reading/writing ID3v2 tags: {TagLib::MPEG::File}, {TagLib::RIFF::AIFF::File} and
# {TagLib::ID3v2::Tag}
# * Reading/writing Ogg Vorbis tags: {TagLib::Ogg::Vorbis::File}
# * Reading/writing FLAC tags: {TagLib::FLAC::File}
#
# ## String Encodings
#
# Sometimes, it is necessary to specify which encoding should be used to
# store strings in tags. For this, the following constants are defined:
#
# * `TagLib::String::Latin1`
# * `TagLib::String::UTF16`
# * `TagLib::String::UTF16BE`
# * `TagLib::String::UTF8`
# * `TagLib::String::UTF16LE`
#
# For ID3v2 frames, you can also set a default text encoding globally
# using the {TagLib::ID3v2::FrameFactory}.
#
# ## Modifying attributes
#
# Mutable Ruby types (String, Array) returned by TagLib cannot be modified in-place.
#
# @example Modifying an attribute in-place does not work
# tag.title = 'Title'
# tag.title
# # => "Title"
# tag.title << ' of the song'
# # => "Title of the song"
# tag.title
# # => "Title"
#
# @example You need to replace the existing attribute value
# tag.title = 'Title'
# tag.title
# # => "Title"
# tag.title = 'Title of the song'
# tag.title
# # => "Title of the song"
module TagLib
# Major version of TagLib the extensions were compiled against
# (major.minor.patch). Note that the value is not actually 0, but
# depends on the version of the installed library.
TAGLIB_MAJOR_VERSION = 0
# Minor version of TagLib the extensions were compiled against
# (major.minor.patch). Note that the value is not actually 0, but
# depends on the version of the installed library.
TAGLIB_MINOR_VERSION = 0
# Patch version of TagLib the extensions were compiled against
# (major.minor.patch). Note that the value is not actually 0, but
# depends on the version of the installed library.
TAGLIB_PATCH_VERSION = 0
# This class allows to read basic tagging and audio properties from
# files, without having to know what the file type is. Thus, it works
# for all tagging formats that taglib supports, but only provides a
# minimal API.
#
# Should you need more, use the file type specific classes, see
# subclasses of {TagLib::File}.
#
# @example Reading tags
# TagLib::FileRef.open("foo.flac") do |file|
# unless file.null?
# tag = file.tag
# puts tag.artist
# puts tag.title
# end
# end
#
# @example Reading audio properties
# TagLib::FileRef.open("bar.oga") do |file|
# unless file.null?
# prop = file.audio_properties
# puts prop.length
# puts prop.bitrate
# end
# end
#
class FileRef
# Creates a new file and passes it to the provided block,
# closing the file automatically at the end of the block.
#
# Note that after the block is done, the file is closed and
# all memory is released for objects read from the file
# (basically everything from the `TagLib` namespace).
#
# Using `open` is preferable to using `new` and then
# manually `close`.
#
# @example Reading a title
# title = TagLib::FileRef.open("file.oga") do |file|
# tag = file.tag
# tag.title
# end
#
# @param (see #initialize)
# @yield [file] the {FileRef} object, as obtained by {#initialize}
# @return the return value of the block
#
# @since 0.4.0
def self.open(filename, read_audio_properties=true,
audio_properties_style=TagLib::AudioProperties::Average)
end
# Create a FileRef from a file name.
#
# @param [String] filename
# @param [Boolean] read_audio_properties
# true if audio properties should be read
# @param [TagLib::AudioProperties constants] audio_properties_style
# how accurately the audio properties should be read, e.g.
# {TagLib::AudioProperties::Average}
def initialize(filename, read_audio_properties=true,
audio_properties_style=TagLib::AudioProperties::Average)
end
# Gets the audio properties. Before accessing it, check if there
# were problems reading the file using {#null?}. If the audio
# properties are accessed anyway, a warning will be printed and it
# will return nil.
#
# @return [TagLib::AudioProperties] the audio properties
def audio_properties
end
# @return [Boolean] if the file is null (i.e. it could not be read)
def null?
end
# Saves the file
#
# @return [Boolean] whether saving was successful
def save
end
# Gets the tag. Before accessing it, check if there were problems
# reading the file using {#null?}. If the tag is accessed anyway, a
# warning will be printed and it will return nil.
#
# @return [TagLib::Tag] the tag, or nil
def tag
end
# Closes the file and releases all objects that were read from the
# file.
#
# @see TagLib::File#close
#
# @return [void]
def close
end
end
# @abstract Base class for files, see subclasses.
class File
# Save the file and the associated tags.
#
# See subclasses, as some provide more control over what is saved.
#
# @return [Boolean] whether saving was successful
def save
end
# Closes the file and releases all objects that were read from the
# file (basically everything from the TagLib namespace).
#
# After this method has been called, no other methods on this object
# may be called. So it's a good idea to always use it like this:
#
# file = TagLib::MPEG::File.new("file.mp3")
# # ...
# file.close
# file = nil
#
# This method should always be called as soon as you're finished
# with a file. Otherwise the file will only be closed when GC is
# run, which may be much later. On Windows, this is especially
# important as the file is locked until it is closed.
#
# As a better alternative to this, use the `open` class method:
#
# TagLib::MPEG::File.open("file.mp3") do |file|
# # ...
# end
#
# @return [void]
def close
end
end
# @abstract Base class for tags.
#
# This is a unified view which provides basic tag information, which
# is common in all tag formats. See subclasses for functionality that
# goes beyond this interface.
class Tag
# @return [String] the album
# @return [nil] if not present
attr_accessor :album
# @return [String] the artist/interpret
# @return [nil] if not present
attr_accessor :artist
# @return [String] the comment
# @return [nil] if not present
attr_accessor :comment
# @return [String] the genre
# @return [nil] if not present
attr_accessor :genre
# @return [String] the title
# @return [nil] if not present
attr_accessor :title
# @return [Integer] the track number
# @return [0] if not present
attr_accessor :track
# @return [Integer] the year
# @return [0] if not present
attr_accessor :year
# @return [Boolean]
def empty?; end
end
# @abstract Base class for audio properties.
class AudioProperties
Fast = 0
Average = 1
Accurate = 2
# @return [Integer] length of the file in seconds
#
# @since 1.0.0
attr_reader :length_in_seconds
# @return [Integer] length of the file in milliseconds
#
# @since 1.0.0
attr_reader :length_in_milliseconds
# @return [Integer] bit rate in kb/s (kilobit per second)
attr_reader :bitrate
# @return [Integer] sample rate in Hz
attr_reader :sample_rate
# @return [Integer] number of channels
attr_reader :channels
end
end
| true
|
fb1a5796603f1f8800ff77e296ee3320f2e9e37b
|
Ruby
|
maxcyp/intro_to_programming
|
/8_hashes/8_3.rb
|
UTF-8
| 181
| 3.046875
| 3
|
[] |
no_license
|
family = { uncles: "bob", sisters: "jane", brothers: "rob", aunts: "sally" }
family.each_key { |i| puts i}
family.each_value { |i| puts i }
family.each {|x, y| puts "#{x}: #{y}"}
| true
|
f69b3804b99f258ed709d6893db4fd1fcc5cbb05
|
Ruby
|
chaoshades/rmvx-ebjb-core
|
/src/Misc Objects/ItemFilter.rb
|
UTF-8
| 3,394
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
#==============================================================================
# ** ItemFilter
#------------------------------------------------------------------------------
# Represents an Item filter
#==============================================================================
class ItemFilter < UsableItemFilter
#//////////////////////////////////////////////////////////////////////////
# * Public Methods
#//////////////////////////////////////////////////////////////////////////
#--------------------------------------------------------------------------
# * Apply method
# x : object to filter
#--------------------------------------------------------------------------
alias apply_baseItemFilter_ebjb apply unless $@
def apply(x)
if x != nil && x.is_a?(RPG::Item)
case mode
when "healing"
return applyHealing(x)
when "support"
return applySupport(x)
when "growth"
return applyGrowth(x)
when "attack"
return applyAttack(x)
#when
#...
else
return apply_baseItemFilter_ebjb(x)
end
else
return nil
end
end
#//////////////////////////////////////////////////////////////////////////
# * Private Methods
#//////////////////////////////////////////////////////////////////////////
#--------------------------------------------------------------------------
# * Apply method (using the hp/mp_recovery, hp/mp_recovery_rate property)
# x : object to filter
#--------------------------------------------------------------------------
def applyHealing(x)
if (x.base_damage < 0 ||
x.hp_recovery > 0 || x.hp_recovery_rate > 0 ||
x.mp_recovery > 0 || x.mp_recovery_rate > 0) == @value
return true
else
return false
end
end
private:applyHealing
#--------------------------------------------------------------------------
# * Apply method (using the minus/plus_state_set, hp/mp_recovery,
# hp/mp_recovery_rate property)
# x : object to filter
#--------------------------------------------------------------------------
def applySupport(x)
if ((x.minus_state_set.length > 0 || x.plus_state_set.length > 0) &&
x.base_damage == 0 &&
x.hp_recovery == 0 && x.hp_recovery_rate == 0 &&
x.mp_recovery == 0 && x.mp_recovery_rate == 0) == @value
return true
else
return false
end
end
private:applySupport
#--------------------------------------------------------------------------
# * Apply method (using the parameter_type property)
# x : object to filter
#--------------------------------------------------------------------------
def applyGrowth(x)
if (x.parameter_type != 0) == @value
return true
else
return false
end
end
private:applyGrowth
#--------------------------------------------------------------------------
# * Apply method (using the applyHealing && applySupport methods)
# x : object to filter
#--------------------------------------------------------------------------
def applyAttack(x)
if (applyHealing(x) == !@value && applySupport(x) == !@value &&
applyGrowth(x) == !@value)
return true
else
return false
end
end
private:applyAttack
end
| true
|
c6d07396bd7413d7c3bfe002c71b5bbdf5d61547
|
Ruby
|
UpAndAtThem/practice_kata
|
/battleship.rb
|
UTF-8
| 719
| 2.859375
| 3
|
[] |
no_license
|
# -create 9*9 board
# -create ships
# -have player 1 place ships
# -each ship should prompt an up down left or right option. and check to see if valid
# -whatever direction take ship.length -1 to auto place the ship (so a 4 ship the player doesn't have to choose 4 positions, just the start and direction)
# -have player 2 place ships
# -whatever direction take ship.length -1 to auto place the ship (so a 4 ship the player doesn't have to choose 4 positions, just the start and direction)
# -take turns attacking until all ships sections of one player are selected
# -player 1 attacks with a a2, g8, etc selection a-i and 1-9
# -player 2 attacks with a a2, g8, etc selection a-i and 1-9
# -declare winner
| true
|
16ee7fe5b38bce821ad53c118551b8a3a7ba39e6
|
Ruby
|
lasanders/site-deals-cli-app
|
/site_deals/lib/site_deals/deals.rb
|
UTF-8
| 791
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
require 'pry'
class SiteDeals::Deals
attr_accessor :name, :price, :availability, :url, :title
@@deals = []
def initialize(name = nil, title = nil, price = nil, url = nil)
@name = name
@price = price
@url = url
@title = title
#binding.pry
@@deals << self
end
def self.today
self.scrape_deals
end
def self.scrape_deals
@@deals << self.scrape_revolve
end
def self.scrape_revolve
doc = Nokogiri::HTML(open("http://www.revolve.com/new/all-new-items/br/7f5946/?navsrc=subnew_i1"))
info = doc.css("div.container .js-plp-container").each do |info|
self.new(info.css("div.js-plp-brand").text, info.css("div.js-plp-name").text, info.css("a span.plp_price").text, info.css("a img.js-plp-image").attr("src").value)
end
end
end
| true
|
b36cea530e38afb6fe26cb162602d5e8a2a176db
|
Ruby
|
xenda/juanfanning
|
/parser.rb
|
UTF-8
| 737
| 2.84375
| 3
|
[] |
no_license
|
require 'rubygems'
require 'nokogiri'
require 'open-uri'
URL = "http://elcomercio.pe/cine/cartelera"
doc = Nokogiri::HTML(open(URL))
cinemas = doc.css("#cine option").map {|cinema| {:id => cinema.attributes["value"], :title => cinema.content } }
cinemas.shift
# We transverse the array creating first a movie chain and then a theatre. The movie chain
movies = doc.css("#pelicula option").map {|movie| {:id => movie.attributes["value"], :title => movie.content } }
movies.shift
#=> Elija la película
#=> Ámame o muérete
#=> La leyenda de los guardianes
#=> Agente Salt
#=> Presencias extrañas
#=> Personalidad múltiple
#=> El regreso de la nana mágica
#=> Resident Evil 4: La resurrección
#=> Tinker Bell: Hadas al rescate
| true
|
7c5dd454959b272f63cc2777d1de1331340d1d76
|
Ruby
|
kruegsw/LaunchSchool-RB100
|
/learn_to_program_chris_pine/proc_practice.rb
|
UTF-8
| 219
| 3.265625
| 3
|
[] |
no_license
|
new_proc = Proc.new do |variable|
puts "call the proc #{variable}"
end
new_proc.call
new_proc.call("test")
def method_with_proc(proc_input)
proc_input.call
proc_input.call("test")
end
method_with_proc(new_proc)
| true
|
6ede6cdcd542239fc8c1192f2cf173e7d5d68087
|
Ruby
|
totechite/Learning_parser_with_Ruby
|
/lib/multi/LookaheadParser.rb
|
UTF-8
| 719
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
class LookaheadParser < Parser
def initialize(input)
super(input)
end
def list
match(ListLexer.L_BRACKET)
elements
match(ListLexer.R_BRACKET)
end
def elements
element
while @lookahead.type == ListLexer.COMMA
match(ListLexer.COMMA)
element
end
end
def element
if LA(1)==LookaheadLexer.NAME && LA(2)==LookaheadLexer.EQUALS
match(LookaheadLexer.NAME)
match(LookaheadLexer.EQUALS)
match(LookaheadLexer.NAME)
elsif LA(1)==LookaheadLexer.NAME
match(LookaheadLexer.NAME)
elsif LA(1)==LookaheadLexer.L_BRACKET
list()
else
raise RuntimeError
end
end
end
| true
|
992b9605305489cb8b04cdbd30173d73aaaa37ff
|
Ruby
|
guillermo/ubuntu_amis
|
/lib/ubuntu_amis.rb
|
UTF-8
| 661
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require "ubuntu_amis/version"
require 'yaml'
require 'net/http'
require 'uri'
module UbuntuAmis
URL="http://cloud-images.ubuntu.com/locator/ec2/releasesTable"
def self.table
fix_table(parse(fix_string(get(uri)))["aaData"])
end
def self.uri
URI(URL).tap { |uri|
uri.query = Time.now.to_i.to_s
}
end
def self.get(uri)
Net::HTTP.get_response(uri).body
end
def self.fix_string(data)
data.reverse.sub(',','').reverse
end
def self.fix_table(table)
table.each_with_index{|row,index|
table[index][6] = row[6][/(ami-[\da-f]{8})/,1]
}
table
end
def self.parse(json)
YAML.load(json)
end
end
| true
|
578b511dd8e38d1d5a5a19f795e4c101325acd0c
|
Ruby
|
GaryZhangUIUC/LocationProfiling
|
/lib/tweet.rb
|
UTF-8
| 906
| 3.015625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require_relative "./tweet_words"
include TweetWords
class Tweet
attr_reader :t_id
attr_reader :u_id
attr_reader :created_at
attr_reader :gps
attr_reader :text
attr_reader :weighted_keywords
attr_reader :keyword_size
def initialize(t_id, u_id, text, gps, created_at)
@t_id = t_id
@u_id = u_id
@created_at = created_at
@gps = gps
@text = text
@weighted_keywords = nil
@keyword_size = nil
generate_keywords()
end
def generate_keywords()
keywords = TweetWords.clean_up(@text)
@weighted_keywords = {}
@keyword_size = 0
keywords.each do |keyword|
if @weighted_keywords.has_key?(keyword)
@keyword_size += 2 * @weighted_keywords[keyword] + 1
@weighted_keywords[keyword] += 1
else
@keyword_size += 1
@weighted_keywords[keyword] = 1
end
end
@keyword_size **= 0.5
end
end
| true
|
22311d1605b576ebc8f4e911f07481c4cc080632
|
Ruby
|
Ger-onimo/multi_class_hw_bears-rivers-fish
|
/river.rb
|
UTF-8
| 501
| 3.46875
| 3
|
[] |
no_license
|
class River
attr_reader :riv_name, :fish_stock
def initialize(riv_name)
# def intializie(riv_name, fish_num)
@riv_name = riv_name
@fish_stock = []
#@fish_num = fish_num for fish count
end
def fish_in_river() #array of fish in river (not sure this is required)
return @fish_stock.length()
end
def add_to_fish_stock(fish)
@fish_stock << fish
end
def remove_fish()
@fish_stock.shift() #explore other options
end
end
| true
|
da87e1a936cbb3e0b0c3348970f20a2ba1bed26c
|
Ruby
|
alexandre025/Twithetic
|
/app/helpers/post_helper.rb
|
UTF-8
| 946
| 2.71875
| 3
|
[] |
no_license
|
module PostHelper
def parse_tweet(message)
hashtags = message.scan(/(#\w+)/).flatten
mentions = message.scan(/(@\w+)/).flatten
return message if hashtags.size == 0 && mentions.size == 0
message = detect_hashtags message if hashtags.size > 0
message = detect_mention message if mentions.size > 0
return message.html_safe
end
def detect_hashtags(message)
linked_message = message.gsub(/\B[#]\S+\b/) do |hash|
tag = hash.tr('#', '')
stored_hashtag = Hashtag.find_by(name: tag)
link_to(hash, hashtag_path(hashtag: stored_hashtag.name)) if stored_hashtag.present?
end
return linked_message
end
def detect_mention(message)
linked_message = message.gsub(/\B[@]\S+\b/) do |mention|
user = mention.tr('@', '')
stored_user = User.find_by(username: user)
link_to(mention, user_path(stored_user)) if stored_user.present?
end
return linked_message
end
end
| true
|
0c7b236d3694b283f1fb89f891edbeed09ef5ffb
|
Ruby
|
joaomarceloods/rails2docker
|
/test/models/product_test.rb
|
UTF-8
| 367
| 2.53125
| 3
|
[] |
no_license
|
require 'test_helper'
class ProductTest < ActiveSupport::TestCase
test "name can't be blank" do
p = Product.new(name: nil).tap(&:validate)
assert_includes p.errors[:name], "can't be blank"
end
test "price must be greater than 0" do
p = Product.new(price: 0).tap(&:validate)
assert_includes p.errors[:price], "must be greater than 0"
end
end
| true
|
7b69b8ec866a87cbafc8c8581a8f20d85bf71c4f
|
Ruby
|
Carter-A/coffee-code
|
/longest_word.rb
|
UTF-8
| 243
| 3.5625
| 4
|
[] |
no_license
|
def find_longest(array)
output = ""
longest = 0
array.each do |word|
if word.length > longest
output = word
longest = word.length
end
end
output
end
animals = %w(cow elephant sheep)
print find_longest(animals)
| true
|
2358e1349debdb4932f75b83568041aeed169719
|
Ruby
|
hybridgroup/taskmapper-cli
|
/lib/tm/string_extensions.rb
|
UTF-8
| 234
| 2.515625
| 3
|
[] |
no_license
|
module TM
module StringExtensions
def to_hash
return '' if self.nil?
self.split(/,/).inject({}) do |hash, kv|
arg, val = kv.split(/:/)
hash[arg.to_sym] = val
hash
end
end
end
end
| true
|
82994284e4705efee11f35254426dee6331f8913
|
Ruby
|
jkeck/dotfiles
|
/bin/with-notify
|
UTF-8
| 946
| 2.953125
| 3
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#!/usr/bin/ruby
class WithNotify
attr_reader :command
def initialize(args = ARGV)
@command = args.join(' ')
end
def self.run
new.run
end
def run
puts "Running \"#{command}\" with notifications..."
run_command
if $?.exitstatus.zero?
`#{notify_command('Command Successful!')}`
else
`#{notify_command('Command Failed!')}`
end
end
private
def run_command
IO.popen(command) do |io|
while (line = io.gets)
puts line
end
end
rescue => error
puts error
end
def notify_command(title)
"#{executable} #{flags.join(' ')} '#{script_command} \"#{command} #{from_dir}\" with title \"#{title}\"'"
end
def from_dir
dir = `pwd`.chomp.scan(%r{.*\/(.*)$}).flatten.first
"(from \\\"#{dir}\\\")"
end
def script_command
'display notification'
end
def flags
['-e']
end
def executable
'osascript'
end
end
WithNotify.run
| true
|
fbf71bdfb1be19800f128c1d50406aac6f68bd52
|
Ruby
|
JaredTan/AppAcademy
|
/Week2/W2D3 - RSPEC/lib/first_tdd.rb
|
UTF-8
| 984
| 3.296875
| 3
|
[] |
no_license
|
class Array
def my_uniq
result = []
self.each do |el|
result << el unless result.include?(el)
end
result
end
def two_sum
pair = []
(0...self.length - 1).each do |idx1|
(idx1 + 1...self.length).each do |idx2|
pair << [idx1, idx2] if self[idx1] + self[idx2] == 0
end
end
pair
end
def my_transpose
new_arr = []
self.each_index do |idx1|
sub_arr = []
(0...self.length).each do |idx2|
sub_arr << self[idx2][idx1]
end
new_arr << sub_arr
end
new_arr
end
def stock_picker
return [] if self.length < 2
current_profit = self[1] - self[0]
results_pair = [0, 1]
self.each_index do |idx1|
(idx1 + 1...self.length).each do |idx2|
current_profit = self[results_pair[1]] - self[results_pair[0]]
if self[idx2] - self[idx1] > current_profit
results_pair = [idx1, idx2]
end
end
end
results_pair
end
end
| true
|
687f5a39ac6a7a1387edb4d4fa77456f297b0fa2
|
Ruby
|
civol/HDLRuby
|
/lib/HDLRuby/high_samples/all_signals.rb
|
UTF-8
| 536
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
require 'HDLRuby'
configure_high
# A simple 16-bit adder
system :adder do
[15..0].input :x,:y
[16..0].output :s
s <= x + y
cur_system.open do
puts "Inputs: ", cur_system.get_all_inputs
puts "Outputs: ", cur_system.get_all_outputs
puts "InOuts: ", cur_system.get_all_inouts
puts "Signals: ", cur_system.get_all_signals
end
end
# Instantiate it for checking.
adder :adderI
#
# # Generate the low level representation.
# low = adderI.to_low
#
# # Displays it
# puts low.to_yaml
| true
|
252fc8ade891d02e0d2bd991d9c198635b79ebe4
|
Ruby
|
tiy-hou-q3-2015-rails/api_examples
|
/stocks/db/seeds.rb
|
UTF-8
| 1,286
| 2.5625
| 3
|
[] |
no_license
|
jwo = User.create email: "jesse@comal.io", password: "12345678"
bwo = User.create email: "brian@comal.io", password: "12345678"
#["ABC", "BMW", "IBM", "XOM"]
google = Company.create! name: "Alphabet", ticker_symbol: "GOOG", last_price: 500
bmw = Company.create! name: "BMW", ticker_symbol: "BMW", last_price: 100
ibm = Company.create! name: "IBM", ticker_symbol: "IBM", last_price: 60
exxon = Company.create! name: "ExxonMobil", ticker_symbol: "XOM", last_price: 125
Company.all.each do |company|
# 50.times do
# # new_stock_price = company.last_price * rand(0.95..1.05)
# # company.sales.create quantity: 5000, price: new_stock_price
# # company.update last_price: new_stock_price
# end
jwo.portfolios.create company: company, quantity: 500
bwo.portfolios.create company: company, quantity: 500
bwo.bids.create company: company, quantity: 500, price: company.last_price * rand(0.95..1.05)
# google_bid = jwo.bids.create company: google, quantity: 500, price: 400
# Sale.create! user: bwo, bid: google_bid, quantity: 500, price: 400
# company.update last_price: 500
# # transfer to bwo from jwo
# jwo_google_holdings = jwo.portfolios.find_by company_id: google.id
# jwo_google_holdings.destroy
# bwo.portfolios.create company: google, quantity: 500
end
| true
|
1212efdba927c311ea538b8730b8fb6a76cfbb82
|
Ruby
|
rlavang/launch-school
|
/101-programming-foundations/small_problems_retry/easy_8_3.rb
|
UTF-8
| 314
| 3.515625
| 4
|
[] |
no_license
|
def substrings_at_start(string)
substrings = []
1.upto(string.length) do |length|
substrings << string.slice(0, length)
end
substrings.sort
end
p substrings_at_start('abc') == ['a', 'ab', 'abc']
p substrings_at_start('a') == ['a']
p substrings_at_start('xyzzy') == ['x', 'xy', 'xyz', 'xyzz', 'xyzzy']
| true
|
d19574b6dbe9961849e9fc3d1b48ddf045e9af17
|
Ruby
|
wengzilla/recurse_center
|
/hacker_rank/20160707_cells/grid.rb
|
UTF-8
| 1,077
| 3.828125
| 4
|
[] |
no_license
|
class Grid
attr_accessor :grid, :num_rows, :num_cols
def initialize(grid, num_rows, num_cols)
@grid = grid
@num_rows = num_rows
@num_cols = num_cols
end
def one_cells
grid.map.with_index { |cell, idx| cell == "1" ? idx : nil }.compact
end
def neighboring_cells(cell)
neighbors = []
unless is_top?(cell)
neighbors << cell - num_cols - 1 unless is_left?(cell)
neighbors << cell - num_cols
neighbors << cell - num_cols + 1 unless is_right?(cell)
end
neighbors << cell - 1 unless is_left?(cell)
neighbors << cell + 1 unless is_right?(cell)
unless is_bottom?(cell)
neighbors << cell + num_cols - 1 unless is_left?(cell)
neighbors << cell + num_cols
neighbors << cell + num_cols + 1 unless is_right?(cell)
end
neighbors
end
private
def is_top?(cell)
cell / num_cols == 0
end
def is_left?(cell)
cell % num_cols == 0
end
def is_bottom?(cell)
cell / num_cols == num_rows - 1
end
def is_right?(cell)
cell % num_cols == num_cols - 1
end
end
| true
|
03cf30a43a3de5d0bcf32e3ba9d54cb930f2ad1f
|
Ruby
|
donjar/ctf-solutions
|
/cryptopals/1/4.rb
|
UTF-8
| 461
| 3.171875
| 3
|
[] |
no_license
|
frequent = %w(a n i h o r t e s A N I H O R T E S)
File.read('4.txt').split("\n").each_with_index do |encrypted, idx|
puts "=== LINE #{idx} ==="
res = 128.times.map do |key|
total = 0
decrypted = encrypted.scan(/../).map do |part|
res_char = (part.to_i(16) ^ key).chr
total += 1 if frequent.include? res_char
res_char
end.join
[decrypted, total]
end.sort { |f, s| f[1] - s[1] }.select { |p| p[1] >= 15 }
puts res
end
| true
|
ac80b6da75dcdcb56695bc42a6ee661a634c4816
|
Ruby
|
cha63506/heap_dump
|
/lib/heap_dump/histogram.rb
|
UTF-8
| 1,721
| 3.078125
| 3
|
[] |
no_license
|
module Rubinius
module HeapDump
class Histogram
class Entry
def initialize(klass, objects=0, bytes=0)
@klass = klass
@objects = objects
@bytes = bytes
end
attr_reader :objects, :bytes
def inc(object)
@objects += 1
@bytes += object.bytes
end
def <=>(other)
@objects <=> other.objects
end
def -(other)
objects = @objects - other.objects
bytes = @bytes - other.bytes
Entry.new(@klass, objects, bytes)
end
end
def initialize(data)
@data = data
end
def self.by_class(objects)
histogram = Hash.new { |h,k| h[k] = Entry.new(k) }
objects.each do |o|
klass = o.class_object
if klass.name
histogram[klass].inc(o)
end
end
return Histogram.new(histogram)
end
def self.by_class_name(objects)
histogram = Hash.new { |h,k| h[k] = Entry.new(k) }
objects.each do |o|
klass = o.class_object
if n = klass.name
histogram[n].inc(o)
end
end
return Histogram.new(histogram)
end
def [](cls)
@data[cls]
end
def to_text
each_sorted do |klass, entry|
puts "%10d %s (%d bytes)" % [entry.objects, klass.name, entry.bytes]
end
end
def each
@data.each do |k,e|
yield k, e
end
end
def each_sorted
sorted = @data.to_a.sort_by { |x| x[1] }
sorted.reverse_each do |klass, entry|
yield klass, entry
end
end
end
end
end
| true
|
45f71daa610d72e8f5b8ca1ccdc4b775cdc9f462
|
Ruby
|
dillon-m/mined_minds_kata
|
/exercise5.rb
|
UTF-8
| 152
| 3.484375
| 3
|
[] |
no_license
|
(1..100).each do|n|
if n % 15 == 0
puts 'Minded Minds'
elsif n % 3 == 0
puts 'Mined'
elsif n % 5 == 0
puts 'Minds'
else
puts n
end
end
| true
|
6435b36d55e98c7302707c2ea93e2d623ad3dd60
|
Ruby
|
JelF/papp
|
/lib/papp/logger.rb
|
UTF-8
| 870
| 2.96875
| 3
|
[] |
no_license
|
module PApp
# Defines a simple logger
class Logger
LEVELS = {
1 => :error,
2 => :warn,
3 => :info,
4 => :debug,
}
attr_accessor :verbosity, :output
LEVELS.each do |v, level|
define_method(level) do |*args|
log!(v, *args) if v <= verbosity
end
end
def initialize(output, verbosity)
self.verbosity = if verbosity.is_a?(Numeric)
verbosity
else
LEVELS.invert[verbosity]
end
self.output = output.respond_to?(:puts) ? output : File.open(output, 'w')
end
def log!(v, *args)
args = args.flat_map { |x| x.to_s.split("\n") }
header = "--- #{LEVELS[v].to_s.upcase} #{Time.now}"
args.each do |arg|
output.puts("#{header}: #{arg}")
end
end
end
end
| true
|
a8ccc0904e61134c95654503a408ba774ad07843
|
Ruby
|
hatsu38/atcoder-ruby
|
/edpc/a.rb
|
UTF-8
| 660
| 3.296875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
### 例
# N
# a_1 b_1
# ...
# a_N b_N
# h,w = gets.chomp.split(' ').map(&:to_i)
# strs = h.times.map{ gets.chomp.split('') }
# input
# 6
# 30 10 60 10 60 50
# output
# 40
n = gets.to_i
strs = gets.chomp.split.map(&:to_i)
# dp = [0, (strs[0]-strs[1]).abs]
# [*2..(n-1)].each do |i|
# dp << [dp[i-2] + (strs[i-2]-strs[i]).abs, dp[i-1] + (strs[i-1]-strs[i]).abs].min
# end
# puts dp[-1]
dp = Array.new(n, 0)
dp[0] = 0
dp[1] = (strs[1] - strs[0]).abs
[*2..(n - 1)].each do |i|
pre_a = dp[i - 1] + (strs[i] - strs[i - 1]).abs
pre_b = dp[i - 2] + (strs[i] - strs[i - 2]).abs
dp[i] = [pre_a, pre_b].min
end
puts dp[n - 1]
| true
|
cf8e6d54474172b77edfb409ff6c0c93b7e115f0
|
Ruby
|
CamillaCdC/seic38-homework
|
/Ryan Bullough/week04/Friday/main.rb
|
UTF-8
| 1,379
| 2.578125
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
require 'pry'
get '/' do
erb :home
end
# NEW
get '/doughnuts/new' do
erb :doughnuts_new
end
# CREATE
post '/doughnuts' do
query = "INSERT INTO doughnuts (name, type, shape, image) VALUES ('#{params["name"]}', '#{params["type"]}', '#{params["shape"]}', '#{params["image"]}')"
query_db query
redirect to('/index')
end
# INDEX
get '/index' do
@doughnuts = query_db 'SELECT * FROM doughnuts'
erb :doughnuts_index
end
# EDIT
get '/doughnuts/:id/edit' do
@doughnut = query_db("SELECT * FROM doughnuts WHERE id=' #{ params["id"] }'").first
erb :doughnuts_edit
end
# UPDATE
post '/doughnuts/:id' do
query = "UPDATE doughnuts SET name= '#{params[:name]}', type= '#{ params[:type] }', shape= '#{ params[:shape] }', image = '#{ params[:image] }' WHERE id=#{ params[:id] }"
query_db query
redirect to("/doughnuts/#{ params[:id] }")
end
# DISPLAY
get '/doughnuts/:id' do
@doughnut = query_db("SELECT * FROM doughnuts WHERE id='#{ params["id"] }'").first
erb :doughnuts_show
end
# DESTROY
get '/doughnuts/:id/delete' do
query_db "DELETE FROM doughnuts WHERE id='#{params[:id]}'"
redirect to('/index')
end
def query_db sql_statement
puts sql_statement
db = SQLite3::Database.new 'database.sqlite3'
db.results_as_hash = true
result = db.execute sql_statement
db.close
result
end
| true
|
ecb0d6470a101210c80f9206eb763f484e66d9c7
|
Ruby
|
paulghaddad/57_exercises_ruby
|
/exercise_11/euro_to_dollar_converter.rb
|
UTF-8
| 283
| 3.4375
| 3
|
[] |
no_license
|
class EuroToDollarConverter
attr_reader :euros, :exchange_rate
CENTS_PER_DOLLAR = 100
def initialize(euros:, exchange_rate:)
@euros = euros
@exchange_rate = exchange_rate
end
def euros_to_dollars
(euros * exchange_rate / CENTS_PER_DOLLAR).round(2)
end
end
| true
|
7689df850a6033bd931124edc7ac5602e20ffdd2
|
Ruby
|
stevehanson/tictactoe
|
/tictactoe.rb
|
UTF-8
| 1,745
| 4.375
| 4
|
[] |
no_license
|
# add win strategy
class Board
attr_reader :row_count, :col_count
def initialize(rows, columns)
@row_count = rows
@col_count = columns
@board = Array.new(rows) {
Array.new(columns) { ' ' }
}
end
def update(row, column, value)
@board[row][column] = value
end
def rows
@board
end
def cols
@board.transpose
end
def get(row, col)
@board[row][col]
end
def to_s
s = ''
@board.each do |row|
s += row.join(' ') + "\n"
end
s
end
end
class RegularWinStrategy
attr_reader :winner
def has_winner(board)
return rows_winner?(board) || cols_winner?(board)
end
def rows_winner?(board)
all_equal_in_group?(board.rows)
end
def cols_winner?(board)
all_equal_in_group?(board.cols)
end
def all_equal_in_group?(groups)
groups.each do |group|
if(group[0] != ' ' and group.uniq.length == 1) then
@winner = group[0]
return true
end
end
false
end
end
class MiddleWinStrategy
attr_reader :winner
def has_winner(board)
middle_val = board.get(board.row_count/2, board.col_count/2)
if(!middle_val.strip.empty?) then
@winner = middle_val
return true
end
return false
end
end
class TicTacToe
def initialize(board, win_strategy)
@board = board
@current_player = 'x'
@win_strategy = win_strategy
end
def play_turn(row, column)
@board.update(row, column, @current_player)
puts @board.to_s
check_winner
toggle_player
end
def check_winner
if(@win_strategy.has_winner(@board)) then
puts @win_strategy.winner + ' wins!!'
end
end
def toggle_player
@current_player = (@current_player=='x') ? 'o' : 'x'
end
end
| true
|
10bf3771d8049cf30ecdb4d4f3cf3248a14af9ee
|
Ruby
|
asandler/mipt
|
/code/algorithms_oop/semester_4/z_function.rb
|
UTF-8
| 609
| 3.296875
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
def zf s
z = [1]
l, r = 0, 0
(1..s.length - 1).each do |i|
if (l..r).include? i
j = i - l
if i + z[j] <= r
z << z[j]
else
t = r
while t < s.length and s[t] == s[t - i]
t += 1
end
z << t - l
l, r = i, t - 1
end
else
t = 0
while t < s.length and s[t] == s[i + t]
t += 1
end
z << t
end
end
z
end
p zf("aaaaaaaaaaaaa")
| true
|
15f5a34c4e31a7a2afa855b9286c65d4a1daec7a
|
Ruby
|
blackhatflow/blog
|
/montecarlo.rb
|
UTF-8
| 347
| 3.59375
| 4
|
[] |
no_license
|
flip = rand 2
if flip == 0
puts "face"
else
puts "pile"
end
i = 0
pile = 0
face = 0
while i < 1
flip = rand 2
if flip == 0
puts "face"
face +=1
else
puts "pile"
pile +=1
end
i += 1
end
puts "on a fait pile #{pile} fois"
puts "on a fait face #{face} fois"
chance = (pile * 100) / i
puts "chance are #{chance} % "
| true
|
ba30af3dbdc603b20728ba2f2ff77b9e7875c4ef
|
Ruby
|
maxipombo/rbnd-toycity-part4
|
/lib/find_by.rb
|
UTF-8
| 409
| 2.78125
| 3
|
[] |
no_license
|
class Module
def create_finder_methods(*attributes)
# Your code goes here!
# Hint: Remember attr_reader and class_eval
attributes.each do |attribute|
finder_methods = %Q{
def self.find_by_#{attribute}(#{attribute})
all.find do |product|
product.#{attribute} == #{attribute}
end
end
}
class_eval(finder_methods)
end
end
end
| true
|
261e98f44768a04cfb75c5ff1c7c5fb3818d2cce
|
Ruby
|
kromitj/bit-counter
|
/lib/assets/byte_counter/and.rb
|
UTF-8
| 569
| 3.53125
| 4
|
[] |
no_license
|
class And
attr_reader :input_a, :input_b
@@logicTable = [
{ inputA: 0, inputB: 0, output: 0},
{ inputA: 1, inputB: 0, output: 0},
{ inputA: 0, inputB: 1, output: 0},
{ inputA: 1, inputB: 1, output: 1}
]
def initialize(input_a, input_b)
@input_a = input_a
@input_b = input_b
@output = self.output
end
defoutput
@output = current_state
end
private
def current_state
out = @@logicTable.find do |row|
(@input_a == row[:inputA]) && (@input_b == row[:inputB])
end
out[:output]
end
end
| true
|
41e68a04fd1ac2114a56631bcf83011062670705
|
Ruby
|
hoodielive/ruby
|
/old/ruby_core/JSON/json.rb
|
UTF-8
| 328
| 2.953125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
#
# JSON
#
require "json"
json_string = '{"name": "Larry", "location": "Pittsburgh", "year": 2018}'
hash = JSON.parse(json_string)
puts hash
puts hash['name']
my_hash = { name: "Lawrence", email: "larrylawrencehamburger@blah.blah" }
puts JSON.dump(my_hash)
puts from_file_json = JSON.load( File.new("./example.json") )
| true
|
9174faa81306253cfcdf4da46bf37dd276eb1322
|
Ruby
|
zapalagrzegorz/chess
|
/pieces/queen.rb
|
UTF-8
| 321
| 2.96875
| 3
|
[] |
no_license
|
require_relative "slideable"
require_relative "piece"
class Queen < Piece
include Slideable
DIRECTION = [:STRAIGHT, :DIAGONAL].freeze
def initialize(color, board, position)
super(color, board, position)
end
def symbol
"♛".colorize(color)
end
protected
def move_dirs
DIRECTION
end
end
| true
|
3301209da95fed9184d264ff03b73b558e0e961a
|
Ruby
|
nkn0t/myrubyutils
|
/utils/active_class_generator.rb
|
UTF-8
| 1,306
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
# instanceのフィールドにハッシュを用いて動的にフィールドを定義する.
# key => フィールド名
# value => フィールドの値
# ハッシュが入れ子になっている場合は
# ハッシュの階層構造を維持したクラスとして定義した上で同様に処理する.
module ActiveClassGenerator
def define_fields_by_hash(instance, hash)
hash.each do |k, v|
class_name = to_camelcase(k)
instance.class.const_set(class_name, Class.new) unless instance.class.const_defined?(class_name)
instance.class.class_eval { attr_accessor k }
if v.kind_of? Hash
obj = instance.class.const_get(class_name).new
define_fields_by_hash(obj, v)
instance.send(k + '=', obj)
elsif v.kind_of? Array
obj = instance.class.const_get(class_name).new
array_obj = instance.send(k)
array_obj = [] unless array_obj
v.each do |val|
if val.kind_of? Hash
hash_instance = Class.new
define_fields_by_hash(hash_instance, val)
array_obj << hash_instance
else
array_obj << val
end
end
instance.send(k + '=', array_obj)
else
instance.send(k + '=', v)
end
end
end
private
def to_camelcase(str)
str.split('_').map{|s| s.capitalize}.join('')
end
end
| true
|
17387f522b4249b44008c09ea11cc2c2d329d26d
|
Ruby
|
DonalMoo/BikeRental
|
/lib/calculator.rb
|
UTF-8
| 69
| 2.984375
| 3
|
[] |
no_license
|
class Calculator
def self.total(n1, n2)
result = n1 * n2
end
end
| true
|
02102c5c701075d7c5ae9c2fe5a37a5d47370913
|
Ruby
|
ruby-rails-mustafa-akgul-oyyk-2019/ruby_101_sunum
|
/codes/classes/method_types.rb
|
UTF-8
| 475
| 3.703125
| 4
|
[
"MIT"
] |
permissive
|
class Person
attr_accessor :name
def initialize(name, surname, age, gender)
@name = name
@surname = surname
@age = age
@gender = gender
end
def self.finder_numbers
10
end
def gender
if age == 'ender'
'male'
else
'female'
end
end
protected
def method_name
end
private
def method_namepp
end
end
p = Person.new('ahmet', 'yurt', '33', 'unknown')
puts p.name
puts Person.finder_numbers
puts p
| true
|
0dc25393ca667fe118f69af2ef91ceb318e1dcb8
|
Ruby
|
zlw241/W2D4
|
/two_sum.rb
|
UTF-8
| 895
| 4.09375
| 4
|
[] |
no_license
|
def bad_two_sum?(arr, target)
arr[0...-1].each do |i|
(i+1...arr.length).each do |j|
return true if arr[i] + arr[j] == target
end
end
false
end
arr = [0, 1, 5, 7]
p bad_two_sum?(arr, 6) # => should be true
p bad_two_sum?(arr, 10) # => should be false
def b_search(arr, target)
return false if arr.empty?
mid = arr / 2
if arr[mid] == target
true
elsif arr[mid] < target
b_search(arr[mid..-1], target)
else
b_search(arr[0...mid], target)
end
end
def okay_two_sum?(arr, target)
sorted_arr = arr.sort
sorted_arr.each { |el| return true if b_search(arr, target-el) }
false
end
def two_sum?(arr, target)
two_sum_hash = Hash.new(0)
arr.each do |el|
return true if two_sum_hash[target-el] > 0
two_sum_hash[el] += 1
end
false
end
arr = [0, 7, 5, 1]
p two_sum?(arr, 6) # => should be true
p two_sum?(arr, 10) # => should be false
| true
|
034d4ce34e1cad60070a4a8d3297093cc989cb28
|
Ruby
|
haja1294/learn-co-sandbox
|
/nested.rb
|
UTF-8
| 190
| 2.96875
| 3
|
[] |
no_license
|
people = [["Kaetlyn","proletariat","potsticker"],["Jon","bougie toucan","fruit loops"]]
people.each do |person,description,food|
puts"#{person} is a #{description} and loves to eat #{food}"
end
| true
|
2adebe10981387c81f6a002979e1d254335db05e
|
Ruby
|
wfslithtaivs/AA_Homeworks_and_Projects
|
/ORM Ruby SQL/tests.rb
|
UTF-8
| 2,119
| 2.6875
| 3
|
[] |
no_license
|
require_relative 'database'
require_relative 'user'
require_relative 'question'
require_relative 'reply'
require_relative 'question_follow'
require_relative 'question_like'
#
# p User.all
# p Question.all
# p Reply.all
quest = Question.find_by_author_id(2)
# p "Question: Find by author #{quest}"
repl = Reply.find_by_user_id(1)
# p " Reply: Find by user id : ------ #{repl}"
# p " Reply: Find by question id: ------ #{Reply.find_by_question_id(1)}"
user = User.find_by_name('Ian', 'H').first
# p user
# p user.authored_questions
# p user.authored_replies
# p quest.first.author
# p quest.first.replies
# p repl.first.author
# p repl.first.question
# p repl.first.parent_reply
# p "repl: #{repl.first}"
# p "Child replies: #{repl.first.child_replies}"
#
# puts "\nMedium Weird Mode\n"
# puts "Followers for question ID: #{QuestionFollow.followers_for_question_id(1)}\n"
# puts "Followed questions for user ID: #{QuestionFollow.followed_questions_for_user_id(1)}\n"
# puts "Followed questions: #{user.followed_questions}"
# puts "Followers: #{quest.first.followers}"
puts "\nHard Mode\n"
# puts "Most followed questions: #{QuestionFollow.most_followed_questions(2)}"
# puts "Question.most_followed: #{Question.most_followed(1)}"
# puts "Likers for question: #{QuestionLike.likers_for_question_id(1)}"
# puts "Num likes for question: #{QuestionLike.num_likes_for_question_id(1)}"
# puts "Liked questions for user: #{QuestionLike.liked_questions_for_user_id(3)}"
# puts "Question.likers: #{quest.first.likers}"
# puts "Question.num_likes: #{quest.first.num_likes}"
# puts "User.liked_questions: #{user.liked_questions}"
# repl = Reply.find_by_id(2)
# p User.all
#
# p repl.instance_variables
# p usr.average_karma
#
usr2 = User.new( {'fname' => "Someone", 'lname' => "Else"} )
usr2.save
# usr2.fname = 'Ian'
# usr2.save
#
# p User.all
#
# quest2 = Question.new( 'title' => "Awesome Ttitle", 'body' => "Super Body", 'user_id' => usr2.id)
# quest2.save
# p Question.all
#
# repl2 = Reply.new( 'question_id' => quest2.id, 'parent_id' => nil, 'user_id' => usr.id, 'body' => "I''m in TEST")
# repl2.save
# p Reply.all
| true
|
2ad86104396c3585739cc74070a77ec99a1eae97
|
Ruby
|
sneakin/CooCoo
|
/examples/mnist.rb
|
UTF-8
| 14,356
| 2.734375
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
require 'pathname'
require 'net/http'
require 'zlib'
require 'ostruct'
# todo read directly from gzipped files
# todo usable by the bin/trainer?
# todo label and map network outputs
# todo blank space needs to be standard part
# todo additional outputs and labels beyond 0-9
module MNist
PATH = Pathname.new(__FILE__)
ROOT = PATH.dirname.join('mnist')
MNIST_URIS = [ "http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz",
"http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz",
"http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz",
"http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz"
]
TRAIN_LABELS_PATH = ROOT.join('train-labels-idx1-ubyte.gz')
TRAIN_IMAGES_PATH = ROOT.join('train-images-idx3-ubyte.gz')
TEST_LABELS_PATH = ROOT.join('t10k-labels-idx1-ubyte.gz')
TEST_IMAGES_PATH = ROOT.join('t10k-images-idx3-ubyte.gz')
Width = 28
Height = 28
module Fetcher
def self.fetch!
ROOT.mkdir unless ROOT.exist?
MNIST_URIS.each do |uri|
uri = URI.parse(uri)
path = ROOT.join(File.basename(uri.path)) #.sub(".gz", ""))
next if path.exist?
CooCoo::Utils::HTTP.download(uri, to: path)
end
end
end
class Example
attr_accessor :label
attr_accessor :pixels
attr_accessor :angle
attr_accessor :offset_x
attr_accessor :offset_y
def initialize(label, pixels, angle = 0, offset_x = 0, offset_y = 0)
@label = label
@pixels = pixels
@angle = angle
@offset_x = offset_x
@offset_y = offset_y
end
def pixel(x, y)
@pixels[y * MNist::Width + x] || 0
end
def to_ascii
CooCoo::Drawing::Ascii.gray_bytes(pixels.flatten, 28, 28)
end
def each_pixel(&block)
return to_enum(__method__) unless block_given?
28.times do |y|
28.times do |x|
yield(pixel(x, y))
end
end
end
end
class DataStreamer
def initialize(labels_path, images_path)
@labels, @size = open_labels(labels_path)
@images, @image_size = open_images(images_path)
end
def close
@labels.close
@images.close
end
def size
@size
end
def next
label = next_label
pixels = next_image
if label && pixels
Example.new(label, pixels)
end
end
private
def open_labels(path)
f = CooCoo::Utils.open_filez(path)
magic, number = f.read(4 * 2).unpack('NN')
raise RuntimeError.new("Invalid magic number #{magic} in #{path}") if magic != 0x801
[ f, number ]
end
def next_label
l = @labels.read(1)
if l
l.unpack('C').first
else
nil
end
end
def open_images(path)
f = CooCoo::Utils.open_filez(path)
magic, num_images, height, width = f.read(4 * 4).unpack('NNNN')
raise RuntimeError.new("Invalid magic number #{magic} in #{path}") if magic != 0x803
[ f, width * height * 1 ]
end
def next_image
p = @images.read(@image_size)
if p
p.unpack('C' * @image_size)
else
nil
end
end
end
class DataStream
def initialize(labels_path = TRAIN_LABELS_PATH, images_path = TRAIN_IMAGES_PATH)
if (labels_path == TRAIN_LABELS_PATH && images_path == TRAIN_IMAGES_PATH) ||
(labels_path == TEST_LABELS_PATH && images_path == TEST_IMAGES_PATH)
if !File.exist?(labels_path) || !File.exist?(images_path)
Fetcher.fetch!
end
end
raise ArgumentError.new("File does not exist: #{labels_path}") unless File.exist?(labels_path)
raise ArgumentError.new("File does not exist: #{images_path}") unless File.exist?(images_path)
@labels_path = labels_path
@images_path = images_path
read_metadata
end
attr_reader :size
attr_reader :width
attr_reader :height
def each(&block)
return enum_for(__method__) unless block_given?
begin
streamer = DataStreamer.new(@labels_path, @images_path)
begin
ex = streamer.next
if ex
block.call(ex)
end
end until ex == nil
ensure
streamer.close
end
end
def to_enum
each
end
private
def read_metadata
read_size
read_dimensions
end
def read_dimensions
CooCoo::Utils.open_filez(@images_path) do |f|
magic, num_images, height, width = f.read(4 * 4).unpack('NNNN')
raise RuntimeError.new("Invalid magic number #{magic} in #{path}") if magic != 0x803
@width = width
@height = height
end
end
def read_size
CooCoo::Utils.open_filez(@labels_path) do |f|
magic, number = f.read(4 * 2).unpack('NN')
raise RuntimeError.new("Invalid magic number #{magic} in #{@labels_path}") if magic != 0x801
@size = number
end
end
public
class Inverter < Enumerator
attr_reader :size, :raw_data
def initialize(data, inverts_only)
@size = data.size * (inverts_only ? 2 : 1)
@raw_data = data
@data = data.to_enum
@inverts_only = inverts_only
super() do |y|
loop do
example = @data.next
img = example.pixels.to_a.flatten
unless @inverts_only
y << Example.new(example.label, img, example.angle, example.offset_x, example.offset_y)
end
y << Example.new(example.label, 255 - CooCoo::Vector[img], example.angle, example.offset_x, example.offset_y)
end
end
end
end
class Rotator < Enumerator
attr_reader :size, :raw_data
def initialize(data, rotations, rotation_range, random = false)
@size = data.size * rotations
@raw_data = data
@data = data.to_enum
@rotations = rotations
@rotation_range = rotation_range
@random = random
super() do |y|
loop do
example = @data.next
@rotations.times do |r|
t = if @random
rand
else
(r / @rotations.to_f)
end
theta = t * @rotation_range - @rotation_range / 2.0
img = rotate_pixels(example.pixels, theta)
y << Example.new(example.label, img.to_a.flatten, theta)
end
end
end
end
def wrap(enum)
self.class.new(enum, @rotations, @rotation_range, @random)
end
def drop(n)
wrap(@data.drop(n))
end
def rotate_pixels(pixels, theta)
rot = CooCoo::Image::Rotate.new(MNist::Width / 2, MNist::Height / 2, theta)
img = CooCoo::Image::Base.new(MNist::Width, MNist::Height, 1, pixels.to_a.flatten)
(img * rot)
end
end
class Translator < Enumerator
attr_reader :size, :raw_data
def initialize(data, num_translations, dx, dy, random = false)
@size = data.size * num_translations
@raw_data = data
@data = data.to_enum
@num_translations = num_translations
@dx = dx
@dy = dy
@random = random
super() do |yielder|
loop do
example = @data.next
@num_translations.times do |r|
x = if @random
rand
else
(r / @num_translations.to_f)
end
x = x * @dx - @dx / 2.0
y = if @random
rand
else
(r / @num_translations.to_f)
end
y = y * @dy - @dy / 2.0
img = translate_pixels(example.pixels, x, y)
yielder << Example.new(example.label, img.to_a.flatten, example.angle, x, y)
end
end
end
end
def wrap(enum)
self.class.new(enum, @num_translations, @dx, @dy, @random)
end
def drop(n)
wrap(@data.drop(n))
end
def translate_pixels(pixels, x, y)
transform = CooCoo::Image::Translate.new(x, y)
img = CooCoo::Image::Base.new(MNist::Width, MNist::Height, 1, pixels.to_a.flatten)
(img * transform)
end
end
# todo eliminate the three enumelators here with a single abstract Transformer that takes a transform chain
# todo Scaler needs to expand the image size, follow with a crop transform
class Scaler < Enumerator
attr_reader :size, :raw_data
def initialize(data, num_translations, amount, random = false)
@size = data.size * num_translations
@raw_data = data
@data = data.to_enum
@num_translations = num_translations
@min_scale, @max_scale = amount
@random = random
super() do |yielder|
loop do
example = @data.next
@num_translations.times do |r|
x = if @random
rand
else
(r / @num_translations.to_f)
end
x = @max_scale * x + @min_scale
y = if @random
rand
else
(r / @num_translations.to_f)
end
y = @max_scale * y + @min_scale
img = scale_pixels(example.pixels, x, y)
yielder << Example.new(example.label, img.to_a.flatten, example.angle, x, y)
end
end
end
end
def wrap(enum)
self.class.new(enum, @num_translations, @dx, @dy, @random)
end
def drop(n)
wrap(@data.drop(n))
end
def scale_pixels(pixels, x, y)
transform = CooCoo::Image::Scale.new(x, y)
img = CooCoo::Image::Base.new(MNist::Width, MNist::Height, 1, pixels.to_a.flatten)
(img * transform)
end
end
end
class TrainingSet
attr_reader :output_size
def initialize(data_stream = MNist::DataStream.new(MNist::TRAIN_LABELS_PATH, MNist::TRAIN_IMAGES_PATH),
output_size = nil)
@stream = data_stream
@output_size = output_size || 10
end
def name
File.dirname(__FILE__)
end
def input_size
Width*Height
end
def size
@stream.size
end
def each(&block)
return to_enum(__method__) unless block
enum = @stream.each
loop do
example = enum.next
a = CooCoo::Vector.new(output_size, 0.0)
a[example.label] = 1.0
m = [ a,
CooCoo::Vector[example.pixels] / 255.0
]
#$stderr.puts("#{m[0]}\t#{m[1]}")
block.call(m)
end
end
end
# todo necessary?
class DataSet
attr_reader :examples
def initialize
@examples = Array.new
end
def load!(labels_path, images_path)
@examples = DataStream.new(labels_path, images_path).each.to_a
self
end
end
def self.default_options
options = OpenStruct.new
options.images_path = MNist::TRAIN_IMAGES_PATH
options.labels_path = MNist::TRAIN_LABELS_PATH
options.translations = 0
options.translation_amount = 10
options.rotations = 0
options.rotation_amount = 90
options.scale = 0
options.scale_amount = [ 0.25, 1.5 ]
options.num_labels = nil
options
end
def self.option_parser options
CooCoo::OptionParser.new do |o|
o.banner = "The MNist data set"
o.on('--images-path PATH') do |path|
options.images_path = path
end
o.on('--labels-path PATH') do |path|
options.labels_path = path
end
o.on('--num-labels INTEGER', Integer) do |n|
options.num_labels = n
end
o.on('--translations INTEGER') do |n|
options.translations = n.to_i
end
o.on('--translation-amount PIXELS') do |n|
options.translation_amount = n.to_i
end
o.on('--rotations INTEGER') do |n|
options.rotations = n.to_i
end
o.on('--rotation-amount DEGREE') do |n|
options.rotation_amount = n.to_i
end
o.on('--scale INTEGER', Integer) do |n|
options.scale = n.to_i
end
o.on('--scale-amount MIN,MAX') do |n|
min, max = CooCoo::Utils.split_csv(n, :to_f)
options.scale_amount = [ min, max || min ].sort
end
o.on('--invert') do
options.invert = true
end
o.on('--inverts-only') do
options.invert = true
options.inverts_only = true
end
end
end
def self.training_set(options)
data = MNist::DataStream.new(options.labels_path, options.images_path)
if options.rotations > 0 && options.rotation_amount > 0
data = MNist::DataStream::Rotator.new(data, options.rotations, options.rotation_amount / 180.0 * ::Math::PI, true)
end
if options.translations > 0 && options.translation_amount > 0
data = MNist::DataStream::Translator.
new(data, options.translations,
options.translation_amount,
options.translation_amount,
true)
end
if options.scale > 0
data = MNist::DataStream::Scaler.new(data, options.scale, options.scale_amount, true)
end
if options.invert
data = MNist::DataStream::Inverter.new(data, options.inverts_only)
end
MNist::TrainingSet.new(data, options.num_labels)
end
end
if __FILE__ == $0
def print_example(ex)
puts(ex.label)
puts(ex.to_ascii)
end
data = MNist::DataStream.new(MNist::TRAIN_LABELS_PATH, MNist::TRAIN_IMAGES_PATH)
i = 0
data.each.
group_by(&:label).
collect { |label, values| [ label, values.first ] }.
sort_by(&:first).
first(10).
each do |(label, e)|
puts(i)
print_example(e)
i += 1
break if i > 20
end
rot = MNist::DataStream::Rotator.new(data.each, 10, Math::PI, false)
rot.drop(10).first(10).each do |example|
print_example(example)
end
puts("#{data.size} total #{data.width}x#{data.height} images")
elsif $0 =~ /trainer$/
[ MNist.method(:training_set),
MNist.method(:option_parser),
MNist.method(:default_options) ]
end
| true
|
fc5b13c7dd30cc04ec83faa917a7738c0f9acaac
|
Ruby
|
JTREX/piglatin1
|
/pruebas.rb
|
UTF-8
| 778
| 4.0625
| 4
|
[] |
no_license
|
# Script: Single word converter to Pig Latin
def translate
# GET a word from user input
p "Give me a Word"
string = gets.chomp.downcase
alpha = ('a'..'z').to_a
vowels = %w[a e i o u]
consonants = alpha - vowels
# IF the word starts with a vowel, add "way" to the end
if vowels.include?(string[0])
string + 'way'
elsif consonants.include?(string[0]) && consonants.include?(string[1])
string[2..-1] + string[0..1] + 'ay'
elsif consonants.include?(str[0])
string[1..-1] + string[0] + 'ay'
else
string
end
end
p translate
# ELSE replace the word with its pig latin equivalent
# GET all of the consonants before the first vowel in the word
# SET the consonants at the end of the word and add "ay"
# ENDIF
# RETURN the pig-latin word
| true
|
d97e67d8db9dd780f59939fd1f5c4b9f5bf546a2
|
Ruby
|
j-eaves/employees_ledger
|
/manager.rb
|
UTF-8
| 2,438
| 3.90625
| 4
|
[] |
no_license
|
module EmailReportable #always ends in "able"
#In the module, I can place a ton of various methods
def send_report
p "I will send report."
p "Here is the report."
end
end
#Employee class
class Employee
attr_reader :first_name, :last_name, :salary, :active #this takes the place of the getter functions below!
attr_writer :active
def initialize(input_options)
#assign values to the instance variables (starts with @)
@first_name = input_options[:first_name]
@last_name = input_options[:last_name]
@salary = input_options[:salary]
@active = input_options[:active]
end
def print_info
p "#{@first_name} #{@last_name} makes #{@salary} per year"
#or
p "#{first_name} #{last_name} makes #{salary} per year"
end
def give_annual_raise
#change salary
@salary = @salary * 1.05
end
def full_name
full_name = @first_name+" "+@last_name
if @last_name[-1] == "s"
full_name = full_name + ", Esquire"
end
return full_name
end
end
#generate first and last name
#Manager class - inherited from Employee class
class Manager < Employee
include EmailReportable
attr_reader :employees
def initialize(input_options)
super
@employees = input_options[:employees]
end
# def employees
# return @employees
# end
def give_all_raises
@employees.each do |employee|
employee.give_annual_raise
end
end
def fire_all_employees
@employees.each do |employee|
employee.active = false
end
end
end
#An intern can do everything that an ployee can do and can also send a report
class Intern < Employee
include EmailReportable
end
intern1 = Intern.new(first_name: "Bob", last_name: "Earl", salary: 0, active: true)
p intern1.first_name
intern1.send_report
#What we learn:
employee1 = Employee.new({:first_name => "Manila", :last_name => "Campos", :salary => 80000, :active => true})
#Current ruby best practice
employee2 = Employee.new(first_name: "Ben", last_name: "Franklin", salary: 70000, active: true)
#p employee1.full_name
#p employee2.full_name
manager1 = Manager.new(first_name: "Jon", last_name: "Eaves", salary: 90000, active: true, employees: [employee1, employee2])
#p manager1.full_name
#p manager1.class
manager1.send_report
p manager1.employees[0].salary
manager1.give_all_raises
p manager1.employees[0].salary
p manager1.employees[0].active
manager1.fire_all_employees
p manager1.employees[0].active
| true
|
33d9ef238b4eee128c4fceef91b6053c991d9b53
|
Ruby
|
pdg137/pi-maze-solver
|
/pi/lib/looped_maze_solver.rb
|
UTF-8
| 5,047
| 3.390625
| 3
|
[] |
no_license
|
require_relative 'maze'
require_relative 'point'
require_relative 'vector'
require_relative 'gridded_maze'
require_relative 'segment_voter'
require_relative 'turning_path_follower'
require 'set'
class LoopedMazeSolver
# Our internal concept of the maze.
# Updated as we explore it.
attr_reader :maze, :pos, :vec, :explored_nodes, :a_star, :voter, :deduced_nodes
def set_initial_position
@pos = Point(0,0)
@vec = Vector(1,0)
end
def initialize(a_star)
@a_star = a_star
set_initial_position
@explored_nodes = Set.new
@deduced_nodes = Set.new
@maze = GriddedMaze.new
@voter = SegmentVoter.new
# assume we start facing a segment
maze.connect(pos, pos+vec)
end
def unexplored_nodes
maze.nodes - explored_nodes
end
def useful_nodes_to_explore
# exclude the current node, and any deduced nodes if the end is known
unexplored_nodes.reject { |node|
pos == node || (maze.end && deduced_nodes.include?(node))
}
end
def estimate_grid_units(distance)
(distance + 3*300)/(6*300)
end
def connect(a,b)
maze.connect(a,b)
puts "connect #{a}-#{b}"
end
def disconnect(a,b)
maze.disconnect(a,b)
puts "disconnect #{a}-#{b}"
end
# true if all possible segments are known to either exist or not,
# according to the voter
def check_deductions(node)
return if @explored_nodes.include? node
all_neighbors_known = node.cartesian_neighbors.map do |neighbor|
voter.known?(node, neighbor)
end.inject(:&)
if all_neighbors_known
@deduced_nodes << node
end
end
def observe_segment(a,b)
voter.vote_connected(a,b)
if voter.connected?(a,b)
connect(a,b)
end
check_deductions(a)
check_deductions(b)
end
def observe_no_segment(a,b)
voter.vote_not_connected(a,b)
if voter.not_connected?(a,b) && maze.nodes.include?(a) && maze.nodes.include?(b)
disconnect(a,b)
end
check_deductions(a)
check_deductions(b)
end
def record_path(follow_min_distance, context)
units = estimate_grid_units context[:distance]
puts "distance #{context[:distance]} -> #{units} units"
# TODO: handle zero!
original_pos = @pos
units.times.each do
old_pos = pos
@pos += vec
puts "at #{pos} #{vec}"
observe_segment(old_pos, pos)
explored_nodes << pos
end
if follow_min_distance < 600
pos1 = original_pos
left = vec.turn(:left)
right = vec.turn(:left)
(units-1).times.each do
pos2 = pos1 + vec
left_node = pos2 + left
right_node = pos2 + right
observe_no_segment(pos2, left_node)
observe_no_segment(pos2, right_node)
pos1 = pos2
end
end
end
def record_intersection(context)
puts "exits: #{context[:exits]}"
[:left,:right,:straight].each do |dir|
exit_vec = vec.turn(dir)
if(context[:exits].include? dir)
observe_segment(pos, pos+exit_vec)
else
observe_no_segment(pos, pos+exit_vec)
end
end
end
def explore_to(target)
while true
puts "Explore to #{target.inspect}"
break if try_explore_to(target)
puts "Try again!!"
end
end
def try_explore_to(target)
explored_nodes = []
turning_path_follower = TurningPathFollower.new(1800,600)
turning_path = maze.get_turning_path(vec, pos, target)
puts "turning path #{turning_path.inspect}"
turning_path_follower.compute(turning_path) do |turn, follow_min_distance|
next if turn == :none
puts "next turn #{turn.inspect}"
puts turn
a_star.turn(turn) do |result|
result.done {
@vec = vec.turn(turn)
}
result.button { raise "button pressed" }
end
puts "follow min=#{follow_min_distance}"
a_star.follow(follow_min_distance) do |result|
result.end {
record_path(follow_min_distance, result.context)
puts "Found end at #{pos}"
maze.end = pos
}
result.intersection {
record_path(follow_min_distance, result.context)
record_intersection(result.context)
if estimate_grid_units(result.context[:distance]) < estimate_grid_units(follow_min_distance+300)
return false # error!
end
}
result.button { raise "button pressed" }
end
puts maze.to_s(pos)
end
true
end
def explore_to_end
explore(true)
end
def explore_entire_maze
explore(false)
end
def explore(stop_on_end)
puts "\n\STARTING EXPLORATION FROM #{pos}\n"
while true
break if stop_on_end && pos == maze.end
distances_from_pos = maze.solve(pos)
closest_unexplored_node = useful_nodes_to_explore.min_by { |node|
distances_from_pos[node]
}
# TODO: handle this better
break if closest_unexplored_node.nil?
explore_to closest_unexplored_node
end
end
def replay_from_zero
set_initial_position
explore_to maze.end
end
end
| true
|
6c963f826ab368a909781270a308b887e56b54d5
|
Ruby
|
pmacaluso3/espark_challenge
|
/lib/domain_string_parseable.rb
|
UTF-8
| 466
| 3.15625
| 3
|
[] |
no_license
|
module DomainStringParseable
NON_NUMERIC_GRADES = { 0 => 'K' }
def parse_domain_string(dom_str)
grade = dom_str.split('.').first
domain = dom_str.split('.').last
[grade.to_i, domain.to_sym]
end
def make_domain_string(domain, grade)
"#{grade}.#{domain}"
end
def print_format(dom_str)
grade, domain = parse_domain_string(dom_str)
grade_letter = NON_NUMERIC_GRADES[grade] || grade
"#{grade_letter}.#{domain.upcase}"
end
end
| true
|
9cda57cfd2a25b18826a9fbe924d7282a3a3d70e
|
Ruby
|
db87987/h2_map_parser
|
/lib/map.rb
|
UTF-8
| 2,915
| 3.140625
| 3
|
[] |
no_license
|
class Map
attr_reader :path, :title, :description, :difficulty, :size, :players, :humans, :computers
def initialize(path)
@path = path
@file = File.read(path);
# magic_byte = file.unpack("N").first
# raise "Incorrect map file" unless magic_byte == 1543503872
end
def title
@file.unpack("x58Z*").first
end
def description
@file.unpack("x118Z*").first
end
def difficulties
{
0 => "Easy",
1 => "Normal",
2 => "Hard",
3 => "Expert",
}
end
def difficulty
level = @file.unpack("x4S").first
difficulties[level]
end
def width
@file.unpack("x6C").first
end
# def height
# @file.unpack("x7C").first
# end
def sizes
{
36 => "S",
72 => "M",
108 => "L",
144 => "XL",
}
end
# def kingdom_colors
# colors.each_with_object([]).with_index do |(enabled, memo), index|
# memo << color_by_index[index] if enabled == 1
# end
# end
# def color_by_index
# {
# 0 => "Blue",
# 1 => "Green",
# 2 => "Red",
# 3 => "Yellow",
# 4 => "Orange",
# 5 => "Purple",
# }
# end
def size
sizes[width]
end
# def colors
# @file.unpack("x8C6")
# end
def players
@file.unpack("x8C6").reject { |n| n == 0 }.count
end
def humans
@file.unpack("x14C6").reject { |n| n == 0 }.count
end
def computers
@file.unpack("x20C6").reject { |n| n == 0 }.count
end
def attributes
# [title, description, difficulty]
{
title: title,
description: description,
difficulty: difficulty,
size: size,
players: players,
humans: humans,
computers: computers,
file: path
}
end
end
# // 0x6 6 Width 1 byte
# // 0x7 7 Height 1 byte
# // 0x8 8 KingdomColors 6 bytes
# // 0xE 14 AllowHumanColors 6 bytes
# // 0x14 20 AllowAIColors 6 bytes
# // 0x1A 26 _ (Kingdom Count?) 3 bytes
# // 0x1D 29 VictoryConditions 1 byte
# // 0x1E 30 AIAlsoWins 1 byte
# // 0x1F 31 AllowNormalVictory 1 byte
# // 0x20 32 VictoryData1 2 bytes
# // 0x22 34 LossConditions 1 byte
# // 0x23 35 LossData1 2 bytes
# // 0x25 37 StartWithHeroes 1 byte
# // 0x26 38 Races 6 bytes
# // 0x2C 44 VictoryData2 2 bytes
# // 0x2e 46 LossData2 2 bytes
# // 0x30 48 _ 10 bytes
# // 0x3A 58 Name 16 bytes
# // 0x4A 74 _ 44 bytes
# // 0x76 118 Description 143 bytes
# // 0x105 261 _ 159 bytes
# // 0x1A4 420 Width (duplicate) 4 bytes
# // 0x1A8 424 Height (duplicate) 4 bytes
# 2.6.2 :004 > str.unpack("N")
# => [1543503872]
| true
|
c2d0f3779882b0f16e2e2a482e868d39257358ac
|
Ruby
|
timhang/im-hungry-pt2
|
/Part1/cuc/features/step_definitions/ResultsPage.rb
|
UTF-8
| 3,349
| 2.625
| 3
|
[] |
no_license
|
## Scenario Search a query then return to search page
Given("I am on the Search Page") do
visit 'localhost:8080/project1/SearchPage.html'
end
Given("I have entered a search query {string}") do |string|
fill_in 'search', :with => string
end
Given("{int} for the number of results to be displayed") do |int|
fill_in 'limit', with: int
end
Given("I clicked the {string} button") do |string|
find('#searchBtn').click
end
## Scenario: Return back to Search Page
Given("I am on the Results Page") do
sleep(2)
expect(page).to have_current_path('/project1/results.html')
end
When("I click Return to Search") do
find("#retToSearchBtn").click
end
Then("I should be on the Search Page") do
uri = URI.parse(current_url)
uri.path == "localhost:8080/project1/SearchPage.html"
end
## Scenario: Correct content
Then("the page will have a title: {string}") do |string|
html = page.evaluate_script("document.getElementById('title').innerHTML.toLowerCase()")
html.should include(string.downcase)
end
Then("the page will have a collage of photos relevant to the query") do
expect(page).to have_css("canvas#myCanvas")
end
Then("the page will have a button labeled {string}") do |string|
html = page.evaluate_script("document.getElementById('manageBtn').innerHTML")
html.should include('Manage List')
html = page.evaluate_script("document.getElementById('retToSearchBtn').innerHTML")
html.should include('Return to Search')
end
Then("the page will have a dropdown with predefined lists") do
expect(page).to have_select 'dropdown',
with_options: ['Favorites', 'To Explore', 'Do Not Show']
end
Then("the page will have two columns of results titled: Restaurants, Recipes") do
expect(page).to have_css('#restaurantTable')
expect(page).to have_css('#recipeTable')
end
Then("the page will have {int} restaurant and recipe results in each column") do |int|
x = page.evaluate_script("document.getElementsByTagName('tr').length")
x == 4
end
Then("each restaurant item on the page will have an address, name, minutes, rating, and price") do
expect(page).to have_css('.restaurantAddress')
expect(page).to have_css('.restaurantName')
expect(page).to have_css('.restaurantTime')
expect(page).to have_css('.restaurantRating')
expect(page).to have_css('.restaurantPrice')
end
Then("each recipe item on the page will have a name, prep time, cook time, and price") do
expect(page).to have_css('.recipeName')
expect(page).to have_css('.recipePrepTime')
expect(page).to have_css('.recipeCookTime')
expect(page).to have_css('.recipePrice')
end
When("I select {string} from the dropdown") do |string|
select string
end
When("I click the {string} button") do |string|
click_on string
end
Then("I will be on the {string} list page") do |string|
expect(page).to have_css('#listName')
end
When("I click on a restaurant with name {string}") do |string|
click_on string
end
Then("I will be on the Restaurant Page of restaurant {string}") do |string|
expect(page).to have_css('#name')
end
When("I click on a recipe with name {string}") do |string|
click_on string
end
Then("I will be on the Recipe Page of recipe {string}") do |string|
expect(page).to have_css('#cookTime')
end
Then("I will be on the Results Page") do
expect(page).to have_current_path('/project1/results.html')
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.