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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
78113bee45fe8d22ce58465a705ab62d4dbe7c17 | Ruby | meedan/check-api | /config/initializers/field_formatters.rb | UTF-8 | 1,598 | 2.53125 | 3 | [
"MIT"
] | permissive | # Define field formatters for our various dynamic field types.
DynamicAnnotation::Field.class_eval do
def field_formatter_type_language
code = self.value.to_s.downcase
CheckCldr.language_code_to_name(code)
end
def field_formatter_name_response_multiple_choice
response_value(self.value)
end
def field_formatter_type_geojson
geojson = JSON.parse(self.value)
value = geojson['properties']['name']
coordinates = geojson['geometry']['coordinates']
value += " (#{coordinates.join(', ')})"
value
end
def field_formatter_type_url
urls = JSON.generate(self.value)
end
def field_formatter_type_datetime
# Capture TZ abbreviation manually because DateTime does not parse it
# http://rubular.com/r/wOfJTCSxlI
# The format string is expect to have a [TZ] placeholder to receive the abbreviation
abbr = ''
match = /\s([[:alpha:]]+)\s?$/.match(self.value)
abbr = match[1] unless match.nil?
I18n.l(DateTime.parse(self.value), format: :task).gsub('[TZ]', abbr)
end
['free_text', 'yes_no', 'single_choice', 'multiple_choice', 'geolocation', 'datetime', 'file_upload', 'number', 'url'].each do |type|
define_method "field_formatter_name_suggestion_#{type}" do
JSON.parse(self.value)['suggestion']
end
end
private
def response_value(field_value)
value = nil
begin
value = JSON.parse(field_value).to_h
rescue
return field_value
end
answer = value['selected'] || []
answer.insert(-1, value['other']) if !value['other'].blank?
[answer].flatten.join(', ')
end
end
| true |
b15efcef49f949238eee3e1dac851c5813d5f4c8 | Ruby | vickerdj/ruby | /02_calculator/calculator.rb | UTF-8 | 359 | 3.5 | 4 | [] | no_license | def add(a,b)
a + b
end
def subtract(a,b)
a - b
end
def sum(array)
i = 0
total = 0
while i < array.length
total += array[i]
i += 1
end
total
end
def multiply(a,b)
a * b
end
def power(a,b)
i = 1
while i <= b
a *= a
i += 1
end
end
def factorial(a)
i = a - 1
while i >= 0
a *= i
i -= 1
end
end | true |
603ed0e2e9b53809e34ad53073b7059beb8e308f | Ruby | hull/hull-ruby | /lib/hull.rb | UTF-8 | 1,455 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'hull/client'
require 'hull/config'
module Hull
extend Config
class << self
# Alias for Hull::Client.new
#
# @return [Hull::Client]
def new(options={})
Hull::Client.new(options)
end
def as(user)
as_user(user)
end
def as_user(user)
if user.is_a?(String)
if user =~ /^[0-9a-z]{24}$/
Hull::Client.new({ access_token: self.user_token({ id: user }) })
else
raise ArgumentError.new("Invalid user_id")
end
else
Hull::Client.new({ access_token: self.user_token(user) })
end
end
def as_account account
if account.is_a?(String)
if account =~ /^[0-9a-z]{24}$/
Hull::Client.new({ access_token: self.account_token({ id: account }) })
else
raise ArgumentError.new("Invalid account_id")
end
else
Hull::Client.new({ access_token: self.account_token(account) })
end
end
# Delegate to Hull::Client
def method_missing(method, *args, &block)
return super unless new.respond_to?(method)
new.send(method, *args, &block)
end
def respond_to?(method, include_private=false)
new.respond_to?(method, include_private) || super(method, include_private)
end
def log msg, level=:debug
Hull.logger.send(level.to_sym, "[hull:#{Hull.domain}] #{msg}") if Hull.logger && Hull.logger.respond_to?(level.to_sym)
end
end
end
| true |
44ccf835311cd7b50f05738cf77ae3a7ff144ff6 | Ruby | brantpastore/May_Tic_Tac_Toe | /lib/tic_tac_toe_board.rb | UTF-8 | 2,758 | 3.578125 | 4 | [] | no_license | require 'board'
class TicTacToeBoard < Board
class InvalidPiece < Exception ; end
attr_reader :x_mark, :o_mark
VALID_PIECES = ['X', 'O'].freeze
def initialize(length = 3)
@length = length
super(length * length)
@x_mark = "X"
@o_mark = "O"
end
def game_over?
full? || !row_winner.nil? ||
!column_winner.nil? || !diagonal_winner.nil?
end
def winner
row_winner || column_winner || diagonal_winner
end
def tie_game?
if game_over? && winner.nil?
true
end
end
def full?
@board_state.compact.size == @size
end
def fill_space(space_number, token)
validate_piece(token)
super(space_number, token)
end
def get_empty_spaces(board)
board_spaces = @board_state
empty_board_spots = []
board_spaces.each_with_index do |space, index|
if space.nil?
empty_board_spots << index
end
end
empty_board_spots
end
def token_that_is_up
if spaces.compact.size.even?
@x_mark
else
@o_mark
end
end
private
def validate_piece(token)
raise InvalidPiece.new unless VALID_PIECES.any? {|valid_piece| valid_piece == token}
end
def row_winner
rows.each do |row|
VALID_PIECES.each do |valid_piece|
return valid_piece if all_spaces_filled_by_same_piece?(row, valid_piece)
end
end
nil
end
def column_winner
columns.each do |column|
VALID_PIECES.each do |valid_piece|
return valid_piece if all_spaces_filled_by_same_piece?(column, valid_piece)
end
end
nil
end
def diagonal_winner
diagonals.each do |diagonal|
VALID_PIECES.each do |valid_piece|
return valid_piece if all_spaces_filled_by_same_piece?(diagonal, valid_piece)
end
end
nil
end
def rows
rows = []
@board_state.each_slice(@length) do |slice|
rows << slice
end
rows
end
def columns
columns = Array.new(@length)
columns.map! {|index| Array.new}
@board_state.each_with_index do |space, space_number|
column_number = space_number % @length
columns[column_number] << space
end
columns
end
def diagonals
left_to_right = []
right_to_left = []
@board_state.each_with_index do |space, space_number|
if space_number == 0
left_to_right << space
elsif space_number == @size - 1
left_to_right << space
else
left_to_right << space if space_number % (@length + 1) == 0
right_to_left << space if space_number % (@length - 1) == 0
end
end
[left_to_right, right_to_left]
end
def all_spaces_filled_by_same_piece?(spaces, piece)
return false if spaces.first.nil?
spaces.all? {|space| space == piece}
end
end
| true |
5b2e41ae19ff962a6afde2333df5324a042e9726 | Ruby | aluisribeiro/envoice-ruby-example | /test/models/item_test.rb | UTF-8 | 701 | 2.578125 | 3 | [] | no_license | require 'test_helper'
class ItemTest < ActiveSupport::TestCase
test "should calculate the total" do
item = Item.new(product: Product.new, amount: 10, product_price: 20)
assert_equal 200, item.total
end
test "should validate the item" do
item = Item.new(product: Product.new, envoice: Envoice.new, amount: 2)
assert item.valid?
end
test "should validate item without amount" do
item = Item.new(product: Product.new, envoice: Envoice.new)
refute item.valid?
end
test "should set product_price before save" do
item = Item.new(product: Product.new(price: 10), envoice: Envoice.new, amount: 2)
item.save
assert_equal 10, item.product_price
end
end
| true |
1ba70a39888d9306cc134496bc9e3b2d7fd3c174 | Ruby | tchartchke/purkamyern | /lib/purkamyern/pokemon.rb | UTF-8 | 510 | 2.734375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class Purkamyern::Pokemon
attr_accessor :name, :types, :id
@@all = Set.new
def initialize(attributes)
@name = attributes['name']
@id = attributes['id']
@types = []
attributes['types'].each do |t|
type = t['type']['name']
@types << type
end
@@all.add(self) unless @@all.find { |entry| entry.name == name }
end
def <=>(other)
id <=> other.id
end
def self.all
@@all
end
def self.discovered
@@all.size
end
end
| true |
1b61d5e5c4bdca2f43e909559c97806eac273120 | Ruby | brady-robinson/ls-rb101 | /small_problems/easy9_6.rb | UTF-8 | 1,306 | 4.5 | 4 | [] | no_license | # problem: take a string and make an array with each word and its
# length represented as separate strings
# data: string, array
# facts: non-alphanumeric characters do not count (not true)
# examples:
# word_lengths("cow sheep chicken") == ["cow 3", "sheep 5", "chicken 7"]
# word_lengths("baseball hot dogs and apple pie") ==
# ["baseball 8", "hot 3", "dogs 4", "and 3", "apple 5", "pie 3"]
# word_lengths("It ain't easy, is it?") == ["It 2", "ain't 5", "easy, 5", "is 2", "it? 3"]
# word_lengths("Supercalifragilisticexpialidocious") ==
# ["Supercalifragilisticexpialidocious 34"]
# word_lengths("") == []
# alg:
# - split the string
# - count the size of each element of the array
# - during the count, append the size to the element with a space
def word_lengths(string)
array = string.split
array.each do |element|
element << " #{element.size}"
end
array
end
p word_lengths("cow sheep chicken") == ["cow 3", "sheep 5", "chicken 7"]
p word_lengths("baseball hot dogs and apple pie") ==
["baseball 8", "hot 3", "dogs 4", "and 3", "apple 5", "pie 3"]
p word_lengths("It ain't easy, is it?") == ["It 2", "ain't 5", "easy, 5", "is 2", "it? 3"]
p word_lengths("Supercalifragilisticexpialidocious") ==
["Supercalifragilisticexpialidocious 34"]
p word_lengths("") == []
| true |
e35ff1eafd61c459c43dc3d8d933a36e1ad95f59 | Ruby | MigueCc99/DS | /P1/S1/RUBY/lib/bicicleta_montana.rb | UTF-8 | 696 | 2.890625 | 3 | [] | no_license | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
require_relative("bicicleta.rb")
module Practica1
class BicicletaMontana < Bicicleta
@@contador_bicicleta = 0
def clone()
@@contador_bicicleta = @@contador_bicicleta + 1
return BicicletaMontana.crear_bicicleta_con_id(@@contador_bicicleta)
end
def self.crear_bicicleta_sin_id()
self.new(0)
end
def self.crear_bicicleta_con_id(id)
self.new(id)
end
private
def initialize(id)
@id_bicicleta = id
@se_ha_retirado = false
end
end
end
| true |
1611ce4fd7492e775796e155f08a3a3137822f59 | Ruby | valesil/QE_training_BDT_ruby | /Silvia/Practices/Session 7/Singleto_practice.rb | UTF-8 | 604 | 3.28125 | 3 | [] | no_license | class Guest
attr_accessor :user
attr_reader :hash
attr_reader :visitors
def initialize
@user = "Guest"
@message = "Welcome to the city"
@visitors = 0
@hash = {}
@hash [@user] = @message
end
def add_to_hash
@user = gets.chomp
@message = gets.chomp
@visitors += @visitors + 1
@hash [@user] = @message
end
end
def singletn_example
@singletn_example ||= Guest.new
end
p singletn_example.add_to_hash
p singletn_example.add_to_hash
p "Last user: #{singletn_example.user}"
p "Visitors: #{singletn_example.visitors}"
p singletn_example.hash | true |
f699cb7c1dcaddac1c80dfd3ac482b93bdb9eb74 | Ruby | sherylhodgson/skillcrush-ruby-challenges | /love_notes.rb | UTF-8 | 228 | 3.40625 | 3 | [] | no_license | puts 'Are roses red? Are violets blue? Is sugar sweet?'
answer = gets.chomp.downcase
while (answer.downcase == 'y')
puts 'I love you'
puts 'Are roses red? Are violets blue? Is sugar sweet?'
answer = gets.chomp.downcase
end | true |
5347212cd5669b2d552c61a75cb83e5444d1fdaa | Ruby | ThePurplePanda/fantasy_on_rails | /app/models/team.rb | UTF-8 | 3,519 | 2.828125 | 3 | [] | no_license | require 'open-uri'
class Team < ActiveRecord::Base
belongs_to :league, inverse_of: :team
has_and_belongs_to_many :trade, inverse_of: :team
has_many :player, inverse_of: :team, dependent: :destroy
def make_players(scraped_players, scraped_values)
scraped_players.select{|p| p[:team] == self.number}.each do |play|
name = play[:name]
position = play[:position]
play_val = scraped_values.select{|p| p[:name] == name}
if play_val.length == 0
Player.create( name: name,
team: self,
position: position,
value: 0)
elsif play_val.length == 1
value = play_val.first[:value]
Player.create( name: name,
team: self,
position: position,
value: value)
else
puts 'There is more than one player with that name and position'
end
end
self.set_starters
end
def set_starters
players = Player.where(team: self).order(value: :desc)
qb = wr = rb = te = flex = 0
players.each do |t|
if t.position == 'QB' && qb == 0
qb += 1
t.update(starter: true)
elsif t.position == 'WR' && wr<2
wr += 1
t.update(starter: true)
elsif t.position == 'RB' && rb<2
rb += 1
t.update(starter: true)
elsif t.position == 'TE' && te == 0
te += 1
t.update(starter: true)
elsif t.position == ('RB'||'WR') && flex == 0
flex += 1
t.update(starter: true)
end
end
end
def get_starters_total
players = Player.where(team: self, starter: true)
total = 0
players.each do |t|
total += t.value
end
return total
end
############# NORMALIZE VALUES
def normalize_values
players = Player.where(team: self)
players.each do |t|
if t.position == ('QB'||'WR'||'RB'||'TE')
free_value = Player.find_by(team: Team.find_by(number: 0), position: t.position).value
old_value = (t.value? ? t.value : 0)
new_value = old_value - free_value
t.update(value: new_value)
end
end
end
############## FREE AGENCY
def get_replacement(position, url, names)
doc = Nokogiri::HTML(open(url))
if self.league.site == 'NFL'
freeAgents = doc.xpath("//a[contains(@class, 'playerName')]")
end
names.each do |f|
freeAgents.each do |g|
if g.text == f
Player.create(name: f, team: self, position: position)
return
end
end
end
end
def get_free_agents(valueUrl, qbUrl, wrUrl, rbUrl, teUrl)
cbs = Nokogiri::HTML(open(valueUrl)).xpath("//td")
playerNames = []
cbs.each do |t|
if t.text.match(/\s+(\w+\s\w+),\s\w+\s+/)
playerNames.push(t.text.match(/\s+(\w+\s\w+),\s\w+\s+/)[1])
end
end
self.get_replacement('QB', qbUrl, playerNames)
self.get_replacement('WR', wrUrl, playerNames)
self.get_replacement('RB', rbUrl, playerNames)
self.get_replacement('TE', teUrl, playerNames)
self.get_values
end
end
| true |
3d08710fedf832229209eddf35942bc030784ee8 | Ruby | foxnewsnetwork/drunken-octo-tyrion | /app/helpers/orders_helper.rb | UTF-8 | 356 | 2.703125 | 3 | [] | no_license | module OrdersHelper
def mtilify material
price = material.unit_price
price = price.abs <= 0.000001 ? 'unknown' : price.abs unless price.is_a? String
{
:image => "http://placehold.it/150x100" ,
:header => material.name ,
:content => material.mass.to_s + " @ $#{price} per #{material.units}" ,
:link => "#"
}
end # tilify
end # Orders
| true |
cdaff0b1130661dcde46b40acd75640f79984610 | Ruby | ilanusse/bio-info | /ex1.rb | UTF-8 | 587 | 3.109375 | 3 | [
"MIT"
] | permissive | require 'bio'
if ARGV.length < 1
puts 'Please add an input file.'
exit 1
elsif ARGV.length > 2
puts 'Please do not add any extra parameters'
exit 1
end
INPUT_FILE = ARGV[0]
OUTPUT_FILE = ARGV[1] || 'ex1result.fas'
puts "Reading from #{INPUT_FILE}..."
begin
entries = Bio::GenBank.open(INPUT_FILE)
rescue => e
puts "Whoops, an error has appeared: #{e}"
exit 1
end
puts "Writing to #{OUTPUT_FILE}..."
File.open(OUTPUT_FILE, 'w') { |file| entries.each_entry { |entry| file.write(entry.to_biosequence.output_fasta) unless entry.to_biosequence.to_s.empty? } }
puts 'Done!'
| true |
32042aea03e265c11a2a9eecea7997452ef983f7 | Ruby | byelipk/exercism-ruby | /say/say.rb | UTF-8 | 852 | 3.734375 | 4 | [] | no_license | class Say
attr_reader :number, :chars, :db
def initialize(n)
@number = n
@chars = hashmap.build
@db = Database.new
end
def in_english
db.lookup[number]
end
def hashmap
@hashmap ||= Hashmap.new(number)
end
end
class Hashmap
attr_reader :n
def initialize(n)
@n = n
end
def build
n.to_s.chars
end
end
class Database
def lookup
{
0 => "zero",
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 => "fifteen",
16 => "sixteen",
17 => "seventeen",
18 => "eighteen",
19 => "nineteen",
20 => "twenty"
}
end
end
| true |
1076d876a2194942f075e14684630575401a5bb3 | Ruby | ladamesny/blog_rails4 | /app/models/user.rb | UTF-8 | 2,153 | 3.140625 | 3 | [] | no_license | require 'digest'
class User < ActiveRecord::Base
#This creates an accessor (variable) that will allow you to set the password before it's encrypted
#Remember, there is no "password" column on your database.
attr_accessor :password
validates_uniqueness_of :email
validates_length_of :email, within: 5..50
validates_format_of :email, :with => /^[^@][\w.-]+@[\w.-]+[.][a-z]{2,4}$/i, :multiline => true
validates_confirmation_of :password
validates_length_of :password, within: 4..20
validates_presence_of :password, :if => :password_required?
has_one :profile
has_many :articles, -> { order('published_at DESC, title ASC')}, :dependent => :nullify
has_many :replies, :through => :articles, :source => :comments
before_save :encrypt_new_password
#This is a class method because "self" defined in the method name is meant to be called on the class itself. That means you don't access
#it via an instance; you access it directly off the class, just as you would find, new, or create
def self.authenticate(email, password)
user = find_by_email(email)
return user if user && user.authenticated?(password)
end
#This is a simple predicate method that checks to make sure the stored hashed_password
#matches the given password after it has been encrypted (via encrypt).
# if it matches, "true" is returned.
def authenticated?(password)
self.hashed_password == encrypt(password)
end
protected
#encrypts password only if password accessor isn't blank.
def encrypt_new_password
return if password.blank?
self.hashed_password = encrypt(password)
end
#this is a predicate method that returns true if a password is required or false if it isn't
#this method is applied as an :if condition on all your password validators
#it's required only if this is a new record (the hashed_password attribute is blank)
#or if the password accessor you created has been used to set a new password (password.present?)
def password_required?
hashed_password.blank? || password.present?
end
def encrypt(string)
Digest::SHA1.hexdigest(string)
end
end
| true |
b4b8a94ba6d212a6259482071b5d7e8efca46cb9 | Ruby | CarlosAndres22/IronHack-1 | /Pre-Work/age_round.rb | UTF-8 | 73 | 3.625 | 4 | [] | no_license | age = 28
puts age.round(-1) # returns 30
puts age.round(1) # returns 28.0 | true |
39f260b024a612f657ace54e8ce3b8f63cb71989 | Ruby | pixelastic/pdf | /lib/command_helper.rb | UTF-8 | 473 | 2.84375 | 3 | [] | no_license | require 'awesome_print'
require 'open3'
# Simplified access to shell commands
module CommandHelper
# Returns true if the specified command exits with 0, false otherwise
def command_success?(command)
return false if command.empty?
_, _, status = Open3.capture3(command)
status.success?
end
# Returns what is output on stdout
def command_stdout(command)
return '' if command.empty?
stdout, = Open3.capture3(command)
stdout.strip
end
end
| true |
af5aceabbe5416d758764134b63c0c39db3f6bde | Ruby | n-ihm/rubiks_cube | /lib/view.rb | UTF-8 | 1,955 | 3.375 | 3 | [] | no_license |
class View
def initialize(cube)
@name = cube
@seiten = @name.get_cube
end
private
#ktr 17. 07
def disp_singl(sidenum, highl = nil)
z1 = 1
#zahlenblock breite 5, spacing 4
print " "
while z1 <= 9
if highl == z1 - 1
print "\033[7m#{@seiten[sidenum][z1 - 1]}\033[0m"
print " "
else
print "#{@seiten[sidenum][z1 - 1]} "
end
if z1%3 == 0
puts ""
print " "
else
end
z1 = z1 + 1
end
puts ""
puts ""
end
private
def disp_quad(a, b, c, d, sideh = nil, tileh = nil)
#ktr 17.07
# 5 spaces between blocks
add_value = 0
z2 = 1
c_sides = 0
c_tile = 0
highl = false
sides = [a, b, c, d]
while z2 <= 36
if sideh == sides[c_sides]
if tileh == c_tile
highl = true
end
end
if highl == true
print "\033[7m#{@seiten[sides[c_sides]][c_tile]}\033[0m"
print" "
highl = false
else
print "#{@seiten[sides[c_sides]][c_tile]} "
end
if z2%3 == 0
if z2%12 == 0
puts""
else
print " "
end
end
if z2%3 == 0
if z2%12 == 0
c_sides = 0
c_tile = c_tile + 1
add_value = add_value + 3
else
c_tile = add_value
c_sides = c_sides + 1
end
else
c_tile = c_tile + 1
end
z2 = z2 + 1
end
puts ""
puts ""
end
public
def display(sideh = nil, tileh = nil)
@seiten = @name.get_cube
if sideh == 2
disp_singl(2, tileh)
else
disp_singl(2)
end
if sideh == 4 || sideh == 0 || sideh == 5 || sideh == 1
disp_quad(4, 0, 5, 1, sideh, tileh)
else
disp_quad(4, 0, 5, 1)
end
if sideh == 3
disp_singl(3, tileh)
else
disp_singl(3)
end
end
end
| true |
355eb51fa6ae728280e89032aa33aa6d9b6cb523 | Ruby | tbowzz/advent_of_code_2020 | /day_05.rb | UTF-8 | 972 | 3.328125 | 3 | [] | no_license | text = File.open('day_05_input.txt').read
seats = []
text.each_line do |raw|
seats.push(raw.strip)
end
max_id = 0
seat_ids = []
seats.each do |seat|
rows = (0..127).to_a
cols = (0..7).to_a
seat.split('').each do |position|
split_point = (rows.length / 2)
if position == 'F'
rows = rows[0..split_point - 1]
next
elsif position == 'B'
rows = rows[split_point..rows.length]
next
end
split_point = (cols.length / 2)
if position == 'L'
cols = cols[0..split_point - 1]
elsif position == 'R'
cols = cols[split_point..cols.length]
end
end
seat_id = rows[0] * 8 + cols[0]
max_id = seat_id if seat_id > max_id
seat_ids.push(seat_id)
end
puts "Part 1: Highest seat id: #{max_id}"
seat_ids.sort!
previous_seat = seat_ids[0] - 1
seat_ids.each do |seat|
if seat != previous_seat + 1
puts "Part 2: Your seat: #{seat - 1}" if seat != previous_seat + 1
break
end
previous_seat = seat
end
| true |
71cb0fa2877edb5092d9789661c51d011eac4a95 | Ruby | kimnorth/codeclan_snakes_ladders | /snakes_ladders/dice.rb | UTF-8 | 133 | 2.828125 | 3 | [] | no_license | class Dice
attr_reader :dice_face
def initialize
@dice_face = 1
end
def roll_dice
return rand(1..6)
end
end | true |
c35aa680b723b7356a897fc98fdac2d8f2d8fa10 | Ruby | namdevlife/looping-for-online-web-prework | /for.rb | UTF-8 | 101 | 3.015625 | 3 | [] | no_license |
def using_for
checklist = 1..10
#your code here
for checklist in (1..10)
puts "Wingardium Leviosa"
end
end
| true |
c9b2d47c0e544fc4a596c21b5f5efbfbddeebc35 | Ruby | thestrauss3/CodeWars | /ruby/AnotherCamelCaseMethod.rb | UTF-8 | 1,075 | 4.25 | 4 | [] | no_license | # Description:
#
# Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized.
#
# Examples:
#
# # returns "theStealthWarrior"
# to_camel_case("the-stealth-warrior")
#
# # returns "TheStealthWarrior"
# to_camel_case("The_Stealth_Warrior")
def to_camel_case(str)
arr = str.split(/[ ,\-,_]/)
newstr = ''
arr.each_with_index do |word, index|
newstr += index == 0 ? word : word.capitalize
end
return newstr
end
# Test Cases:
#
# Test.assert_equals(to_camel_case(''), '', "An empty string was provided but not returned")
# Test.assert_equals(to_camel_case("the_stealth_warrior"), "theStealthWarrior", "to_camel_case('the_stealth_warrior') did not return correct value")
# Test.assert_equals(to_camel_case("The-Stealth-Warrior"), "TheStealthWarrior", "to_camel_case('The-Stealth-Warrior') did not return correct value")
# Test.assert_equals(to_camel_case("A-B-C"), "ABC", "to_camel_case('A-B-C') did not return correct value")
| true |
e511cd1cba718a3ea48413c1b2bbec7c2f77d4c8 | Ruby | sunoko/ruby-grimoire | /mokey_patch.rb | UTF-8 | 255 | 3.1875 | 3 | [] | no_license | #==============================
#
# モンキーパッチ
# (既存クラスの振る舞いを変更)
#
#==============================
p "abc".reverse #=> "cba"
class String
def reverse
"monkey patch"
end
end
p "abc".reverse #=> "monkey patch"
| true |
3122083bfddcf47e189fd475f5f599492692a573 | Ruby | srebalaji/100DaysOfAlgorithm | /day46/match_sum_of_arrays.rb | UTF-8 | 548 | 3.859375 | 4 | [] | no_license | # Given two array of integers, swap two numbers so that the sum of two arrays must be same.
ar1 = [4,1,2,1,1,2]
ar2 = [3,6,3,3]
ha1 = {}
ha2 = {}
def add_to_hash_sum_it(arr, ha)
sum = 0
arr.each do |ar|
sum += ar
if ha.key? ar
ha[ar] += 1
else
ha[ar] = 1
end
end
return sum
end
sum1 = add_to_hash_sum_it(ar1, ha1)
sum2 = add_to_hash_sum_it(ar2, ha2)
diff = (sum1 - sum2).abs
ar1.each do |ar|
next if ar >= diff
target = (diff - ar).abs
if ha2.key? target
p "#{target} #{ar}"
break
end
end
| true |
7ea390469e1b26d26ef722962860adee1e0480be | Ruby | jorgemolinan/lab | /regex4_identificadores.rb | UTF-8 | 643 | 3.5 | 4 | [] | no_license | # 1. \d es equivalente a /[0-9]/
# 2. \D es equivalente a /[^0-9]/
# 3. \w es equivalente a /[a-zA-Z0-9_]/ (cualquier letra o número)
# 4. \W es equivalente a /[^a-zA-Z0-9_]/ (cualquier letra o número al comienzo)
# 5. \s espacio (espacio, indentación, salto de línea, ...)
# 6. \b límite de palabra (inicio o fin de una palabra)
# 7. . equivale a cualquier caracter
# 8. [aB9] equivale a 'a' o 'B' o '9'
# 9. [0-9] equivale a cualquier caracter numérico
# 10. [a-zA-Z] equivale a cualquier caracter alfabético
# 11. [^a-c] equivlae a cualquier caracter EXCEPTO 'a', 'b' o 'c'
puts "ese".match?(/es[^a-c]/)
puts "esa".match?(/es[^a-c]/) | true |
cf4b8b3caa2135cef25ab72d9961b1e78b2db259 | Ruby | celestelayne/CHI_BEWD1 | /Week3/Lesson1/Homework/assignments/kent_green/kg_apartment_objects/lib/building.rb | UTF-8 | 599 | 3.53125 | 4 | [] | no_license | #Building Class
class Building
#first you have to have the attr_accessor
attr_accessor :building_name, :building_address, :apartments #these are the class-level variables
#next we have to initialize, so that all of our variables will be required
def initialize(building_name, building_address, apartments=[]) #params in the () are the methods of the initializer
#@ = the attributes of the class. These correspond to the class-level variables above and they _have_ to match.
@building_name = building_name
@building_address = building_address
@apartments = apartments
end
end
| true |
81682958b111ca8abd8559ba4e4dfd38a9613e88 | Ruby | tiabas/oauth2-provider | /lib/oauth2-provider/request.rb | UTF-8 | 2,680 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'addressable/uri'
module OAuth2Provider
class Request
RESPONSE_TYPES = [:code, :token]
GRANT_TYPES = [:authorization_code, :password, :client_credentials, :refresh_token]
attr_reader :response_type, :grant_type, :client_id, :client_secret, :state, :scope,
:errors, :username, :password, :code, :refresh_token, :redirect_uri
attr_accessor :validated
def initialize(opts = {})
@client_id = opts[:client_id]
@client_secret = opts[:client_secret]
@redirect_uri = opts[:redirect_uri]
@response_type = opts[:response_type]
@grant_type = opts[:grant_type]
@state = opts[:state]
@scope = opts[:scope]
@code = opts[:code]
@username = opts[:username]
@password = opts[:password]
@refresh_token = opts[:refresh_token]
@errors = {}
@validated = nil
end
def valid?
# REQUIRED: Check that client_id is valid
validate_client_id!
# OPTIONAL: Check the provided redirect URI is valid
validate_redirect_uri!
# REQUIRED: Either response_type or grant_type
unless @response_type || @grant_type
fail Error::InvalidRequest, 'response_type or grant_type is required'
end
if @response_type
validate_response_type!
else
validate_grant_type!
end
end
def validate_response_type!
if @response_type.nil?
fail Error::InvalidRequest, 'response_type required'
end
unless RESPONSE_TYPES.include?(@response_type.to_sym)
fail Error::UnsupportedResponseType, 'unsupported response_type'
end
true
end
def validate_grant_type!
if @grant_type.nil?
fail Error::InvalidRequest, 'grant_type required'
end
unless GRANT_TYPES.include?(@grant_type.to_sym)
fail Error::UnsupportedGrantType, 'unsupported grant_type'
end
true
end
def validate_client_id!
if @client_id.nil? || @client_id.empty?
fail Error::InvalidRequest, 'client_id is required'
end
end
def validate_redirect_uri!
return true if @redirect_uri.nil? || @redirect_uri.empty?
@errors[:redirect_uri] = []
uri = Addressable::URI.parse(@redirect_uri)
unless %w(https http).include? uri.scheme
@errors[:redirect_uri] << 'unsupported uri scheme'
end
unless uri.fragment.nil?
@errors[:redirect_uri] << 'uri may not include fragment'
end
if @errors[:redirect_uri].any?
fail Error::InvalidRequest, @errors[:redirect_uri].join(', ')
end
true
end
end
end
| true |
6681bfe7a051cf6d4a260abb1747742e70d3ec9c | Ruby | roseliux/ruby-coding-exercises | /sum_array_spec.rb | UTF-8 | 296 | 3.21875 | 3 | [
"MIT"
] | permissive | def sum(array)
array.inject(0){ |sum, e| sum += e }
end
describe 'sum' do
it 'returns the sum of the elements of given array' do
expect(sum([])).to eq(0)
expect(sum([-1, 1])).to eq(0)
expect(sum([1, 2, 3])).to eq(6)
expect(sum([1, 2, 34, 5, 6, 7, 8, 9])).to eq(72)
end
end
| true |
1a20a03b8c79682117a54528772646acce50cd8b | Ruby | mcmire/super_diff | /lib/super_diff/object_inspection/inspection_tree.rb | UTF-8 | 6,458 | 2.609375 | 3 | [
"MIT"
] | permissive | module SuperDiff
module ObjectInspection
class InspectionTree
include Enumerable
def initialize(disallowed_node_names: [], &block)
@disallowed_node_names = disallowed_node_names
@nodes = []
instance_eval(&block) if block
end
Nodes.registry.each do |node_class|
define_method(node_class.method_name) do |*args, **options, &block|
add_node(node_class, *args, **options, &block)
end
end
def each(&block)
nodes.each(&block)
end
def before_each_callbacks
@_before_each_callbacks ||= Hash.new { |h, k| h[k] = [] }
end
def render_to_string(object)
nodes.reduce("") do |string, node|
result = node.render_to_string(object)
string + result
end
end
def render_to_lines(object, type:, indentation_level:)
nodes
.each_with_index
.reduce(
[TieredLines.new, "", ""]
) do |(tiered_lines, prelude, prefix), (node, index)|
UpdateTieredLines.call(
object: object,
type: type,
indentation_level: indentation_level,
nodes: nodes,
tiered_lines: tiered_lines,
prelude: prelude,
prefix: prefix,
node: node,
index: index
)
end
.first
end
def evaluate_block(object, &block)
instance_exec(object, &block)
end
def insert_array_inspection_of(array)
insert_separated_list(array) do |value|
# Have to do these shenanigans so that if value is a hash, Ruby
# doesn't try to interpret it as keyword args
if SuperDiff::Helpers.ruby_version_matches?(">= 2.7.1")
add_inspection_of(value, **{})
else
add_inspection_of(*[value, {}])
end
end
end
def insert_hash_inspection_of(hash)
keys = hash.keys
format_keys_as_kwargs = keys.all? { |key| key.is_a?(Symbol) }
insert_separated_list(keys) do |key|
if format_keys_as_kwargs
as_prefix_when_rendering_to_lines { add_text "#{key}: " }
else
as_prefix_when_rendering_to_lines do
add_inspection_of key, as_lines: false
add_text " => "
end
end
# Have to do these shenanigans so that if hash[key] is a hash, Ruby
# doesn't try to interpret it as keyword args
if SuperDiff::Helpers.ruby_version_matches?(">= 2.7.1")
add_inspection_of(hash[key], **{})
else
add_inspection_of(*[hash[key], {}])
end
end
end
def insert_separated_list(enumerable, &block)
enumerable.each_with_index do |value, index|
as_lines_when_rendering_to_lines(
add_comma: index < enumerable.size - 1
) do
when_rendering_to_string { add_text " " } if index > 0
evaluate_block(value, &block)
end
end
end
private
attr_reader :disallowed_node_names, :nodes
def add_node(node_class, *args, **options, &block)
if disallowed_node_names.include?(node_class.name)
raise DisallowedNodeError.create(node_name: node_class.name)
end
append_node(build_node(node_class, *args, **options, &block))
end
def append_node(node)
nodes.push(node)
end
def build_node(node_class, *args, **options, &block)
node_class.new(self, *args, **options, &block)
end
class UpdateTieredLines
extend AttrExtras.mixin
method_object %i[
object!
type!
indentation_level!
nodes!
tiered_lines!
prelude!
prefix!
node!
index!
]
def call
if rendering.is_a?(Array)
concat_with_lines
elsif rendering.is_a?(PrefixForNextNode)
add_to_prefix
elsif tiered_lines.any?
add_to_last_line
elsif index < nodes.size - 1 || rendering.is_a?(PreludeForNextNode)
add_to_prelude
else
add_to_lines
end
end
private
def concat_with_lines
additional_lines =
prefix_with(prefix, prepend_with(prelude, rendering))
[tiered_lines + additional_lines, "", ""]
end
def prefix_with(prefix, text)
prefix.empty? ? text : [text[0].prefixed_with(prefix)] + text[1..-1]
end
def prepend_with(prelude, text)
if prelude.empty?
text
else
[text[0].with_value_prepended(prelude)] + text[1..-1]
end
end
def add_to_prefix
[tiered_lines, prelude, rendering + prefix]
end
def add_to_last_line
new_lines =
tiered_lines[0..-2] +
[tiered_lines[-1].with_value_appended(rendering)]
[new_lines, prelude, prefix]
end
def add_to_prelude
[tiered_lines, prelude + rendering, prefix]
end
def add_to_lines
new_lines =
tiered_lines +
[
Line.new(
type: type,
indentation_level: indentation_level,
value: rendering
)
]
[new_lines, prelude, prefix]
end
def rendering
if defined?(@_rendering)
@_rendering
else
@_rendering =
node.render(
object,
preferably_as_lines: true,
type: type,
indentation_level: indentation_level
)
end
end
end
class DisallowedNodeError < StandardError
def self.create(node_name:)
allocate.tap do |error|
error.node_name = node_name
error.__send__(:initialize)
end
end
attr_accessor :node_name
def initialize(_message = nil)
super("#{node_name} is not allowed to be used here!")
end
end
end
end
end
| true |
a49fa0dc9e704f8ceb245820784e41fa8e52f1a7 | Ruby | Sakura-Hirokawa/Ruby_2 | /lesson2.rb | UTF-8 | 81 | 2.921875 | 3 | [] | no_license | puts "私の名前は"+"sakura"+"です。"
puts "年齢は"+23.to_s+"です。"
| true |
9be8ab1479182581436867481af79846dc1cc7b0 | Ruby | rcalves82/CucumberBasic | /Exemplo1/imc/src/imc.rb | UTF-8 | 279 | 2.640625 | 3 | [] | no_license | class Imc
def calcula(peso, altura)
imc = (peso.to_i / (altura.to_f * 2)).round(2)
if imc > 22
return 'IMC deu ruim. #PartiuAcademia #NoPainNoGain'
else
return 'IMC Ok. #PartiuBK'
end
end
end | true |
f6b7833da23da41335659057c149660aa7a71ff4 | Ruby | toddt67878/udemy-learn-to-code-with-ruby | /METHODS/Parameters_and_arguments.rb | UTF-8 | 807 | 4.03125 | 4 | [] | no_license | #Argument is an input to a method
def person(name)
puts "#{name} is amazing"
puts "#{name} is charming"
puts "#{name} is talented"
end
#When calling the method we need to add the name as well to make it work,
#see below:
person ("Aga")
person ("Dave")
person ("Marta")
person "Pizza" # will work as well although it is without parenthesis
#we can just put the names in the quotes but the best practice is to put them
#as well in parenthesis
#If I have more that one argument in a method and when calling it I will
#provide only one, I'm going to get an error
puts
#Multiple arguments:
def animal(name, size)
puts "this is #{name} and it's #{size}"
end
animal("cat", "small")
animal("tiger", "big")
animal("ant", "tiny") #we don't need to put p before calling the method as
#there is no computation
| true |
6e03dc0da7fb72f1933accc02201cb222447f722 | Ruby | MelanieS/ptraj_Builder | /step_time.rb | UTF-8 | 3,798 | 3.21875 | 3 | [] | no_license | #ruby 2.2.1p85 (2015-02-26 revision 49769)
#energies files must contain time on left column, energy on right, separated by space
#change paths on line 73
#This opens the energies file, and splits it into an array at newlines
energies = Dir.glob('*energies.txt')
energies = energies.pop
text = File.open(energies).read
text = text.to_s
array = text.split("\n")
#creates time_arr which only holds time (same indices as main array)
time_arr =[]
#takes input data from energies.txt and pulls only the time at which energy occurs
#retains the whitespace char at the end of each time as well
array.each do |i|
whitespace = i.index(" ")
whitespace = whitespace.to_i
time = i[0..whitespace]
time_arr.push(time)
end
#this inserts a whitespace in front of each time allowing for grepping
time_arr.map! {|x| " " + x}
new_str_arr = []
def file_checker(file_path, time_arr, new_str_arr)
puts " "
count = 1
to_del = []
$stub = file_path.split("_")[0]
time_arr.each do |i|
#this gives us the size of the project so a status can be seen with "count"
size = time_arr.size
puts "Grepping time #{count} of #{size} in #{file_path}"
#opens an .out file, pulls data, and splits into array on newline
grepped = File.open(file_path).read.to_s
grepped_array = grepped.split("\n")
count = count + 1
grepped_array.each do |e|
#arrays look roughly like this
#NSTEP = 5180000 TIME(PS) = 5215.000 TEMP(K) = 309.60 PRESS = 0.0
#Etot = 43.0108 EKtot = 43.3737 EPtot = -0.3629
#BOND = 17.4371 ANGLE = 13.2322 DIHED = 32.3214
#1-4 NB = 17.1057 1-4 EEL = 72.6723 VDWAALS = -9.9034
#EELEC = -143.2282 EHBOND = 0.0000 RESTRAINT = 0.0000
if e.include? i
puts "Item found: #{i}"
#if item found in .out file, a path is made for it, substituting the current
#.out filename for .mdcrd. For example, if found in dyn1.out, the corresponding
#.mdcrd path is dyn1.mdcrd
mdcrd_path = file_path.gsub 'out', 'mdcrd'
#grabs the step associated with the time
#unclear on how the code works
#example line:
#NSTEP = 2765000 TIME(PS) = 202800.000 TEMP(K) = 411.39 PRESS = 0.0
#time = 202800.000
#associated step is 2765000
clean_str = e.scan(/\d+/).first
math_str = clean_str.to_i
#Divides the step by 500 to account for ... why?
math_str = math_str/500
#creates a string for output
new_str = "trajin #{mdcrd_path} #{math_str} #{math_str}"
new_str_arr.push(new_str)
#inserts the time used here into a new array for maintenance/speed
to_del.push(i)
end
end
end
#this removes a "used" time so it is not searched for after instance is found
to_del.each do |f|
time_arr.delete(f)
end
to_del = []
end
#iterates through the array of new strings
def answer(new_str_arr)
new_str_arr.each do |b|
end
end
def stub(file_path)
end
#runs the program
Dir.glob('*out') do |file_path|
results = file_checker(file_path, time_arr, new_str_arr)
end
#grabs file prefix and uses it to name files
#stub = $file_path.split("_")[0]
#writes to new file
new = File.new("ptraj.in", "w")
#puts trajin strings from the file_checker and answer methods into the file
new.puts answer(new_str_arr)
new.puts
new.puts "trajout #{$stub}.pdb pdb"
new.close
| true |
5ddfb99d336fd2c12c7491b2b0bc6ce32cf2494a | Ruby | michelemendel/misc | /projects/pgt/src/ranking.rb | UTF-8 | 1,546 | 3.375 | 3 | [] | no_license | #
# Ranking
#
# Author:: Michele Mendel
# Date:: Oslo 2009-05-11
#
# Ranking:
# 1. Number of points in all matches
# 2. Number of points in the internal matches between teams with a equal number of points
# 3. Best goal difference in all matches
# 4. Most goals scored in all matches
#
require 'pp'
require 'util'
require 'csv'
#
def get_scores(score_card_file)
score_card = []
CSV.open(score_card_file, 'r') do |row|
row.shift
score_card << row
end
divs = {}
score_card.flatten.each do |row|
div_id, teams, score = row.split(':')
divs[div_id] ||= []
divs[div_id] << [teams, score]
end
divs
end
#points, wins, loses, ties, goals for, goals against
def calculate_stats(scores)
teams = {}
scores.each do |score|
t = score[0].split('-')
s = score[1].split('-').map {|sc| sc.to_i}
2.times do |i|
teams[t[i]] ||= {:gf=>0, :ga=>0, :wn=>0, :lo=>0, :ti=>0, :pt=>0 }
teams[t[i]][:gf] += s[i]
teams[t[i]][:ga] -= s[(i-1)%2]
end
if(s[0]>s[1])
teams[t[0]][:wn] += 1; teams[t[1]][:lo] += 1
teams[t[0]][:pt] += 3
elsif(s[1]>s[0])
teams[t[1]][:wn] += 1; teams[t[0]][:lo] += 1
teams[t[1]][:pt] += 3
else
teams[t[0]][:pt] += 1; teams[t[1]][:pt] += 1
teams[t[0]][:ti] += 1; teams[t[1]][:ti] += 1
end
end
teams
end
scores = get_scores("reports/score_card.csv")
#pp scores
stats = {}
scores.each do |div, scores|
stats[div] = calculate_stats(scores)
end
pp stats | true |
0f4cf4af456b8dba34fca2354cb0603255ca793f | Ruby | hegyi/isbn_tool | /lib/isbn_tool/group.rb | UTF-8 | 299 | 2.71875 | 3 | [
"MIT"
] | permissive | module IsbnTool
class Group
attr_reader :prefix, :group_id
attr_accessor :rules
def initialize(group_text)
@prefix, @group_id = group_text.split("-")
@rules = []
end
def add_rule(rule)
@rules += Array(rule)
end
alias :add_rules :add_rule
end
end
| true |
207a0fd51dc2cdfb2b4390882903386f165b054d | Ruby | gangelo/com.realcruiter | /app/services/crypted_uri_token_creator.rb | UTF-8 | 1,641 | 2.953125 | 3 | [] | no_license | require 'openssl'
require 'base64'
require 'uri'
class CryptedUriTokenCreator
def initialize(text, action=:encrypt, params={context: nil, key: nil})
@text = ensure_text(text)
@action = ensure_action(action)
@context = ensure_context(params[:context])
@key = ensure_key(params[:key])
end
def execute
if encrypt?
URI.escape(encrypt(@context, @key, @text)[0])
else
decrypt(@context, @key, URI.unescape(@text))
end
end
private
def encrypt?
@action == :encrypt
end
def encrypt(context, key, text)
key = key + context if context.presence
crypted = aes(:encrypt, key, text)
crypted.unpack('H*')
end
def decrypt(context, key, text)
text = text[0] if text.instance_of? Array
text = [text].pack('H*')
key = key + context if context.presence
aes(:decrypt, key, text)
end
def aes(mode, key, text)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(mode)).key = Digest::SHA256.digest(key)
aes.update(text) << aes.final
end
def ensure_text(value)
if value.instance_of? String
return value
elsif value.instance_of? Fixnum
return value.to_s
else
raise "Parameter 'value' is not a String or Fixnum"
end
end
def ensure_key(key)
key.presence || Rails.application.secrets.salt
end
def ensure_action(action)
if action.presence && (action == :encrypt || action == :decrypt)
action
else
:encrypt
end
end
def ensure_context(context)
if context.presence
context = context.to_s if context.instance_of? Symbol
context
else
nil
end
end
end | true |
fd7d7f3efa170081d7cce854e75a9d07006e1ecb | Ruby | niaeashes/ume | /spec/models/pokemon_spec.rb | UTF-8 | 3,426 | 2.640625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Pokemon, type: :model do
describe "is valid" do
context "with name" do
subject { build :pokemon, name: name }
let(:name) { "mew" }
it { is_expected.to be_valid }
end
context "without name" do
subject { build :pokemon, name: nil }
it { is_expected.not_to be_valid }
end
context "with basename" do
subject { build :pokemon, basename: basename }
let(:basename) { "eevee" }
it { is_expected.to be_valid }
end
context "without basename" do
subject { build :pokemon, basename: nil }
it { is_expected.not_to be_valid }
end
context "with too short basename" do
subject { build :pokemon, basename: "A"*1 }
it { is_expected.not_to be_valid }
end
context "with too large basename" do
subject { build :pokemon, basename: "A"*13 }
it { is_expected.not_to be_valid }
end
[1, 131, 500].each do |value|
context "with valid speed" do
subject { build :pokemon, speed: value }
it { is_expected.to be_valid }
end
end
context "with minus speed" do
subject { build :pokemon, speed: -10 }
it { is_expected.not_to be_valid }
end
context "with too big speed" do
subject { build :pokemon, speed: 501 }
it { is_expected.not_to be_valid }
end
context "without name" do
subject { build :pokemon, name: nil }
it { is_expected.not_to be_valid }
end
context "without type1" do
subject { build :pokemon, type1: nil }
it { is_expected.not_to be_valid }
end
context "without type2" do
subject { build :pokemon, type2: nil }
it { is_expected.to be_valid }
end
context "with type2" do
subject { build :pokemon, type2: "Water" }
it { is_expected.to be_valid }
end
context "with incorrect type as type1" do
subject { build :pokemon, type1: "Bot" }
it { is_expected.not_to be_valid }
end
context "with incorrect type as type2" do
subject { build :pokemon, type2: "Bot" }
it { is_expected.not_to be_valid }
end
context "with 5 skills" do
subject { build :pokemon, skills: build_list(:skill, 5) }
it { is_expected.not_to be_valid }
end
context "with 4 skills" do
subject { build :pokemon, skills: build_list(:skill, 4) }
it { is_expected.to be_valid }
end
context "with 0 skills" do
subject { build :pokemon, skills: [] }
it { is_expected.not_to be_valid }
end
end
describe "#typeN=" do # N = 1 or 2
context "when provide as Japanese name" do
before { subject.type1 = "ひこう" }
it { expect(subject.type1).to eq "Flying" }
end
context "when provide as Japanese name with invalid kana" do
before { subject.type1 = "どらごん" }
it { expect(subject.type1).to eq "Dragon" }
end
end
describe "association: has many Skill" do
let(:skill) { build :skill }
subject { build :pokemon, skills: [skill] }
it { is_expected.to be_valid }
end
describe "normal?" do
context "when normal type pokemon" do
subject { build :pokemon, type1: "Normal" }
it { is_expected.to be_normal }
end
context "when dragon type pokemon" do
subject { build :pokemon, type1: "Dragon" }
it { is_expected.not_to be_normal }
end
end
end
| true |
27f625d81ecab0e825b1a2265df6b5d889351e43 | Ruby | brodock/DW-ETL | /lib/old/re_test.rb | UTF-8 | 2,156 | 3.046875 | 3 | [] | no_license | require "rubygems"
require "xml"
require "benchmark"
puts "Importador de XML para base relaciona MySQL"
class ParserXML
attr_reader :files, :tags, :xml
MAX_AMOUNT_OF_FILES = 1000
def initialize
@path = "/Users/brodock/Projetos/XML"
@files = Dir.glob("#{@path}/*.xml")
end
def parse_libxml
resultdoc = XML::Document.new
resultdoc.root = XML::Node.new 'CURRICULO-VITAE'
@tags = {}
@files.each_index do |i|
if i > MAX_AMOUNT_OF_FILES
return
end
file = File.new(@files[i])
doc = XML::Document.io(file)
root = doc.find('/CURRICULO-VITAE').first
@tags = recursive_walk(root, @tags)
end
end
protected
def recursive_walk_new(tree, tags)
tree.each do |c|
unless tags.member?(c.name) # Se não existir no hash, armazenar o node
node = c.copy(true)
node.child = nil
array = []
array[0] = {}
array[1] = node
tags.store(c.name, array)
end
unless c.child.nil?
tags[c.name][0] = recursive_walk(c.child, tags[c.name][0])
end
end
tags
end
def recursive_walk(tree, tags)
arraytags = {}
arraynodes = []
unless tree.child.nil?
tree.child.each do |c|
unless tags.member?(c.name) # Tag nova, vamos adicionar
node = c.copy(true)
childrens = recursive_walk(c, arraytags)
unless childrens.nil?
if childrens.member?('nodes')
childrens.each do |cn|
node << cn.copy(true) if cn.is_a?(XML::Node)
end
end
tags.store(c.name, childrens['tags'])
else
tags.store(c.name, nil)
end
arraynodes << node.copy(true)
end
end
result = {}
result.store 'tags', tags
result.store 'nodes', arraynodes
result
end
end
end
Benchmark.bm do |x|
x.report("Instantiation ") { @t = ParserXML.new }
x.report("Parse with LibXML") { @t.parse_libxml }
end
#outdoc = REXML::Document.new(@t.xml.to_s)
#outdoc.write($stdout, 2)
| true |
60dbb27b6dfd60d81d2e99f9b9c330113b2de508 | Ruby | sumnerjj/antcat | /app/models/rank.rb | UTF-8 | 3,132 | 3.28125 | 3 | [] | no_license | # coding: UTF-8
class Rank
def initialize hash
@hash = hash
end
def string
@hash[:string]
end
def display_string
string.titlecase
end
def uncommon?
@hash[:uncommon]
end
# Returns only Genus for species and Family for genus.
# Can't take subfamily or subgenus into consideration.
# These cases should be handled in code where there is more information
# avaiable.
def parent
parent_index = index - 1
return nil if parent_index < 0
parent = at parent_index
parent = parent.parent if parent.uncommon?
parent
end
def child
child_index = index + 1
return nil if child_index >= self.class.ranks.size
child = at child_index
child = child.child if child.uncommon?
child
end
def write_selector
"#{@hash[:string]}=".to_sym
end
def read_selector
"#{@hash[:string]}".to_sym
end
def to_sym *options
options.include?(:plural) ? @hash[:plural_symbol] : @hash[:symbol]
end
def plural
@hash[:plural_string]
end
def to_s *options
numeric_argument = options.find {|option| option.kind_of? Numeric}
options << :plural if numeric_argument && numeric_argument > 1 #hmm
s = (options.include?(:plural) ? @hash[:plural_string] : @hash[:string]).dup
s = s.titleize if options.include? :capitalized
s
end
def to_class
@hash[:klass]
end
def includes? identifier
@hash.values.include? identifier
end
def index
self.class.ranks.index do |rank|
@hash[:string] == rank.string
end
end
def at index
self.class.ranks[index]
end
def self.find identifier
return nil if identifier.blank?
identifier = identifier.class if identifier.kind_of? Taxon
identifier = identifier.first.class if identifier.kind_of? Enumerable
identifier = identifier.first.class if identifier.kind_of? ActiveRecord::Relation
identifier = identifier.downcase if identifier.kind_of? String
ranks.find { |rank| rank.includes? identifier } or raise "Couldn't find rank for '#{identifier}'"
end
class << self; alias_method :[], :find end
def self.ranks
@_ranks ||= [
Rank.new(string: 'family', plural_string: 'families', symbol: :family, plural_symbol: :families, klass: Family),
Rank.new(string: 'subfamily', plural_string: 'subfamilies', symbol: :subfamily, plural_symbol: :subfamilies, klass: Subfamily),
Rank.new(string: 'tribe', plural_string: 'tribes', symbol: :tribe, plural_symbol: :tribes, klass: Tribe, uncommon: true),
Rank.new(string: 'genus', plural_string: 'genera', symbol: :genus, plural_symbol: :genera, klass: Genus),
Rank.new(string: 'subgenus', plural_string: 'subgenera', symbol: :subgenus, plural_symbol: :subgenera, klass: Subgenus, uncommon: true),
Rank.new(string: 'species', plural_string: 'species', symbol: :species, plural_symbol: :species, klass: Species),
Rank.new(string: 'subspecies', plural_string: 'subspecies', symbol: :subspecies, plural_symbol: :subspecies, klass: Subspecies),
]
end
end
| true |
b52a2548ad5c8d14b841a26f7d7abc5fe2a80e0f | Ruby | takagotch/ruby1 | /LIST/01BigFloat/P012to_b.rb | SHIFT_JIS | 491 | 3.75 | 4 | [] | no_license | #!/usr/local/bin/ruby
# to_b.rb
# Usage: to_b n value
# value must be 0.xxxx
#
require "BigFloat"
n = ARGV.shift.to_i
v = BigFloat.new(ARGV.shift)
b = BigFloat.new("1.0")
if v >= b
raise "2Ԗڂ̈͂PȉɂĂˁI"
end
t = BigFloat.new("0.0")
s = "0."
n.times {
b = b/2.0
if t+b > v
s = s + "0"
elsif t+b < v
s = s + "1"
t = t + b
else
s = s + "1"
t = t + b
print "ϊłAI\n"
break
end
}
print "2i = ",s
| true |
b045f82fa2090fa046edfbbae6f28abf5210d8cd | Ruby | pdavidow/MetronomeApp | /test/unit/tick_test.rb | UTF-8 | 3,216 | 2.625 | 3 | [] | no_license | require 'test_helper'
class TestTick < ActiveSupport::TestCase
def test_state
Mongoid.purge!
u1 = User.create(email:'u1@user.com', password:'qewr5675jkljgrty')
p1 = u1.pieces.create(name: 'a', composer: 'c1')
p1.measures.push(Measure.new)
p1.measures.last.beats.push(Beat.new(rh:3, lh:4))
u1 = User.first
p1 = u1.pieces.find_by(name: 'a', composer: 'c1')
metronome = PolyrhythmicMetronome.new(p1)
metronome.setting.classic_ticks_per_beat = 3
ticks = metronome.validated_ticks_of_interest
self.assert_equal(12, ticks.size)
range = (0..11)
self.assert_equal([0,4,8], range.select{|each| ticks[each].is_classic})
self.assert_equal([0,4,8], range.select{|each| ticks[each].is_right_hand})
self.assert_equal([0,3,6,9], range.select{|each| ticks[each].is_left_hand})
self.assert_equal([1,2,5,7,10,11], range.select{|each| ticks[each].is_background})
end
def test_display_1
Mongoid.purge!
u1 = User.create(email:'u1@user.com', password:'qewr5675jkljgrty')
p1 = u1.pieces.create(name: 'a', composer: 'c1')
p1.measures.push(Measure.new)
p1.measures.last.beats.push(Beat.new(rh:1, lh:1))
u1 = User.first
p1 = u1.pieces.find_by(name: 'a', composer: 'c1')
metronome = PolyrhythmicMetronome.new(p1)
metronome.setting.classic_ticks_per_minute = 60
metronome.setting.classic_ticks_per_beat = 1
ticks = metronome.validated_ticks_of_interest
self.assert_equal("measure 0, beat 0, tick 0", ticks.first.location_description)
end
def test_display_2
Mongoid.purge!
u1 = User.create(email:'u1@user.com', password:'qewr5675jkljgrty')
p1 = u1.pieces.create(name: 'a', composer: 'c1')
p1.measures.push(Measure.new)
p1.measures.last.beats.push(Beat.new(rh:1, lh:4))
p1.measures.last.beats.push(Beat.new(rh:2, lh:4))
p1.measures.push(Measure.new)
p1.measures.last.beats.push(Beat.new(rh:3, lh:4))
p1.measures.last.beats.push(Beat.new(rh:4, lh:4))
u1 = User.first
p1 = u1.pieces.find_by(name: 'a', composer: 'c1')
metronome = PolyrhythmicMetronome.new(p1)
metronome.setting.classic_ticks_per_minute = 10
metronome.setting.classic_ticks_per_beat = 2
metronome.setting.begin_measure_index = 0
metronome.setting.begin_beat_index = 0
metronome.setting.end_measure_index = 1
metronome.setting.end_beat_index = 1
classic_ticks = metronome.validated_ticks_of_interest.select{|each| each.is_classic}
self.assert_equal(8, classic_ticks.size)
self.assert_equal("measure 0, beat 0, tick 0", classic_ticks[0].location_description)
self.assert_equal("measure 0, beat 0, tick 2", classic_ticks[1].location_description)
self.assert_equal("measure 0, beat 1, tick 0", classic_ticks[2].location_description)
self.assert_equal("measure 0, beat 1, tick 2", classic_ticks[3].location_description)
self.assert_equal("measure 1, beat 0, tick 0", classic_ticks[4].location_description)
self.assert_equal("measure 1, beat 0, tick 6", classic_ticks[5].location_description)
self.assert_equal("measure 1, beat 1, tick 0", classic_ticks[6].location_description)
self.assert_equal("measure 1, beat 1, tick 2", classic_ticks[7].location_description)
end
end | true |
196d0963b95848b6a81e62327d64afaa6ebe1d6c | Ruby | dingzishidtc/dzPython | /ruby.rb | UTF-8 | 979 | 2.9375 | 3 | [] | no_license | #!/usr/bin/ruby -w
# -*- coding : utf-8 -*-
# require 'rubygems'
# require 'selenium-webdriver'
# # driver = webdriver.Chrome("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe")
# driver = Selenium::WebDriver.for :Chrome
# driver.navigate.to "http://baidu.com"
# sleep 3
# element = driver.find_element(:name, 'q')
# element.send_keys "Hello WebDriver!"
# element.submit
# puts driver.title
# driver.quit
# a=[1,3.22,2.3,12,5.55]
# b=[5,3.4,2.9,1.6,4]
# p a=a.sort
# p b=b.sort
# c=[]
# a.each{|a1|
# b.each{|b1|
# p a1,b1,c
# if a1<=b1
# c<<a1
# p "取a表第一"
# else
# c<<b1
# p "取b表第一"
# end
# p a1,b1,c
# p '--------------------------------'
# break
# }
# p a,b,a1
# p '出一次循环-------------------------'
# }
list_ = ['lll', 'lKK', 'wXy']
# def f(s):
# return s[0:1].upper() + s[1:].lower()
# a = map(f, list_)
a=map(lambda x:x[0:1].upper()+x[1:].lower(), list_)
print(a)
print(list(a)) | true |
e4fbce93c7b0f79b6fb0963466616eddb3d1949c | Ruby | ellenlt/WA | /Project2/group.rb | UTF-8 | 926 | 4.28125 | 4 | [] | no_license | require 'set'
module Enumerable
=begin
This method is an iterator that yields two items at a time:
a one-character string and an array of all input values
starting with that character.
=end
def each_group_by_first_char
used_ch = Set.new
self.each_entry do |entry|
next if entry.empty?
ch = entry[0]
if !used_ch.include?(ch) then
#Keeps track of characters that have already been used
used_ch << ch
#Selects all words in array beginning with ch
words = self.select {|word| word.start_with?(ch)}
yield(ch, words)
end
end
end
end
#Test code 1
arr = ["abcd", "axyz", "able", "xyzab", "qrst"]
puts "Array: #{arr}"
arr.each_group_by_first_char do |ch, words|
printf("%s: %s\n", ch, words.join(" "))
end
puts
#Test code 2
arr = ["abcd", "", " oops", " space in front"]
puts "Array: #{arr}"
arr.each_group_by_first_char do |ch, words|
printf("%s: %s\n", ch, words.join(" "))
end
puts | true |
a9d20ca15287552ade585e98df2d64a4faab57dc | Ruby | seand08/ruby_practice | /five_numbers.rb | UTF-8 | 468 | 4.15625 | 4 | [] | no_license | puts "Give me 5 numbers."
first = gets.chomp.to_i
second = gets.chomp.to_i
third = gets.chomp.to_i
fourth = gets.chomp.to_i
fifth = gets.chomp.to_i
my_array = [first, second, third, fourth, fifth]
sum = 0
product = 1
my_array.each do |x|
sum += x
end
my_array.each do |i|
product *= i
end
puts "The Sum is " + sum.to_s
puts "The product is " + product.to_s
puts "The largest number is " + my_array.max.to_s
puts "The smallest number is " + my_array.min.to_s | true |
7eb646db5e908346bd6861f02eb310e31a151246 | Ruby | abishekaditya/exercism | /ruby/raindrops/raindrops.rb | UTF-8 | 311 | 3.125 | 3 | [] | no_license | module BookKeeping
VERSION = 3
end
# number to string based on factors
class Raindrops
def self.convert(number)
str = ''
str += 'Pling' if (number % 3).zero?
str += 'Plang' if (number % 5).zero?
str += 'Plong' if (number % 7).zero?
str == '' ? number.to_s : str
end
end
| true |
d76fb36434c31079d4efc75696c427f46b15e4cc | Ruby | josiahsp/wallerhill | /app/models/address.rb | UTF-8 | 425 | 2.6875 | 3 | [] | no_license | class Address < ActiveRecord::Base
belongs_to :user
validates_presence_of :name, :address1, :city, :state, :zip, :phone
def array
address = [self.name]
if self.company.present?
address << self.company
end
address << self.address1
if self.address2.present?
address << self.address2
end
address << self.city
address << self.state
address << self.zip
return address
end
end
| true |
cc1aa9a1babc3ad7b830db4c1ffb8867359f0736 | Ruby | berga/hacker_news_stats | /lib/hacker_news_stats/gui/cli/application.rb | UTF-8 | 942 | 2.53125 | 3 | [
"WTFPL"
] | permissive | require "awesome_print"
module HackerNewsStats
module Gui
module Cli
class Application
def initialize(posts)
@posts = posts
end
def display
puts "Hacker News Stats - Latest posts and user's statistics\n--------------"
@posts.each do |post|
self.show(post)
puts "------"
end
puts "======= END ======"
end
def show(post)
ap({
author: post.author,
karma: post.karma,
submitted: post.submitted,
stack_user: post.stack_user,
stack_reputation: post.stack_reputation,
twitter_user: post.twitter_user,
twitter_tweets: post.twitter_tweets
})
end
def self.start
self.new(Client::HackerNewsFeed.new.latest).display
end
end
end
end
end | true |
3c7f2511b7af649283bf2aeed5b3c463a3996537 | Ruby | tiagoit/code-challenges | /hackerrank/27-insertion-sort-2/solve.rb | UTF-8 | 694 | 4.09375 | 4 | [] | no_license | # https://www.hackerrank.com/contests/microverse-coding-challenges/challenges/insertionsort2
# 27 - Insertion Sort 2 - 20191020
def insertion_sort n, arr
# puts arr.join(' ')
# puts
(n - 1).times do |i|
j = i
while arr[j + 1] < arr[j] && j >= 0
arr[j], arr[j + 1] = arr[j + 1], arr[j]
j -= 1
end
puts arr.join(' ')
end
end
def solve
# insertion_sort(6, [1, 4, 3, 5, 6, 2])
# # 1 4 3 5 6 2
# # 1 3 4 5 6 2
# # 1 3 4 5 6 2
# # 1 3 4 5 6 2
# # 1 2 3 4 5 6
insertion_sort(8, [8, 7, 6, 5, 4, 3, 2, 1])
# 7 8 6 5 4 3 2 1
# 6 7 8 5 4 3 2 1
# 5 6 7 8 4 3 2 1
# 4 5 6 7 8 3 2 1
# 3 4 5 6 7 8 2 1
# 2 3 4 5 6 7 8 1
# 1 2 3 4 5 6 7 8
end
| true |
517be8fe261ce3ad3b200bbe5e4dc77cdc1bf8ac | Ruby | carojane/bank_account | /account.rb | UTF-8 | 671 | 3.125 | 3 | [] | no_license | class Account
attr_reader :name, :starting_balance
def initialize(name, starting_balance)
@name = name
@starting_balance = starting_balance.to_f
end
def current_balance
@current_balance = @starting_balance
CSV.foreach('bank_data.csv', headers: true) do |row|
if row['Account'] == @name
@current_balance += row['Amount'].to_f
end
end
@current_balance
end
def summary
@transactions = []
CSV.foreach('bank_data.csv', headers: true) do |row|
if row['Account'] == @name
transaction = Transaction.new(row)
@transactions << transaction.summary
end
end
@transactions
end
end
| true |
03b97c3b81443f0bfe78f25cc574182337ae55cc | Ruby | leo-orellana/gustavo-o | /iteracion-02/ejercicios/snaker.rb | UTF-8 | 103 | 3.046875 | 3 | [] | no_license | class Snaker
def snakear(input)
if input == "holamundo"
"HoLaMuNdO"
else
""
end
end
end
| true |
d1a7f412a2158fcc7ba9d99792070d3cffc9d83b | Ruby | hiki/hiki | /lib/hiki/pluginutil.rb | UTF-8 | 3,964 | 2.890625 | 3 | [] | no_license | #
# apply_plugin(str):
# Eval the string as a plugin.
#
# methodwords(str):
# Separte a string to a method and arguments for plugins.
#
# Copyright (C) 2004 Masao Mutoh <mutoh@highway.ne.jp>
#
# Based on shellwords.rb(in ruby standard library).
require "cgi" unless Object.const_defined?(:Rack)
require "erb"
module Hiki
module Util
DIGIT_RE = /^[-+]?\d+(\.\d+)?$/
STRING_RE = /\A"(.*)"\z/m
NIL_RE = /^\s*nil\s*$/
LSTRIP_RE = /\A\s+/
module_function
def apply_plugin(str, plugin, conf)
return str unless conf.use_plugin
set_conf(conf)
method, *args = methodwords(str)
begin
method.untaint
if plugin.respond_to?(method) && !Object.method_defined?(method)
if args
plugin.send(method, *args)
else
plugin.send(method)
end
else
raise PluginException, "not plugin method"
end
rescue Exception
raise PluginException, plugin_error("inline plugin", $!)
end
end
def convert_value(field, escape = false)
if DIGIT_RE =~ field
$1 ? field.to_f : field.to_i
elsif STRING_RE =~ field
$1
elsif NIL_RE =~ field
nil
elsif field.size > 0
field = ERB::Util.h(field) if escape
field
else
:no_data
end
end
ARG_REG_A = /\A\[/
ARG_REG_B = /\A\]/
ARG_REG_C = /\A"(([^"\\]|\\.)*)"/
ARG_REG_D = /\\(.)/
ARG_REG_E = /\A"/
ARG_REG_F = /\A'([^']*)'/
ARG_REG_G = /\A'/
ARG_REG_H = /\A(\(|\)|,)/
ARG_REG_I = /\A\\(.)/
ARG_REG_J = /\A([^\s\\'"\(\),\]]+)/
def argwords(args, escape = false)
args= String.new(args) rescue
raise(ArgumentError, "Argument must be a string")
args.sub!(LSTRIP_RE, "")
words = []
is_ary = false
until args.empty?
field = ""
loop do
if args.sub!(ARG_REG_A, "") then
child_words, args = argwords(args)
words << child_words
elsif args.sub!(ARG_REG_B, "") then
val = convert_value(field, escape)
words.push(val) unless val == :no_data
return [words, args]
elsif args.sub!(ARG_REG_C, "") then
snippet = %Q|"#{$1.gsub(ARG_REG_D, '\1').gsub(/"/, '"')}"|
elsif args =~ ARG_REG_E then
raise ArgumentError, "Unmatched double quote: #{args}"
elsif args.sub!(ARG_REG_F, "") then
snippet = %Q|"#{$1.gsub(/"/, '"')}"|
elsif args =~ ARG_REG_G then
raise ArgumentError, "Unmatched single quote: #{args}"
elsif args.sub!(ARG_REG_H, "") then
snippet = nil
break
elsif args.sub!(ARG_REG_I, "") then
snippet = $1
elsif args.sub!(ARG_REG_J, "") then
snippet = $1
else
args.sub!(LSTRIP_RE, "")
break
end
field.concat(snippet) if snippet
end
val = convert_value(field, escape)
words.push(val) unless val == :no_data
end
[words, args]
end
METHOD_REG_A = /\A([^\s\\'"\(\)]+)/
def methodwords(line)
line = String.new(line) rescue
raise(ArgumentError, "Argument must be a string")
line.sub!(LSTRIP_RE, "")
words = []
meth = ""
while ! line.empty?
if line.sub!(METHOD_REG_A, "") then
meth.concat($1)
words.push(meth)
else
child_words, = argwords(line)
words += child_words
break
end
end
words
end
end
end
if __FILE__ == $0
p Hiki::Util.methodwords("foo")
p Hiki::Util.methodwords(%Q[foo "bar", "a
iueo|
kaki"])
p Hiki::Util.methodwords(%Q[foo('ba"r', "a'iueo" )])
p Hiki::Util.methodwords(%Q[foo File, ["h]oge", "f[uga"], "bar", [1, 2.0, 0.4]])
p Hiki::Util.methodwords(%Q[foo [[0,1],[2,3]]])
p Hiki::Util.methodwords(%Q[foo nil, nil, "hoge"])
end
| true |
00af18bf63ad162002507b15044d9a8b4e3137cf | Ruby | filinivan/thinknetica | /5/station.rb | UTF-8 | 617 | 3.328125 | 3 | [] | no_license | class Station
attr_reader :name, :trains
@@stations = []
include InstanceCounter
def initialize(name)
@name = name
@trains = []
@@stations << self
register_instance
end
def self.all
@@stations.each.with_index(1) {|station, x| puts "#{x} - #{station.name}"}
end
def add_train(train)
@trains << train
end
def del_train(train)
@trains.delete(train)
end
def show_all
@trains.each {|train| puts "#{train.number} - #{train.class}"}
end
def trains_by_type(type)
@trains.each do |train|
puts train if train.class.to_s == type
end
end
end
| true |
1cf21b767df655c225d9495aa84541161f203cf0 | Ruby | drunkwater/leetcode | /medium/ruby/c0178_357_count-numbers-with-unique-digits/00_leetcode_0178.rb | UTF-8 | 647 | 3.65625 | 4 | [] | no_license | # DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#357. Count Numbers with Unique Digits
#Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
#Example:
#Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])
#Credits:
#Special thanks to @memoryless for adding this problem and creating all test cases.
## @param {Integer} n
## @return {Integer}
#def count_numbers_with_unique_digits(n)
#end
# Time Is Money | true |
4f55ec28800d06e9fe8982d965825a4dffa43dc5 | Ruby | nullkal/mastodon_healthchecker | /lib/mastodon_healthchecker/hash_hosts.rb | UTF-8 | 2,985 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
##
# Copyright (C) 2017 nullkal.
#
# This program is a derived work from Resolv::Hosts of Ruby 2.4
# (https://github.com/ruby/ruby/).
#
# ----
#
# Copyright (C) 1993-2013 Yukihiro Matsumoto. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
require 'resolv'
module MastodonHealthchecker
class HashHosts
def initialize(hosts)
@name2addr = hosts
@addr2name = {}
hosts.each do |name, addrs|
addrs.each do |addr|
@addr2name[addr] ||= []
@addr2name[addr] << name
end
end
end
##
# Gets the IP address of +name+ from the hosts file.
def getaddress(name)
each_address(name) {|address| return address}
raise ResolvError.new("#{@filename} has no name: #{name}")
end
##
# Gets all IP addresses for +name+ from the hosts file.
def getaddresses(name)
ret = []
each_address(name) {|address| ret << address}
return ret
end
##
# Iterates over all IP addresses for +name+ retrieved from the hosts file.
def each_address(name, &proc)
if @name2addr.include?(name)
@name2addr[name].each(&proc)
end
end
##
# Gets the hostname of +address+ from the hosts file.
def getname(address)
each_name(address) {|name| return name}
raise ResolvError.new("#{@filename} has no address: #{address}")
end
##
# Gets all hostnames for +address+ from the hosts file.
def getnames(address)
ret = []
each_name(address) {|name| ret << name}
return ret
end
##
# Iterates over all hostnames for +address+ retrieved from the hosts file.
def each_name(address, &proc)
@addr2name[address]&.each(&proc)
end
end
end
| true |
b0a714a3011270b76e8d3948d6e53c7a0d010654 | Ruby | kch/aliastool | /src/aliastool.rb | UTF-8 | 1,851 | 2.6875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env macruby
# encoding: utf-8
framework 'Foundation'
require 'hex_string'
require 'raisins'
require 'alias'
module Commands
extend self
USAGE = <<-EOS.gsub(/^ {4}/, '')
Usage:
{name} make TARGET [PATH] # Creates an alias to TARGET in PATH. PATH defaults to the current directory.
{name} resolve PATH # Prints the target path from resolving the alias at PATH.
{name} hex print PATH # Prints alias data to PATH as a hex-encoded string.
{name} hex resolve HEX_STRING # Resolves HEX_STRING to a system path.
{fill} # HEX_STRING is a hex-encoded string as dumped via 'hex print'.
EOS
def make
path = ARGV[2] || "."
path = File.join(path, File.basename(ARGV[1])) if File.directory? path
path_url = NSURL.fileURLWithPath(path)
alias_data = Alias.data_from_path(ARGV[1], :for_file)
raisingNSError { |e| NSURL.writeBookmarkData(alias_data, toURL: path_url, options: 0, error: e) }
end
def resolve
puts Alias.path_from_alias_path(ARGV[1])
end
def hex_resolve
puts Alias.path_from_data(HexString.decode(ARGV[2]).to_data)
end
def hex_print
puts HexString.encode(Alias.data_from_path(ARGV[2]))
end
def usage
h = { name: (s = File.basename($0)), fill: s.gsub(/./, ' ') }
puts USAGE.gsub(/\{(\w+)\}/) { h[$1.to_sym] }
exit 1 unless %w( -h --help help usage ).include? ARGV[0]
end
end
((cmd = ARGV[0, 1]) == %w( make ) && ARGV[1] && !ARGV[3]) or
((cmd = ARGV[0, 1]) == %w( resolve ) && ARGV[1] && !ARGV[2]) or
((cmd = ARGV[0, 2]) == %w( hex resolve ) && ARGV[2] && !ARGV[3]) or
((cmd = ARGV[0, 2]) == %w( hex print ) && ARGV[2] && !ARGV[3]) or
((cmd = %w( usage )))
begin
Commands.send(cmd.join("_"))
rescue => e
$stderr.puts e.description
exit 1
end
| true |
d4e713d461d44fcf7ea8984eeb51ab65b238c69d | Ruby | southerncross/document-converter | /something2excel/postgres2txt.rb | UTF-8 | 582 | 2.71875 | 3 | [] | no_license | #!/bin/ruby
# -*- coding: utf-8 -*-
require "pg"
require "Date"
conn = PG.connect dbname: "pku"
Dir.mkdir "./output" unless Dir.exist? "./output"
Date.new(2000, 01, 01).upto(Date.new(2000, 12, 31)) do |date|
sql = "SELECT year, story FROM history WHERE month=#{date.mon} AND day=#{date.day} ORDER BY year"
name = "/Users/lishunyang/workspace/interesting/something2excel/output/#{date.mon}月#{date.day}日.txt"
File.open(name, "w") do |file|
conn.exec(sql).each do |row|
file.printf "%s\n%s\n\n", row["year"].sub(/\n/, ""), row["story"].strip
end
end
end
| true |
2382b82ad1d833162cb032a3c38957c6f3344c6e | Ruby | wenbo/rubyg | /sample/CHAPTER08/180/matrix.rb | EUC-JP | 1,859 | 3.625 | 4 | [] | no_license | require 'matrix'
# 2x2ι
m1 = Matrix[[1, 2], [3, 4]]
m2 = Matrix[[5.0, 6.6], [7.2, 8.9]]
# 4гѹ
Matrix.diagonal(1,2,3,4) # => Matrix[[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]
# βû
m1+m2 # => Matrix[[6.0, 8.6], [10.2, 12.9]]
# ξ軻
m1*m2 # => Matrix[[19.4, 24.4], [43.8, 55.4]]
# Υ顼ܡ
m1*3 # => Matrix[[3, 6], [9, 12]]
3*m1 # => Matrix[[3, 6], [9, 12]]
# ߾衣Τߡ
m1**5 # => Matrix[[1069, 1558], [2337, 3406]]
# ǤѴ
m1f = m1.map{|x| x.to_f } # => Matrix[[1.0, 2.0], [3.0, 4.0]]
# չRuby 1.8Integerγ껻ƤޤϤǤʤ
# ǤFloatˤ뤳ȤDzǤ롣
m1.inv # => Matrix[[-2, 1], [1, -1]]
m1f.inv # => Matrix[[-2.0, 1.0], [1.5, -0.5]]
#
m2.det # => -3.02
#
m2.rank # => 2
# žֹ
m2.t # => Matrix[[5.0, 7.2], [6.6, 8.9]]
# ȥ졼
m2.tr # => 13.9
# 2ĥ٥ȥ롣
v1 = Vector[3, 4]
# Ƚĥ٥ȥξ軻
m1*v1 # => Vector[11, 25]
# ٥ȥΥ顼ܡRuby 1.8ȥХꥨ顼ˤʤäƤޤޤ
v1*4 # => Vector[12, 16]
4*v1 rescue $! # => #<TypeError: Vector can't be coerced into Fixnum>
# ٥ȥβû
v1+v1 # => Vector[6, 8]
# ٥ȥ벽
v1.covector # => Matrix[[3, 4]]
#
v1.r # => 5.0
#
v1.inner_product v1 # => 25
| true |
a202b14e921f28e6c65abca4de6ed4ad858d77ed | Ruby | adore/daylight | /rails/extensions/read_only_attributes.rb | UTF-8 | 909 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | module ReadOnlyAttributes
extend ActiveSupport::Concern
included do
# place the read_only attributes along side the other class_attributes for a Serializer
class_attribute :_read_only
self._read_only = []
end
module ClassMethods
##
# Records the attribues as read only then stores them as attributes
#
# See
# ActiveModel::Serializer.attributes
def read_only(*attrs)
# strip predicate '?' marks of and convert them to symbols
normalized_attrs = attrs.map { |a| a.to_s.gsub(/\?$/,'').to_sym }
# record which attributes will be read only
self._read_only = _read_only.dup
self._read_only.push(*normalized_attrs).uniq
# pass them off to attributes to do all the work
attributes(*attrs)
end
end
end
# Add the ReadOnlyAttributes to the Serializer
ActiveModel::Serializer.class_eval do
include ReadOnlyAttributes
end
| true |
e4ac5f1d19d3826d8dea78a4e180902f19c73961 | Ruby | kamilkamilc/Projekt-Euler | /501.rb | UTF-8 | 178 | 3.046875 | 3 | [] | no_license | def ile_dzielnikow (n)
(1..n).select {|k| n % k == 0 }.size
end
require "prime"
y = 500500
liczba = 1
tab = Prime.first(y)
tab.each_with_index {|v, i| puts "#{i}: #{v}"}
| true |
ce5d5083467c418d4ca218b980f52187ca2c59db | Ruby | beaucouplus/hospitalshifts | /level5/hospital/test/models/shift_test.rb | UTF-8 | 979 | 2.53125 | 3 | [] | no_license | require 'test_helper'
class ShiftTest < ActiveSupport::TestCase
setup do
@worker = Worker.create(first_name: "Vladimir", status: "medic")
@shift = Shift.new(worker_id: @worker.id,start_date: "2018-01-18")
end
test "empty shift should be invalid" do
shift = Shift.new
refute shift.valid?
end
test "shift should be valid with all parameters" do
assert @shift.valid?
end
test "shift should be invalid without worker_id" do
@shift.worker_id = nil
refute @shift.valid?
end
test "shift should be invalid without start_date" do
@shift.start_date = nil
refute @shift.valid?
end
test "shift should be invalid if start_date is an invalid date" do
@shift.start_date = "boom"
refute @shift.valid?
end
test "2 shifts should not be able to happen on the same day" do
shift_1 = Shift.create(worker_id: @worker.id, start_date: "2018-02-18")
@shift.start_date = "2018-02-18"
refute @shift.valid?
end
end
| true |
d972152bdfd450fc8b2b5144a148330f75083c14 | Ruby | MaxMEllon/ika-fry | /lib/ika/analyzer.rb | UTF-8 | 779 | 2.53125 | 3 | [] | no_license | module IkaFry
class Analizer
class << self
# @param Record::ActiveRecord_Associations_CollectionProxy<Record> records
def analyse_by_rule records
grouped = records.group_by { |r| r.rule_name }
inital = { battle: 0, win: 0, kill: 0, death: 0, assist: 0 }
grouped.map do |k, v|
[
k.to_sym,
ComposedResult.new(v.inject(inital) do |memo, r|
{
name: k,
battle: memo[:battle] + 1,
win: memo[:win] + (r.win ? 1 : 0),
kill: memo[:kill] + r.kill,
death: memo[:death] + r.death,
assist: memo[:assist] + r.assist,
}
end)
]
end.to_h
end
end
end
end
| true |
2a87289767913281f851ba552f91e5e31a1e45fe | Ruby | young10270/basic_Ruby_Python | /OOP_variable/1.rb | UTF-8 | 195 | 3.21875 | 3 | [] | no_license | class C
def initialize v
@value = v
end
def show
p @value
end
end
c1 = C.new 10
c1.show
#메소드 밖에서 직접 인스턴스 변수에 접근 불가
#p c1.value
#c1.value=20
| true |
df80ab1d2a45a47e7039a5d3799380f7827f2477 | Ruby | hanfak/ruby-database | /database.rb | UTF-8 | 3,970 | 3.609375 | 4 | [] | no_license | class String
def red; "\e[31m#{self}\e[0m" end
def green; "\e[32m#{self}\e[0m" end
def blue; "\e[34m#{self}\e[0m" end
end
@people =[["Entry","Surname","Forename", "Nationality", "Age", "Hobby"]]
@i=1
def fill_in_blanks entry
entry.map! {|item_entry| item_entry=="" ? "N/A" : item_entry}
end
def add_person_details
person =[@i]
puts "Please add the surname of person"
person << gets.chomp
puts "Please add the first name of person"
person << gets.chomp
puts "Please add the nationality"
person << gets.chomp
puts "Please add the age"
person << gets.chomp
puts "Please add a hobby"
person << gets.chomp
@i+=1
fill_in_blanks person
end
def add_person
p @people << add_person_details
end
def display_entries (database = [])
print "Here is a list of all the entries in the database\n\n"
database != [] ? database : database = @people
max_lengths = database[0].map { |word| word.length }
database.each do |x|
x.each_with_index do |e, i|
s = e.size
max_lengths[i] = s if s > max_lengths[i]
end
end
database.each { |x| puts max_lengths.map { |_| "|%#{_}s" }.join(" " * 5) % x }
puts
end
def update_person
puts "Which entry do you want to update, choose number between 1 and #{@i-1}"
choice = gets.chomp.to_i
row_to_update = [@people[0]] << @people[choice]
p display_entries row_to_update
puts "Which item to change: (1) SURNAME, (2) FORENAME, (3) NATIONALITY, (4) AGE, or (5) HOBBY."
puts "Choose a number"
item = gets.chomp.to_i
puts "To change to:"
new_data = gets.chomp
new_data = "N/A" if new_data == ""
puts "Confirm update type 'y'"
confirmation = gets.chomp
if confirmation == "y"
@people[choice][item] = new_data
elsif confirmation == "n"
return nil
else
puts "Type y or n"
update_person
end
end
def delete_person
puts "Choose entry to delete: 1 to #{@i-1}"
entry = gets.chomp.to_i
p display_entries [@people[0], @people[entry]] ###use display_entries
puts "Confirm deletion: y"
choice = gets.chomp
@people.delete_at(entry) if choice == "y"
end
def save_database
a = @people.collect {|element| element.join(",")}
File.open("database.csv", "w+") do |f|
a.each { |element| f.puts(element) }
end
end
def load_database
@people = File.foreach('database.csv').map { |line| line.split(' ') }.flatten.collect{|row| row.split(",")}
@i = @people.length
end
def menu_choice
title = "Menu"
puts title.center(60)
puts ("="*title.size).center(60)
puts "1. Add a person to database".green
puts "2. Display database".green
puts "3. Update database".green
puts "4. Search database (under construction)".red
puts "5. Delete an entry".green
puts "6. Save database to CSV (export)".blue
puts "7. Load database fro CSV (import)".blue
puts "999 to exit"
gets.chomp.to_i
end
def database
puts "Welcome to the database. Please choose from the following options, by typing in the number and pressing enter."
loop do
case menu_choice
when 1
add_person
display_entries
puts "now we have #{@i-1} entries\n\n"
when 2
display_entries
when 3
if @people.length > 1
update_person
display_entries
else
puts "\nNothing to update\n\n"
end
when 4
puts "Under Construction, choose another option."
when 5
delete_person
display_entries if @people.length > 1
puts
when 6
save_database
puts "database is saved"
when 7
load_database
puts "datbase is loaded"
display_entries
when 999
puts "\nThank you for using the database.\n\n"
exit
else
puts "\nPlease enter an option that is available.\n\n"
end
end
end
database | true |
1058275bcce660b30b712950f6db05161ac906f9 | Ruby | UltimateCoder00/Codility-Challenges | /lib/Lesson 4 Counting Elements/MissingInteger/missing_integer.rb | UTF-8 | 155 | 2.828125 | 3 | [
"MIT"
] | permissive | def missing_integer(a)
a.select! { |x| x > 0 }
return 1 if a.empty?
a.sort!.uniq!
for i in 1..(a.length+1)
return i if a[i-1] != i
end
end
| true |
aa21a352a8ea86bff283114791d2e24505c48ab8 | Ruby | abdulkalam7/kalam | /ex16.rb | UTF-8 | 597 | 3.421875 | 3 | [] | no_license | file = ARGV.first
puts "the selected file is #{file}"
puts "to cancle enter ctrl^c"
puts "opening the file"
$stdin.gets
target = open(file, 'w')
puts "about to truncate"
target.truncate(0)
puts "enter the new elements \n"
puts "enter line 1: "
line1 = $stdin.gets.chomp
puts "enter line 2:"
line2 = $stdin.gets.chomp
puts "enter line 3: "
line3 = $stdin.gets.chomp
puts "we are about to write the lines"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
puts "lets close the file"
target.close | true |
278f622f1a89f7b534c5b83817adc3fdc2cad954 | Ruby | johnwahba/LegalBacon | /script/add_opinion_starts_to_paragraph.rb | UTF-8 | 234 | 2.6875 | 3 | [] | no_license | p "running"
count = Opinion.count
Opinion.all.each_with_index do |opinion, idx|
paragraph = opinion.paragraphs.first
paragraph.start_of_opinion = true
paragraph.save!
if idx % 1000 == 0
p idx.to_s + "/" + count.to_s
end
end
| true |
89dda0fdedb7fe00755cb8c2976750fa0e2ca8c3 | Ruby | rike422/moguro | /lib/moguro/method_reference.rb | UTF-8 | 1,140 | 2.875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Moguro
# MethodReference represents original method reference that was
# decorated by contracts.ruby. Used for instance methods.
# This class borrowed many source code from https://github.com/egonSchiele/contracts.ruby
# License:: https://github.com/egonSchiele/contracts.ruby/blob/master/LICENSE
class MethodReference
attr_reader :name
# name - name of the method
# method - method object
def initialize(method)
@name = method.name
@method = method
end
# Returns method_position, delegates to Support.method_position
def position
file, line = @method.source_location
if file.nil? || line.nil?
''
else
"#{file}:#{line}"
end
end
def parameters
@method.parameters
end
end
# The same as MethodReference, but used for singleton methods.
class SingletonMethodReference < MethodReference
private
def private?(this)
this.private_methods.map(&:to_sym).include?(name)
end
def protected?(this)
this.protected_methods.map(&:to_sym).include?(name)
end
end
end
| true |
70479336f4bfb496c752a58a8fa64d8593de2be3 | Ruby | enspirit/bmg | /lib/bmg/operator/allbut.rb | UTF-8 | 2,794 | 2.859375 | 3 | [
"MIT"
] | permissive | module Bmg
module Operator
#
# Allbut operator.
#
# Projects operand's tuples on all but given attributes, that is,
# removes attributes in the list. The operator takes care of removing
# duplicates.
#
# Example:
#
# [{ a: 1, b: 2 }] allbut [:b] => [{ a: 1 }]
#
# All attributes in the butlist SHOULD be existing attributes of the
# input tuples.
#
class Allbut
include Operator::Unary
def initialize(type, operand, butlist)
@type = type
@operand = operand
@butlist = butlist
end
protected
attr_reader :butlist
public
def each
return to_enum unless block_given?
seen = {}
@operand.each do |tuple|
allbuted = tuple_allbut(tuple)
unless seen.has_key?(allbuted)
yield(allbuted)
seen[allbuted] = true
end
end
end
def insert(arg)
case arg
when Hash then operand.insert(valid_tuple!(arg))
when Enumerable then operand.insert(arg.map{|t| valid_tuple!(t) })
else
super
end
end
def update(tuple, predicate = Predicate.tautology)
operand.update(valid_tuple!(tuple), predicate)
end
def delete(predicate = Predicate.tautology)
operand.delete(predicate)
end
def to_ast
[:allbut, operand.to_ast, butlist.dup]
end
protected ### optimization
def _allbut(type, butlist)
operand.allbut(self.butlist|butlist)
end
def _matching(type, right, on)
# Always possible to push the matching, since by construction
# `on` can only use attributes that have not been trown away,
# hence they exist on `operand` too.
operand.matching(right, on).allbut(butlist)
end
def _page(type, ordering, page_index, options)
return super unless self.preserving_key?
operand.page(ordering, page_index, options).allbut(butlist)
end
def _project(type, attrlist)
operand.project(attrlist)
end
def _restrict(type, predicate)
operand.restrict(predicate).allbut(butlist)
end
protected ### inspect
def preserving_key?
operand.type.knows_keys? && operand.type.keys.find{|k|
(k & butlist).empty?
}
end
def args
[ butlist ]
end
private
def tuple_allbut(tuple)
TupleAlgebra.allbut(tuple, @butlist)
end
def valid_tuple!(tuple)
offending = tuple.keys & butlist
raise InvalidUpdateError, "#{offending.inspect} cannot be updated" unless offending.empty?
tuple
end
end # class Allbut
end # module Operator
end # module Bmg
| true |
f5f8e3ec38f22cee5e2f94d3eaecee37238d5f0c | Ruby | michaelsexton/rhubarb | /app/helpers/occurrences_helper.rb | UTF-8 | 316 | 2.9375 | 3 | [] | no_license | module OccurrencesHelper
def to_dms(ord)
deg= (ord - ord%1).to_i
min= (ord%1 *60 - (ord%1 *60 %1)).to_i
sec= ((ord%1 *60 - min)*60).to_i
return deg.to_s+("%02d"%min)+("%02d"%sec)
end
def popular(long, lat)
e = "E"+to_dms(long.abs)
s = "S"+to_dms(lat.abs)
return s+s+e+e
end
end
| true |
ec0996153a9cb0a91ef0d7a0f9ce39c86b9b2d03 | Ruby | viniavancii/TreinamentoRuby | /lib/curso/Aula33.rb | UTF-8 | 819 | 4.40625 | 4 | [] | no_license | #Range
puts intervalo = 1..5
#verificar se algum número esta dentro do intervalo
puts "\n3 está dentro do intervalo 1-5? " + intervalo.include?(3).to_s
puts "\n6 está dentro do intervalo 1-5? " + intervalo.include?(6).to_s
#metodo each = apresenta cada indice por vez
puts "\nUm de cada vez"
intervalo.each { |i| puts i}
#Map - 1*1, 2*2, 3*3, 4*4, 5*5
puts "\nNúmeros da lista multiplicados " + intervalo.map { |i| i * i }.to_s
#case
puts "\nDigite um valor entre 1 e 5: "
entrada = gets.to_i
case entrada
when 1..2 then puts "Entre 1 e 2"
when 2..5 then puts "Entre 2 e 5"
else puts "Inválido"
end
#Metodo booleano - sempre pergunta algo
a = 1
b = 1
puts a.eql? b #verifica se o valor é igual ao outro | true |
fa8b1a1e579ce1ba5e9acec7d7b22a950bd7ff66 | Ruby | huaiyulin/leetCodeRuby | /Compare Version Number.rb | UTF-8 | 368 | 3.296875 | 3 | [] | no_license | # @param {String} version1
# @param {String} version2
# @return {Integer}
def compare_version(version1, version2)
arr1 = version1.split(".")
arr2 = version2.split(".")
for i in 0..arr1.length
if arr1[i].to_i > arr2[i].to_i
return 1
elsif arr2[i].to_i >arr1[i].to_i
return -1
end
end
return 0
end | true |
83d0c0cd1da6987b561b109553e8d59a731bc775 | Ruby | naemono/checkout_system | /lib/checkout.rb | UTF-8 | 3,095 | 2.9375 | 3 | [] | no_license | # frozen_string_literal: false
require 'command_line_reporter'
require 'sequel'
require_relative './base'
require_relative './special'
# Class to hold a list of items to be calculated at a future date
# for a total price.
class Checkout < Base
attr_reader :database, :checkout_id, :specials
include CommandLineReporter
def initialize
super
@checkout_id = generate_checkout_id
@specials = initialize_specials
end
# Scan item using it's code, inserting a transaction into the database.
#
# @param [String] The item's code to process
# @return nil
# @raise ArgumentError, if the item's code was not found
def scan(item)
product = Product[code: item]
raise ArgumentError, "Item code #{item} not found" unless product
Transactions.insert(
checkout_id: @checkout_id,
product_id: product[:id]
)
end
# Sum up all transaction, applying discounts, and returning the total
#
# @return [Float] The total of all transactions
def sum
total = 0.0
discounts = apply_specials.flatten
Transactions.where(checkout_id: @checkout_id).each do |t|
total += Product[id: t[:product_id]][:price]
end
discounts.each do |d|
total -= d[:price]
end
total.round(2)
end
# Produce a line-itemed receipt of items, and discounts, with a final total.
#
# @return [nil]
def receipt
running_total = 0.0
discounts = apply_specials.flatten
discounts.each do |d|
running_total -= d[:price]
end
table(border: true) do
row do
column('Item', width: 20)
column('Discount', width: 30, align: 'right', padding: 5)
column('Price', width: 15)
end
Transactions.where(checkout_id: @checkout_id).each do |t|
running_total += Product[id: t[:product_id]][:price]
row do
column(Product[id: t[:product_id]][:code])
column('')
column(Product[id: t[:product_id]][:price])
end
end
discounts.each do |d|
row do
column('')
column(d[:code])
column(d[:price])
end
end
row do
column('Total')
column('')
column(running_total.round(2))
end
end
end
private
# Find all specials associated with a checkout id, and verify if any apply
#
# @return [Array, Float] Cost of each discount to subtract from total
def apply_specials
specials.map { |special| special.discounts_for_items(@checkout_id) }
end
# Find all specials in Discounts table, and return them
#
# @return [Array, Special] Array of Special model
def initialize_specials
specials = []
Discounts.each do |discount|
specials.push(Special.new(@database, **discount))
end
specials
end
# Generate a checkout id from the most recent in Database we can associated
# with every transaction
#
# @return [Int] Checkout id
def generate_checkout_id
last_id = Transactions.order(:checkout_id).last
last_id.nil? ? 0 : last_id[:checkout_id] + 1
rescue Sequel::DatabaseError
0
end
end
| true |
f1fd3e878bd129a367a1988f7f1c8872fb03d605 | Ruby | Haar/coderetreats | /sheffield-May7_2011/iteration2/spec/conways_spec.rb | UTF-8 | 716 | 2.734375 | 3 | [] | no_license | require 'conways'
describe Cell do
context "#live?" do
it "returns true when initialized as live" do
cell = Cell.new(:state => :live)
cell.live?.should be_true
end
it "returns false when initialized as dead" do
cell = Cell.new(:state => :dead)
cell.live?.should be_false
end
end
context "when live with 0 live neighbours" do
it "has a next state of dead" do
cell = Cell.new(:state => :live, :neighbours => 0)
cell.next_state.should == false
end
end
context "when live with 2 neighbours" do
it "has a next state of live" do
cell = Cell.new(:state => :live, :neighbours => 2)
cell.next_state.should == true
end
end
end | true |
cc338495bdb80c96aa13c660612aeda856fc0190 | Ruby | candyapplecorn/ruby-definition-clearer | /def-clearer.rb | UTF-8 | 1,462 | 3.046875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #!/usr/bin/env ruby
require 'byebug'
if ARGV.empty?
abort "\tUsage: def-clear source.rb [destination]"
elsif ARGV.any?{|a| a =~ /\-h|help/i}
abort "def-clear:
\tremoves all lines of code
\tbetween 'def' and 'end',
\twriting the result to STDOUT.
\t
\tOutput will be redirected to
\tdestination if provided."
end
$source = ARGV.first
# if a destination is provided, add .temp in case
# source is destation.
$des = ARGV.last + '.temp' if ARGV.length > 1
# Get the files and abort upon error
begin
$sfh = File.new($source, "r")
$dfh = File.new($des, "w") unless $des.nil?
rescue Exception => e
abort e.to_s.sub('@ rb_sysopen ', '')
end
$incrementers = Regexp.new(%w{^\s*if loop while until begin until do\W}.map{|s| "#{s}"}.join("|"))
$flag = true
$count = 0
# Traverse the file, omitting method bodies
$sfh.each do |line|
uncommented = line.sub(/#.*/, '')
#unless uncommented =~ /#/
$count += 1 if uncommented =~ $incrementers # nested ends? better skip them
$count += 1 if uncommented =~ /^\s*def / && !$flag # nested defs
if uncommented =~ /^\s*end/ && $count > 0 # coming out of the nesting? handle it
$count -= 1
next
end
#end
$flag = true if uncommented =~ /^\s*end/
if $des.nil?
puts line.chomp if $flag
else
$dfh.puts line.chomp if $flag
end
$flag = false if uncommented =~ /^\s*def/
end
# Rename the destination file if it was provided
File.rename($des, $des.sub('.temp', '')) unless $des.nil?
| true |
ee24e70821fff62715f0928b7e279baf46192d65 | Ruby | kpam92/app_academy_coursework | /w3d2/question_follow.rb | UTF-8 | 2,156 | 2.890625 | 3 | [] | no_license | require_relative 'questions_database'
require_relative 'question'
require_relative 'user'
class QuestionFollow
attr_accessor :user_id, :question_id
def self.all
data = QuestionsDatabase.instance.execute("SELECT * FROM question_follows")
data.map { |datum| QuestionFollow.new(datum) }
end
def initialize(options = {})
@id = options['id']
@user_id = options['user_id']
@question_id = options['question_id']
end
def self.find_by_id(id)
question_follow = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
question_follows
WHERE
id = ?
SQL
return nil unless question_follow.length > 0
QuestionFollow.new(question_follow.first)
end
def self.followers_for_question_id(question_id)
followers = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
question_follows
INNER JOIN
users
ON
question_follows.user_id = users.id
WHERE
question_follows.question_id = ?
SQL
return nil unless followers.length > 0
followers.map {|x| User.new(x)}
end
def self.followed_questions_by_user_id(user_id)
questions = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
question_follows
INNER JOIN
questions
ON
question_follows.user_id = questions.author_id
WHERE
question_follows.user_id = ?
SQL
return nil unless questions.length > 0
questions.map {|x| Question.new(x)}
end
def self.most_followed_questions(n)
questions = QuestionsDatabase.instance.execute(<<-SQL, n)
SELECT
COUNT(*) as num_follows, q.id, q.body, q.title, q.author_id
FROM
question_follows
INNER JOIN
questions q
ON
question_follows.question_id = q.id
GROUP BY
q.id
ORDER BY
COUNT(*)
DESC
LIMIT
?
SQL
return nil unless questions.length > 0
questions.map {|x| Question.new(x)}
end
def create
end
def update
end
end
| true |
bb8ecb22d012f5cb8a3ba751047f729c07a119d0 | Ruby | Michel-hub/ruby_arreglos | /venta_meses.rb | UTF-8 | 313 | 3.0625 | 3 | [] | no_license | ventas = {
Octubre: 65000,
Noviembre: 68000,
Diciembre: 72000
}
ventas.each do |k,v|
ventas[k] *= 1.1
end
puts ventas
ventas1 = {
Octubre: 65000,
Noviembre: 68000,
Diciembre: 72000
}
nuevo_ventas = {}
ventas1.each do |k,v|
nuevo_ventas[k] = v * 0.8
end
puts nuevo_ventas
| true |
7aa7ad3f3b9dca5e3f03b2d783862cee2283d7dc | Ruby | RubyCrypto/ed25519 | /lib/ed25519/verify_key.rb | UTF-8 | 1,431 | 2.859375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
module Ed25519
# Public key for verifying digital signatures
class VerifyKey
# Create a Ed25519::VerifyKey from its serialized Twisted Edwards representation
#
# @param key [String] 32-byte string representing a serialized public key
def initialize(key)
Ed25519.validate_key_bytes(key)
@key_bytes = key
end
# Verify an Ed25519 signature against the message
#
# @param signature [String] 64-byte string containing an Ed25519 signature
# @param message [String] string containing message to be verified
#
# @raise Ed25519::VerifyError signature verification failed
#
# @return [true] message verified successfully
def verify(signature, message)
if signature.length != SIGNATURE_SIZE
raise ArgumentError, "expected #{SIGNATURE_SIZE} byte signature, got #{signature.length}"
end
return true if Ed25519.provider.verify(@key_bytes, signature, message)
raise VerifyError, "signature verification failed!"
end
# Return a compressed twisted Edwards coordinate representing the public key
#
# @return [String] bytestring serialization of this public key
def to_bytes
@key_bytes
end
alias to_str to_bytes
# Show hex representation of serialized coordinate in string inspection
def inspect
"#<#{self.class}:#{@key_bytes.unpack1('H*')}>"
end
end
end
| true |
5eea17c701ae7b0ca58c4991a204c01e295f8353 | Ruby | citin/training | /codewars/unique_in_order.rb | UTF-8 | 214 | 3.375 | 3 | [] | no_license | # https://www.codewars.com/kata/54e6533c92449cc251001667
def unique_in_order(iterable)
result = []
for pos in (0..iterable.size - 1)
c = iterable[pos]
result << c if c != result[-1]
end
result
end
| true |
1ce0dfffa958fecc921a39e45200c2e742b40f7f | Ruby | luketurnerdev/codewars-challenges | /remove_smallest.rb | UTF-8 | 868 | 4.46875 | 4 | [] | no_license | # Given an array of integers, remove the smallest value.
# Do not mutate the original array/list.
# If there are multiple elements with the same value,
# remove the one with a lower index. If you get an empty array/list,
# return an empty array/list.
# Don't change the order of the elements that are left.
def remove_smallest(numbers)
smallest = 0
i = 0
while i < numbers.length-1
if numbers[i] < numbers[i+1]
smallest = numbers[i]
end
p smallest
# p numbers[i+1]
i+=1
end
numbers.delete(smallest)
numbers
end
p remove_smallest([1,2,3,4,6,3]) #Should remove 1.
#Look through the array for the smallest item
#start with first element, and if this is smaller than the next element, mark it as the smallest
#then check if i+1 is smaller than 'smallest'
#remove this item | true |
aea3d7743bd547afd9c532f9b05a676bfa74dd56 | Ruby | surgentt/bespoke-challenge | /bin/run.rb | UTF-8 | 595 | 3.734375 | 4 | [] | no_license | require_relative '../config/environment'
player1_wins = 0
player2_wins = 0
text=File.open('./lib/poker.txt').read
text.each_line do |line|
cards = line.split(' ')
hand1 = Hand.new(cards[0..4])
hand2 = Hand.new(cards[5..9])
turn = Turn.new(hand1, hand2)
winner = turn.winner
if winner == 'hand1'
player1_wins += 1
elsif winner == 'hand2'
player2_wins += 1
end
end
puts "Player 1 won #{player1_wins} times"
puts "Player 2 won #{player2_wins} times"
if player1_wins > player2_wins
puts 'Player one is the better player'
else
puts 'Player two is the better player'
end | true |
228c98e325442cc8a93ac33f2fe393811c3a4e81 | Ruby | Bcharlotin/ruby-intro-to-arrays-lab-online-web-prework | /lib/intro_to_arrays.rb | UTF-8 | 1,131 | 3.71875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def instantiate_new_array
instantiate_new_array = []
@my_new_array = instantiate_new_array
end
def array_with_two_elements
array_with_two_elements = [1, 2]
@my_two_array = array_with_two_elements
end
def first_element(my_first_element)
@taylor_swift = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"]
my_first_element = @taylor_swift.first
end
def third_element(my_third_element)
@random = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"]
my_third_element = @random[2]
end
def last_element(my_last_element)
@random = ["Welcome to New York", "Blank Space", "Style", "Out of The Woods"]
my_last_element = @random[-1]
end
def first_element_with_array_methods(first_country)
@asia = ["Thailand", "Korea", "Japan", "Myanmar"]
first_country = @asia.first
end
def last_element_with_array_methods(last_country)
@asia = ["Thailand", "Korea", "Japan", "Myanmar"]
last_country = @asia.last
end
def length_of_array(length)
@programming_languages = ["Ruby", "Javascript", "Python", "C++", "Java", "Lisp", "PHP", "Clojure"]
length = @programming_languages.length
end
| true |
41f4e12e0e0d92c24c56a38092a92cfec0e07a55 | Ruby | Oxford-G/tic_tac_toe | /lib/board.rb | UTF-8 | 345 | 2.953125 | 3 | [
"MIT"
] | permissive | class Board
def print_game(layout)
puts ' 1 2 3'
puts '-------------'
puts "| #{layout[0]} | #{layout[1]} | #{layout[2]} |"
puts '-------------'
puts "| #{layout[3]} | #{layout[4]} | #{layout[5]} |"
puts '-------------'
puts "| #{layout[6]} | #{layout[7]} | #{layout[8]} |"
puts '-------------'
end
end
| true |
66368f352018038f7a1ca4ffbc32537e82ea1e8d | Ruby | NolanHughes/ttt-with-ai-project-v-000 | /lib/players/computer.rb | UTF-8 | 2,182 | 3.53125 | 4 | [] | no_license | require 'pry'
module Players
class Computer < Player
def move(board = nil)
@board = board
if board.valid_move?("5")
"5"
elsif board.turn_count == 1
"1"
elsif close_to_winning?
close_to_winning?
elsif board.turn_count == 3
["3", "7", "9"].sample
else
["1", "2", "3", "4", "6", "7", "8", "9"].sample
end
end
WIN_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
def offense
WIN_COMBINATIONS.detect do |win_combination|
win_index_1 = win_combination[0]
win_index_2 = win_combination[1]
win_index_3 = win_combination[2]
position_1 = @board.cells[win_index_1]
position_2 = @board.cells[win_index_2]
position_3 = @board.cells[win_index_3]
if (position_1 == "O" && position_2 == "O" && position_3 != "X") || (position_2 == "O" && position_3 == "O" && position_1 != "X") || (position_1 == "O" && position_3 == "O" && position_2 != "X")
true
end
end
end
def defense
WIN_COMBINATIONS.detect do |win_combination|
win_index_1 = win_combination[0]
win_index_2 = win_combination[1]
win_index_3 = win_combination[2]
position_1 = @board.cells[win_index_1]
position_2 = @board.cells[win_index_2]
position_3 = @board.cells[win_index_3]
if (position_1 == "X" && position_2 == "X" && position_3 != "O") || (position_2 == "X" && position_3 == "X" && position_1 != "O") || (position_1 == "X" && position_3 == "X" && position_2 != "O")
true
end
end
end
def close_to_winning?
if offense
winning_array = offense
elsif defense
winning_array = defense
end
if winning_array
if @board.cells[winning_array[0]] == " "
winning_array[0] + 1
elsif @board.cells[winning_array[1]] == " "
winning_array[1] + 1
elsif @board.cells[winning_array[2]] == " "
winning_array[2] + 1
end
end
end
end
end
| true |
eb3219575ba8373bbd8cd5df747da2f944bd831e | Ruby | hiratai/strftime_jp_week | /lib/strftime_jp_week.rb | UTF-8 | 382 | 2.6875 | 3 | [
"MIT"
] | permissive | require "strftime_jp_week/version"
require "date"
require "strftime_jp_week/date"
require "strftime_jp_week/date_time"
require "strftime_jp_week/time"
module StrftimeJPWeek
JP_WEEK = ["日", "月", "火", "水", "木", "金", "土"].freeze
def strftime(format = nil)
if format.nil?
super()
else
super(format.gsub("%jw", JP_WEEK[wday]))
end
end
end
| true |
bfefa0e73097dc9dc850cff7796dd3b14f98bca9 | Ruby | neilmcdonagh1985/wk2-d2-lab | /specs/bus_spec.rb | UTF-8 | 973 | 3.046875 | 3 | [] | no_license | require('minitest/autorun')
require('minitest/rg')
require_relative("../bus")
class BusTest < MiniTest::Test
def setup
@bus = Bus.new(33, 'ocean terminal', [])
end
def test_route
assert_equal(33, @bus.route())
end
def test_destination
assert_equal("ocean terminal", @bus.destination)
end
def test_passengers
assert_equal([], @bus.passengers)
end
def test_if_bus_can_drive
assert_equal("broom broom", @bus.drive())
end
def test_how_many_passengers
@bus = Bus.new(33, 'ocean terminal', ['Steve', 'Lisa', 'Mark'])
assert_equal(3, @bus.how_many_passengers)
end
def test_add_passenger
@bus.add_passenger('Mike')
assert_equal(1, @bus.how_many_passengers)
end
def test_drop_off_passenger
@bus.drop_off_passenger('Mike')
assert_equal(0, @bus.how_many_passengers)
end
def test_remove_all_passengers
@bus.remove_all_passengers
assert_equal(0, @bus.how_many_passengers)
end
end
| true |
f6dab9ce7a64d64d66ac96ae49c395f0c8551aa9 | Ruby | AustWick/employees-webclient | /app/models/employee.rb | UTF-8 | 415 | 3.15625 | 3 | [] | no_license | class Employee
attr_accessor :id, :first_name, :last_name, :email, :birthday
def initialize(options_hash)
@id = options_hash["id"]
@first_name = options_hash["first_name"]
@last_name = options_hash["last_name"]
@email = options_hash["email"]
@birthday = options_hash["birthday"] ? Date.parse(options_hash["birthday"]) : "N/A"
end
def full_name
"#{first_name} #{last_name}"
end
end | true |
7385f95d024a7b7539e8735bfe583cde5f085265 | Ruby | junster90/homestay | /app/helpers/reservations_helper.rb | UTF-8 | 231 | 2.578125 | 3 | [] | no_license | module ReservationsHelper
def booked_dates(listing_id)
dates =[]
bookings = Reservation.where(listing_id: listing_id)
bookings.each do |b|
dates += (b.check_in..b.check_out-1).map(&:to_s)
end
return dates
end
end
| true |
d56923ef66134b2d11d371b51b4d16f769a19bc5 | Ruby | jeff-h4/test-ruby | /day5_exercises/sinatra/course/apps.rb | UTF-8 | 5,949 | 2.5625 | 3 | [] | no_license |
require "sinatra"
require "sinatra/reloader" if development?
require "faker" # for BS
# This allows using the sessions feature in Sinatra
enable :sessions
# From Sinatra FAQ: HTTP Authentication
helpers do
def protected!
return if authorized?
headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"'
halt 401, "Not authorized\n"
end
def authorized?
@auth ||= Rack::Auth::Basic::Request.new(request.env)
@auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == ['admin', 'admin']
end
end
# END From Sinatra FAQ: HTTP Authentication
#========================================================
# Configuration
#========================================================
before do
@title = "BEFORE-FILTER: Company BS"
end
#========================================================
# Routes
#========================================================
# Basic Route
get "/" do # This is a GET Request from the client
route_get_slash
end
post "/" do
route_post_slash
end
get "/companybs" do
route_get_companybs
end
post "/companybs" do
route_post_companybs
end
get "/winner" do
route_get_winner
end
post "/winner" do
route_post_winner
end
get "/test_protected" do
protected!
"you're in"
end
post "/route" do
session[:bgcolor] = params["color_selection"]
#erb :index, layout: :application
redirect back
end
# the solution for color setting is
# get "/color/:name" do
# session[:bg_color] = params[:name]
# redirect back
#end
#========================================================
# Homework
#========================================================
get "/personality_result" do
route_get_personality_result
end
post "/personality_result" do
route_post_personality_result
end
get "/calculator" do
@route = "/calculator"
@page_title = "Calculator"
@intro = "Welcome to the Calculator page"
erb :calculator, layout: :application
end
post "/calculator" do
@route = "/calculator"
@page_title = "Calculator"
@intro = "Calculation..."
@num1 = params["num1"].to_f
@num2 = params["num2"].to_f
# operate on the 2 numbers
# params["num1"] and params["num2"]
case params["math-op"]
when "+"
@calculator_output = @num1.to_f + @num2.to_f
@selected_plus = "selected"
@selected_minus = ""
@selected_mult = ""
@selected_div = ""
when "-"
@calculator_output = @num1.to_f - @num2.to_f
@selected_plus = ""
@selected_minus = "selected"
@selected_mult = ""
@selected_div = ""
when "x"
@calculator_output = @num1.to_f * @num2.to_f
@selected_plus = ""
@selected_minus = ""
@selected_mult = "selected"
@selected_div = ""
when "/"
if @num2 == 0
@calculator_output = "ERROR: Division by Zero not valid."
else
@calculator_output = @num1.to_f / @num2.to_f
end
@selected_plus = ""
@selected_minus = ""
@selected_mult = ""
@selected_div = "selected"
end
erb :calculator, layout: :application
end
#
#========================================================
# Route Definitions
#========================================================
def route_get_slash
@route = "/"
@page_title = "Home"
@intro = "Welcome Home"
@company_slogan = "Not Set"
if session[:num_visits]
session[:num_visits] += 1
else
session[:num_visits] = 1
end
erb :index, {layout: :application}
end
def route_post_slash
@route = "/"
@page_title = "Home"
@page_title = "Home"
@intro = "Welcome Home"
erb :index, {layout: :application}
end
def route_get_companybs
@route = "/companybs"
@page_title = "Home"
@page_title = "Company BS"
@intro = "Let's make some BS"
@company_slogan = "Not Set"
erb :companybs, {layout: :application}
end
def route_post_companybs
@route = "/companybs"
@page_title = "Company BS"
@intro = "Starting the BS process"
@company_slogan = Faker::Company.catch_phrase
erb :companybs, {layout: :application}
end
def route_get_winner
@route = "/winner"
@page_title = "Let's pick a winner"
@intro = "Who is feeling lucky?"
erb :winner, {layout: :application}
end
def route_post_winner
@route = "/winner"
@page_title = "We picked a winner"
@intro = ""
winner = params["name-list"].split(",").sample
@winner_string = "The winner is #{winner}"
session[:the_last_winner] = winner
erb :winner, {layout: :application}
end
def route_get_personality_result
@route = "/personality_result"
@page_title = "Personality test (index)"
@intro = "Let's start the Personality test"
erb :personality_result, {layout: :application}
#"Welcome to the Personality Test"
end
def route_post_personality_result
@route = "/personality_result"
# it looks like 'params' hash is available, without having to explicitly pass it
@page_title = "Personality Result Page"
@intro = "Here are the results:"
work_best = params["question1"]
interested_in = params["question2"]
consider_yourself = params["question3"]
if work_best == "with-deadlines" &&
interested_in == "ideas" &&
consider_yourself == "rational"
@type = "Rational"
else
@type = "I don't know"
end
erb :personality_result, {layout: :application}
end
# # post <URL>
# # This is where index.erb's form action must go
# post "/sinatra_temperature" do
# # params is a Hash object that is given to us by Sinatra
# # It contains the key / value pairs from the parameters
# # received from the client.
# # If this is a web form, the key matches the "name" HTML attribute,
# # and the value will be whatever the uer enters in the input field
# temp_deg = params[:temp_deg]
# temp_fahr = temp_deg.to_i*9/5.0 + 32
# "The temperature in fahrenheit is #{temp_fahr.to_s} degrees"
# end
| true |
5a27fde877068a7d6e732fafa8bd7d39b6f073b5 | Ruby | DanielVartanov/tty-prompt | /spec/unit/slider_spec.rb | UTF-8 | 5,102 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
RSpec.describe TTY::Prompt, "#slider" do
subject(:prompt) { TTY::TestPrompt.new }
let(:symbols) { TTY::Prompt::Symbols.symbols }
let(:left_right) { "#{symbols[:arrow_left]}/#{symbols[:arrow_right]}"}
it "specifies ranges & step" do
prompt.input << "\r"
prompt.input.rewind
expect(prompt.slider("What size?", min: 32, max: 54, step: 2)).to eq(44)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:line] * 6,
"\e[32m#{symbols[:bullet]}\e[0m",
"#{symbols[:line] * 5} 44",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m44\e[0m\n\e[?25h"
].join)
end
it "specifies default value" do
prompt.input << "\r"
prompt.input.rewind
expect(prompt.slider("What size?", min: 32, max: 54, step: 2, default: 38)).to eq(38)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:line] * 3,
"\e[32m#{symbols[:bullet]}\e[0m",
"#{symbols[:line] * 8} 38",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m38\e[0m\n\e[?25h"
].join)
end
it "specifies range through DSL" do
prompt.input << "\r"
prompt.input.rewind
value = prompt.slider("What size?") do |range|
range.help "(Move with arrows)"
range.default 6
range.min 0
range.max 20
range.step 2
range.format "|:slider| %d%%"
end
expect(value).to eq(6)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:pipe] + symbols[:line] * 3,
"\e[32m#{symbols[:bullet]}\e[0m",
"#{symbols[:line] * 7 + symbols[:pipe]} 6%",
"\n\e[90m(Move with arrows)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m6\e[0m\n\e[?25h"
].join)
end
it "formats via proc" do
prompt.input << "\r"
prompt.input.rewind
value = prompt.slider("What size?") do |range|
range.default 6
range.max 20
range.step 2
range.format ->(slider, value) { "|#{slider}| %d%%" % value }
end
expect(value).to eq(6)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:pipe] + symbols[:line] * 3,
"\e[32m#{symbols[:bullet]}\e[0m",
"#{symbols[:line] * 7 + symbols[:pipe]} 6%",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m6\e[0m\n\e[?25h"
].join)
end
it "changes display colors" do
prompt.input << "\r"
prompt.input.rewind
options = {active_color: :red, help_color: :cyan}
expect(prompt.slider("What size?", **options)).to eq(5)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:line] * 5,
"\e[31m#{symbols[:bullet]}\e[0m",
"#{symbols[:line] * 5} 5",
"\n\e[36m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[31m5\e[0m\n\e[?25h"
].join)
end
it "doesn't allow values outside of range" do
prompt.input << "l\r"
prompt.input.rewind
prompt.on(:keypress) do |event|
if event.value = "l"
prompt.trigger(:keyright)
end
end
res = prompt.slider("What size?", min: 0, max: 10, step: 1, default: 10)
expect(res).to eq(10)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
symbols[:line] * 10,
"\e[32m#{symbols[:bullet]}\e[0m 10",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? ",
symbols[:line] * 10,
"\e[32m#{symbols[:bullet]}\e[0m 10",
"\e[2K\e[1G",
"What size? \e[32m10\e[0m\n\e[?25h"
].join)
end
it "changes all display symbols" do
prompt = TTY::TestPrompt.new(symbols: {
bullet: "x",
line: "_"
})
prompt.input << "\r"
prompt.input.rewind
expect(prompt.slider("What size?", min: 32, max: 54, step: 2)).to eq(44)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
"_" * 6,
"\e[32mx\e[0m",
"#{"_" * 5} 44",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m44\e[0m\n\e[?25h"
].join)
end
it "changes all display symbols per instance" do
prompt = TTY::TestPrompt.new
prompt.input << "\r"
prompt.input.rewind
answer = prompt.slider("What size?", min: 32, max: 54, step: 2) do |range|
range.symbols bullet: "x", line: "_"
end
expect(answer).to eq(44)
expect(prompt.output.string).to eq([
"\e[?25lWhat size? ",
"_" * 6,
"\e[32mx\e[0m",
"#{"_" * 5} 44",
"\n\e[90m(Use #{left_right} arrow keys, press Enter to select)\e[0m",
"\e[2K\e[1G\e[1A\e[2K\e[1G",
"What size? \e[32m44\e[0m\n\e[?25h"
].join)
end
end
| true |
5b1f292cc7430df31131df7ca1b287b90f88d268 | Ruby | mcartmell/greygoomud | /lib/greygoo/testagent.rb | UTF-8 | 927 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'rack/test'
require 'mud'
require 'json'
class GreyGoo
class TestAgent
attr_reader :browser
attr_accessor :user_id
def app
Mud
end
def initialize
@browser = Rack::Test::Session.new(Rack::MockSession.new(Mud))
@browser.header('Accept', 'application/json')
register_user
end
def name
"TestBot#{object_id}"
end
# Register a user, save their id and draw their sword
def register_user
res = json_get("/enter?name=#{name}")
@browser.header('X-Authentication', res['session_key'])
res = json_get('/self')
@user_id = res['id']
weapon_id = res['objects'][0]['id']
res = json_get("/object/#{weapon_id}/wield")
end
%w{get put post}.each do |method|
define_method("json_#{method}") do |url|
browser.send(method, url)
while browser.last_response.redirect?
browser.follow_redirect!
end
JSON.parse(browser.last_response.body)
end
end
end
end
| true |
eff67fbd9a7ff99d232418b566e84caeff24c839 | Ruby | danreedy/dice_bag | /lib/dice_bag/dice.rb | UTF-8 | 746 | 3.453125 | 3 | [
"MIT"
] | permissive | module DiceBag
class Dice
DEFAULT_SIDES = 6
attr_reader :sides
def initialize(sides=DEFAULT_SIDES)
sides = sides.to_i
raise DiceBag::InvalidSidesError, 'Dice must have a positive integer number of sides' if sides <= 0
raise DiceBag::TooLargeError, 'Dice has too many sides' if sides > 1000
@sides = sides
end
def roll(seed=nil)
randomizer(seed).rand(1..@sides)
end
def rolls(number_of_times)
raise DiceBag::InvalidSidesError, 'number of times to roll must be a positive integer' if number_of_times < 0
number_of_times.times.collect { roll }
end
private
def randomizer(seed)
@randomizer ||= (seed.nil? ? Random.new : Random.new(seed))
end
end
end
| true |
86967e0c24272360fe1529cf5ba29f2a43eca472 | Ruby | Baxxis/final_project | /app/models/order.rb | UTF-8 | 456 | 2.625 | 3 | [] | no_license | # order class
class Order < ApplicationRecord
belongs_to :customer
before_create :set_order_status
belongs_to :order_status
has_many :order_items
before_save :update_subtotal
def subtotal
order_items
.collect { |item| item.valid? ? (item.quantity.to_i * item.unit_price.to_f) : 0 }
.sum
end
private
def set_order_status
self.order_status_id = 1
end
def update_subtotal
self[:subtotal] = subtotal
end
end
| true |
c0356e61aec9e95d2bb195e7b7c5ba001642f865 | Ruby | hinrik/ircsupport | /lib/ircsupport/masks.rb | UTF-8 | 2,379 | 3 | 3 | [
"MIT"
] | permissive | require 'ircsupport/case'
module IRCSupport
module Masks
# @private
@@mask_wildcard = '[\x01-\xFF]{0,}'
# @private
@@mask_optional = '[\x01-\xFF]{1,1}'
module_function
# Match strings to an IRC mask.
# @param [String] mask The mask to match against.
# @param [String] string The string to match against the mask.
# @param [Symbol] casemapping The IRC casemapping to use in the match.
# @return [Boolean] Will be true of the string matches the mask.
def matches_mask(mask, string, casemapping = :rfc1459)
if mask =~ /\$/
raise ArgumentError, "Extended bans are not supported"
end
string = IRCSupport::Case.irc_upcase(string, casemapping)
mask = Regexp.quote(irc_upcase(mask, casemapping))
mask.gsub!('\*', @@mask_wildcard)
mask.gsub!('\?', @@mask_optional)
mask = Regexp.new(mask, nil, 'n')
return true if string =~ /\A#{mask}\z/
return false
end
# Match strings to multiple IRC masks.
# @param [Array] masks The masks to match against.
# @param [Array] strings The strings to match against the masks.
# @param [Symbol] casemapping The IRC casemapping to use in the match.
# @return [Hash] Each mask that was matched will be present as a key,
# and the values will be arrays of the strings that matched.
def matches_mask_array(masks, strings, casemapping = :rfc1459)
results = {}
masks.each do |mask|
strings.each do |string|
if matches_mask(mask, string, casemapping)
results[mask] ||= []
results[mask] << string
end
end
end
return results
end
# Normalize (expand) an IRC mask.
# @param [String] mask A partial mask (e.g. 'foo*').
# @return [String] A normalized mask (e.g. 'foo*!*@*).
def normalize_mask(mask)
mask = mask.dup
mask.gsub!(/\*{2,}/, '*')
parts = []
remainder = nil
if mask !~ /!/ && mask =~ /@/
remainder = mask
parts[0] = '*'
else
parts[0], remainder = mask.split(/!/, 2)
end
if remainder
remainder.gsub!(/!/, '')
parts[1..2] = remainder.split(/@/, 2)
end
parts[2].gsub!(/@/, '') if parts[2]
(1..2).each { |i| parts[i] ||= '*' }
return parts[0] + "!" + parts[1] + "@" + parts[2]
end
end
end
| true |
3d5e46e7b98bd5d7dda80c403c4e8ac9b07e2c1e | Ruby | datenreisender/codersdojo_client | /app/console_view.rb | UTF-8 | 3,679 | 3 | 3 | [] | no_license | require 'shell_wrapper'
class ConsoleView
def initialize scaffolder
@scaffolder = scaffolder
end
def show_help
puts <<-helptext
CodersDojo-Client, http://www.codersdojo.org, Copyright by it-agile GmbH (http://www.it-agile.de)
CodersDojo-Client automatically runs your code kata, logs the progress and uploads the kata to codersdojo.org.
helptext
show_usage
end
def show_usage
puts <<-helptext
Usage: #{$0} command [options]
Commands:
help, -h, --help Print this help text.
help <command> See the details of the command.
setup <framework> <kata_file> Setup the environment for running the kata.
upload <framework> <session_dir> Upload the kata to http://www.codersdojo.org
Report bugs to <codersdojo@it-agile.de>
helptext
end
def show_detailed_help command
if command == 'setup' then
show_help_setup
elsif command == 'start' then
show_help_start
elsif command == 'upload' then
show_help_upload
else
show_help_unknown command
end
end
def show_help_setup
templates = @scaffolder.list_templates
puts <<-helptext
setup <framework> <kata_file_no_ext> Setup the environment for the kata for the given framework and kata file.
The kata_file should not have an extension. Use 'prime' and not 'prime.java'.
By now <framework> is one of #{templates}.
Use ??? as framework if your framework isn't in the list.
Example:
:/dojo/my_kata% #{$0} setup ruby.test-unit prime
Show the instructions how to setup the environment for kata execution with Ruby and test/unit.
helptext
end
def show_help_start
puts <<-helptext
start <shell_command> <kata_file> Start the continuous test runner, that runs <shell-command> whenever <kata_file>
changes. The <kata_file> has to include the whole source code of the kata.
Whenever the test runner is started, it creates a new session directory in the
directory .codersdojo where it logs the steps of the kata.
helptext
end
def show_help_upload
templates = @scaffolder.list_templates
puts <<-helptext
upload <framework> <session_directory> Upload the kata written with <framework> in <session_directory> to codersdojo.com.
<session_directory> is relative to the working directory.
By now <framework> is one of #{templates}.
If you used another framework, use ??? and send an email to codersdojo@it-agile.de
Example:
:/dojo/my_kata$ #{$0} upload ruby.test-unit .codersdojo/2010-11-02_16-21-53
Upload the kata (written in Ruby with the test/unit framework) located in directory ".codersdojo/2010-11-02_16-21-53" to codersdojo.com.
helptext
end
def show_help_unknown command
puts <<-helptext
Command #{command} not known. Try '#{$0} help' to list the supported commands.
helptext
end
def show_start_kata command, file
puts "Starting PersonalCodersDojo with command #{command} and kata file #{file}. Use Ctrl+C to finish the kata."
end
def show_missing_command_argument_error command
puts "Command <#{command}> recognized but no argument was provided (at least one argument is required).\n\n"
show_usage
end
def show_upload_start hostname
puts "Start upload to #{hostname}"
end
def show_upload_result result
puts result
end
def show_socket_error command
puts "Encountered network error while <#{command}>. Is http://www.codersdojo.com down?"
end
end
| true |
89433d9190f2ffc020ca1ec1e2633d3adf7bb48e | Ruby | exercism/ruby | /exercises/practice/robot-name/.meta/example.rb | UTF-8 | 221 | 2.875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Robot
def self.forget
@@name_enumerator = [*'AA000'..'ZZ999'].shuffle.each
end
self.forget
attr_reader :name
def initialize
reset
end
def reset
@name = @@name_enumerator.next
end
end
| true |
a3901db5fb69feab6daa5e9c287cfc3b12daa91b | Ruby | bryanl/luhnybin | /luhnyrb/spec/luhnyrb/chunker_spec.rb | UTF-8 | 484 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
describe Luhnyrb::Chunker do
it "chunks up text" do
text = "this is a longer string of text for testing"
chunker = Luhnyrb::Chunker.new(text)
chunker.chunk(14).must_equal("this is a long")
chunker.chunk(14).must_equal("his is a longe")
end
it "returns nil when we have no more text to chunk" do
text = "s"
chunker = Luhnyrb::Chunker.new(text)
chunker.chunk(1).must_equal("s")
chunker.chunk(1).must_equal(nil)
end
end
| true |
8271d17aad339a3f11d39592c243998154c663f5 | Ruby | digitalronin/github-actions | /reject-escalated-privileges-yaml/reject-escalated-privileges-yaml.rb | UTF-8 | 1,962 | 2.640625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require "json"
require "octokit"
require "yaml"
require File.join(File.dirname(__FILE__), "github")
# can expand this list spliting with spaces. e.g %w(cluster-admin root webops)
STRING_LIST = %w[cluster-admin]
# Output the yaml file and the code if any of the strings in the STRING_LIST is
# present in the files.
# The below code recurse through each of hash and array and pattern match if
# any of the string is present in any of the key or value field.
def main(gh)
pattern = Regexp.union(STRING_LIST)
yaml_files_in_pr(gh).find_all { |file|
if FileTest.exists?(file)
hash = YAML.load_file(file)
recurse(hash, pattern) do |path, value|
line = "#{path}:\t#{value}"
if pattern.match?(line)
message = <<~EOF
The YAML file below
#{file}
contain the code
#{line}
which will grant the user escalated privileges.
Please correct them and resubmit this PR.
EOF
gh.reject_pr(message)
exit 1
end
end
end
}
end
def recurse(obj, pattern, current_path = [], &block)
if obj.is_a?(String)
path = current_path.join(".")
if obj =~ pattern || path =~ pattern
yield [path, obj]
end
elsif obj.is_a?(Hash)
obj.each do |key, value|
recurse(value, pattern, current_path + [key], &block)
end
elsif obj.is_a?(Array)
obj.each do |value|
recurse(value, pattern, current_path, &block)
end
end
end
# Attempt to parse all the yaml/yml files in a PR,
# aside from those with 'secret' in the filename.
# Files with 'secret' in the name are very often
# git-crypted, and so would cause this action to
# fail.
def yaml_files_in_pr(gh)
gh.files_in_pr
.grep(/\.(yaml|yml)$/)
.reject { |f| f =~ /secret/ }
end
############################################################
gh = GithubClient.new
main(gh)
| true |
9c18a91a5f78d6d80075fa8812562d71ba0dfda8 | Ruby | shannonjen/sportsrocket-wdi | /day7/validation-app/app/models/user.rb | UTF-8 | 459 | 2.5625 | 3 | [] | no_license | class User < ApplicationRecord
# validates :email, length: { minimum: 4, maximum: 8 }
validates :email, uniqueness: true
before_save :some_method
before_validation :append_random_id
after_validation :geocode_address
def some_method
puts "HI!!!! We are all stardust"
end
def append_random_id
self.email = self.email + (rand*1000).ceil.to_s
end
def geocode_address
latlng = Geocoder.new(request.ip)
puts latlng
end
end
| true |
577e11a036bf0c64512e964668857f9f21146245 | Ruby | adccb/tic-tac-toe | /ruby/index.rb | UTF-8 | 1,718 | 4.0625 | 4 | [] | no_license | require "colorize"
require_relative "./class/Board.rb"
require_relative "./class/Game.rb"
require_relative "./class/Renderer.rb"
def parse_move raw
raise ArgumentError if raw.size > 2 or raw.size < 2
raw_x, raw_y = raw.split ""
raise ArgumentError if not raw_x =~ /[[:alpha:]]/ or not raw_y.to_i.between?(0, 3)
{
:x => ["a", "b", "c"].find_index { |itm| itm == raw_x.downcase },
:y => raw_y.to_i - 1
}
end
def get_move
x = nil
y = nil
while x == nil and y == nil
begin
parsed = parse_move gets.chomp
x = parsed[:x]
y = parsed[:y]
rescue ArgumentError
puts "valid moves are in the form number then letter, e.g. a1 or b2."
end
end
{ :x => x, :y => y}
end
def main
@board = Board.new
@game = Game.new :board => @board
@renderer = Renderer.new :game => @game, :board => @board
won = false
moves = 0
x = -1
y = -1
begin
while not won
@renderer.render
puts "\n\n"
puts "#{@game.current_player}'s move"
puts "\n"
puts "where would you like to move? (letter then number, e.g. #{"a1".yellow})"
x, y = get_move.values_at :x, :y
# wait for a valid move?
while not @board.can_move x, y
puts "you can't move there -- someone already did! try again."
x, y = get_move.values_at :x, :y
end
@game.move x, y, @game.current_player
moves += 1
if @game.win? x, y
won = true
@renderer.render
puts "\n\n"
puts "congratulations #{@game.change_player.red}!"
end
if moves == 9
won = true
@renderer.render
puts "\n\n"
puts "looks like nobody won this one. #{":(".blue}"
end
end
rescue Interrupt
# no-op
end
end
main
| true |
765f9a31c88ce7a5a9448c675c3e3c8c9a9906ad | Ruby | S-Maitland/Rock_Paper_Scissors_GAME | /controller.rb | UTF-8 | 287 | 2.671875 | 3 | [] | no_license | require('sinatra')
require('sinatra/contrib/all')
require('pry-byebug')
require_relative('models/rps.rb')
get "/" do
erb(:home)
end
# TODO: add a controller
get "/rps/:hand1/:hand2" do
game = RPS.new(params[:hand1], params[:hand2])
@winner = game.play_game()
erb(:result)
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.