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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4a646e9a04653f3920b28d0c60d4f096b6da71d2 | Ruby | clejacquet/c2asmjs | /core/error_handler.rb | UTF-8 | 194 | 2.796875 | 3 | [] | no_license | require('singleton')
class ErrorHandler
include Singleton
attr_reader :errors
def initialize
@errors = Array.new
end
def register_error(error)
@errors.push(error)
end
end | true |
5b3dab4e5d1e07a2be598e91deb96b30d577f0aa | Ruby | Rainiugnas/password_manager | /lib/cli_file_crypter.rb | UTF-8 | 2,579 | 2.96875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'cli'
# Handle actions related to the cli file crypter interface.
module CliFileCrypter
# Starter point of the cli file crypter.
# Run CliFileCrypter.run, it use the ARGV arguments to find and execute an action.
# Catch all PasswordManager::PasswordManagerError to stop the execution and print the error.
def self.run
option = success! Cli::Option.new
storage = success!(Cli::Storage.new option.file)
password = success!(Cli::Input::PasswordConfirmation.new "Enter your password: \n")
crypters = [
PasswordManager::Crypter::Aes.new(password.value),
PasswordManager::Crypter::Base64.new
]
send find_action(option), storage, crypters, option
rescue PasswordManager::PasswordManagerError => e
print e.message
end
# Raise a password manager exception with the given message
# @param message [String] Error message
# @raise [PasswordManager::PasswordManagerError] Exception raise
def self.interupt! message; raise PasswordManager::PasswordManagerError, message end
# Check that the given object have true success and return the object.
# @param [Object] object Object to check, must respond to success and error method
# @raise [PasswordManager::PasswordManagerError] When success is false
def self.success! object
return object if object.success
interupt! object.error
end
# @!group Actions
# Encrypt the file
# @param storage [Storage] Hold and handle the data of the given file
# @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data
# @param _option [Option] Parsed ARGV arguments
def self.encrypt storage, crypters, _option
crypters.each { |crypter| storage.data = crypter.encrypt storage.data }
storage.save!
end
# Decrypt the file
# @param storage [Storage] Hold and handle the data of the given file
# @param crypters [Arrays(Crypter)] Crypters to encrypt / decrypt the data
# @param _option [Option] Parsed ARGV argumentss
def self.decrypt storage, crypters, _option
crypters.reverse_each { |crypter| storage.data = crypter.decrypt storage.data }
storage.save!
end
# Find the option action to execute (encrypt or decrypt)
# @param option [Option] Hold the action to execute from ARGV
def self.find_action option
%i(encrypt decrypt).each do |action|
return action if option.send action
end
interupt! 'Option must be file and either encrypt or decrypt. Other option are not suported.'
end
private_class_method :find_action, :encrypt, :decrypt, :success!
end
| true |
9d4ce190afe9d87ec341074fe1dd2f061c40d61d | Ruby | dkackar/assignment_ruby_warmup | /stock_picker.rb | UTF-8 | 685 | 3.453125 | 3 | [] | no_license | def stock_picker(arr)
max = arr.size - 1
min = 0
diff = 0
save_buy_index = 0
save_sell_index = 0
(max - 1).times do |buy_index|
buy_index+1.upto(max) do |sell_index|
if (arr[sell_index] - arr[buy_index]) >= diff
save_buy_index = buy_index
save_sell_index = sell_index
diff = arr[sell_index] - arr[buy_index]
end
end
end
puts "Stock buy at #{arr[save_buy_index]} index #{save_buy_index}"
puts "Stock sell at #{arr[save_sell_index]} index #{save_sell_index}"
return [save_buy_index,save_sell_index].inspect
end
puts stock_picker([44, 30, 24, 32, 35, 30, 40, 38, 15])
puts stock_picker([35,40,41,38,36,10]) | true |
bc339d20c789a8d2d4540569247a690176d52379 | Ruby | Jamalp/calculator | /Menu.rb | UTF-8 | 592 | 3.765625 | 4 | [] | no_license |
BREAD = 5
CHEESE = 3
STEAK = 25
SALMON = 20
CAKE = 7
PUDDING = 6
total = 0
puts "What would you like for starters?" +
"we have" + " cheese or bread"
appetizer = gets.chomp
if appetizer == "bread"
total += BREAD
else
total += CHEESE
end
puts "ok, what about for an entree, steak or salmon?"
entree = gets.chomp
if entree == "steak"
total += STEAK
else
total += SALMON
end
puts "and dessert, we have cake or pudding"
dessert = gets.chomp
if dessert == "cake"
total += CAKE
else
total += PUDDING
end
puts "your total is #{total} ".to_s | true |
90698cff4ab1f62c216b314f61d8a4463d7405c7 | Ruby | omiron33/ruby_april_2018 | /shane_fisher/oop/Human/human.rb | UTF-8 | 523 | 3.921875 | 4 | [] | no_license | class Human
attr_accessor :str, :int, :stealth, :health
def initialize
@str = 3
@int = 3
@stealth = 3
@health = 100
end
def attack(object)
if object.class.ancestors.include? Human
object.health -= 10
puts "Target has #{object.health} left."
self
else
puts "You can't attack a non-Human"
self
end
end
end
Eric = Human.new
Todd = Human.new
Eric.attack(Todd).attack(Todd).attack(Todd) | true |
9982a28f31e9334fac2e6e8efc8e26a5aeb75297 | Ruby | pu-dc/RubySpace | /Chapter-1/operator-logic.rb | UTF-8 | 632 | 3.546875 | 4 | [
"MIT"
] | permissive | =begin
Logic operator digunakan untuk menggabung dua sub-conditional menjadi satu. Operan dari operasi logic harus bertipe logic, baik TrueClass maupun FalseClass. Daftar Logic operator didalam Ruby dapat dilihat pada table dibawah ini :
&& AND
|| OR
! NOT
and &&
or ||
not !
=end
puts "Insert some words : "
text = gets
vocal = 0
text.each_char { |c| #
c = c.downcase
if c == 'a' or
c == 'i' ||
c == 'u' or
c == 'e' ||
c == 'o' then
vocal += 1
end
}
puts "Vocal character count : #{vocal}" | true |
5d2cb131252576d0b7529be190db5fdeb38942b8 | Ruby | conyekwelu/rb101 | /basics_review/basics_arrays.rb | UTF-8 | 1,638 | 4.625 | 5 | [] | no_license | CORE CONCEPTS
- Array.map iterates over an array and returns a new array with each element transformed based on the block return value
- Array.each returns the original array
- Array.select takes a boolean (or expression that evaluates to one) in the block and returns a new array with the chosen elements
New Pet
pets = ['cat', 'dog', 'fish', 'lizard']
my_pet = pets[2]
puts "I have a pet #{my_pet}!"
More Than One
pets = ['cat', 'dog', 'fish', 'lizard']
my_pet = pets[2..3]
puts "I have a pet #{my_pet[0]} and a pet #{my_pet[0]}!"
Free the Lizard
pets = ['cat', 'dog', 'fish', 'lizard']
my_pets = pets[2..3]
my_pets.pop
puts "I have a pet #{my_pet[0]}!"
One Isnt Enough
pets = ['cat', 'dog', 'fish', 'lizard']
my_pets = pets[2..3]
my_pets.pop
my_pets << pets[1] # or my_pets.push(pets[1])
puts "I have a pet #{my_pet[0]} and a pet #{my_pet[0]}!"
What Color Are You?
colors = ['red', 'yellow', 'purple', 'green']
colors.each do |color|
puts "I'm the color #{color}!"
end
Doubled
numbers = [1, 2, 3, 4, 5]
doubled_numbers = numbers.map do |number|
number * 2
end
p doubled_numbers
Divisible by Three
numbers = [5, 9, 21, 26, 39]
divisible_by_three = numbers.select do |number|
number % 3 == 0
end
p divisible_by_three
Favorite Number (Part 1)
['Dave', 7, 'Miranda', 3, 'Jason', 11]
[['Dave', 7], ['Miranda', 3], ['Jason', 11]]
Favorite Number (Part 2)
favorites = [['Dave', 7], ['Miranda', 3], ['Jason', 11]]
flat_favorites = favorites.flatten
p flat_favorites
Are We The Same?
array1 = [1, 5, 9]
array2 = [1, 9, 5]
puts array1 == array2
| true |
88ffac4db465c0df0fc8d59b6be31da9fad05abd | Ruby | DragonController/Exercise-1b-Names | /main.rb | UTF-8 | 330 | 3.46875 | 3 | [] | no_license | class Bike
# ...
end
class RedBicycle < Bike
amount = 10
def initialize(height, weight, color)
@height = height
@weight = weight
@color = color
end
def get_color
@color
end
def get_height
@height
end
def decrease_weight_by_amount
@weight -= amount
end
end | true |
bbe357150c7ec7687a8ea47cb76794a715f7bba7 | Ruby | ieda/think_compass | /core/core.rb | UTF-8 | 7,596 | 3 | 3 | [] | no_license | module MenuTree
def self.get_menu_tree(root_sym = :default)
case root_sym
when :default; return [:recognization, :resouce, :motivation]
when :recognization; return [:purpose, :path]
when :resouce; return [:time, :money, :tool, :human, :infomation]
when :motivation; return [:positiveness, :concentration, :patience, :leeway]
end
end
def self.get_menu_name(menu_sym, lang=:ja_JP)
case lang
when :ja_JP
case menu_sym
when :recognization; return "理解"
when :resouce; return "資源"
when :motivation; return "気持ち"
when :purpose; return "目的"
when :path; return "やり方"
when :time; return "時間"
when :money; return "お金"
when :tool; return "道具"
when :human; return "人"
when :infomation; return "情報"
when :positiveness; return "やる気"
when :concentration; return "集中"
when :patience; return "根気"
when :leeway; return "ゆとり"
end
end
end
def self.get_menu_sym(menu_name, lang=:ja_JP)
case lang
when :ja_JP
case menu_name
when "理解"; return :recognization
when "資源"; return :resouce
when "気持ち"; return :motivation
when "目的"; return :purpose
when "やり方"; return :path
when "時間"; return :time
when "お金"; return :money
when "道具"; return :tool
when "人"; return :human
when "情報"; return :infomation
when "やる気"; return :positiveness
when "集中"; return :concentration
when "根気"; return :patience
when "ゆとり"; return :leeway
end
end
end
def self.get_menu_names_with_tree(root_sym = :default, lang = :ja_JP)
get_menu_tree(root_sym).map{|e| get_menu_name(e, lang)}
end
end
class Question
attr_reader :description
def initialize(description: "")
@description = description
end
def to_s
@description
end
end
class SelectAnswerQuestion < Question
attr_reader :menu
def initialize(description: "選択肢を選んで回答する質問", menu: [])
super(description: description)
throw ArgumentError.new("選択肢のデータが不正です。") if menu.length == 0
@menu = menu
end
def to_s
str = super
@menu.each_with_index{|m, i| str += "\n#{convert_index_to_input(i)}. #{m}"}
str
end
def convert_index_to_input(index)
input_str = ""
if (index < 9 && index >= 0)
data_set = []
data_set[0] = "a"
data_set[1] = "s"
data_set[2] = "d"
data_set[3] = "f"
data_set[4] = "g"
data_set[5] = "h"
data_set[6] = "j"
data_set[7] = "k"
data_set[8] = "l"
input_str = data_set[index]
else
throw ArgumentError.new("インデックスが不正です。:#{index}")
end
input_str
end
end
class AnswerManager
def initialize
@mode_menu_pair = []
end
def add(mode, selected_menu)
@mode_menu_pair << [mode, selected_menu]
end
def first_selected_menu
@mode_menu_pair[0][1]
end
def last_mode
@mode_menu_pair[@mode_menu_pair.length - 1][0]
end
def last_selected_menu
@mode_menu_pair[@mode_menu_pair.length - 1][1]
end
def count
@mode_menu_pair.length
end
def select_with_mode(mode)
@mode_menu_pair.select{|pair| pair[0] == mode}.map{|pair| pair[1]}
end
end
class ThinkCompassCore
attr_reader :answers, :question, :result
def initialize
init
end
def init
@received_answers = {}
@answers = AnswerManager.new
@current_language = :ja_JP
@question = go_next_question
@on_result = false
@result = nil
end
def receive_answer(data)
if (data != nil)
selected_index = nil
if (@question.is_a?(SelectAnswerQuestion))
selected_index = convert_input_to_index(data)
@answers.add(@current_question_mode, MenuTree.get_menu_sym(@menu[selected_index], @current_language))
end
end
end
def go_next_question
if to_go_result?
@on_result = true
@result = build_result
end
case @current_question_mode
when nil, :more
@current_question_mode = :less
if @current_tree_root == nil
@current_tree_root = :default
@current_tree = MenuTree.get_menu_tree(@current_tree_root)
else
@current_tree_root = @answers.select_with_mode(:less)[-1]
@current_tree = MenuTree.get_menu_tree(@current_tree_root)
end
if @current_tree != nil
@menu = MenuTree.get_menu_names_with_tree(@current_tree_root, @current_language)
@question = SelectAnswerQuestion.new(description: "一番不足しているのはどれですか?", menu: @menu)
else
@question = nil
end
when :less
@current_question_mode = :more
if @answers.count == 1
selected_index = MenuTree.get_menu_tree(@current_tree_root).index(@answers.last_selected_menu)
@menu.slice!(selected_index)
@question = SelectAnswerQuestion.new(description: "一番余裕があるのはどれですか?", menu: @menu)
else
@current_tree_root = @answers.select_with_mode(:more)[-1]
@current_tree = MenuTree.get_menu_tree(@current_tree_root)
if @current_tree != nil
@menu = MenuTree.get_menu_names_with_tree(@current_tree_root, @current_language)
@question = SelectAnswerQuestion.new(description: "一番余裕があるのはどれですか?", menu: @menu)
else
@question = nil
end
end
end
@question
end
def to_go_result?
@answers.count >= 2
end
def go_result
@on_result = true
@question = nil
set_next_question(nil, nil, nil)
end
def on_result?
@on_result
end
def continue_question
@on_result = false
@current_question_mode = @answers.last_mode == :more ? :less : :more
end
private
def set_next_question(current_question_mode, menu, next_question)
@current_question_mode = current_question_mode
@menu = menu
@next_question = next_question
end
def set_second_enough_question
next_id = nil
latest_answer_sym = MenuTree.get_menu_sym(@received_answers[:enough_element], @current_language)
case latest_answer_sym
when :resouce
next_id = :enough_element_資源
when :motivation
next_id = :enough_element_気持ち
when :recognization
next_id = :enough_element_理解
end
menu = MenuTree.get_menu_names_with_tree(latest_answer_sym, :ja_JP)
set_next_question(next_id, menu, SelectAnswerQuestion.new(description: "一番余裕があるのはどれですか?", menu: menu))
end
def nested_key_each(hash, &block)
hash.each_key{|key|
block.call(key)
nested_key_each(hash[key], &block) if hash[key].length != 0
}
end
def convert_input_to_index(data)
selected_index = 0
if (data.length == 1)
data_set = []
data_set[0] = ["1", "a"]
data_set[1] = ["2", "s"]
data_set[2] = ["3", "d"]
data_set[3] = ["4", "f"]
data_set[4] = ["5", "g"]
data_set[5] = ["6", "h"]
data_set[6] = ["7", "j"]
data_set[7] = ["8", "k"]
data_set[8] = ["9", "l"]
selected_index = data_set.index{|d| d.include?(data)}
else
throw ArgumentError.new("回答データが不正です。:#{data}") if selected_index < 0 || selected_index >= @menu.length
end
selected_index
end
def build_result
return nil if @answers.count < 2
return {less: @answers.select_with_mode(:less), more: @answers.select_with_mode(:more)}
end
end
| true |
1a3c894b16d7b083c94034d9fc3be07c904f8903 | Ruby | e-pavlica/riser_chart | /lib/wedge.rb | UTF-8 | 859 | 3 | 3 | [] | no_license | # frozen_string_literal: true
class Wedge
DIMENSIONS = [
{ step: 'Floor', width: 36.4 },
{ step: 1, width: 36.4 },
{ step: 2, width: 42.8 },
{ step: 3, width: 49.1 },
{ step: 4, width: 55.5 },
{ step: 5, width: 61.9 },
{ step: 6, width: 68.2 },
{ step: 7, width: 74.6 },
{ step: 8, width: 81.0 },
{ step: 9, width: 87.3 }
].freeze
attr_reader :rows
def initialize(space)
@rows = build_rows(space)
end
def build_rows(space)
DIMENSIONS.map do |dim|
Row.new(dim[:width], dim[:step], space)
end
end
def fill_wedge(singers)
idx = 0
rows.each do |row|
row.spaces.times do
row.add_singer(singers[idx])
idx += 1
end
row.sort_by_section!
end
end
def available_spaces
@available_spaces ||= rows.collect(&:spaces).reduce(:+)
end
end
| true |
184a47674bcb689e5632078f53c26ef19d15aeda | Ruby | gnovos/mobj | /lib/ext/symbol.rb | UTF-8 | 225 | 2.9375 | 3 | [] | no_license | module Mobj
class ::Symbol
def walk(obj)
to_s.walk(obj)
end
def method_missing(name, *args, &block)
str = to_s
str.respond_to?(name) ? str.send(name, *args, &block) : super
end
end
end | true |
0e8403fc5138e254113241d10f33b75beb8748f8 | Ruby | ozyborg/advent-of-code | /2021/day-08/part-01.rb | UTF-8 | 226 | 3.234375 | 3 | [] | no_license | def process(data)
data.flat_map(&:last).count { |d| [2, 4, 3, 7].include?(d.length) }
end
def input
File.readlines(ARGV.first).map do |l|
l.chomp.split(' | ').map { |ll| ll.split(' ') }
end
end
puts process(input)
| true |
ea43f78dea3990123ae14116b0c967e25c71f642 | Ruby | imanagashodai/algorithm | /Ruby/クラスカル法.rb | UTF-8 | 635 | 3.421875 | 3 | [] | no_license | # https://www.slideshare.net/iwiwi/ss-3578491
N = 3
par = Array.new(N)
N.times do |n|
par[n] = n
end
E = 3 # 経路の数
def find(x,par)
return x if par[x] == x
return par[x] = find(par[x],par)
end
def same(x,y,par)
return find(x,par) == find(y,par)
end
def union(x,y,par)
x = find(x,par)
y = find(y,par)
return if x == y
par[x] = y
end
edges = [[20,0,1],[3,1,2],[100,2,0]]
edges.sort!
def kruskal(edges, par)
res = 0
edges.each do |edge|
if !same(edge[1],edge[2],par)
res += edge[0]
union(edge[1],edge[2],par)
end
end
return res
end
p kruskal(edges,par) | true |
1640509524bd7319b7708c5f902a85ecb2ed67db | Ruby | ash-leigh/day_2_functions_lab | /ruby_functions_practice.rb | UTF-8 | 1,244 | 4.21875 | 4 | [] | no_license | def return_10()
return 10
end
def add(first_number, second_number)
return first_number + second_number
end
def subtract(first_number, second_number)
return first_number - second_number
end
def multiply (first_number, second_number)
return first_number * second_number
end
def divide (first_number, second_number)
return first_number / second_number
end
def length_of_string(length)
return "A string of length 21".length
end
def join_string(string_1, string_2)
return "#{string_1}#{string_2}"
end
def add_string_as_number(first_number, second_number)
return first_number.to_i + second_number.to_i
end
def number_to_full_month_name(month)
case month
when 1
"January"
when 3
"March"
when 9
"September"
else
"there are not that many months"
end
end
puts number_to_full_month_name(1)
def number_to_short_month_name(month)
case month
when 1
"Jan"
when 3
"Mar"
when 9
"Sep"
else
"there are not that many months"
end
end
puts number_to_short_month_name(3)
def volume_of_cube(edge)
return edge**3
end
puts volume_of_cube(10)
def volume_of_sphere(radius)
return (4.19)*(radius**3)
end
puts volume_of_sphere(10)
| true |
6ccc2bce435495f6ae548a0eb9a87339794e51ed | Ruby | valentinorusconi/ruby-exercises | /objects-and-methods/exercise-2/spec/candy_spec.rb | UTF-8 | 550 | 3.09375 | 3 | [
"MIT"
] | permissive | require 'rspec'
require_relative '../lib/candy'
RSpec.describe Candy do
it 'has a type' do
candy = Candy.new('Skittles')
expect(candy.type).to eq('Skittles')
end
xit 'can have a different type' do
candy = Candy.new('Mars')
expect(candy.type).to eq('Mars')
end
xit 'has 100g of sugar by default' do
candy = Candy.new('Smarties')
expect(candy.sugar).to eq(100)
end
xit 'can be created with a different amount of sugar' do
candy = Candy.new('Pop Rocks', 75)
expect(candy.sugar).to eq(75)
end
end
| true |
7123adb907410a2c6b302b907bd1ed3be07956e1 | Ruby | jessiebbaxter/toy-robot | /lib/router.rb | UTF-8 | 1,205 | 3.546875 | 4 | [] | no_license | class Router
def initialize(controller)
@controller = controller
@running = true
end
# Displays simulator interface and retrieves user input
def run
puts "---------------------------------------"
puts "Welcome to your Toy Robot Simulator! 🤖"
puts "---------------------------------------"
puts ""
puts "Please input your command (EXIT to quit):"
puts ""
while @running
print "> "
action = gets.chomp
route_action(action)
end
end
# Routes user input to appropriate method in the controller
def route_action(action)
case action
when pattern = /PLACE\s(?<position_x>\d+),(?<position_y>\d+),(?<direction>NORTH|SOUTH|EAST|WEST)/
then
match_data = action.match(pattern)
@controller.place(match_data[:position_x].to_i,
match_data[:position_y].to_i, match_data[:direction])
when 'MOVE' then @controller.move
when 'LEFT' then @controller.rotate('left')
when 'RIGHT' then @controller.rotate('right')
when 'REPORT' then @controller.report
when 'EXIT' then stop
else
puts "Invalid command"
puts ""
end
end
def stop
@running = false
end
end | true |
c136e6334f4e6ee5bdb37323b180228ad0f1af60 | Ruby | copiousfreetime/flat_kit | /lib/flat_kit/record.rb | UTF-8 | 2,572 | 3.28125 | 3 | [
"MIT"
] | permissive | module FlatKit
# Public: The base class that all record classes should inherit from.
#
# Its goal is to be an efficient comparator of data that can be inflated from
# a source structure to a fully realized hash.
#
# All records need to be able to be initialized from a data structure that it
# is handed to it by the Reader intance within the same Format.
#
# Records are generally not going to be created outside of this library, they
# are tied to a specific format and provide a common interface that can be
# used for:
#
# * comparison between records from different source / destinations formats
# * conversion to a different format
#
# Given that - the way to create a record is either from another Record
# instance:
#
# Record.from_record(other) # create a record from another record
#
# or the way a Reader will do it
#
# Record.new(...) # generally only used by a Reader instance to
# # yield new reocrds
#
#
# When Implementing a new Format, the corresponding Record class for that
# Format must:
#
# * implement `#[](key)` which will be used to lookup the values of the
# comparable fields.
# * implement `#to_hash` which is used when conversions
# * implement `.from_record` which is used in conversion
# # the initialize method must call super(data:, compare_fields:) to
# initializa the root data structures
class Record
include Comparable
attr_reader :data
attr_reader :compare_fields
def initialize(data:, compare_fields:)
@data = data
@compare_fields = compare_fields
end
def format_name
self.class.format_name
end
def <=>(other)
compare_result = nil
compare_fields.each do |field|
my_val = self[field]
other_val = other[field]
if my_val.nil? && other_val.nil? then
compare_result = 0
elsif my_val.nil?
compare_result = -1
elsif other_val.nil?
compare_result = 1
else
compare_result = my_val.<=>(other_val)
end
return compare_result unless compare_result.zero?
end
compare_result
end
def [](key)
raise NotImplementedError, "#{self.class} must implement #[](key)"
end
def to_hash
raise NotImplementedError, "#{self.class} must implement #to_hash"
end
def self.from_record
raise NotImplementedError, "#{self.class} must implement #{self.class}.from_record"
end
end
end
| true |
05d097970b78ae36f2678bd8881f87759b152c75 | Ruby | PetePhx/intro-to-programming-ruby | /2_variables/5_prog_output.rb | UTF-8 | 461 | 3.8125 | 4 | [] | no_license | # Program 1:
x1 = 0
3.times do
x1 += 1
end
puts x1
# output: 3
# x1 is initialized in the outer scope (0), then updated in the inner scope (3).
# everything is fine.
# Program 2:
y = 0
3.times do
y += 1
x2 = y
end
puts x2
# output: error. undefined local variable or method `x2' for main:Object (NameError)
# x2 is initialized in the inner scope (within the .times method)
# the outer scope can not access the variable x2 defined in the inner scope.
| true |
cb1daae1617b8918d1849a2b3ab64fbd6646bda6 | Ruby | stonegao/gisting | /lib/gisting/spec.rb | UTF-8 | 466 | 2.875 | 3 | [] | no_license | module Gisting
# A Spec contains multiple Inputs and a single Output
class Spec
def initialize
@map_inputs = []
end
def add_input
input = Input.new
@map_inputs << input
input
end
def map_inputs
@map_inputs
end
def output
@map_output ||= Output.new
end
def map_input_count
@map_inputs.size
end
def reduce_output_count
@map_output.num_tasks
end
end
end | true |
e5991f11e840de38dd16c5b5f5327e0d71a6637a | Ruby | Satyrr/University | /Programming in Ruby/lista7/client.rb | UTF-8 | 501 | 2.65625 | 3 | [] | no_license | require 'drb/drb'
SERVER_URI="druby://localhost:9999"
#ustanowienie polaczenia i przyznanie id
DRb.start_service
log_service=DRbObject.new_with_uri(SERVER_URI)
my_id = log_service.assign_id
menu = "1.nowa wiadomosc\n"\
"0.zamknij klienta"
puts menu
option=gets.chomp.to_i
while option!=0 do
if option == 1
puts "Podaj wiadomosc:\n"
msg = gets.chomp
if log_service.respond_to?('save')
log_service.save(my_id,msg) # wyslanie wiadomosci
end
end
puts menu
option=gets.chomp.to_i
end | true |
2bb020a661fe4681664fba3fc3db0495ccc55c5f | Ruby | Mycobee/flash_cards | /test/deck_test.rb | UTF-8 | 994 | 3.421875 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require "pry"
require './lib/turn'
require './lib/card'
require './lib/deck'
class DeckTest < Minitest::Test
def setup
@card_1 = Card.new("What is the capital of Alaska?", "Juneau", :Geography)
@card_2 = Card.new("The Viking spacecraft sent back to Earth photographs and reports about the surface of which planet?", "Mars", :STEM)
@card_3 = Card.new("Describe in words the exact direction that is 697.5° clockwise from due north?", "North north west", :STEM)
@cards = [@card_1, @card_2, @card_3]
@deck = Deck.new(@cards)
end
def test_it_exists
assert_instance_of Deck, @deck
end
def test_which_cards_are_in_the_deck
assert_equal @cards.first, @deck.cards.first
end
def test_how_many_cards_are_in_the_deck
assert_equal @deck.cards.length, @deck.count
end
def test_the_cards_category
actual = @deck.cards_in_category(:STEM)
assert_equal [@card_2, @card_3], actual
end
end
| true |
51de5c320f072a6861e522b4eca8dfd9cb664b55 | Ruby | Chrispayneable/Exercism.io | /ruby/two-fer/two_fer.rb | UTF-8 | 91 | 2.828125 | 3 | [] | no_license | class TwoFer
def self.two_fer(word = 'you')
"One for #{word}, one for me."
end
end
| true |
81c32242e3315a0513f48c27c98f95a8286ae33b | Ruby | da99/i_love_u | /src/Uni_Lang/Noun/Noun_Number.rb | UTF-8 | 216 | 2.765625 | 3 | [
"MIT"
] | permissive |
class Noun_Number
include Noun::Module
def data_type?
true
end
def valid? str, program
pos = ( str =~ /\d+(\.\d+)?/ )
return false if pos == nil
true
end
end # === class Noun_Word
| true |
c060db4d34a04b5c53d82ac8bd676477d72c811b | Ruby | kp1/exifparser | /lib/exifparser.rb | UTF-8 | 6,963 | 3.203125 | 3 | [
"Ruby",
"BSD-2-Clause"
] | permissive | #
#
#= exifparser.rb - Exif tag parser written in pure ruby
#
#Author:: Ryuchi Tamura (r-tam@fsinet.or.jp)
#Copyright:: Copyright (C) 2002 Ryuichi Tamura.
#
# $Id: exifparser.rb,v 1.1.1.1 2002/12/16 07:59:00 tam Exp $
#
#== INTRODUCTION
#
#There are 2 classes you work with. ExifParser class is
#the Exif tag parser that parses all tags defined EXIF-2.2 standard,
#and many of extension tags uniquely defined by some digital equipment
#manufacturers. Currently, part of tags defined by FujiFilm, and
#Olympus is supported. After initialized with the path to image file
#of EXIF format, ExifParser will provides which tags are available in
#the image, and how you work with them.
#
#Tags availble from ExifParser is objects defined under Exif::Tag module,
#with its name being the class name. For example if you get "Make" tag
#from ExifParser, it is Exif::Tag::DateTime object. Inspecting it looks
#following:
#
# #<Exif::Tag::TIFF::Make ID=0x010f, IFD="IFD0" Name="Make", Format="Ascii" Value="FUJIFILM">
#
#here, ID is Tag ID defined in EXIF-2.2 standard, IFD is the name of
#Image File Directory, Name is String representation of tag ID, Format is
#string that shows how the data is formatted, and Value is the value of
#the tag. This is retrieved by Exif::Tag::Make#value.
#
#Another example. If you want to know whether flash was fired when the image
#was generated, ExifParser returns Exif::Tag::Flash object:
#
# tag = exif['Flash']
# p tag
# => #<Exif::Tag::Exif::Flash ID=0x9209, IFD="Exif" Name="Flash", Format="Unsigned short" Value="1">
# p tag.value
# => 1
#
#It may happen that diffrent IFDs have the same tag name. In this case,
#use Exif#tag(tagname, IFD)
#
#The value of the tag above, 1, is not clearly understood
#(supposed to be 'true', though). Exif::Tag::Flash#to_s will provides
#more human-readable form as String.
#
# tag.to_s #=> "Flash fired."
#
#many of these sentences are cited from Exif-2.2 standard.
#
#== USAGE
# require 'exifparser'
#
# exif = ExifParser.new("fujifilm.jpg")
#
# 1. get a tag value by its name('Make') or its ID (0x010f)
# exif['Make'] #=> 'FUJIFILM'
# exif[0x010f] #=> 'FUJIFILM'
#
# if the specified tag is not found, nil is returned.
#
# 2. to see the image has the value of specified tag
# exif.tag?('DateTime') #=> true
# exif.tag?('CameraID') #=> false
#
# 3. get all the tags contained in the image.
#
# exif.tags
#
# or, if you want to know all the tags defined in specific IFD,
#
# exif.tags(:IFD0) # get all the tags defined in IFD0
#
# you can traverse each tag and work on it.
#
# exif.each do |tag|
# p tag.to_s
# end
#
# # each tag in IFD0
# exif.each(:IFD0) do |ifd0_tag|
# p ifd0_tag.to_s
# end
#
# 4. extract thumbnail
#
# File.open("thumb.jpg") do |dest|
# exif.thumbnail dest
# end
#
# dest object must respond to '<<'.
#
require 'exifparser/scan'
module Exif
class Parser
#
# create a new object. fpath is String.
#
def initialize(file_handler)
@scanner = Exif::Scanner.new prepare_file(file_handler)
@scanner.scan
init_from_scanner
end
def init_from_scanner
@IFD0 = @scanner.result[:IFD0]
@IFD1 = @scanner.result[:IFD1]
@Exif = @scanner.result[:Exif]
@GPS = @scanner.result[:GPS]
@Interoperability = @scanner.result[:Interoperability]
@MakerNote = @scanner.result[:MakerNote]
@thumbnail = @scanner.result[:Thumbnail]
end
def prepare_file(handler)
if handler.is_a? String
@fpath = handler
File.open(handler, "rb")
elsif handler.is_a?(StringIO) || handler.is_a?(File)
@fpath = 'dummy_file'
handler
end
end
def inspect
sprintf("#<%s filename=\"%s\" entries: IFD0(%d) IFD1(%d) Exif(%d) GPS(%d) Interoperability(%d) MakerNote(%d)>", self.class, @fpath, @IFD0.length, @IFD1.length, @Exif.length, @GPS.length, @Interoperability.length, @MakerNote.length)
end
#
# return true if specified tagid is defined or has some value.
#
def tag?(tagid)
search_tag(tagid) ? true : false
end
#
# search tag on the specific IFD
#
def tag(tagname, ifd=nil)
search_tag(tagname, ifd)
end
#
# search the specified tag values. return value is object of
# classes defined under Exif::Tag module.
#
def [](tagname)
self.tag(tagname)
end
#
# set the specified tag to the specified value.
# XXX NOT IMPLEMETED XXX
#
def []=(tag, value)
# not implemented
end
#
# extract the thumbnail image to dest. dest should respond to
# '<<' method.
#
def thumbnail(dest)
dest << @thumbnail
end
#
# return the size of the thumbnail image
#
def thumbnail_size
@thumbnail.size
end
#
# return all the tags in the image.
#
# if argument ifd is specified, every tags defined in the
# specified IFD are passed to block.
#
# return value is object of classes defined under Exif::Tag module.
#
# allowable arguments are:
# * :IFD0
# * :IFD1
# * :Exif
# * :GPS
# * :Interoperability
# * :MakerNote (if exist)
def tags(ifd=nil)
if ifd
@scanner.result[ifd]
else
[
@IFD0,
@IFD1,
@Exif,
@GPS,
@Interoperability,
@MakerNote
].flatten
end
end
#
# execute given block with block argument being every tags defined
# in all the IFDs contained in the image.
#
# if argument ifd is specified, every tags defined in the
# specified IFD are passed to block.
#
# return value is object of classes defined under Exif::Tag module.
#
# allowable arguments are:
# * :IFD0
# * :IFD1
# * :Exif
# * :GPS
# * :Interoperability
# * :MakerNote
def each(ifd=nil)
if ifd
@scanner.result[ifd].each{ |tag| yield tag }
else
[
@IFD0,
@IFD1,
@Exif,
@GPS,
@Interoperability,
@MakerNote
].flatten.each do |tag|
yield tag
end
end
end
def marshal_dump
{scanner: Marshal.dump(@scanner)}
end
def marshal_load marshaled
@scanner = Marshal.load marshaled[:scanner]
init_from_scanner
end
private
def search_tag(tagID, ifd=nil)
if ifd
@scanner.result(ifd).find do |tag|
case tagID
when Fixnum
tag.tagID.hex == tagID
when String
tag.name == tagID
end
end
else
[
@IFD0,
@IFD1,
@Exif,
@GPS,
@Interoperability,
@MakerNote
].flatten.find do |tag|
case tagID
when Fixnum
tag.tagID.hex == tagID
when String
tag.name == tagID
end
end
end
end
end # module Parser
end # module Exif
ExifParser = Exif::Parser
| true |
d5bfd7ca630b0323d74fd3ed0180068164c2f7b4 | Ruby | Redvanisation/data-algorithm | /1-basic-data/ex21-minstack.rb | UTF-8 | 1,189 | 4.09375 | 4 | [
"MIT"
] | permissive | class Node
attr_accessor :value, :previous_node, :next_node
def initialize(value, previous_node=nil, next_node=nil)
@value = value
@previous_node = previous_node
@next_node = next_node
end
end
class Stack
def initialize()
@tail = Node.new(nil)
end
def push(number)
this_node = Node.new(number)
if @tail == nil
@tail = this_node
return "this stack is empty!"
else
@tail.next_node = this_node
this_node.previous_node = @tail
@tail = this_node
return "number is added to the tail!"
end
end
def pop
if @tail == nil
return "this stack is empty!"
else
pop_node = @tail
@tail = @tail.previous_node
@tail.next_node = nil
return pop_node.value
end
end
def min
min = @tail.value
node = @tail
while node
if node&.value != nil &&min > node&.value
min = node.value
end
node = node.previous_node
end
return min
end
end
stack = Stack.new
stack.push(3)
stack.push(5)
puts stack.min
# => 3
stack.pop
stack.push(7)
puts stack.min
# => 3
stack.push(2)
puts stack.min
# => 2
stack.pop
puts stack.min
# => 3
| true |
4afdc804221213799d4f2ec04406c188705b245d | Ruby | psteiger/desafios | /2.rb | UTF-8 | 728 | 4.1875 | 4 | [] | no_license | #!/usr/bin/env ruby
def upToTwoThirdsJumbled(string1, string2)
jumbled = 0
string1.chars.each_with_index do |char, i|
jumbled += 1 if char != string2[i]
end
jumbled < (string1.length * 2) / 3
end
def isPermutation(string1, string2)
# creio que as strings serem do mesmo tamanho e terem os mesmos caracteres eh
# criterio fundamental pra decidir se eh permutacao.
string1.chars.sort == string2.chars.sort &&
string1[0] == string2[0] &&
(string1.length <= 3 || upToTwoThirdsJumbled(string1, string2))
end
if __FILE__ == $0
if ARGV.length < 2
puts "Exemplo de uso: ./2.rb cama casa"
return nil
end
string1 = ARGV[0]
string2 = ARGV[1]
puts isPermutation(string1, string2)
end
| true |
50017f18244b70859782f35c5263e57cdd1b88ac | Ruby | spohlenz/mongomodel | /lib/mongomodel/concerns/attributes.rb | UTF-8 | 2,048 | 2.53125 | 3 | [
"MIT"
] | permissive | require 'active_support/core_ext/module/aliasing'
module MongoModel
module Attributes
extend ActiveSupport::Concern
def initialize(attrs={}, options={})
assign_attributes(attrs || {}, options)
yield self if block_given?
end
def attributes
@attributes ||= Attributes::Store.new(self)
end
def assign_attributes(attrs, options={})
return unless attrs
attrs.each do |attr, value|
if respond_to?("#{attr}=")
send("#{attr}=", value)
else
write_attribute(attr, value)
end
end
end
def attributes=(attrs)
assign_attributes(attrs)
end
def freeze
attributes.freeze; self
end
def frozen?
attributes.frozen?
end
# Returns duplicated record with unfreezed attributes.
def dup
obj = super
obj.instance_variable_set('@attributes', instance_variable_get('@attributes').dup)
obj
end
def to_mongo
attributes.to_mongo
end
def embedded_documents
docs = []
docs.concat attributes.values.select { |attr| attr.is_a?(EmbeddedDocument) }
attributes.values.select { |attr| attr.is_a?(Collection) }.each do |collection|
docs.concat collection.embedded_documents
end
attributes.values.select { |attr| attr.is_a?(Map) && attr.to <= EmbeddedDocument }.each do |map|
docs.concat map.values
end
docs
end
protected
def sanitize_for_mass_assignment(attrs, options={})
attrs
end
module ClassMethods
def from_mongo(hash)
if hash
doc = class_for_type(hash['_type']).new
doc.attributes.load!(hash)
doc
end
end
private
def class_for_type(type)
klass = type.constantize
if klass.ancestors.map(&:name).include?(name)
klass
else
raise DocumentNotFound, "Document not of the correct type (got #{type})"
end
rescue NameError
self
end
end
end
end
| true |
f7693fc8462e5bc25eac23bc508c1d124ef67938 | Ruby | cjc162/D2 | /game_test.rb | UTF-8 | 2,015 | 3.34375 | 3 | [] | no_license | require 'minitest/autorun'
require_relative 'game'
# GameTest
class GameTest < Minitest::Test
# UNIT TESTS FOR METHOD create_map()
# Equivalence classes:
# no param -> returns the 2D map specified in the requirement #3
# The map specified in requirement #3 is returned.
def test_create_map
map = [
['Enumerable Canyon', 'Duck Type Beach', 'Monkey Patch City'],
['Duck Type Beach', 'Enumerable Canyon', 'Matzburg'],
['Monkey Patch City', 'Nil Town', 'Enumerable Canyon', 'Matzburg'],
['Nil Town', 'Hash Crossing', 'Monkey Patch City'],
['Matzburg', 'Monkey Patch City', 'Duck Type Beach', 'Hash Crossing', 'Dynamic Palisades'],
['Hash Crossing', 'Matzburg', 'Dynamic Palisades', 'Nil Town'],
['Dynamic Palisades', 'Hash Crossing', 'Matzburg']
]
game = Game.new(1, 3)
assert_equal map, game.create_map
end
# UNIT TESTS FOR METHOD start(prospector_count, prospect)
# Equivalence classes:
# prospector_count = -INFINITY..0 -> returns nil
# prospector_count = 1 -> INFINITY, prospect = Of type prospector -> returns number of turns completed
# prospect = Not a prospector type -> returns nil
# If a a negative number or zero is given for prospector_count, nil is returned.
# EDGE CASE
def test_game_prospector_count_negative
game = Game.new(1, 3) # Set turn limit to 3
game.create_map
prospector = Minitest::Mock.new('prospector')
def prospector.go_mining(_p1, _p2)
1
end
def prospector.move_to_next_location(_p1)
1
end
assert_nil game.start(-1, prospector)
end
# If a nonnegative turn limit is given, the same turn limit is returned (in this case 3).
def test_game_correct_turns
game = Game.new(1, 3) # Set turn limit to 3
game.create_map
prospector = Minitest::Mock.new('prospector')
def prospector.go_mining(_p1, _p2)
1
end
def prospector.move_to_next_location(_p1)
1
end
assert_equal 3, game.start(1, prospector)
end
end
| true |
48e37fa5406a115dcf973cbdec1ace040d051cd9 | Ruby | marquesavery/ttt-with-ai-project-online-web-sp-000 | /lib/board.rb | UTF-8 | 1,064 | 4.09375 | 4 | [] | no_license | require "pry"
class Board
attr_accessor :cells
def initialize
reset!
end
def reset!
@cells = Array.new(9, " ")
end
def display
puts " #{@cells[0]} | #{@cells[1]} | #{@cells[2]} "
puts "-----------"
puts " #{@cells[3]} | #{@cells[4]} | #{@cells[5]} "
puts "-----------"
puts " #{@cells[6]} | #{@cells[7]} | #{@cells[8]} "
end
def position(input)
user_input = input.to_i - 1
@cells[user_input]
end
def full?
if @cells.all?{|value| value != " "}
true
else
false
end
end
def turn_count
@cells.count("X") + @cells.count("O")
end
def taken?(input)
if position(input) == "X"
true
elsif position(input) == "O"
true
elsif position(input) == " "
false
end
end
def valid_move?(input)
if input.to_i.between?(1, 9)
if taken?(input) == true
false
elsif taken?(input) == false
true
end
else
false
end
end
def update(index, player)
@cells[index.to_i - 1] = player.token
end
end
| true |
67e172342691d11785d00384d4bb1658ef92f16f | Ruby | seangoedecke/toy-paxos | /main.rb | UTF-8 | 866 | 2.984375 | 3 | [] | no_license | require_relative './node'
require_relative './cluster'
require_relative './network'
# Sets up a cluster with three nodes on an unreliable network and makes a write
# NB: Paxos only comes to consensus on _one_ decision. You need something else tracking round numbers to get you to
# multiple decisions or a unified log. That's why "Multi-Paxos" has "multi" in the name - because it gives you
# multiple rounds
DROP_CHANCE = 0
SHUFFLE_CHANCE = 2
NUMBER_OF_NODES = 3
network = Network.new(DROP_CHANCE, SHUFFLE_CHANCE)
cluster = PaxosCluster.new
NUMBER_OF_NODES.times do
PaxosNode.new(cluster, network)
end
cluster.write 'bar'
cluster.write 'foo' # Feel free to add more writes here. With a sufficiently unreliable network, any write can win
network.process_queue # Force any messages that are waiting in the queue to get sent
puts cluster.get_consensus.inspect
| true |
b1453460198e2b16c7a6fc615d1b38309a87560e | Ruby | mayorau3/neko-taku-app | /spec/models/cat_spec.rb | UTF-8 | 1,815 | 2.53125 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Cat, type: :model do
describe '#create' do
before do
@cat = FactoryBot.build(:cat)
end
it '全ての入力項目が存在すれば登録できること' do
expect(@cat).to be_valid
end
it '画像が空では登録できないこと' do
@cat.images = nil
@cat.valid?
expect(@cat.errors.full_messages).to include("Images can't be blank")
end
it '商品画像の2枚目が空でも登録できること' do
@cat.images[1] = nil
expect(@cat).to be_valid
end
it '名前が空では登録できないこと' do
@cat.name = nil
@cat.valid?
expect(@cat.errors.full_messages).to include("Name can't be blank")
end
it '説明が空では登録できないこと' do
@cat.explanation = nil
@cat.valid?
expect(@cat.errors.full_messages).to include("Explanation can't be blank")
end
it '年齢が空では登録できないこと' do
@cat.age_id = nil
@cat.valid?
expect(@cat.errors.full_messages).to include("Age can't be blank")
end
it '年齢が「---」では登録できないこと' do
@cat.age_id = 1
@cat.valid?
expect(@cat.errors.full_messages).to include('Age Select')
end
it '性別が空(=「---」の時)では登録できないこと' do
@cat.sex = nil
@cat.valid?
expect(@cat.errors.full_messages).to include("Sex can't be blank")
end
it '性格の全ての項目が空でも登録できること' do
@cat.chara_clever = nil
@cat.chara_sleep = nil
@cat.chara_active = nil
@cat.chara_quiet = nil
@cat.chara_greedy = nil
@cat.chara_lonely = nil
@cat.chara_own = nil
expect(@cat).to be_valid
end
end
end
| true |
84edb684fd1fba0848f63fdf4f31786fa7bad1a4 | Ruby | petlove/ruby-push-notifications | /lib/ruby-push-notifications/mpns/mpns_pusher.rb | UTF-8 | 1,173 | 2.625 | 3 | [
"MIT"
] | permissive |
module RubyPushNotifications
module MPNS
# This class is responsible for sending notifications to the MPNS service.
#
class MPNSPusher
# Initializes the MPNSPusher
#
# @param certificate [String]. The PEM encoded MPNS certificate.
# @param options [Hash] optional. Options for GCMPusher. Currently supports:
# * open_timeout [Integer]: Number of seconds to wait for the connection to open. Defaults to 30.
# * read_timeout [Integer]: Number of seconds to wait for one block to be read. Defaults to 30.
# (http://msdn.microsoft.com/pt-br/library/windows/apps/ff941099)
def initialize(certificate = nil, options = {})
@certificate = certificate
@options = options
end
# Actually pushes the given notifications.
# Assigns every notification an array with the result of each
# individual notification.
#
# @param notifications [Array]. Array of MPNSNotification to send.
def push(notifications)
notifications.each do |notif|
notif.results = MPNSConnection.post notif, @certificate, @options
end
end
end
end
end
| true |
57028be15727bf5f763f7778476184b57b88f798 | Ruby | KoKumagai/manga_read_man | /lib/manga_read_man.rb | UTF-8 | 206 | 2.515625 | 3 | [] | no_license | require "manga_read_man/manga"
module MangaReadMan
BASE_URL = 'http://www.mangareader.net/'
def self.image_urls(title, chapter = nil)
manga = Manga.new(title, chapter)
manga.execute
end
end
| true |
033c3b9ea09d93993030db741fde8f366636240d | Ruby | mutsey/ruby-puppy-online-web-pt-110419 | /lib/dog.rb | UTF-8 | 298 | 2.625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Dog
@@all = []
attr_accessor :name
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
end
.clear_all = []
attr_accessor :name
def initialize(all dogs)
@@all = all dogs
@@all << all dogs
end
def clear.all
@@all
| true |
88f25b05d80bc3c3e5e8c61ecb4e51a479329a81 | Ruby | raganwald-deprecated/ick | /test/test_advisor.rb | UTF-8 | 1,782 | 2.890625 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/test_helper.rb'
class NoAdvice < Ick::Advisor
end
class NameUpdator < Ick::Advisor
around :only => :value= do |callback, receiver, sym, *args|
callback.call()
receiver.name = receiver.to_s
end
end
class NameUpdatorByMethod < Ick::Advisor
around :update, :only => :value=
def self.update(callback, receiver, sym, *args)
callback.call()
receiver.name = receiver.to_s
end
end
class DoublePlusOne < Ick::Advisor
around :only => :value= do |callback, receiver, sym, *args|
callback.call()
receiver.name = receiver.to_s
end
end
class TestAdvisor < Test::Unit::TestCase
def setup
@box1 = Box.new(1)
@box_one = Box.new(1)
end
def test_no_advice
nullo = NoAdvice.new(@box1)
nullo.value = 2
assert_equal(2, @box1.value)
end
def test_simple_around_advice
old_string = @box1.name
@box1.value = 2
assert_equal(2, @box1.value)
assert_equal(old_string, @box1.name) # The name has not changed
assert_not_equal(old_string, @box1.to_s) # but the string has
updating = NameUpdator.new(@box_one)
updating.value = 2
assert_equal(updating.to_s, updating.name) # updated the name
end
def test_simple_by_method
updating = NameUpdatorByMethod.new(@box_one)
updating.value = 2
assert_equal(updating.to_s, updating.name) # updated the name
end
def test_simple_around_advice
old_string = @box1.name
@box1.value = 2
assert_equal(2, @box1.value)
assert_equal(old_string, @box1.name) # The name has not changed
assert_not_equal(old_string, @box1.to_s) # but the string has
updating = NameUpdator.new(@box_one)
updating.value = 2
assert_equal(updating.to_s, updating.name) # updated the name
end
end | true |
828bd623d862a415342e537d6e4c5fdb1f4f7aac | Ruby | ULL-ESIT-LPP-1819/tdd-alu0100893601 | /lib/InfNut/paciente.rb | UTF-8 | 1,070 | 2.859375 | 3 | [] | no_license | require_relative "valoracionnutricional.rb"
class Paciente < ValoracionNutricional
attr_reader :identificacion, :nsegsocial
def initialize (id , nss, name, age, gender, weight, height, circun, plieg)
@identificacion = id
@nsegsocial= nss
super(name, age, gender, weight, height, circun, plieg)
end
end
class Consulta < Paciente
attr_reader :cita
def initialize (consul, id , nss, name, age, gender, weight, height, circun, plieg)
@cita = consul
super(id , nss, name, age, gender, weight, height, circun, plieg)
end
end
class TratarObesidad < Paciente
attr_reader :obesidad
def initialize (obe, id , nss, name, age, gender, weight, height, circun, plieg)
@obesidad = obe
super(id , nss, name, age, gender, weight, height, circun, plieg)
end
def calcularTratoDeObesidad
aux = evaluar_imc
#puts aux
if aux=="Obesidad 1"
@obesidad = true
elsif aux=="Obesidad 2"
@obesidad = true
elsif aux=="Obesidad 3"
@obesidad = true
end
aux2 = @obesidad
aux2
end
end | true |
bdb84d9066144a9c74ee38014f4cbeb8f422ddc6 | Ruby | kmeyer313/phase-0 | /week-5/gps2_2.rb | UTF-8 | 5,616 | 3.96875 | 4 | [
"MIT"
] | permissive | #---ARRAY ATTEMPT DURING GPS---ABORTED---SCROLL DOWN FOR HASH ATTEMPT POST-GPS---
# Method to create a list
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# define the METHOD
# add name of array as a parameter
# set parameter equal blank array
# print the list to the console [can you use one of your other methods here?]
# output: array - item(index)
#def new_list
# Array.new
#end
#target = new_list
#wholefoods = new_list
#target = []
#target = [carrots]
# Method to add an item to a list
# input: array, item we want to add
# steps:
# define the METHOD
# give two parameters: array, item
# push the item into the array
# output: array with the item we wanted to add
#def add(array, item)
# array.push(item)
# p array
#end
#add(target, "carrots")
# Method to remove an item from the list
# input: array, item to remove
# steps:
# define the METHOD
# give two parameters: array, item
# write name of array -carrots
# output: array without item removed
#def remove(array)
# array.pop
# p array
#end
#remove(target)
#p target
# Method to update the quantity of an item
# input:
# steps:
# output:
# Method to print a list and make it look pretty
# input:
# steps:
#--------------HASH ATTEMPT-----------------
# Method to create a list
# input: list of key/value pairs of items separated by commas (example: {"carrots" => 2, "apples" => 5, "cereal" => 1 "pizza" => 1}
# steps:
# CREATE new hash with key/value pairs
# p the list to the console
# output: hash
groceries_hash = {
"carrots" => 2,
"apples" => 5,
"cereal" => 1,
}
p groceries_hash
# Method to add an item to a list
# input: item name and quantity
# steps:
# output: p updated list
groceries_hash["pizza"] = 1
p groceries_hash
# Method to remove an item from the list
# input: item name and quantity
# steps:
# output: p updated list
groceries_hash.delete("carrots")
p groceries_hash
# Method to update the quantity of an item
# input: hash key with new value for updated quantity to overwrite previous entry.
# steps:
# output: p updated list
groceries_hash["cereal"] = 2
p groceries_hash
# Method to print a list and make it look pretty
# input: method call to print a list of each item: quantity to a separate line
# steps:
# output: list of items and quanitites
groceries_hash.each do |item, quantity|
puts "#{item}: #{quantity}"
end
#-------------REFLECTION--------------------
#What did you learn about pseudocode from working on this challenge?
# => The set up for this was kind of confusing. I get the "input", "output", "steps" structure, but I think I might have been less tripped up if it hadn't already been set up for us. It was hard to think through where I would start when they already got us started. I'm not sure if it would have been better to have no pseudocode already ready for us. I tried to use the pseuocode standard reference while we were pairing, but I feel like it was hard to switch back and forth between the two, my pair, and the guide. I think I prefer pseudocoding with paper and pencil first to sketch my ideas out and will do that on future challenges before synthesizing them into readable steps here.
#What are the tradeoffs of using Arrays and Hashes for this challenge?
# => We both thought hashes would probably be better for this challenge, but were a little insecure about it. So we tried to do this it using an array, which I think threw us off even more. Using arrays would have been a little more cumbersome as it would have been hard to assign the quantity to items. I still don't know how we could have done it with an array. Hash made it easier to work with because we were able to send the item: quantity pair into a hash that could easily generate a list.
#What does a method return?
# => A method could return is the value of something is true or false. In the case here, we were modifying the list of groceries by adding, deleting, and modifying the items and their quantities. To see how the methods affected the groceries_hash, we used p to return the changed hash. The final method where we used .each was able to iterate through the list of key/value pairs and print them in a format that looked like a list.
#What kind of things can you pass into methods as arguments?
# You can pass different variables (strings, integers, etc.) through the methods parameters as arguments.
#How can you pass information between methods?
# => For this challenge, the methods all took place within the same scope, so groceries_hash changed a little with each method. After each method, I used "p groceries_hash" to see the updated version of the hash.
#What concepts were solidified in this challenge, and what concepts are still confusing?
# => I was a little shook up from this challenge because we got really lost in the directions and world of arrays during our GPS hour. It was hard for me to recall what I had learned about hashes and I needed to go back and read through my CodeAcademy notes as well as reread relevent sections from the Rubyist. I definitely was over thinking the challenge (the memory of doing the "Night at the Movies" section of CodeAcademy was looming in the back of my head as we worked, but I couldn't recall how it worked - which ended up being much more complicated than what was necessary - using case/when and gets.chomp)
# => For each of the methods I wrote, I needed to use the Rubyist to get the format. I realize that I am reading/learning more passively and that I need to spend more time plunking this stuff out on my keyboard to start solidifying what I am learning.
| true |
1c766acb94b79d99b25e7c4e8985ff8441d3bdb5 | Ruby | gramos/migral | /lib/migral/migration.rb | UTF-8 | 1,334 | 2.90625 | 3 | [] | no_license | require 'csv'
require 'erb'
module Migral
class Migration
attr_reader :attributes
def initialize(type, csv_file_path, table_name, separator = ",")
@type = type
@table_name = table_name
@csv_file_path = csv_file_path
@separator = separator || ","
end
def dump!
@row_count = IO.readlines(@csv_file_path).size
@row_number = 0
CSV.foreach(@csv_file_path, {:col_sep => @separator}) do |row|
if @row_number == 0
@attributes = row
@first_row = false
else
sum_attr_size! row
return generate(@attributes, @table_name) if im_on_the_last_line?
end
@row_number += 1
end
end
##############################################################################
#
private
def generate(attributes, table_name)
@template = File.read "lib/templates/#{@type}.erb"
@migration = ERB.new(@template, 0, '<>').result(binding)
end
def im_on_the_last_line?
@row_number + 1 == @row_count
end
def sum_attr_size!(row)
@sum_attr_size ||= []
row.size.times do |n|
next if row[n].nil?
if @sum_attr_size[n].nil? or row[n].size > @sum_attr_size[n]
@sum_attr_size[n] = row[n].size
end
end
end
end
end
| true |
780fe6ab7eba0706d64206f1cb27f862b3332636 | Ruby | cliffeh/util | /examples/ruby/hashes.rb | UTF-8 | 288 | 3.59375 | 4 | [] | no_license | #!/usr/bin/ruby
# -*- coding: utf-8 -*-
# create a hash
books = {} # or Hash.new(0)
# :splendid is a symbol
books["Gravity's Rainbow"] = :splendid
puts books.keys
puts books.values
books.keys.each { |title| puts title }
books.each { |title, symbol| print title, " => ", symbol, "\n"}
| true |
2f81264df98f8c9027dbb970bc714fb2534aa674 | Ruby | WilfredTA/algorithmic_acrobatics | /Sorting/bubble_sort.rb | UTF-8 | 582 | 3.78125 | 4 | [] | no_license | # Two pointer slide
# swap vals at pointers if val at pointer 1 > val at pointer 2
# largest value therefore bubbles to the top on each passthrough
def bubble_sort(array)
limit = array.length - 1
while limit >= 0 do
pointer1 = 0
pointer2 = 1
while pointer2 <= limit do
if array[pointer1] > array[pointer2]
array[pointer1], array[pointer2] = array[pointer2], array[pointer1]
end
pointer1 += 1
pointer2 += 1
end
limit -= 1
end
array
end
ary = [7,6,5,3,2]
ary2 = [1,3,8,7,6,4,2]
p bubble_sort(ary)
p bubble_sort(ary2)
| true |
6542f3e49dd2530af931c7d0fce63d6df7bc3f63 | Ruby | jutonz/cuesnap | /lib/cuesnap/splitter.rb | UTF-8 | 3,877 | 3.140625 | 3 | [
"MIT"
] | permissive | require 'hashie'
require 'rubycue'
require 'shellwords'
module CueSnap
class FileNotFound < StandardError; end
class MP3FileNotFound < FileNotFound; end
class CueFileNotFound < FileNotFound; end
class CueFileTooLarge < StandardError
def message
'Only cue files less than 1MB are allowed.'
end
end
class Splitter
attr_reader :mp3_file, :cue_file, :output_folder, :options
# Public: Loads an mp3 and a RubyCue cuesheet.
#
# mp3_file - String file path to an mp3 file.
# cue_file - The path to a cuesheet for the target cue file (default: the
# name of the mp3, with .cue added).
# options - Hash of options.
# no_numbers - No number prefix for tracks.
# output_folder - The output folder to use (default: the name
# of the mp3).
#
# Returns the initalized object.
def initialize(mp3_file, cue_file = nil, options = {})
raise CueSnap::MP3FileNotFound, mp3_file unless File.exists? mp3_file
@mp3_file = mp3_file
if cue_file and cue_file.strip != ''
@cue_file = cue_file
else
@cue_file = File.expand_path("#{mp3_filename}.cue", File.dirname(@mp3_file))
end
raise CueSnap::CueFileNotFound, @cue_file unless File.exists? @cue_file
# If cue file is larger than 1MB, raise an error.
raise CueSnap::CueFileTooLarge if (File.size(@cue_file).to_f / 2**20) > 1
@options = Hashie::Mash.new options
@output_folder = @options.output_folder
@output_folder ||= mp3_filename
end
# Internal: Parses the cue file using RubyCue and sets the @cuesheet
# variable.
#
# Returns nothing.
def parse_cue_file
file_contents = File.read @cue_file
# Try to fix unicode problems
# use iconv if on Ruby 1.8
# From: bit.ly/bGmrCnCOPY
require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
file_contents.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
file_contents.encode!('UTF-8', 'UTF-16')
else
ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
file_contents = ic.iconv(file_contents)
end
@cuesheet = RubyCue::Cuesheet.new file_contents
@cuesheet.parse!
end
# Public: Splits the mp3 into files based on track_names and saves them to
# the output folder.
#
# Returns nothing.
def split!
# Wait until the last second to parse the cue file, in case the user
# changes it before we split.
parse_cue_file
format = @options.format or "@p - @t"
unless @options.no_numbers or @options.format
song_count_length = (@cuesheet.songs.length + 1).to_s.length
number_format = "@N#{song_count_length > 1 ? song_count_length : ''}"
format = "#{number_format} #{format}"
end
# Got to esape the spaces for the shell
format = Shellwords.escape format
command = ['mp3splt',
"-d #{escaped_output_folder}",
"-o #{format}",
"-c #{escaped_cue_file}"]
command.push '-Q' if @options.quiet
command.push escaped_mp3_file
system command.join(' ')
end
# Public: The filename for the mp3 file with the .mp3 extension removed.
def mp3_filename
File.basename(@mp3_file, '.mp3')
end
# Public: The space-escaped mp3 file path.
def escaped_mp3_file
escape_path @mp3_file
end
# Public: The space-escaped output folder path.
def escaped_output_folder
escape_path @output_folder
end
# Public: The space-escaped cue file path.
def escaped_cue_file
escape_path @cue_file
end
private
# Internal: Escape a path for the shell.
def escape_path(file)
Shellwords.escape file
end
end
end
| true |
f3abd5f0145c5adda22ea3db92937dda95de8086 | Ruby | Protobit/ridoku | /lib/ridoku/cook.rb | UTF-8 | 2,200 | 2.71875 | 3 | [
"BSD-2-Clause"
] | permissive | #
# Command: cook
#
require 'rugged'
require 'ridoku/base'
module Ridoku
register :cook
class Cook < Base
def run
command = Base.config[:command]
sub_command = (command.length > 0 && command[1]) || nil
Base.fetch_stack
case sub_command
# when 'list', nil
# list
when 'update'
update
when 'run'
cook
else
print_cook_help
end
end
protected
def list
update unless File.exists?(cookbook_path)
end
def update
$stdout.puts "Updating custom cookbooks..."
Base.run_command(Base.update_cookbooks(Base.extract_instance_ids))
end
class << self
def valid_recipe_format?(recipes)
return false if recipes.length == 0
recipe = %r(^[a-zA-Z0-9_\-]+(::[a-zA-Z0-9_\-]+){0,1}$)
recipes.each do |cr|
return false unless cr.match(recipe)
end
true
end
def cook_recipe(recipes, custom_json = nil)
cook_recipe_on_layers(recipes, nil, custom_json)
end
def cook_recipe_on_layers(recipes, layers, custom_json = nil)
Base.fetch_app()
recipes = [recipes] unless recipes.is_a?(Array)
unless valid_recipe_format?(recipes)
$stderr.puts 'Invalid recipes provided.'
print_cook_help
exit 1
end
instance_ids = Base.extract_instance_ids(layers)
if instance_ids.length == 0
$stderr.puts 'No valid instances available.'
exit 1
end
$stdout.puts "Running recipes:"
recipes.each do |arg|
$stdout.puts " #{$stdout.colorize(arg, :green)}"
end
command = Base.execute_recipes(Base.app[:app_id], instance_ids,
Base.config[:comment], recipes, custom_json)
Base.run_command(command)
end
end
def cook
Ridoku::Cook.cook_recipe(ARGV)
end
def print_cook_help
$stderr.puts <<-EOF
Command: cook
List/Modify the current app's associated domains.
cook:run run a specific or set of 'cookbook::recipe'
cook:update update the specified instance 'cookboooks'
EOF
end
end
end | true |
c725559cb65b53920112c97ae0740675bc9f249d | Ruby | DavyJonesLocker/client_side_validations | /test/active_model/cases/test_numericality_validator.rb | UTF-8 | 3,406 | 2.578125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'active_model/cases/test_base'
module ActiveModel
class NumericalityValidatorTest < ClientSideValidations::ActiveModelTestBase
def test_numericality_client_side_hash
expected_hash = { messages: { numericality: 'is not a number' } }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age]).client_side_hash(@person, :age)
end
def test_numericality_client_side_hash_with_allow_nil
expected_hash = { messages: { numericality: 'is not a number' }, allow_blank: true }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age], allow_nil: true).client_side_hash(@person, :age)
end
def test_numericality_client_side_hash_with_custom_message
expected_hash = { messages: { numericality: 'bad number' } }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age], message: 'bad number').client_side_hash(@person, :age)
end
def test_numericality_client_side_hash_with_options
expected_hash = {
messages: {
numericality: 'is not a number',
only_integer: 'must be an integer',
greater_than: 'must be greater than 10',
greater_than_or_equal_to: 'must be greater than or equal to 10',
equal_to: 'must be equal to 10',
less_than: 'must be less than 10',
less_than_or_equal_to: 'must be less than or equal to 10',
odd: 'must be odd',
even: 'must be even'
},
only_integer: true,
greater_than: 10,
greater_than_or_equal_to: 10,
equal_to: 10,
less_than: 10,
less_than_or_equal_to: 10,
odd: true,
even: true
}
test_hash = NumericalityValidator.new(attributes: [:age],
only_integer: true, greater_than: 10, greater_than_or_equal_to: 10,
equal_to: 10, less_than: 10, less_than_or_equal_to: 10,
odd: true, even: true).client_side_hash(@person, :age)
assert_equal expected_hash, test_hash
end
def test_numericality_message_always_present
expected_hash = { messages: { numericality: 'is not a number', only_integer: 'must be an integer' }, only_integer: true }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age], only_integer: true).client_side_hash(@person, :age)
end
def test_numericality_client_side_hash_ignore_proc
@person.stubs(:years).returns(5)
expected_hash = { messages: { numericality: 'is not a number' } }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age], equal_to: proc { |o| o.years }).client_side_hash(@person, :age)
end
def test_numericality_client_side_hash_observe_proc
@person.stubs(:years).returns(5)
expected_hash = { messages: { numericality: 'is not a number', equal_to: 'must be equal to 5' }, equal_to: 5 }
assert_equal expected_hash, NumericalityValidator.new(attributes: [:age], equal_to: proc { |o| o.years }).client_side_hash(@person, :age, true)
end
end
end
| true |
ec9de487fb1a3f0dd7e9cb8bdda3cb9f5203e421 | Ruby | sharonkeikei/hotel | /test/reservation_test.rb | UTF-8 | 1,080 | 2.703125 | 3 | [] | no_license | require_relative 'test_helper'
describe "Reservation class" do
before do
@new_hotel = Hotel::HotelController.new(10)
@new_hotel.reserve_room(Date.new(2010,02,10),Date.new(2010,02,13), "Sharon")
@new_reservation = @new_hotel.reservation_list[1]
end
describe "Initializer" do
it "is an instance of Reservation" do
expect(@new_reservation).must_be_kind_of Hotel::Reservation
end
end
describe "cost" do
it "will calculate the total cost of the reservation" do
expect(@new_reservation.cost).must_equal 600
end
end
describe "check_valid_room(request_room)" do
it "will return true if the request room matches with the room the reservation itself" do
expect(@new_reservation.check_valid_room("Room 1")).must_equal true
expect(@new_reservation.check_valid_room("Room 10")).must_equal false
end
end
describe "check_status" do
it "will return false is the status of the reservation is not equal to :open_hotel_block" do
expect(@new_reservation.check_status).must_equal false
end
end
end
| true |
13fda0c2a45e32a46c0c5d822cb4d70f9ef8660e | Ruby | devteds/e9-cloudformation-docker-ecs | /app/service.rb | UTF-8 | 817 | 2.90625 | 3 | [] | no_license | require 'sinatra'
require "sinatra/namespace"
class Book
@@books = [
{ id: "123", name: "Docker for Beginners" },
{ id: "124", name: "Docker with Kubernetes" },
{ id: "125", name: "Docker on ECS" }
]
def self.all
@@books
end
def self.find(book_id)
@@books.select { |p| p[:id] == book_id }.first
end
end
get '/' do
'Healthy!!!'
end
get '/stat' do
'Healthy!!!'
end
namespace '/api' do
before do
content_type 'application/json'
end
# /api/books
get '/books' do
Book.all.to_json
end
# /api/books/:id
get '/books/:id' do
if (book = Book.find(params[:id])) != nil
book.to_json
else
halt(404, { message:'book Not Found'}.to_json)
end
end
end
| true |
6b07a696796cc6616806aff1096a1a5e2833d49d | Ruby | tylerthomasallen/aahomework | /W1D5/map.rb | UTF-8 | 543 | 3.546875 | 4 | [] | no_license | class Map
def initialize
@array = []
end
def set(key, value)
idx = @array.each_index { |ele| ele[0] == key }
if idx
@array[idx][1] = value
else
@array.push([key, value])
end
end
def get(key)
@array.each { |ele| return ele[1] if ele[0] == key }
nil
end
def delete(key)
val = get(key)
@array.reject! { |ele| ele[0] == key }
val
end
def show
deep_dup(@array)
end
private
def deep_dup(arr)
arr.map { |ele| ele.is_a?(Array) ? deep_dup(arr) : ele }
end
end
| true |
8648c379db26475d74411fe8abefc10a91b604ee | Ruby | kenman21/key-for-min-value-web-022018 | /key_for_min.rb | UTF-8 | 488 | 3.65625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
if name_hash != {}
arrayofmaxes = []
min_name = ""
name_hash.each do |names, values|
arrayofmaxes.push(values)
end
max = arrayofmaxes.max
name_hash.each do |names, value|
if value <= max
max = value
min_name = names
end
end
min_name
else
nil
end
end | true |
7d4299ec09d94668d03ba589575d0e84a1ab423d | Ruby | masayasviel/algorithmAndDataStructure | /from101to150/ABC115/mainC.rb | UTF-8 | 178 | 2.96875 | 3 | [] | no_license | n, k = gets.chomp.split(" ").map(&:to_i)
h = []
ans = 1 << 30
n.times do
h << gets.chomp.to_i
end
h.sort!
(n-k+1).times do |i|
ans = [ans, h[i+k-1]-h[i]].min
end
puts ans | true |
10d5cf3f59702223faea5f6eb8a2c6371193fb8e | Ruby | feroult/dxdojo | /codebreaker/lib/codebreaker/game.rb | UTF-8 | 937 | 3.5625 | 4 | [] | no_license | module Codebreaker
class Game
def initialize(output)
@output = output
end
def start(code = nil)
@code = code
@output.puts "welcome to codebreaker"
@output.puts "submit a guess:"
end
def guess(guess)
@output.puts "+"*exact_match_count(guess) + "-"*number_match_count(guess)
end
def exact_match_count(guess)
(0..3).inject(0) do |count, index|
count += ( exact_match?(guess, index) ? 1 : 0 )
end
end
def total_match_count(guess)
code = @code.split('')
count = 0
guess.split('').each do |d|
if code.index(d)
count += 1
code.delete_at(code.index(d))
end
end
count
end
def number_match_count(guess)
total_match_count(guess) - exact_match_count(guess)
end
def exact_match?(guess, index)
@code[index] == guess[index]
end
end
end
| true |
72473230b4d5735e0db9d51ff0e7edd15623e104 | Ruby | ndelforno/Hatchway_assessment | /report.rb | UTF-8 | 2,466 | 3.5 | 4 | [] | no_license | require 'csv'
require 'json'
require "awesome_print"
students_array = []
marks_array = []
courses_array = []
tests_array = []
puts "path of students file?"
filename = gets.chomp
students = CSV.read(filename)[1 .. -1]
puts "Path of marks file?"
filename = gets.chomp
marks = CSV.read(filename)[1 .. -1]
puts "Path of courses file?"
filename = gets.chomp
courses = CSV.read(filename)[1 .. -1]
puts "Path of tests file?"
filename = gets.chomp
tests = CSV.read(filename)[1 .. -1]
students.each do |student|
students_array << {:id => student[0], :name => student[1]}
end
marks.each do |mark|
marks_array << {:test_id => mark[0], :student_id => mark[1], :mark => mark[2]}
end
courses.each do |course|
courses_array << {:id => course[0], :name => course[1], :teacher => course[2]}
end
tests.each do |test|
tests_array << {:id => test[0], :course_id => test[1], :weight => test[2]}
end
def total_student_average(student_id,marks_array, tests_array)
total_weight = 0
total_average = 0
student_marks = []
marks_array.each do |mark|
tests_array.each do |test|
if test[:id] == mark[:test_id] && mark[:student_id] == student_id.to_s
total_weight += test[:weight].to_i
student_marks << mark[:mark].to_i * test[:weight].to_i
end
end
end
total_average = (student_marks.sum.to_f / total_weight.to_f)
return total_average.round(2)
end
def find_grade(course_id, student_id, marks_array, tests_array)
total_weight = 0
grade = 0
student_marks = []
marks_array.each do |mark|
tests_array.each do |test|
if test[:id] == mark[:test_id] && mark[:student_id] == student_id.to_s && test[:course_id] == course_id
total_weight += test[:weight].to_i
student_marks << mark[:mark].to_i * test[:weight].to_i
end
end
end
if total_weight != 0
grade = (student_marks.sum.to_f / total_weight.to_f)
return grade.round(2)
else
return grade.round(2)
end
end
students_array.each do |student|
total_average = total_student_average(student[:id], marks_array, tests_array)
print "student Id: #{student[:id]}, name: #{student[:name]}\n"
print "total Average: #{total_average} % \n"
courses_array.each do |course|
final_grade = find_grade(course[:id],student[:id], marks_array, tests_array)
print " Course: #{course[:name]}, Teacher: #{course[:teacher]}\n"
print " Final Grade: #{final_grade} %\n"
end
puts "--------"
end
| true |
9dfb4a27108dc16c260b4efe9b63139ab3cd8b62 | Ruby | usutani/hsms | /hsms_server.rb | UTF-8 | 957 | 2.65625 | 3 | [] | no_license | require "rubygems"
require "eventmachine"
require "hsms_factory"
require "hsms_state"
class HSMSServer < EM::Connection
def initialize
@factory = HSMSFactory.new
@state = HSMSState.new
puts @state.to_s
end
def post_init
@state.connected
puts @state.to_s
end
def unbind
@state.disconnected
puts @state.to_s
end
def receive_data(data)
@factory.feed(data)
@factory.each { |message|
receive_message(message)
}
@factory.clear
end
def receive_message(message)
case message.s_type
when SType::DATA_MESSAGE
send_data(HSMSMessage.empty_data(SType::DATA_MESSAGE))
when SType::SELECT_REQ
send_data(HSMSMessage.empty_data(SType::SELECT_RSP))
@state.selected
puts @state.to_s
when SType::DESELECT_REQ, SType::SEPARATE_REQ
send_data(HSMSMessage.empty_data(SType::DESELECT_RSP))
@state.deselected
puts @state.to_s
end
end
end
| true |
c8ee42db2003d9e79b5738d34a09d296f19fab2b | Ruby | jkschub/general-activities-app | /ga-app/db/seeds.rb | UTF-8 | 2,324 | 2.75 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
require 'faker'
def rand_int(from, to)
rand_in_range(from, to).to_i
end
def rand_price(from, to)
rand_in_range(from, to).round(2)
end
def rand_time(from, to=Time.now)
Time.at(rand_in_range(from.to_f, to.to_f))
end
def rand_in_range(from, to)
rand * (to - from) + from
end
Category.create(name: "Arts & Culture")
Category.create(name: "Community & Environment")
Category.create(name: "Dancing")
Category.create(name: "Education & Learning")
Category.create(name: "Fitness")
Category.create(name: "Food & Drink")
Category.create(name: "Games")
Category.create(name: "Hobbies & Craft")
Category.create(name: "Movies & Film")
Category.create(name: "Music")
Category.create(name: "Outdoors & Adventure")
Category.create(name: "Photography")
Category.create(name: "Tech")
Category.create(name: "Other")
5.times do
User.create(is_admin: false,
name: Faker::Name.name,
email: Faker::Internet.email,
cohort: Faker::Team.creature,
avatar_url: "http://www.gravatar.com/avatar/6f7587bc566de4570e5a63a84ad234b3.png",
oauth_token: Faker::Lorem.characters(30)
)
end
users = [1, 2, 3, 4, 5]
events = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
boolean = [true, false]
categories = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
15.times do
Event.create(name: Faker::Company.name,
description: "This is a description.",
category_id: categories.sample,
price: rand_price(10, 50), user_id: users.sample,
signup_start: rand_time(2.days.ago),
signup_end: 2.days.from_now,
event_start: 3.days.from_now,
event_end: 4.days.from_now,
uses_paypal: false
)
end
25.times do
Attendance.create(user_id: users.sample,
event_id: events.sample,
is_paid: boolean.sample )
end
20.times do
Comment.create(user_id: users.sample,
event_id: events.sample,
content: "This is a comment.")
end
| true |
e212d33e87df7bd3dabb99601b6f3b65e4f2b535 | Ruby | triperodericota/redrock | /db/seeds.rb | UTF-8 | 3,359 | 2.640625 | 3 | [
"MIT"
] | permissive | require 'faker'
def set_photo(path_file, model)
begin
File.open(path_file) do |file|
model.photo = file
puts model.photo.url
model.save!
end
rescue
puts "\n Without photo"
end
end
Photo.destroy_all
# fan's users
Fan.destroy_all
puts "Fans: \n"
(1..15).each do
f = Fan.create!(first_name: Faker::Name.first_name, last_name: Faker::Name.last_name)
f.reload
User.create!(email: Faker::Internet.unique.free_email(name: f.first_name), username: Faker::Internet.unique.user_name(specifier: 1..20),
password: '12345678', password_confirmation: '12345678', profile_type: 'Fan', profile_id: f.id)
puts "\nFan #{f.id} = #{f.inspect} - #{f.user.inspect}"
set_photo("public/uploads/user/photo/#{f.user.id}/profile#{f.user.id}.jpg", f.user)
end
#artist's users
Artist.destroy_all
puts "Artists: \n"
(1..5).each do
a = Artist.create!(name: Faker::Music::RockBand.unique.name)
a.reload
User.create!(email: Faker::Internet.unique.email(name: a.name), username: Faker::Internet.unique.user_name(specifier: 1..20),
password: '12345678', password_confirmation: '12345678', profile_type: 'Artist', profile_id: a.id)
puts "\n Artist #{a.id} = #{a.inspect} - #{a.user.inspect}"
a.fans = Fan.all.sample(Random.rand(15))
puts "\n Artist #{a.id} followers = #{a.fans.inspect}"
set_photo("public/uploads/user/photo/#{a.user.id}/profile#{a.user.id}.jpg", a.user)
end
#events and audiences
Event.destroy_all
puts "Events: \n"
Artist.all.each do |a|
events_number = Random.rand(1..3)
events_number.times do |event_number|
sd = event_number.odd? ? Faker::Time.forward(days: 100) : Faker::Time.between(from: 3.days.ago, to: 2.days.ago)
ed = (sd + Random.rand(5).hours) + Random.rand(45).minutes
puts "event start day: #{sd} / event end day: #{ed}"
e = Event.create!(title: "#{event_number}#{event_number.ordinal} event"[0..39], description: Faker::Lorem.paragraph, place: Faker::TvShows::GameOfThrones.city,
start_date: sd, end_date: ed, artist: a)
puts "\n Event #{e.id} = #{e.inspect}"
e.reload
e.fans= Fan.all.sample(Random.rand(15))
e.save
puts "\n Event #{e.id} audience = #{e.fans.inspect}"
set_photo("public/uploads/event/photo/#{e.id}/event#{e.id}.jpg", e)
end
end
# products and orders
Product.destroy_all
Order.destroy_all
photo_index = 1
puts "Products: \n"
Artist.all.each do |a|
if a.id.odd?
2.times do |product_number|
p = Product.create!(title: "product #{a.id} - #{product_number}", description: Faker::Lorem.sentence, price: Random.rand(50.to_f...500.to_f).round(2),
stock: Random.rand(10...50), artist: a)
puts "\n Product #{p.id} = #{p.inspect}"
# set product's photos
p.reload
if p.id <= 3
(p.id).times do
photo = Photo.create!(product: p)
photo.reload
set_photo("public/uploads/photo/image/#{photo_index}/product-photo#{p.id}.jpg", p)
photo_index += 1
end
end
puts "\n Product #{p.id} photos = #{p.photos.inspect}"
# set product's orders
#if p.id.odd?
# order = Order.create(product: p, fan: Fan.all.sample, units: Random.rand(1...5), buyer: buyer)
# puts "\n Order #{order.id} for product #{p.id} = #{order.inspect}"
#end
end
end
end
| true |
ee76efa9f38a86bd7e7dbba06989f3201c32fbc9 | Ruby | ffi/ffi | /bench/bench_FrV.rb | UTF-8 | 804 | 2.53125 | 3 | [
"MIT",
"BSD-3-Clause"
] | permissive | require_relative 'bench_helper'
module BenchFrV
module LibTest
extend FFI::Library
ffi_lib LIBTEST_PATH
attach_function :bench_f32_v, [ :float ], :void
def self.rb_bench(i0); nil; end
end
puts "Benchmark [ :float ], :void performance, #{ITER}x calls"
f = 1.0
10.times {
puts Benchmark.measure {
i = 0; while i < ITER
LibTest.bench_f32_v(f)
LibTest.bench_f32_v(f)
LibTest.bench_f32_v(f)
LibTest.bench_f32_v(f)
i += 4
end
}
}
puts "Benchmark ruby method(1 arg) performance, #{ITER}x calls"
10.times {
puts Benchmark.measure {
i = 0; while i < ITER
LibTest.rb_bench(f)
LibTest.rb_bench(f)
LibTest.rb_bench(f)
LibTest.rb_bench(f)
i += 4
end
}
}
end
| true |
5c2b321ef6bae9bd0268b41336601a231526d222 | Ruby | andrewhchang/pacmansimulator | /lib/grid.rb | UTF-8 | 672 | 3.421875 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'position'
# Grid class
class Grid
attr_reader :x_size
attr_reader :y_size
# Initialize table with an X and Y dimension
def initialize(x_size, y_size)
unless x_size < 1 || y_size < 1
@x_size = x_size - 1
@y_size = y_size - 1
end
end
# Check the bounds of the position with the Grid x and y size
# return true if position is valid within all bounds and positive.
def validate_position(position)
return false unless position.is_a?(Position) && !position.nil?
position.x <= @x_size &&
position.y <= @y_size &&
position.x >= 0 &&
position.y >= 0
end
end
| true |
8061eff1e00f224f86c69e17f2cf1c394dc08fd9 | Ruby | snorkleboy/sse | /server.rb | UTF-8 | 1,141 | 3.3125 | 3 | [] | no_license | require 'socket'
class Server
def initialize()
@server = TCPServer.new 2000
loop do
Thread.start(@server.accept) do |client|
handleClient client
end
end
end
def handleClient(client)
msg = client.recv(300).split("\n")
if (msg[0].include?"GET / HTTP")
handleHTTP(client, msg)
end
end
def handleHTTP(client, headers)
puts headers
client.puts "HTTP/1.1 200\r\n" # 1
client.puts "Content-Type: text/html\r\n" # 2
client.puts "Access-Control-Allow-Origin: *"
client.puts "\r\n" # 3
handleMagicSocket(client)
end
def handleMagicSocket(client)
client.puts "Hello! The time is #{Time.now}.\r\n" #4
read(client)
write(client)
end
def read(client)
Thread.new{
while(line = client.gets)
puts line
end
}
end
def write(client)
puts "\n\n\n type in message to send to client"
while (true)
client.puts(gets.chomp)
end
end
end
Server.new() | true |
0cdd8f9239bdeff596be5000f04a61a73603d0e7 | Ruby | jgroeneveld/attributed_object | /spec/attributed_object_spec.rb | UTF-8 | 8,147 | 3 | 3 | [
"MIT"
] | permissive | require 'attributed_object'
describe AttributedObject do
class SimpleFoo
include AttributedObject::Strict
attribute :bar
end
class DisallowingNil
include AttributedObject::Strict
attribute :bar, disallow: nil
end
class DefaultFoo
include AttributedObject::Strict
attribute :bar, default: "my default"
attribute :dynamic, default: -> { count }
def self.reset
@count = 0
end
def self.count
@count ||= 0
@count += 1
end
end
class AttributedObjectWithWhitelist
include AttributedObject::Strict
PLANET_EARTH = 'earth'.freeze
PLANET_MARS = 'mars'.freeze
attribute :planet, :string, whitelist: [PLANET_EARTH, PLANET_MARS]
end
class ChildFoo < DefaultFoo
attribute :lollipop, default: "lecker"
end
it 'requires attributes by default' do
expect { SimpleFoo.new }.to raise_error(AttributedObject::MissingAttributeError)
expect(SimpleFoo.new(bar: 1).bar).to eq(1)
end
describe 'nil control' do
it 'allows explicit nil values' do
expect(SimpleFoo.new(bar: nil).bar).to eq(nil)
end
it 'can be controlled to not allow explicit nil' do
expect { DisallowingNil.new(bar: nil).bar }.to raise_error(AttributedObject::DisallowedValueError)
end
end
describe 'whitelist' do
it 'allows whitelisted values' do
object = AttributedObjectWithWhitelist.new(planet: AttributedObjectWithWhitelist::PLANET_EARTH)
expect(object.planet).to eq(AttributedObjectWithWhitelist::PLANET_EARTH)
end
it 'crashes when provided with not-whitelisted value' do
expect { AttributedObjectWithWhitelist.new(planet: 'sun') }.to raise_error(AttributedObject::DisallowedValueError)
end
end
describe 'default value' do
before { DefaultFoo.reset }
it 'can specify a default value' do
expect(DefaultFoo.new.bar).to eq("my default")
expect(DefaultFoo.new(bar: 'other').bar).to eq("other")
end
it 'can specify a lambda as default value' do
expect(DefaultFoo.new.dynamic).to eq(1)
expect(DefaultFoo.new.dynamic).to eq(2)
end
end
describe 'extra_options' do
context 'inheritance' do
it 'is passed to the children' do
class Papa
include AttributedObject::Strict
attributed_object default_to: nil
attribute :foo
attribute :bar, default: 'hi'
end
class Sohn < Papa
attribute :something_else
end
expect(Sohn.new.something_else).to eq(nil)
expect(Sohn.new.bar).to eq('hi')
end
end
describe 'default_to' do
it 'allows changing default for all fields' do
class Defaulting
include AttributedObject::Strict
attributed_object default_to: nil
attribute :foo
attribute :bar, default: 'hi'
end
expect(Defaulting.new.foo).to eq(nil)
expect(Defaulting.new.bar).to eq('hi')
end
it 'allows type defaulting' do
class TypeDefaulting
include AttributedObject::Strict
attributed_object default_to: AttributedObject::TypeDefaults.new
attribute :a_string, :string
attribute :a_boolean, :boolean
attribute :a_integer, :integer
attribute :a_float, :float
attribute :a_numeric, :numeric
attribute :a_symbol, :symbol
attribute :a_string_by_class, String
attribute :another_class, SimpleFoo
attribute :a_array, :array
attribute :a_hash, :hash
attribute :something_with_default, :string, default: 'foobar'
attribute :something_without_type
end
expect(TypeDefaulting.new.a_string).to eq('')
expect(TypeDefaulting.new.a_boolean).to eq(false)
expect(TypeDefaulting.new.a_integer).to eq(0)
expect(TypeDefaulting.new.a_float).to eq(0.0)
expect(TypeDefaulting.new.a_numeric).to eq(0)
expect(TypeDefaulting.new.a_symbol).to eq(nil)
expect(TypeDefaulting.new.a_string_by_class).to eq(nil)
expect(TypeDefaulting.new.another_class).to eq(nil)
expect(TypeDefaulting.new.a_array).to eq([])
expect(TypeDefaulting.new.a_hash).to eq({})
expect(TypeDefaulting.new.something_with_default).to eq('foobar')
expect(TypeDefaulting.new.something_without_type).to eq(nil)
end
it 'is possible to overwrite and add type defaults' do
class TypeDefaultingOverwrites
include AttributedObject::Strict
attributed_object default_to: AttributedObject::TypeDefaults.new(
:string => 'my_default_string',
SimpleFoo => SimpleFoo.new(bar: 'kekse')
)
attribute :a_string, :string
attribute :a_integer, :integer
attribute :foo, SimpleFoo
end
expect(TypeDefaultingOverwrites.new.a_string).to eq('my_default_string')
expect(TypeDefaulting.new.a_integer).to eq(0)
expect(TypeDefaultingOverwrites.new.foo).to eq(SimpleFoo.new(bar: 'kekse'))
end
end
describe 'ignore_extra_keys' do
it 'allows extra_keys' do
class FooWithExtra
include AttributedObject::Strict
attributed_object ignore_extra_keys: true
attribute :bar, :integer, default: 42
end
expect { FooWithExtra.new(bar: 12, not_defined: 'asd') }.not_to raise_error
expect(FooWithExtra.new(bar: 12, not_defined: 'asd').attributes).to eq(bar: 12)
expect(FooWithExtra.new( not_defined: 'asd').attributes).to eq(bar: 42)
end
end
describe 'disallow' do
it 'gives default to disallow' do
class FooWithExtra
include AttributedObject::Strict
attributed_object disallow: nil
attribute :bar, :integer
attribute :has_other_disallow, :integer, disallow: 0
end
expect { FooWithExtra.new(bar: 1, has_other_disallow: 1) }.not_to raise_error
expect { FooWithExtra.new(bar: 1, has_other_disallow: nil) }.not_to raise_error
expect { FooWithExtra.new(bar: nil, has_other_disallow: 1) }.to raise_error(AttributedObject::DisallowedValueError)
expect { FooWithExtra.new(bar: 1, has_other_disallow: 0) }.to raise_error(AttributedObject::DisallowedValueError)
end
end
end
it 'throws an error for unknown attributes' do
expect { SimpleFoo.new(whatever: 'xxx') }.to raise_error(AttributedObject::UnknownAttributeError)
end
it 'inherits the attributes from its superclass' do
f = ChildFoo.new
expect(f.bar).to eq("my default")
expect(f.lollipop).to eq("lecker")
end
it 'does not modify the args' do
args = {bar: "asd"}
f = SimpleFoo.new(args)
f.bar = 'different'
expect(f.bar).to eq('different')
expect(args[:bar]).to eq('asd')
end
describe '#==' do
it 'is equals for same attributes' do
expect(SimpleFoo.new(bar: 12)).to eq(SimpleFoo.new(bar: 12))
end
it 'is not equal for different attributes' do
expect(SimpleFoo.new(bar: 77)).to_not eq(SimpleFoo.new(bar: 12))
end
end
describe 'attribute storage' do
class InnerStructureFoo
include AttributedObject::Coerce
attribute :bar, :string, default: 'default'
attribute :foo, :string, default: 'default'
attribute :number, :integer, default: 0
def foo=(f)
@foo = "prefix-#{f}-suffix"
end
def number=(n)
@number = n+1
end
end
describe '#attributes' do
it 'returns the attributes as hash' do
expect(InnerStructureFoo.new(bar: 'hi').attributes).to eq(
bar: 'hi',
foo: 'prefix-default-suffix',
number: 1
)
end
end
it 'stores the data in instance vars' do
expect(InnerStructureFoo.new(bar: 'hi').instance_variable_get('@bar')).to eq('hi')
end
it 'uses setters' do
expect(InnerStructureFoo.new(foo: 'middel').foo).to eq('prefix-middel-suffix')
end
it 'uses setters after coercion' do
expect(InnerStructureFoo.new(number: '42').number).to eq(43)
end
end
end
| true |
653434610c4de6ede3d4b51dc9b104ce5d46fd63 | Ruby | Alkex1/TextGet | /db/seeds.rb | UTF-8 | 2,185 | 2.828125 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
subjects = [
{ name: "Biology" },
{ name: "Chemistry" },
{ name: "Physics"},
{ name: "Maths" },
{ name: "History" }
]
# Creating subjects in database
if Subject.count == 0
for subject in subjects
subject = Subject.create(subject)
puts "Created #{subject.name}"
end
end
# making user data for database
if User.count == 0
for i in 1..5 do
usere = User.create(
email: Faker::Internet.email,
password: "blahblah"
)
puts "created #{usere}"
end
end
# variable for condition of made textbook
quality = [
"Like New",
"Good",
"Poor quality"
]
# making textbook data for database, with a limit of 100 for the sake of test data
unless Textbook.count == 100
for i in 1..20
b = rand(1..User.all.count)
# variable to take a user's id to assign it to a textbook.
userx = User.find(b).id
tbook = Textbook.create(
name: Faker::Book.title,
release_date: Faker::Date.between_except(from: 10.year.ago, to: 1.year.from_now, excepted: Date.today),
author: Faker::Book.author,
ISBN: Faker::Code.isbn,
# ISBN: rand(1..10000000),
condition: quality.sample,
price: rand(20..2000),
retail_price: rand(50..5000),
user_id: userx
)
puts "Made #{tbook}"
end
end
# associating random Textbooks with random subjects for database
# for i in 1..Textbook.count do
# x = rand(1..Textbook.count)
# y = rand(1..Subject.count)
# TextbooksSubject.create(textbook_id: x, subject_id: y)
# end
subject_ids = Subject.pluck(:id)
textbook_ids = Textbook.pluck(:id)
for textbook_id in textbook_ids
TextbooksSubject.create(textbook_id: textbook_id, subject_id: subject_ids.sample)
end | true |
517ade00c69d87d44bae804cac97ce83d77597ee | Ruby | karthik-mallavarapu/site_crawler | /crawler.rb | UTF-8 | 1,227 | 2.84375 | 3 | [] | no_license | require 'nokogiri'
require 'uri'
require 'open-uri'
require 'pry'
module Crawler
EXCLUDE_PATTERN = /.(jpg|jpeg|png|gif|pdf|svg|mp4)\z/
def scrape_page(url)
page = get_page(url)
return [] if page.nil?
links = page.css('a')
urls = links.map { |link| link['href'] }
urls.compact!
urls.uniq!
sanitize_urls(urls).compact.uniq
end
def get_page(url)
begin
page = Nokogiri::HTML(open(url))
rescue Exception => e
puts "Warning: Get page for #{url} resulted in #{e.message}"
end
end
def sanitize_urls(urls)
urls.map do |link|
begin
uri = URI(URI.encode(link))
if uri.absolute? && uri.hostname == domain &&
(uri.scheme == "http" || uri.scheme == "https") && !fragmented?(link)
URI.decode(uri.to_s)
elsif uri.relative? && !fragmented?(link)
URI.decode(URI(URI.encode(base_url)).merge(uri).to_s)
end
rescue Exception => e
puts "Warning: #{e.message}"
next
end
end
end
def disallowed?(url)
!!(url =~ EXCLUDE_PATTERN)
end
def reachable?(url)
return true if get_page(url)
false
end
def fragmented?(url)
!(URI(url).fragment.nil?)
end
end
| true |
2a904d42d496387ffce1a8591c0510901b87af9b | Ruby | lilijreey/rails-note | /ra/view/artflow/presenters/lib/creation_summary.v1.rb | UTF-8 | 682 | 2.546875 | 3 | [] | no_license | #---
# Excerpted from "The Rails View",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/warv for more book information.
#---
class CreationSummary
delegate :to_json, :to => :data
def initialize(creation, user)
@creation = creation
@user = user
end
def data
case @user
when Admin
data_with_estimate
when Designer
standard_data
else
sanitized_data
end
end
end
| true |
618a16cd65bf9ed694a5f25caff946c2ee918325 | Ruby | QuantaEx/payeer | /lib/payeer.rb | UTF-8 | 2,294 | 2.609375 | 3 | [] | no_license | require 'net/https'
require 'logger'
class Payeer
API_URL = 'https://payeer.com/ajax/api/api.php'
class AuthError < Exception
end
class ApiError < Exception
end
attr_accessor :account, :api_id, :api_secret, :config, :logger
DEFAULTS = {
language: 'ru'
}
def initialize(account, api_id, api_secret, options = {})
@account = account
@api_id = api_id
@api_secret = api_secret
@config = DEFAULTS.merge(options)
@logger = Logger.new @config[:log] ? STDOUT : nil
end
def balance
api_call action: 'balance'
end
def transaction_history(transaction_id)
response = api_call action: 'historyInfo', historyId: transaction_id
if response['info'].is_a? Hash
response['info']
end
end
def transfer_funds(options = {})
payload = {
'action' => 'transfer',
'curIn' => options[:currency_from] || 'USD',
'sum' => options[:amount],
'curOut' => options[:currency_to] || 'USD',
'to' => options[:to],
'comment' => options[:comment],
}
payload['anonim'] = options[:anonim] if options[:anonim]
payload['protect'] = options[:protect] if options[:protect]
payload['protectPeriod'] = options[:protectPeriod] if options[:protectPeriod]
payload['protectCode'] = options[:protectCode] if options[:protectCode]
response = api_call payload
response['historyId']
end
def api_call(options = {})
uri = URI API_URL
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(prepare_params(options))
logger.info "Payeer API Request url: #{uri}, payload: #{prepare_params(options)}"
response = http.request(request)
json_response = JSON.parse(response.body)
logger.info "Payeer API Response: #{json_response.inspect}"
raise AuthError if json_response["auth_error"].to_i > 0
raise ApiError, json_response["errors"].inspect if json_response["errors"] && json_response["errors"].any?
json_response
end
def prepare_params(params)
auth = {
account: account,
apiId: api_id,
apiPass: api_secret,
lang: config[:language]
}
params.merge(auth)
end
end | true |
81307d8d743b12d1450513dcc100a36797b543fb | Ruby | jfurukawa4392/aa_homework | /W2D4/poker/spec/card_spec.rb | UTF-8 | 418 | 3.078125 | 3 | [] | no_license | require 'card'
describe Card do
describe "#initialize" do
subject(:card) {Card.new(["A","C"])}
it "is initialized with a value and a suit" do
expect(card.value).to eq("A")
expect(card.suit).to eq("C")
end
it "raises an error if card is invalid" do
expect{ Card.new(5) }.to raise_error(ArgumentError)
expect{ Card.new("S") }.to raise_error(ArgumentError)
end
end
end
| true |
7b27969619b267ef5facf25517afd61c65351a64 | Ruby | MasonChinkin/aA_hw | /w2d4/octopus_problems.rb | UTF-8 | 740 | 3.484375 | 3 | [
"Apache-2.0"
] | permissive | FISH = ["fish", "fiiish", "fiiiiish", "fiiiish", "fffish", "ffiiiiisshh", "fsh", "fiiiissshhhhhh"]
def sluggish(arr)
longest = ""
arr.each do |ele1|
if arr.none? { |ele2| ele1 != ele2 && ele2.length > ele1.length }
longest = ele1
end
end
longest
end
def merge_sort(arr, &prc)
return self if self.length < 2
mid = arr.length / 2
left = arr.take(mid).merge_sort(&prc)
right = arr.drop(mid).merge_sort(&prc)
merge(left, right, &prc)
end
def merge(left, right, &prc)
sorted = []
case prc.call(left[0], right[0])
when -1
sorted << left.shift
when 0
sorted << left.shift
when 1
sorted << right.shift
end
sorted + left + right
end
# calling it quits after 30 min. A lot to take in...
| true |
0fceba16de9b6566b3e4edf0102703c68b5eac76 | Ruby | chrisjenson/Projects | /RE-SERVD/code/app/controllers/opportunities_controller.rb | UTF-8 | 4,793 | 2.65625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
#
# Filename: opportunity_controller.rb
# Description: this file is the controller file for all of the opportunities and actions
# associated with the events page.
class OpportunitiesController < ApplicationController
before_action :set_opportunity, only: %i[favorite show edit update destroy]
# GET /opportunities
# GET /opportunities.json
# Function: favorite
# Parameters:none
# Pre-Condition: the user wants to favorite an event
# Post-Condition: will favorite or unfavorite an event
def favorite
type = params[:type]
if type == 'favorite'
current_user.favorites << @opportunity
redirect_to :back, notice: 'You favorited ' + @opportunity.name
elsif type == 'unfavorite'
current_user.favorites.delete(@opportunity)
redirect_to :back, notice: 'Unfavorited ' + @opportunity.name
else
redirect_to :back, notice: 'Nothing happened.'
end
end
# Function: index
# Paramters: none
# Pre-Condition: the user tries to get to the events page
# Post-Condition: will display all of the events in the table in the view
def index
@opportunities = Opportunity.all
@opportunities = @opportunities.sort_by &:on_date
return if current_user.nil? || current_user.tag.nil?
@recommended_list = Opportunity.where(tag: current_user.tag) # gets all tags that are ligned up
@recommended_list = @recommended_list.sort_by &:on_date
@opportunities -= @recommended_list # takes the recommended events out from the
# event list to avoid duplicates
end
# GET /opportunities/1
# GET /opportunities/1.json
# Function: show
# Paramters: none
# Pre-Condition: the user clicks on a view button for one of the events
# Post-Condition: user is redirected to a page with all of the selected events information
def show; end
# GET /opportunities/new
# Function: new
# Parameters: none
# Pre-Condition: user selects new opportunity
# Post-Condition: will render a page for the user to create a new opportunity
def new
@opportunity = Opportunity.new
end
# GET /opportunities/1/edit
# Function: edit
# Parameters: none
# Pre-Condition: user selects the edit button for one of the opportunities in the view
# Post-Condition: user is taken to the edit page to alter the opportunities information
def edit; end
# POST /opportunities
# POST /opportunities.json
# Function: create
# Parameters: none
# Pre-Condition: the user has filled out the new opportunity form and then selects create event
# Post-Condition: the new opportunity will be added to the datatable
def create
p = opportunity_params
p[:email] = user_email
@opportunity = Opportunity.new(p)
respond_to do |format|
if @opportunity.save
format.html { redirect_to @opportunity, notice: 'Opportunity was successfully created.' }
format.json { render :show, status: :created, location: @opportunity }
else
format.html { render :new }
format.json { render json: @opportunity.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /opportunities/1
# PATCH/PUT /opportunities/1.json
# Function: update
# Parameters: none
# Pre-Condition: the user has made some changes to the edit view forms and selected the update button
# Post-Condition: the event in the table will be updated with the new information
def update
respond_to do |format|
if @opportunity.update(opportunity_params)
format.html { redirect_to @opportunity, notice: 'Opportunity was successfully updated.' }
format.json { render :show, status: :ok, location: @opportunity }
else
format.html { render :edit }
format.json { render json: @opportunity.errors, status: :unprocessable_entity }
end
end
end
# DELETE /opportunities/1
# DELETE /opportunities/1.json
# Function: destroy
# Parameters: none
# Pre-Condition: the user selects on the delete button for the event in the view
# Post-Condition: the event will be removed from the opportunity table
def destroy
@opportunity.destroy
respond_to do |format|
format.html { redirect_to opportunities_url, notice: 'Opportunity was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_opportunity
@opportunity = Opportunity.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def opportunity_params
params.require(:opportunity).permit(:name, :address, :city, :state, :zip_code, :transportation, :description, :frequency, :email, :on_date, :start_time, :end_time, :issue_area, :tag)
end
end
| true |
1e494d9a7c8922d925381b173853ed1080d18ff8 | Ruby | airbnb/ruby | /rubocop-airbnb/lib/rubocop/cop/airbnb/const_assigned_in_wrong_file.rb | UTF-8 | 2,740 | 2.71875 | 3 | [
"MIT"
] | permissive | require_relative '../../airbnb/inflections'
require_relative '../../airbnb/rails_autoloading'
module RuboCop
module Cop
module Airbnb
# This cop checks for a constant assigned in a file that does not match its owning scope.
# The Rails autoloader can't find such a constant, but sometimes
# people "get lucky" if the file happened to be loaded before the method was defined.
#
# @example
# # bad
#
# # foo/bar.rb
# module Foo
# BAZ = 42
# end
#
# # good
#
# # foo.rb
# module Foo
# BAZ = 42
# end
class ConstAssignedInWrongFile < Base
include Inflections
include RailsAutoloading
# FOO = 42
ASSIGNMENT_MSG =
"In order for Rails autoloading to be able to find and load this file when " \
"someone references this const, move the const assignment to a file that defines " \
"the owning module. Const %s should be defined in %s.".freeze
# FOO = 42 at global scope
GLOBAL_ASSIGNMENT =
"In order for Rails autoloading to be able to find and load this file when " \
"someone references this const, move the const assignment to a file that defines " \
"the owning module. Const %s should be moved into a namespace or defined in %s.".freeze
# FOO = 42
def on_casgn(node)
path = node.source_range.source_buffer.name
return unless run_rails_autoloading_cops?(path)
return unless node.parent_module_name
# Ignore assignments like Foo::Bar = 42
return if node.children[0]
const_name = node.children[1]
parent_module_name = normalize_module_name(node.parent_module_name)
fully_qualified_const_name = full_const_name(parent_module_name, const_name)
expected_dir = underscore(fully_qualified_const_name)
allowable_paths = allowable_paths_for(expected_dir)
if allowable_paths.none? { |allowable_path| path =~ allowable_path }
add_error(const_name, node)
end
end
private
def add_error(const_name, node)
parent_module_names = split_modules(node.parent_module_name)
expected_file = "#{parent_module_names.map { |name| underscore(name) }.join("/")}.rb"
if expected_file == ".rb" # global namespace
expected_file = "#{underscore(const_name)}.rb"
add_offense(node, message: GLOBAL_ASSIGNMENT % [const_name, expected_file])
else
add_offense(node, message: ASSIGNMENT_MSG % [const_name, expected_file])
end
end
end
end
end
end
| true |
ef8b8780e5b2340e02e65bad7e6ef2827fffc091 | Ruby | lllisteu/headlamp | /test/tests/test_canvas_base.rb | UTF-8 | 1,090 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'test/unit'
require 'headlamp/canvas'
class Test_canvas_base < Test::Unit::TestCase
def test_base
sheet = Headlamp::Canvas.new
assert_equal sheet.height, sheet.width
sheet = Headlamp::Canvas.new 5
assert_equal 25, sheet.to_a.size
assert_equal 5, sheet.width
assert_equal 5, sheet.height
sheet = Headlamp::Canvas.new 10, 20
assert_equal 200, sheet.to_a.size
assert_equal 10, sheet.width
assert_equal 20, sheet.height
end
def test_init_with_object
d = Headlamp::Dev::Generic.new
d.config.merge!( { :width => 3, :height => 6 } )
sheet = Headlamp::Canvas.new d
assert_equal 18, sheet.to_a.size
assert_equal 3, sheet.width
assert_equal 6, sheet.height
end
def test_each
sheet = Headlamp::Canvas.new 15
sheet.each { |p| p.rr = 256 }
sheet.each_with_index do |p,i|
assert_equal 256, p.rr
end
sheet.each_with_index { |p,i| p.b = i }
sheet.each_with_coordinates { |p,r,c| p.r = r; p.g = c }
sheet.each do |p|
assert_equal p.b, p.r * 15 + p.g
end
end
end
| true |
c4f467805aa31380130e08fed4636a5480372200 | Ruby | victornava/ruby-list | /spec/list/intersection_spec.rb | UTF-8 | 1,418 | 3.28125 | 3 | [] | no_license | require 'spec_helper'
describe "#&" do
it "creates a list with elements common to both arrays (intersection)" do
(List[] & List[]).should == List[]
(List[1, 2] & List[]).should == List[]
(List[] & List[1, 2]).should == List[]
(List[ 1, 3, 5 ] & List[ 1, 2, 3 ]).should == List[1, 3]
end
it "creates a list with no duplicates" do
(List[ 1, 1, 3, 5 ] & List[ 1, 2, 3 ]).should == List[1, 3]
end
it "creates a list with elements in order they are first encountered" do
(List[ 1, 2, 3, 2, 5 ] & List[ 5, 2, 3, 4 ]).should == List[2, 3, 5]
end
it "does not modify the original list" do
l = List[1, 1, 3, 5]
l & List[1, 2, 3]
l.should == List[1, 1, 3, 5]
end
it "determines equivalence between elements in the sense of eql?" do
(List[5.0, 4.0] & List[5, 4]).should == List[]
(List["x"] & List["x"]).should == List["x"]
end
it "does not return subclass instances for List subclasses" do
(ListSubclass[1, 2, 3] & List[]).should be_an_instance_of(List)
(ListSubclass[1, 2, 3] & ListSubclass[1, 2, 3]).should be_an_instance_of(List)
(List[] & ListSubclass[1, 2, 3]).should be_an_instance_of(List)
end
it "does not call to_ary on array subclasses" do
(List[5, 6] & ListSubclass[1, 2, 5, 6]).should == List[5, 6]
end
it "raises TypeError if other is not a List" do
lambda { List[] & "" }.should raise_error(TypeError)
end
end
| true |
19fa6930cab02854121554fbd0c61ad5fd126677 | Ruby | arttracks/nazi_hunter | /lib/nazi_hunter/nazi_detector.rb | UTF-8 | 5,580 | 2.75 | 3 | [
"MIT"
] | permissive | require_relative "nazi_tests.rb"
require "geo_deluge"
require "museum_provenance"
module NaziHunter
class NaziDetector
include NaziHunter::NaziTests
def initialize(opts = {})
@strict = opts.fetch(:strict, false)
geo_deluge_cache = opts.fetch(:geo_deluge_cache, "./caches/fast_cache.json")
@lookup = GeoDeluge::Lookup.new(cache_file: geo_deluge_cache)
end
def analyse_provenance(record)
# initialize some useful variables
provenance_text = record["provenance"]
places = record["places"]
artists = record["actors"].find_all{|a| a["role"] == "creator"}
artist_names = artists.collect{|e| e["name"]}.flatten
artist_nationalities = artists.collect{|e| e["nationality"]}.flatten
per_test_options = {places: places}
scanned_periods = []
# Handle blank provenance
if provenance_text.nil?
return {
status: NaziTests::PROBLEMATIC,
message: "No recorded provenance",
periods: []
}
end
# Handle unreadable or unbparsable provenance
begin
provenance_events = MuseumProvenance::Provenance.extract(provenance_text)
rescue
return {
status: NaziTests::PROBLEMATIC,
message: "The provenance text was unreadable.",
periods: []
}
end
# If strict mode is disabled,
# handle American works with no mention of Europe
artist_is_american = (artist_nationalities.count == 1 && artist_nationalities.first == "American")
if !@strict && artist_is_american && provenance_is_american(provenance_events, places)
return {
status: NaziTests::SAFE,
message: "Artist is American, and none of the periods before #{END_OF_NAZI_ERA} mention Europe.",
periods: []
}
end
# Set the current period to the first transaction
current_period = provenance_events.earliest
# Skip the first period if it is the artist
# or the first period includes the word "artist" (unless @strict)
if current_period && artist_names.include?(current_period.party.name)
current_period = current_period.next_period
elsif !@strict && current_period && current_period.to_s.downcase.include?("artist")
current_period = current_period.next_period
end
if !current_period
return {
status: NaziTests::SAFE,
message: "The only recorded provenance is the artist.",
periods: []
}
end
while current_period
# run each of the tests (unless one returns conclusively)
conclusions = []
NaziTests.public_instance_methods.each do |current_test|
result = self.send(current_test, current_period, per_test_options)
conclusions << result
if [NaziTests::PROBLEMATIC,NaziTests::SAFE,NaziTests::SKIP].include? result[0]
break
end
end
# retrieve the result of the last test that was run
final_conclusion = conclusions.last
# structure the resulting data and save it
period_results = {
period_text: current_period.to_s,
status: final_conclusion[0],
message: final_conclusion[1]
}
scanned_periods << period_results
# move on to the next period if we haven't been able to determine
# the final status of the provenance
if [NaziTests::SKIP, NaziTests::INCONCLUSIVE].include? period_results[:status]
current_period = current_period.next_period
else
current_period = nil
end
end
begin
return {
status: scanned_periods.last[:status],
message: scanned_periods.last[:message],
periods: scanned_periods
}
rescue => e
puts e
puts scanned_periods.inspect
puts record
exit
end
end
############################################################################
def provenance_is_american(provenance_events, places)
work_is_american = false
current_period = provenance_events.earliest
while current_period
if (current_period.earliest_possible &&
current_period.earliest_possible > END_OF_NAZI_ERA) ||
current_period.next_period.nil?
while current_period
country = get_country(current_period,places)
break if EUROPEAN_COUNTRIES.include?(country)
current_period = current_period.previous_period
end
work_is_american = true
break
else
current_period = current_period.next_period
end
end
return work_is_american
end
############################################################################
def get_country(period, places)
return nil if period.location.nil? || places.nil?
loc = places.find{|p| p.keys.first == period.location.name}
return nil if loc.nil?
uri = loc.values.first
id = @lookup.mapzen_id(uri)
@lookup.get_country(id)
end
############################################################################
def output_text(record, show_provenance = false)
return nil if record.nil?
str = "#{record["accession_number"].to_s.ljust(10)} - #{record["title"]}\n"
str += "-----------\n#{record["provenance"]}\n\n" if show_provenance
str
end
end
end | true |
6785ec7c4d4d4147cb498d05fc7a69257db42f69 | Ruby | dry-rb/dry-configurable | /lib/dry/configurable/setting.rb | UTF-8 | 1,907 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
require "set"
module Dry
module Configurable
# A defined setting.
#
# @api public
class Setting
include Dry::Equalizer(:name, :default, :constructor, :children, :options, inspect: false)
OPTIONS = %i[default reader constructor mutable cloneable settings config_class].freeze
DEFAULT_CONSTRUCTOR = -> v { v }.freeze
MUTABLE_VALUE_TYPES = [Array, Hash, Set, Config].freeze
# @api public
attr_reader :name
# @api public
attr_reader :default
# @api public
attr_reader :mutable
# @api public
attr_reader :constructor
# @api public
attr_reader :children
# @api public
attr_reader :options
# @api private
def self.mutable_value?(value)
MUTABLE_VALUE_TYPES.any? { |type| value.is_a?(type) }
end
# @api private
def initialize(
name,
default:,
constructor: DEFAULT_CONSTRUCTOR,
children: EMPTY_ARRAY,
**options
)
@name = name
@default = default
@mutable = children.any? || options.fetch(:mutable) {
# Allow `cloneable` as an option alias for `mutable`
options.fetch(:cloneable) { Setting.mutable_value?(default) }
}
@constructor = constructor
@children = children
@options = options
end
# @api private
def reader?
options[:reader].equal?(true)
end
# @api public
def mutable?
mutable
end
alias_method :cloneable?, :mutable?
# @api private
def to_value
if children.any?
(options[:config_class] || Config).new(children)
else
value = default
value = constructor.(value) unless value.eql?(Undefined)
mutable? ? value.dup : value
end
end
end
end
end
| true |
736d5e5796e5ad62b82e9f8327689284ad702391 | Ruby | ruckc/gocd | /tools/jruby/lib/ruby/gems/1.8/gems/rubygems-update-1.3.5/test/test_gem_validator.rb | UTF-8 | 1,624 | 2.5625 | 3 | [
"Apache-2.0",
"LGPL-2.1-only",
"CPL-1.0",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"Ruby",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain"
] | permissive | #--
# Copyright 2006 by Chad Fowler, Rich Kilmer, Jim Weirich and others.
# All rights reserved.
# See LICENSE.txt for permissions.
#++
require File.join(File.expand_path(File.dirname(__FILE__)), 'gemutilities')
require File.join(File.expand_path(File.dirname(__FILE__)), 'simple_gem')
require 'rubygems/validator'
class TestGemValidator < RubyGemTestCase
def setup
super
@simple_gem = SIMPLE_GEM
@validator = Gem::Validator.new
end
def test_verify_gem_file
gem_file = File.join @tempdir, 'simple_gem.gem'
File.open gem_file, 'wb' do |fp| fp.write @simple_gem end
assert_equal nil, @validator.verify_gem_file(gem_file)
end
def test_verify_gem_file_empty
e = assert_raises Gem::VerificationError do
@validator.verify_gem_file ''
end
assert_equal 'missing gem file ', e.message
end
def test_verify_gem_file_nonexistent
file = '/nonexistent/nonexistent.gem'
e = assert_raises Gem::VerificationError do
@validator.verify_gem_file file
end
assert_equal "missing gem file #{file}", e.message
end
def test_verify_gem
assert_equal nil, @validator.verify_gem(@simple_gem)
end
def test_verify_gem_empty
e = assert_raises Gem::VerificationError do
@validator.verify_gem ''
end
assert_equal 'empty gem file', e.message
end
def test_verify_gem_invalid_checksum
e = assert_raises Gem::VerificationError do
@validator.verify_gem @simple_gem.upcase
end
assert_equal 'invalid checksum for gem file', e.message
end
def test_verify_gem_no_sum
assert_equal nil, @validator.verify_gem('words')
end
end
| true |
67ced385f526f6ddf26ef22a45ab8ce8f002e5b0 | Ruby | helloklow/model-class-methods-lab-online-web-pt-011419 | /app/models/boat.rb | UTF-8 | 2,023 | 2.8125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Boat < ActiveRecord::Base
belongs_to :captain
has_many :boat_classifications
has_many :classifications, through: :boat_classifications
def self.first_five
# return 5 boats by limiting results to this number only
all.limit(5)
end
def self.dinghy
# find and return boats less than 20 ft
where("length < 20")
end
def self.ship
# find and return all boats 20 ft or longer
where("length >= 20")
end
def self.last_three_alphabetically
# return last 3 boats alphabetically by organizing all boats
# by name, in descending order, and limiting results to only 3
all.order(name: :desc).limit(3)
end
def self.without_a_captain
# find and return all boats with no captain associated to them
where(captain_id: nil)
end
def self.sailboats
# return all sailboats by ensuring a classification is included
# and then finding only the boats of the specified classification
includes(:classifications).where(classifications: { name: 'Sailboat' })
end
def self.with_three_classifications
# This is really complex! It's not common to write code like this
# regularly. Just know that we can get this out of the database in
# milliseconds whereas it would take whole seconds for Ruby to do the same.
#
# return all boats that have 3 classifications by joining all classifications
# and then grouping records based on boat id, allowing for counting the
# number of classifications associated with each boat
joins(:classifications).group("boats.id").having("COUNT(*) = 3").select("boats.*")
end
def self.non_sailboats
# return all non-sailboats by finding boats that do not have a classification
# id that matches the classification id for sailboats
where("id NOT IN (?)", self.sailboats.pluck(:id))
end
def self.longest
# return longest boat by organizing all boats by length in descending order
# and limiting results to the first only
order('length DESC').first
end
end
| true |
7f298b1175bfc735d787df2518d3b6a4a3665f7c | Ruby | TylerNHansen/TicTacToe | /tictactoe.rb | UTF-8 | 1,176 | 3.921875 | 4 | [] | no_license | require './board.rb'
require './supercomputerplayer.rb'
require './humanplayer.rb'
class TicTacToe
class IllegalMoveError < RuntimeError
end
attr_reader :board, :players, :turn
def initialize(player1, player2)
@board = Board.new
@players = { x: player1, o: player2 }
@turn = :x
end
def run
play_turn until self.board.over?
if self.board.won?
winning_player = self.players[self.board.winner]
puts "#{winning_player.name} won the game!"
else
puts 'No one wins!'
end
end
def show
# not very pretty printing!
self.board.rows.each { |row| p row }
end
private
def place_mark(pos, mark)
if self.board.empty?(pos)
self.board[pos] = mark
true
else
false
end
end
def play_turn
loop do
current_player = self.players[self.turn]
pos = current_player.move(self, self.turn)
break if place_mark(pos, self.turn)
end
# swap next whose turn it will be next
@turn = ((self.turn == :x) ? :o : :x)
end
end
if __FILE__ == $PROGRAM_NAME
hp = HumanPlayer.new('Evan')
cp = SuperComputerPlayer.new('SKYNET')
TicTacToe.new(hp, cp).run
end
| true |
84d20ec55efa17c6fda4542c5fb2d1d4f32d5abf | Ruby | cos404/Petsonic | /lib/parser.rb | UTF-8 | 961 | 2.875 | 3 | [] | no_license | require 'curb'
require 'nokogiri'
require 'colorize'
require_relative 'items_parser'
# The main module responsible for starting parsing categories and items
module Parser
def self.start
puts 'Parse category'.light_green
html = Nokogiri::HTML(Curl.get(CATEGORY).body_str)
id_category = get_category_id(html)
items_count = get_items_count(html)
full_category = "#{CATEGORY}?id_category=#{id_category}&n=#{items_count}"
html = Nokogiri::HTML(Curl.get(full_category).body_str)
items_links = get_items_links(html)
ItemsParser.start(items_links)
end
private_class_method def self.get_category_id(html)
html.xpath("//form//input[@name='id_category']/@value")
end
private_class_method def self.get_items_count(html)
html.xpath("//form//input[@name='n']/@value")
end
private_class_method def self.get_items_links(html)
html.xpath("//a[@class='product_img_link product-list-category-img']/@href")
end
end
| true |
d9ce2c2fda54abc9dda600c3d584597456c23bdf | Ruby | EdwardAcosta/my_fave_rests2 | /next_rails/record_store/record.rb | UTF-8 | 125 | 2.859375 | 3 | [] | no_license | class Record
attr_reader :name , :artist
def initialize(name, artist)
@name = name
@artist = artist
end
end | true |
e71f231ae4a9d2dd7c04cc67814bdc595f8ee73a | Ruby | jdan/adventofcode | /2015/rb/2015/05a-nice-strings.rb | UTF-8 | 215 | 2.984375 | 3 | [] | no_license | # http://adventofcode.com/day/5
total = 0
ARGF.each do |line|
next if line =~ /(ab|cd|pq|xy)/
if line.scan(/[aeiou]/).size >= 3 and line =~ /(.)\1/
total += 1
end
end
puts total
| true |
f1e2985f036f6a9bd8952304ee78bc696f9b8d71 | Ruby | youbin/BookStand | /app/models/common_methods.rb | UTF-8 | 1,077 | 3 | 3 | [] | no_license | class CommonMethods
def self.makeHash(*args)
args_size = args.size
if args_size % 2 != 0
return false
end
result = Hash.new
i = 0
while i < args_size
result[args[i]] = args[i+1]
i = i + 2
end
p result
return result
end
def self.makeParArgs(*args)
args_size = args.size
if args_size % 2 != 0
return false
end
result = Array.new
i = 0
j = 0
while i < args_size
if args[i+1] != nil
result[j] = args[i]
result[j+1] = args[i+1]
j = j + 2
end
i = i + 2
end
return result
end
def self.makeArgs(params, *args)
args_size = args.size
result = Array.new
i = 0
while i < args_size
result << args[i]
result << params[args[i]]
i = i + 1
end
return result
end
def timestamp_to_year_month_day(timestamp)
return CommonMethods.timestamp_to_year_month_day(timestamp)
end
def self.timestamp_to_year_month_day(timestamp)
return Time.at(timestamp.to_i).strftime("%Y%m%d")
end
end
| true |
19bf441be88e8b2d6e702a3f6f065681e2bba4c2 | Ruby | lfv89/play-parser | /lib/playparser/services/file_parser.rb | UTF-8 | 347 | 2.953125 | 3 | [] | no_license | class FileParser
attr_reader :content
class << self
attr_accessor :dependence, :dependence_method
end
def initialize(file)
@file = file
@dependence = self.class.dependence
@dependence_method = self.class.dependence_method
end
def content
@content ||= @dependence.method(@dependence_method).call(@file)
end
end
| true |
f6f76ec946f97589b912e2f9fde739290c00bb97 | Ruby | mivok/md2evernote | /kramdown_evernote_html.rb | UTF-8 | 2,507 | 2.78125 | 3 | [] | no_license | require 'kramdown/converter/html'
module Kramdown
module Converter
class EvernoteHtml < Html
# Code block style that evernote generates
CODEBLOCK_STYLE = "box-sizing: border-box; padding: 8px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: rgb(51, 51, 51); border-top-left-radius: 4px; border-top-right-radius: 4px; border-bottom-right-radius: 4px; border-bottom-left-radius: 4px; background-color: rgb(251, 250, 248); border: 1px solid rgba(0, 0, 0, 0.14902); background-position: initial initial; background-repeat: initial initial;-en-codeblock:true;"
def convert_p(el, indent)
# Output paragraphs as <divs>
# The evernote mac client uses them for exported notes
if el.options[:transparent]
inner(el, indent)
else
format_as_block_html(:div, el.attr, inner(el, indent), indent)
end
end
def convert_text(el, indent)
# Evernote will run text together withoutspaces if you don't convert
# newlines.
escape_html(el.value.gsub(/\n/, ' '))
end
def convert_codeblock(el, indent)
# Outputs codeblocks using evernote's custom style for code blocks.
# We don't need any special processing kramdown provides in the
# original method such as highlighting or showing spaces, so that can
# be left out here.
result = escape_html(el.value)
result.chomp!
result.gsub!("\n", "</div><div>")
# Evernote encodes multiple spaces as alternating nbsp and normal
# spaces, and doesn't escape them.
result.gsub!(" ", "\u00a0 ")
result.gsub!(" ", " \u00a0") # deal with odd numbers of spaces
"#{' '*indent}<div style=\"#{CODEBLOCK_STYLE}\"><div>#{result}</div></div>\n"
end
def convert_header(el, indent)
# Convert headers to bold text
# Evernote uses divs and spans with style for bold text
"#{' ' * indent}<div><span style=\"font-weight: bold;\">#{inner(el, indent)}</span></div>"
end
def convert_codespan(el, indent)
# Code spans aren't really supported in evernote, so just remove them
escape_html(el.value)
end
def convert_blank(el, indent)
# This preserves blank lines in the markdown input in the final
# evernote note. If things look too spaced out, then remove this
# method.
"<div><br/></div>\n"
end
end
end
end
| true |
331b56e57755582706ea822e2599fdec8866de32 | Ruby | Monte-Amador/rb101-foundations | /lesson_4/2_collections_basics/pedac_test.rb | UTF-8 | 388 | 3.265625 | 3 | [] | no_license | str = "lulucha"
result = []
substring = str.chars
# if substring.length > 2
# loop do
# base = 0
# counter = 1
# letter_set = substring[base]+ substring[counter]
# result.push(letter_set) if letter_set == letter_set.reverse
# base += 1
# break if base == substring.length
# end
# p "Here: #{result}"
# end
while substring.length > 2
puts "this works"
end | true |
9e85492e583616f28159f902547372b6db313301 | Ruby | VikiAnn/cms_practice | /test/models/page_test.rb | UTF-8 | 1,637 | 2.859375 | 3 | [] | no_license | require './test/test_helper'
class PageTest < Minitest::Test
def test_it_stores_a_page
page_data = {:slug => "about-us",
:content => "Our site is great!"}
returned_page = Page.create( page_data )
found_page = Page.find_by_slug( page_data[:slug] )
assert_equal returned_page, found_page
assert_equal page_data[:slug], found_page.slug
assert_equal page_data[:content], found_page.content
end
def test_it_can_find_all_pages
page_data_1 = {:slug => "location",
:content => "We're located in Denver, CO!"}
page_data_2 = {:slug => "contact",
:content => "Call us at 111-222-3333"}
returned_page_1 = Page.create(page_data_1)
returned_page_2 = Page.create(page_data_2)
assert_includes Page.all, returned_page_1
assert_includes Page.all, returned_page_2
end
def test_it_can_delete_a_page
page_data_1 = {:slug => "location",
:content => "We're located in Denver, CO!"}
page_data_2 = {:slug => "contact",
:content => "Call us at 111-222-3333"}
returned_page_1 = Page.create(page_data_1)
returned_page_2 = Page.create(page_data_2)
Page.delete(page_data_2[:slug])
refute_includes Page.all, returned_page_2
end
def test_it_can_edit_a_page
page_data_1 = {:slug => "location",
:content => "We're located in Denver, CO!"}
Page.create(page_data_1)
new_data = {slug: "new location",
content: "We moved, yo"}
new_page = Page.update(page_data_1[:slug], new_data)
assert_includes Page.all, new_page
end
end
| true |
8d372bbaf660f90725cdf2ee3e3c5fb062bd1bd6 | Ruby | michaeld55/week3_day3_music_collection_lab | /models/album.rb | UTF-8 | 1,422 | 3.03125 | 3 | [] | no_license | class Album
attr_accessor :id, :title, :genre
attr_reader :artist_id
require_relative('../db/sql_runner.rb')
def initialize(options)
@id = options['id'].to_i if options['id']
@title = options['title']
@genre = options['genre']
@artist_id = options['artist_id'].to_i
end
def save
sql = "INSERT INTO albums(
title, genre, artist_id
) values (
$1, $2, $3
) RETURNING id"
values = [@title, @genre, @artist_id]
@id = SqlRunner.run(sql, values)[0]['id'].to_i
end
def find_artist
sql = "SELECT * FROM artists WHERE id = $1"
values = [@id]
artists = SqlRunner.run(sql, values)
return artists.map { |artist| Artist.new(artist)}
end
def update
sql = "UPDATE albums SET (title, genre, artist_id) = ($1, $2, $3) WHERE id = $4"
values = [@title, @genre, @artist_id, @id]
SqlRunner.run(sql, values)
end
def delete
sql = "DELETE FROM albums WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.delete_all
sql = "DELETE FROM albums"
SqlRunner.run(sql)
end
def self.find_all
sql = "SELECT * FROM albums"
results = SqlRunner.run(sql)
return results.map { |result| Album.new(result)}
end
def self.find_by_id(id)
sql = "SELECT * FROM albums WHERE id = $1"
values = [id]
result = SqlRunner.run(sql, values).first
return Album.new(result)
end
end
| true |
376a5a22792348bc29206c62c061a6f2fa64925a | Ruby | 223yu/cloud9_ruby | /ruby/lesson7-1.rb | UTF-8 | 158 | 3.359375 | 3 | [] | no_license | puts '2つの値を入力してください'
nam1 = gets.to_i
nam2 = gets.to_i
calc = nam1 * nam2
puts "計算結果を出力します"
puts "a*b= #{calc}" | true |
6692820ef113c8432655b9bd1f2faea2012d3aeb | Ruby | mpkato/clusty | /app/models/project.rb | UTF-8 | 1,559 | 2.59375 | 3 | [] | no_license | require 'csv'
class Project < ActiveRecord::Base
belongs_to :user
has_many :elements, dependent: :destroy
has_many :clusters, dependent: :destroy
attr_accessor :element_file
validates :label, presence: true
validates :element_file, presence: true, on: :create
def read_tsv
CSV.foreach(self.element_file.tempfile, :col_sep => "\t") do |row|
yield row
end
end
def save_with_elements
begin
Project.transaction do
self.save!
self.load_elements!
end
rescue Exception => e
return false
else
return true
end
end
def load_elements!
begin
raise Exception.new("Project ID is empty") if self.id.nil?
Element.transaction do
read_tsv do |row|
if row.size != 2
errors.add(:element_file, "should include exactly two columns")
raise Exception.new("Failed to load elements")
end
element = Element.new_from_row(row)
element.project_id = self.id
element.save!
end
end
rescue => e
errors.add(:element_file, "#{e}")
raise Exception.new("Failed to load elements: #{e}")
end
end
def to_tsv
result = ''
elements = self.elements.includes(:clusters)
elements.each do |elem|
cluster_ids = elem.clusters.pluck(:id)
cluster_names = elem.clusters.pluck(:name)
result += [self.id, self.label, elem.key, elem.body,
cluster_ids.join(','), cluster_names.join(',')].join("\t") + "\n"
end
return result
end
end
| true |
2983f3a6ee4f12df510578f7f03a7eb916ad0a00 | Ruby | EOSullivanBerlin/Internet---101 | /app.rb | UTF-8 | 202 | 2.59375 | 3 | [] | no_license | require 'sinatra'
get '/random-cat' do
@name =["Amigo", "Oscar", "Viking"].sample
erb(:index)
end
get '/named-cat' do
p params
@name = params[:name]
erb(:index)
end
get '/2' do
'Frog'
end
| true |
d6383170019deee4d0d10e0732c8a8e60ae768aa | Ruby | AaronC81/interphase | /lib/interphase/widgets/layout.rb | UTF-8 | 1,278 | 2.78125 | 3 | [] | no_license | # frozen_string_literal: true
require 'gtk2'
module Interphase
# A high-level widget which is described using a layout description string,
# abbreviated to LDS. The LDS specifies a grid in which there are a fixed
# number of widgets occupying a fixed space.
class Layout < Grid
attr_reader :lds, :description
# Create a new layout.
# +lds+:: The LDS to create the grid from.
def initialize(lds, **options, &block)
@lds = lds
parser = Helpers::LayoutParser.new(lds)
@description = parser.parse
@set_slot_names = []
super(parser.rows, parser.columns, **options, &block)
end
# Set the widget contained within a slot. This may only be done once per
# slot.
# +slot+:: The name of the slot.
# +widget+:: The widget to put in the slot.
def []=(name, widget)
raise "Already set a widget for slot named #{name}" \
if @set_slot_names.include? name
raise "No slot named #{name}" unless @description.widgets.include? name
@set_slot_names << name
slot_description = @description.widgets[name]
add(
widget,
slot_description.left,
slot_description.right,
slot_description.top,
slot_description.bottom
)
end
end
end
| true |
4f86bac17d439d9190d1887c0047a795dda214e2 | Ruby | adkadziadka/evaluation-tool | /app/models/batch.rb | UTF-8 | 1,526 | 2.984375 | 3 | [] | no_license | class Batch < ApplicationRecord
has_many :performances, through: :students
has_many :students, dependent: :destroy
validates :number, presence: true
def percentages
rates = []
students.each do |student|
student.performances.each do |performance|
rates << performance.rate
end
end
{
green: (rates.count(3) * 100) / rates.size ,
yellow: (rates.count(2) * 100) / rates.size,
red: (rates.count(1) * 100) / rates.size
}
end
#algorithm
# def get_student
# students = []
# loop do
# rate = [1, 2, 3].sample
# students = Student.joins(:performances).where(batch_id: id, 'performances.rate' => rate)
# break if !students.empty?
# end
# students.sample
# end
# another:
# def get_student
# students_array = []
# loop do
# rate = [1, 2, 3].sample
# students.each do |student|
# student.performances.each do |performance|
# students_array << student.performances == rate
# end
# end
# break if !students_array.empty?
# end
# students_array.sample
# end
# # best choice:
def get_student
students_array = []
students.each do |student|
student.performances.each do |performance|
students_array += [student] if performance.rate == 3
students_array += [student, student] if performance.rate == 2
students_array += [student, student, student] if performance.rate == 1
end
end
students_array.sample
end
def self.search(search)
if search
where(:start_date => search)
else
Batch.all
end
end
end
| true |
10c407f2b1e6149104643083e5ad5621b4b55993 | Ruby | halcyon/hpt | /hpt.rb | UTF-8 | 2,189 | 2.671875 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'optparse'
require 'rubygems'
require 'xmlsimple'
options = {}
optparse = OptionParser.new do|opts|
opts.banner = "Usage: ./hpt.rb [options]"
# Define the options, and what they do
options[:polling] = nil
opts.on( '-p', '--[no-]polling', 'Enable or Disable SCM Polling' ) do|p|
options[:polling] = p
end
options[:node] = nil
opts.on( '-n', '--node=val', String, 'Assign node' ) do|n|
options[:node] = n
end
# This displays the help screen, all programs are
# assumed to have this option.
opts.on( '-h', '--help', 'Display this screen' ) do
puts opts
exit
end
end
def assignNode(filename,node)
config = XmlSimple.xml_in(filename,'KeepRoot'=>true)
root=config.keys[0];
config[root][0]['assignedNode']=[node]
output = XmlSimple.xml_out(config,'KeepRoot'=>true, 'OutputFile'=>filename, 'XmlDeclaration'=>"<?xml version='1.0' encoding='UTF-8'?>")
end
def enablePolling(filename)
config = XmlSimple.xml_in(filename,'KeepRoot'=>true)
root=config.keys[0];
config[root][0]['triggers']=[{"class"=>"vector", "hudson.triggers.SCMTrigger"=>[{"spec"=>["* * * * *"]}]}]
output = XmlSimple.xml_out(config,'KeepRoot'=>true, 'OutputFile'=>filename, 'XmlDeclaration'=>"<?xml version='1.0' encoding='UTF-8'?>")
end
def disablePolling(filename)
config = XmlSimple.xml_in(filename,'KeepRoot'=>true)
root=config[0];
config[root][0]['triggers']=[{"class"=>"vector"}]
output = XmlSimple.xml_out(config,'KeepRoot'=>true, 'OutputFile'=>filename, 'XmlDeclaration'=>"<?xml version='1.0' encoding='UTF-8'?>")
end
begin
optparse.parse! ARGV
raise OptionParser::MissingArgument if options[:polling].nil?
#raise OptionParser::MissingArgument if options.empty?
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts optparse
exit 1
end
if options[:node]
puts "Assigning node: " + options[:node]
Dir['.hudson/jobs/*/config.xml'].each { |f| assignNode(f,options[:node]) }
end
if options[:polling]
puts "Polling"
Dir['.hudson/jobs/*/config.xml'].each { |f| enablePolling f }
else
puts "Not Polling"
Dir['.hudson/jobs/*/config.xml'].each { |f| disablePolling f }
end
| true |
1db5e741a1a1ee58e21ef60603d7cb8a3a528596 | Ruby | mxenabled/atrium-ruby | /lib/atrium-ruby/api/users_api.rb | UTF-8 | 14,167 | 2.65625 | 3 | [
"MIT"
] | permissive | =begin
#MX API
#The MX Atrium API supports over 48,000 data connections to thousands of financial institutions. It provides secure access to your users' accounts and transactions with industry-leading cleansing, categorization, and classification. Atrium is designed according to resource-oriented REST architecture and responds with JSON bodies and HTTP response codes. Use Atrium's development environment, vestibule.mx.com, to quickly get up and running. The development environment limits are 100 users, 25 members per user, and access to the top 15 institutions. Contact MX to purchase production access.
=end
require 'uri'
module Atrium
class UsersApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Create user
# Call this endpoint to create a new user. Atrium will respond with the newly-created user object if successful. This endpoint accepts several parameters: identifier, metadata, and is_disabled.<br> Disabling a user means that accounts and transactions associated with it will not be updated in the background by MX. It will also restrict access to that user's data until they are no longer disabled. Users who are disabled for the entirety of an Atrium billing period will not be factored into that month's bill.
# @param body User object to be created with optional parameters (identifier, is_disabled, metadata)
# @param [Hash] opts the optional parameters
# @return [UserResponseBody]
def create_user(body, opts = {})
data, _status_code, _headers = create_user_with_http_info(body, opts)
data
end
# Delete user
# Calling this endpoint will permanently delete a user from Atrium. If successful, the API will respond with Status: 204 No Content.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @return [nil]
def delete_user(user_guid, opts = {})
delete_user_with_http_info(user_guid, opts)
nil
end
# List users
# Use this endpoint to list every user you've created in Atrium.
# @param [Hash] opts the optional parameters
# @option opts [Integer] :page Specify current page.
# @option opts [Integer] :records_per_page Specify records per page.
# @return [UsersResponseBody]
def list_users(opts = {})
data, _status_code, _headers = list_users_with_http_info(opts)
data
end
# Read user
# Use this endpoint to read the attributes of a specific user.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @return [UserResponseBody]
def read_user(user_guid, opts = {})
data, _status_code, _headers = read_user_with_http_info(user_guid, opts)
data
end
# Update user
# Use this endpoint to update the attributes of a specific user. Atrium will respond with the updated user object.<br> Disabling a user means that accounts and transactions associated with it will not be updated in the background by MX. It will also restrict access to that user's data until they are no longer disabled. Users who are disabled for the entirety of an Atrium billing period will not be factored into that month's bill.<br> To disable a user, update it and set the is_disabled parameter to true. Set it to false to re-enable the user.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @option opts [UserUpdateRequestBody] :body User object to be updated with optional parameters (identifier, is_disabled, metadata)
# @return [UserResponseBody]
def update_user(user_guid, opts = {})
data, _status_code, _headers = update_user_with_http_info(user_guid, opts)
data
end
private
# Create user
# Call this endpoint to create a new user. Atrium will respond with the newly-created user object if successful. This endpoint accepts several parameters: identifier, metadata, and is_disabled.<br> Disabling a user means that accounts and transactions associated with it will not be updated in the background by MX. It will also restrict access to that user's data until they are no longer disabled. Users who are disabled for the entirety of an Atrium billing period will not be factored into that month's bill.
# @param body User object to be created with optional parameters (identifier, is_disabled, metadata)
# @param [Hash] opts the optional parameters
# @return [Array<(UserResponseBody, Fixnum, Hash)>] UserResponseBody data, response status code and response headers
def create_user_with_http_info(body, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersApi.create_user ...'
end
# verify the required parameter 'body' is set
if @api_client.config.client_side_validation && body.nil?
fail ArgumentError, "Missing the required parameter 'body' when calling UsersApi.create_user"
end
# resource path
local_var_path = '/users'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.mx.atrium.v1+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(body)
auth_names = ['apiKey', 'clientID']
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'UserResponseBody')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersApi#create_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Delete user
# Calling this endpoint will permanently delete a user from Atrium. If successful, the API will respond with Status: 204 No Content.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers
def delete_user_with_http_info(user_guid, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersApi.delete_user ...'
end
# verify the required parameter 'user_guid' is set
if @api_client.config.client_side_validation && user_guid.nil?
fail ArgumentError, "Missing the required parameter 'user_guid' when calling UsersApi.delete_user"
end
# resource path
local_var_path = '/users/{user_guid}'.sub('{' + 'user_guid' + '}', user_guid.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.mx.atrium.v1+json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['apiKey', 'clientID']
data, status_code, headers = @api_client.call_api(:DELETE, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersApi#delete_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# List users
# Use this endpoint to list every user you've created in Atrium.
# @param [Hash] opts the optional parameters
# @option opts [Integer] :page Specify current page.
# @option opts [Integer] :records_per_page Specify records per page.
# @return [Array<(UsersResponseBody, Fixnum, Hash)>] UsersResponseBody data, response status code and response headers
def list_users_with_http_info(opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersApi.list_users ...'
end
# resource path
local_var_path = '/users'
# query parameters
query_params = {}
query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?
query_params[:'records_per_page'] = opts[:'records_per_page'] if !opts[:'records_per_page'].nil?
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.mx.atrium.v1+json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['apiKey', 'clientID']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'UsersResponseBody')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersApi#list_users\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Read user
# Use this endpoint to read the attributes of a specific user.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @return [Array<(UserResponseBody, Fixnum, Hash)>] UserResponseBody data, response status code and response headers
def read_user_with_http_info(user_guid, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersApi.read_user ...'
end
# verify the required parameter 'user_guid' is set
if @api_client.config.client_side_validation && user_guid.nil?
fail ArgumentError, "Missing the required parameter 'user_guid' when calling UsersApi.read_user"
end
# resource path
local_var_path = '/users/{user_guid}'.sub('{' + 'user_guid' + '}', user_guid.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.mx.atrium.v1+json'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
auth_names = ['apiKey', 'clientID']
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'UserResponseBody')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersApi#read_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
# Update user
# Use this endpoint to update the attributes of a specific user. Atrium will respond with the updated user object.<br> Disabling a user means that accounts and transactions associated with it will not be updated in the background by MX. It will also restrict access to that user's data until they are no longer disabled. Users who are disabled for the entirety of an Atrium billing period will not be factored into that month's bill.<br> To disable a user, update it and set the is_disabled parameter to true. Set it to false to re-enable the user.
# @param user_guid The unique identifier for a `user`.
# @param [Hash] opts the optional parameters
# @option opts [UserUpdateRequestBody] :body User object to be updated with optional parameters (identifier, is_disabled, metadata)
# @return [Array<(UserResponseBody, Fixnum, Hash)>] UserResponseBody data, response status code and response headers
def update_user_with_http_info(user_guid, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: UsersApi.update_user ...'
end
# verify the required parameter 'user_guid' is set
if @api_client.config.client_side_validation && user_guid.nil?
fail ArgumentError, "Missing the required parameter 'user_guid' when calling UsersApi.update_user"
end
# resource path
local_var_path = '/users/{user_guid}'.sub('{' + 'user_guid' + '}', user_guid.to_s)
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/vnd.mx.atrium.v1+json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(opts[:'body'])
auth_names = ['apiKey', 'clientID']
data, status_code, headers = @api_client.call_api(:PUT, local_var_path,
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => 'UserResponseBody')
if @api_client.config.debugging
@api_client.config.logger.debug "API called: UsersApi#update_user\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
return data, status_code, headers
end
end
end
| true |
186c1d4481a0283830da8385f43f306781559936 | Ruby | NadaMarawan/Opportutoring | /app/controllers/students_controller.rb | UTF-8 | 2,140 | 2.609375 | 3 | [] | no_license | class StudentsController < ApplicationController
def show
# disallow a student to view a non-existing student's profile
begin
@student = Student.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to root_url
return
end
end
def index
@students = Student.all
end
def mytutors
@student = Student.find(params[:id])
end
#This action will render app/views/students/new.html.erb
def new
#initialize but not save an empty student; so that the form we renders knows which fields to use and where to submit
@student = Student.new
end
def create
@student = Student.new(student_params)
if @student.save
session[:student_id] = @student.id
session[:tutor_id] = nil
redirect_to root_url, notice: "Logged in!"
else
# can setup an error message here @student.errors [coming from validations]
render :new
end
end
#This action will render app/views/students/edit.html.erb
def edit
# disallow a student to edit a non-existing student's profile
begin
@student = Student.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to root_url
return
end
# disallow a student to edit another student's profile
if session[:student_id] != @student.id
redirect_to root_url
end
end
def update
@student = Student.find(params[:id])
if @student.update(student_params)
redirect_to action: "show", id: @student.id
else
# can setup an error message here
render :edit
end
end
# helper
private
# require a student object to be in "params" object (= object that contains all parameters being passed into the request)
# also requires (only) specified paramaters to exits in "params" object
# permit some attributes to be used in the returned hash (whitelist), (but not need to have them)
# if checks are passed, returns a hash that is used here to create or update a student object
def student_params
params.require(:student).permit(:name, :password, :password_confirmation, :country, :level, :email, :image)
end
end
| true |
59f42486038c2cb47e1fd0382974a9155f24819b | Ruby | fizvlad/vk-music-rb | /lib/vk_music/playlist.rb | UTF-8 | 1,380 | 2.625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module VkMusic
# Class representing VK playlist
class Playlist
extend Forwardable
include Enumerable
# @return [Integer, nil] playlist ID
attr_reader :id
# @return [Integer, nil] playlist owner ID
attr_reader :owner_id
# @return [String, nil] access hash which should be part of link for some playlists
attr_reader :access_hash
# @return [String] playlist title
attr_reader :title
# @return [String, nil] playlist subtitle. May be empty
attr_reader :subtitle
# @return [Integer, nil] real size of playlist or +nil+ if unknown
attr_reader :real_size
# @return [Array] audios array
attr_reader :audios
# Initialize new playlist
# @param audios [Array] list of audios in playlist
# @param id [Integer, nil]
# @param owner_id [Integer, nil]
# @param access_hash [String, nil]
# @param title [String]
# @param subtitle [String, nil]
# @param real_size [Integer, nil]
def initialize(audios, id: nil, owner_id: nil, access_hash: nil, title: '', subtitle: nil, real_size: nil)
@audios = audios.dup
@id = id
@owner_id = owner_id
@access_hash = access_hash
@title = title.to_s.strip
@subtitle = subtitle
@real_size = real_size
end
def_delegators :@audios, :each, :length, :size, :[], :empty?
end
end
| true |
5766585b7981368dca9cdaf9f8ffdca0405005f0 | Ruby | emanuelbierman/ruby-collaborating-objects-lab-v-000 | /lib/artist.rb | UTF-8 | 1,027 | 3.609375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Artist
attr_accessor :name
@@all = []
def initialize(name)
@name = name
@songs = []
end
def add_song(song)
@songs << song
end
def songs
@songs
end
def self.all
@@all
end
def save
@@all << self
end
def self.find_or_create_by_name(name)
new = Artist.new(name)
already_artist = @@all.select {|artist| artist.name == new.name}
if already_artist[0] != nil
already_artist[0]
elsif already_artist == []
new.save
@@all.last
# new # would also work here
end
end
# this is a very elegant solution:
#
# def self.find_or_create_by_name(name)
# self.find(name) ? self.find(name) : self.create(name)
# end
#
# def self.find(name)
# self.all.find {|artist| artist.name == name }
# end
#
# def self.create(name)
# self.new(name).tap {|artist| artist.save}
# end
#
# def save
# @@all << self
# end
def print_songs
@songs.each {|song| puts song.name}
end
end
| true |
31cab2051bfc9395a4a15f5b53e48620f2392d28 | Ruby | PBillingsby/collections_practice-online-web-pt-100719 | /collections_practice.rb | UTF-8 | 593 | 3.84375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def sort_array_asc(array)
array.sort
end
def sort_array_desc(array)
array.sort.reverse
end
def sort_array_char_count(array)
array.sort {|a,b| a.length <=> b.length}
end
def swap_elements(array)
array[1], array[2] = array[2], array[1]
array
end
def reverse_array(array)
array.reverse
end
def kesha_maker(array)
array.each {|n| n[2] = "$"}
end
def find_a(array)
array.select {|n| n[0] == "a"}
end
def sum_array(array)
array.inject {|sum, num| sum + num}
end
def add_s(array)
array.each_with_index.collect do |word, index|
index == 1 ? word : word + "s"
end
end | true |
ce017e9cf8e69ca87ce84a0cec6487bad0ada150 | Ruby | ooesili/game-server-challenge | /app/controllers/game_controller.rb | UTF-8 | 3,423 | 2.875 | 3 | [] | no_license | class GameController < ApplicationController
def create
# create game and player
game = Game.build
player = game.players.new(nick: params[:nick])
game.creator = player
game.save
# respond with appropriate data
render json: {
game_id: game.uuid,
player_id: player.uuid,
nick: player.nick,
}
end
def join
# try to find game
game = Game.find_by(uuid: params[:game_id])
if not game or game.status != 'Waiting'
# game not found or already started
render status: :not_found, json: {
registered: false,
player_id: nil,
nick: nil,
}
return
end
# game found
player = game.players.create(nick: params[:nick])
render json: {
registered: true,
player_id: player.uuid,
nick: player.nick,
}
end
def start
# try to find game
game = Game.find_by(uuid: params[:game_id])
# make sure the game exists
if not game
render json: {
success: false,
message: 'game not found',
grid: [],
}
return
end
# try to find player
player = game.players.find_by(uuid: params[:player_id])
# make sure the player exists
if not player
render json: {
success: false,
message: 'player not found',
grid: [],
}
return
end
# make sure the creator is trying to start the game
if player != game.creator
render json: {
success: false,
message: 'you are not the creator of the game',
grid: [],
}
return
end
# see if game is already started
if game.status != 'Waiting'
render json: {
success: false,
message: 'game already started',
grid: [],
}
return
end
# success
game.update!(status: 'In Play')
render json: {
success: true,
message: 'all good',
grid: game.board,
}
end
def info
# find game
game = Game.find_by(uuid: params[:game_id])
if not game
render status: :not_found, json: {
message: 'game not found'
}
return
end
# find player
player = game.players.find_by(uuid: params[:player_id])
if not player
render status: :not_found, json: {
message: 'player not found'
}
return
end
# render information
players = game.players
render json: {
game_status: game.status,
current_player: game.current_player.nick,
turn_seq: players.pluck(:nick).rotate(game.turn),
words_done: game.words_done,
scores: players.pluck(:nick, :score).to_h,
grid: game.board,
}
end
def play
# find game
game = Game.find_by(uuid: params[:game_id])
if not game
render status: :not_found, json: {
message: 'game not found'
}
return
end
# find player
player = game.players.find_by(uuid: params[:player_id])
if not player
render status: :not_found, json: {
message: 'player not found'
}
return
end
if game.current_player != player
render json: {
success: false,
score: 0,
}
return
end
# make sure we got a word
word = params[:word]
if word.nil?
score = 0
else
score = game.play!(word)
end
render json: {
success: score > 0,
score: score,
}
end
end
| true |
5441679c223f56a5943a48cc143331dcae1caba2 | Ruby | egorzhdan/diskretka-1st-semester | /Lab3/Task18.rb | UTF-8 | 504 | 3.375 | 3 | [] | no_license | input = File.open('brackets2num.in', 'r')
output = File.open('brackets2num.out', 'w')
b = input.readline.strip
cnt = Array.new(b.size + 5) {Array.new(b.size + 5, 0)}
cnt[0][0] = 1
(1..b.size).each do |len|
(0..b.size).each do |balance|
cnt[len][balance] = cnt[len - 1][balance - 1] + cnt[len - 1][balance + 1]
end
end
ans = 0
balance = 0
(0..b.size - 1).each do |i|
if b[i] == '('
balance += 1
else
ans += cnt[b.size - 1 - i][balance + 1]
balance -= 1
end
end
output.puts ans
| true |
bdd0db527214db6ab3a1bd3aa72c7da2791505be | Ruby | nrolland/information-theory-inference | /lib/image_voodoo_ext.rb | UTF-8 | 2,270 | 2.953125 | 3 | [] | no_license | require 'rubygems'
require 'image_voodoo'
require 'matrix'
require 'matrix_ext'
require 'forwarder'
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
class Pixels
include Enumerable
def initialize(img)
@raster =img.to_java.getRaster()
@widthPix = @raster.getWidth()
@heightPix = @raster.getHeight()
end
def [](i,j)
#p i, j
@raster.getSample(j,i,0)
end
def []=(i,j,val)
@raster.setSample(j,i,0,val)
@raster.setSample(j,i,1,val)
@raster.setSample(j,i,2,val)
end
#add checksize etc
def copy_from(pix)
if pix.class == Array or pix.class == Vector then
i = 0
self.each_slice(@widthPix) do |indexes|
indexes.each do |index|
self[i, index - i*@widthPix] = pix[index]
end
i +=1
end
else if pix.class == Matrix
pix.each do |ij| i,j = ij
self[i,j] = pix[i,j]
end
end
end
end
def each
0.upto(@heightPix-1) do |i|
0.upto(@widthPix-1) do |j|
yield(i*(@widthPix)+j)
end
end
end
def each_rowcol
0.upto(@heightPix-1) do |i|
(0..@widthPix -1).each{ |j| yield(i,j) }
end
end
def each_line
0.upto(@heightPix-1) do
|i| yield(i)
end
end
def lines
a = []
self.each_line { |i| a << 0.upto(@widthPix-1).inject([]){ |arr,j| arr << self[i,j] }}
a
end
def to_a
ar= []
i = 0
self.each_slice(@widthPix) do |indexes|
ar << indexes.map{ |index| self[i, index - i*@widthPix] }
i +=1
end
ar
end
def to_s
self.to_a.to_s
end
def to_vector
Vector[self.to_a.flatten]
end
def to_matrix
matrix.rows[ self.lines ]
end
end
class ImageVoodoo
include Forwarder
def self.from_dim(width, height)
image = ImageVoodoo.new(BufferedImage.new width, height, RGB)
image && block_given? ? yield(image) : image
end
def copy()
ImageVoodoo.new(@src)
end
def pixels
pixels = Pixels.new(self)
block_given? ? pixels.each_rowcol{ |i,j| yield(i,j,pixels)} : pixels
end
def getbwpicture
target = copy.greyscale
target.pixels{ |i,j,p| p[i,j] = p[i,j]> 100 ? 255: 0 }
block_given? ? yield(target) : target
end
end
| true |
e8f2f5f3eff38e8a658cda6a24a861d95dc82da3 | Ruby | anandberylsystems/traning | /ruby_basic/find_position.rb | UTF-8 | 387 | 3.65625 | 4 | [] | no_license | =begin
arr=[10,20,30,40]
for i in 0 .. 3
a=arr[i].to_i
if a==30
pos=i
end
end
puts "position is #{pos}"
=end
arr=Array[]
for i in 0 .. 5
puts"enter the number"
input=gets
input=input.to_i
arr.push(input)
end
puts"enter the number for which searched"
num=gets
num=num.to_i
for i in 0 .. arr.length
a=arr[i].to_i
if a==num
pos=i
end
end
puts"postion is #{pos}" | true |
917d0e53bd2814cc526410c347933cdca4d7e26b | Ruby | blegloannec/CodeProblems | /HackerRank/the_bomberman_game.rb | UTF-8 | 953 | 3.3125 | 3 | [] | no_license | #!/usr/bin/env ruby
# N() = neighborhood, C() = complementary
# 0 initial conf. I
# 1 I
# 2 full O
# 3 C.N(I)
# 4 full O
# 5 C.N(3) = C.N.C.N(I)
# 6 full O
# 7 C.N(5) = C.N.C.N.C.N(I) = C.N(I) = (3)
# (without proof, N.C.N.C.N(X) = N(X),
# or alternatively C.N.C.N(Y) = Y for
# Y = {y such that N(y) is included in N(X)},
# in particular X is included in Y)
# it loops...
require 'set'
def cn(s)
res = Set.new((0...$h).to_a.product((0...$w).to_a))
s.each{|i,j| [[i-1,j],[i+1,j],[i,j],[i,j-1],[i,j+1]].each{|x,y| res.delete([x,y])}}
res
end
def main()
$h,$w,t = gets.split.map(&:to_i)
grid = $h.times.map{gets.chomp}
if t==1
out = grid
elsif t%2==0
out = $h.times.map{'O'*$w}
else
s = Set.new()
$h.times{|i| $w.times{|j| s.add([i,j]) if grid[i][j]=='O'}}
s = cn(t%4==3 ? s : cn(s))
out = $h.times.map{|i| $w.times.map{|j| s.include?([i,j]) ? 'O' : '.'}.join}
end
puts out.join("\n")
end
main()
| true |
81f45b5146d204cd715198d65206fd074e55f7bd | Ruby | simonholroyd/git_team_stats | /bin/git_team_stats | UTF-8 | 5,336 | 2.734375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'json'
require 'progress_bar'
require 'language_sniffer'
require 'gli'
require 'git_team_stats'
include GLI::App
program_desc 'Analyze commits and committers in mulitple git repos and output project-level statistics'
desc "The path to your config file"
flag [:config_path], :default_value => File.join(Dir.pwd,'.git_team_stats.json')
desc "The path to your cache files"
flag [:cache_path], :default_value => File.join(Dir.pwd,'tmp')
desc "The time period to group values by"
flag [:time_period], :default_value => :week
desc "The project name to run on"
flag [:project], :default_value => :none
desc "A switch to turn off loading from cache"
switch [:ignore_cache]
desc "A switch to turn off writing to cache"
switch [:no_cache]
pre do |global_options,command,options,args|
$dir = Dir.pwd
$users = []
$projects = []
$project = nil
if File.exists? global_options[:config_path]
config = JSON.parse(File.read(global_options[:config_path]), {:symbolize_names => true})
$users = (config[:users].empty?) ? [] : config[:users]
$projects = (config[:projects].empty?) ? [] : config[:projects]
end
if $projects.empty?
$projects.push({
:name => "current",
:repos => [Dir.pwd],
:ignored_directories => [],
:default => true
})
end
true
end
def require_user(options)
if options[:user] == :none
if $users.select{ :default == true }.empty?
help_now!('user is required, either as a command line arg or a default in .git_team_stats.json')
else
$user = $users.select{ :default == true }[0]
end
else
$user = {
:name => options[:user].to_s,
:aliases => [options[:user].to_s]
}
end
end
def require_project(global_options)
if global_options[:project] == :none
if !$projects.select{ |proj| proj[:default] == true }.empty?
$project = $projects.select{ |proj| proj[:default] == true }[0]
end
else
if !$projects.select{ |proj| proj[:name] == global_options[:project] }.empty?
$project = $projects.select{ |proj| proj[:name] == global_options[:project] }[0]
end
end
if ($project == nil)
puts $projects
help_now!('project is required, either as a command line arg or a default in .git_team_stats.json')
end
GitTeamStats.start($project)
load_cache(global_options)
end
def load_cache(global_options)
if (global_options[:ignore_cache])
return
end
cache_file_path = File.join(global_options[:cache_path], GitTeamStats.get_cache_file_name() + '.json')
if (File.exist?(cache_file_path))
output = JSON.parse(File.open(cache_file_path, 'rb').read, {:symbolize_names => true})
puts "Loading data from cache".color(:yellow)
GitTeamStats.load_from_cache(output)
end
end
desc "Count the total commits in the project"
command :count_commits do |c|
c.action do |global_options,options,args|
require_project(global_options)
GitTeamStats.inspect_commits()
puts "Total commits : " + GitTeamStats.count_commits().to_s
end
end
desc "Run the standard project inspection"
command :inspect_commits do |c|
c.action do |global_options,options,args|
require_project(global_options)
puts GitTeamStats.inspect_commits()
end
end
desc "Gather cumulative statistics on the team"
command :team_cumulative_stats do |c|
c.action do |global_options,options,args|
require_project(global_options)
stats = GitTeamStats.team_cumulative_stats()
puts "~~~ Cumulative Team Statistics ~~~~~~~~".color(:green)
stats.each{ |key, value|
if (key == :file_types)
puts "languages: "
value.each{ |language, data|
puts " " + language.to_s
puts " edits : " + data[:edits].to_s
puts " lines : " + data[:lines].to_s
}
else
puts key.to_s + " : " + value.to_s
end
}
end
end
desc "Gather cumulative statistics on a specific user"
command :user_cumulative_stats do |c|
c.flag [:user], :default_value => :none
c.action do |global_options,options,args|
require_project(global_options)
require_user(options)
stats = GitTeamStats.user_cumulative_stats($user)
headline = "~~~ Cumulative User Statistics (%s) ~~~~~~~~" % $user[:name].to_s
puts headline.color(:green)
stats.each{ |key, value|
if (key == :file_types)
puts "languages: "
value.each{ |language, data|
puts " " + language.to_s
puts " edits : " + data[:edits].to_s
puts " lines : " + data[:lines].to_s
}
else
puts key.to_s + " : " + value.to_s
end
}
end
end
post do |global_options,command,options,args|
if (global_options[:no_cache])
return
end
if (Dir.exist?(global_options[:cache_path]))
output = GitTeamStats.get_cache_output()
cache_file_path = File.join(global_options[:cache_path], GitTeamStats.get_cache_file_name() + '.json')
if (File.exist?(cache_file_path))
f = File.open(cache_file_path, "w+")
else
f = File.new(cache_file_path, "w+")
end
f.write(output.to_json)
f.close()
else
puts "Could not cache results, could not write to cache directory".color(:yellow)
end
true
end
on_error do |exception|
puts exception
end
exit run(ARGV) | true |
fcd022cc754db6d630df9c5c1cd6cfd6d75272b4 | Ruby | youngjun-na/AAClasswork | /W3D5/youngjun_polytreenode/lib/00_tree_node.rb | UTF-8 | 1,175 | 3.71875 | 4 | [] | no_license | class PolyTreeNode
attr_accessor :children, :value
attr_reader :parent
def initialize(value)
@value = value
@parent = nil
@children = []
end
def inspect
{ "value"=>@value, "parent"=>@parent, "children"=>@children }.inspect
end
def parent=(node)
@parent.children.delete(self) if @parent != nil
@parent = node
if node != nil
node.children << self unless node.children.include?(self)
end
end
def add_child(child_node)
child_node.parent = self
end
def remove_child(child_node)
if !self.children.include?(child_node)
raise "it's not your child!"
else
child_node.parent = nil
end
end
def dfs(target)
#check self.value
#returning node matching target
return self if self.value == target
self.children.each do |child|
correct_node = child.dfs(target)
return correct_node unless correct_node == nil
end
return nil
end
def bfs(target)
queue = [self]
until queue.empty?
node = queue.shift
if node.value == target
return node
else
queue += node.children
end
end
return nil
end
end | true |
736e59a5dd27a09f48e7eafe74b15475c74688f9 | Ruby | supremebeing7/expense_organize_sql | /expenses_ui.rb | UTF-8 | 3,038 | 3.390625 | 3 | [] | no_license | require 'pg'
require './lib/expense'
require './lib/category'
require './lib/company'
DB = PG.connect({:dbname => 'expenses'})
def ascii_art
system "clear"
print "\e[1;32m
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$ $
$ __ _____ $
$ |__ | $
$ |__ XPENSE | RACKER $
$ $
$ $
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
"
end
def main_menu
ascii_art
puts "\n'Exp' - Add expense"
puts "'Cat' - Add category"
puts "'Com' - Add company"
puts "'Show' - Show expenses by category"
puts "'Del' - Delete all data"
puts "'Q' - Quit"
choice = gets.chomp.upcase
case choice
when 'EXP'
add_expense
when 'CAT'
add_category
when 'COM'
add_company
when 'SHOW'
show_expenses_by_category
when 'DEL'
puts "Are you sure?"
case gets.chomp.upcase
when 'Y', 'YES'
DB.exec("DELETE FROM expenses *;")
DB.exec("DELETE FROM categories *;")
DB.exec("DELETE FROM companies *;")
DB.exec("DELETE FROM expenses_categories *;")
puts "DELETED"
sleep(1.5)
main_menu
else
main_menu
end
when 'Q'
system 'clear'
puts "\n\tGoodbye\n\n"
else
puts "Invalid entry"
main_menu
end
end
def add_expense
system "clear"
puts "\nWhat did you purchase?"
description = gets.chomp
puts "\nHow much did it cost?"
amount = gets.chomp.gsub(',','').to_f
puts "\nWhen did you purchase? (Format YYYY-MM-DD)"
date = gets.chomp
puts "\nFrom what company did you purchase?"
company_name = gets.chomp.capitalize
new_company = Company.create({'name' => company_name})
new_expense = Expense.create({'description' => description, 'amount' => amount, 'company_id' => new_company.id, 'date' => date})
add_category_to_expense(new_expense)
puts "Expense added!"
puts "#{new_expense.description} - $#{'%.2f' % new_expense.amount} - Company: #{new_company.name}"
puts "\nAdd another expense?"
choice = gets.chomp.upcase
case choice
when 'Y', 'YES'
add_expense
else
main_menu
end
end
def add_category_to_expense(new_expense)
puts "\nEnter a category:"
category_name = gets.chomp.capitalize
new_category = Category.create({'name' => category_name})
new_category.add_to_expenses_categories(new_expense)
puts "\nWould you like to add an additional category?"
case gets.chomp.upcase
when 'Y', 'YES'
add_category_to_expense(new_expense)
end
end
def add_category
main_menu
end
def add_company
main_menu
end
def show_expenses_by_category
system "clear"
Category.all.each_with_index do |category, index|
category_percent = '%.1f' % (category.show_percent_spent * 100)
puts "#{index + 1}. #{category.name}\t\tPercent of total: #{category_percent}%"
category.show_categorized_expenses.each do |expense|
puts "\t#{expense['date']} - $#{'%.2f' % expense['amount']} - #{expense['description']}"
end
end
puts "\n\nPress 'enter' to continue"
gets.chomp
main_menu
end
main_menu
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.