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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cfe95c5e0f1d451fd95b79fce4b24c4e03f86090 | Ruby | ysulaiman/communique | /experiments/experiment_helpers.rb | UTF-8 | 769 | 2.53125 | 3 | [] | no_license | require 'benchmark'
require 'rubygems'
require 'text-table'
require_relative '../lib/dbc_method'
require_relative '../lib/dbc_object'
require_relative '../lib/dbc_use_case'
require_relative '../lib/noise_generator'
require_relative '../lib/planner'
def solve_and_report(use_case)
planner = Planner.new(:best_first_forward_search)
planner.set_up_initial_state(use_case)
planner.goals = use_case.postconditions
puts "Solving UC #{use_case.name} ..."
planner.solve
puts "Solution: ", prettify_plan(planner.plan)
puts "# Goal Tests: #{planner.number_of_states_tested_for_goals}\n\n"
end
def prettify_plan(raw_plan, header = nil)
return raw_plan if raw_plan == :failure
([header] + raw_plan.map { |e| e.values }).to_table(first_row_is_head: true)
end
| true |
aa759d3a040b21c54a77d55a6732f259d9554b65 | Ruby | minoritea/ruby_rspec | /spec/lib/VendingMachine_spec.rb | UTF-8 | 4,400 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | # -*- encoding: utf-8 -*-
require 'spec_helper'
describe VendingMachine do
let(:vm){ VendingMachine.new }
#let(:yen10) {Money.new 10}
context '初期状態のテスト' do
it '何も投入しなければ合計0件' do
vm.total.should eq 0
end
it '何も投入しなければつり銭ボックスは' do
vm.change.should eq 0
end
end
context 'コインを投入したときの合計値についてのテスト' do
it '10円入れたら合計10円' do
vm.add 10
vm.total.should eq 10
end
it '50円入れたら合計50円' do
vm.add 50
vm.total.should eq 50
end
it '100円入れたら合計100円' do
vm.add 100
vm.total.should eq 100
end
it '500円入れたら合計500円' do
vm.add 500
vm.total.should eq 500
end
it '1000円入れたら合計1000円' do
vm.add 1000
vm.total.should eq 1000
end
end
context '複数回入れた時は合計金額がその合計になる' do
it '10円と50円ならば合計60円' do
vm.add 10
vm.add 50
vm.total.should eq 60
end
it '100円と500円と1000円ならば合計1600円' do
vm.add 100
vm.add 500
vm.add 1000
vm.total.should eq 1600
end
end
describe '釣り銭の確認' do
context '釣り銭は合計金額を返して、内部合計金額を0にする' do
it '100円投入して、100円帰ってきて、内部の合計は0になる' do
vm.add 100
vm.payback.should eq 100
vm.total.should eq 0
vm.change.should eq 100
end
end
context '現在の合計金額がジュースの値段以上のとき' do
it '釣り銭は投入金額からジュースの値段を引いた値段' do
#前提条件
initial_amount = vm.stock[:coke][:amount]
vm.add 500
#購入
vm.purchase :coke
vm.payback
#結果
vm.change.should eq 380
end
end
context '現在の合計金額がジュースの値段未満のとき' do
it '釣り銭はそのまま' do
#前提条件
initial_amount = vm.stock[:coke][:amount]
vm.add 100
#購入
vm.purchase :coke
vm.payback
#結果
vm.change.should eq 100
end
end
end
context '想定していないお金が投入された時' do
it '1円を入れると、1円返ってきて、合計が0円のまま' do
vm.add 1
vm.total.should eq 0
vm.change.should eq 1
end
it '5円を入れると、5円返ってきて、合計が0円のまま' do
vm.add 5
vm.total.should eq 0
vm.change.should eq 5
end
it '5000円を入れると、5000円返ってきて、合計が0円のまま' do
vm.add 5000
vm.total.should eq 0
vm.change.should eq 5000
end
end
describe 'ジュース情報の取得' do
context '初期状態の時' do
it '120円のコーラが5本ある' do
vm.stock.should eq coke: {price: 120, amount: 5}
end
end
end
describe '売上金を取得する' do
context '初期状態の時' do
it '売上が0円となる' do
vm.sale_amount.should eq 0
end
end
end
describe 'ジュースの購入' do
context '現在の合計金額がジュースの値段以上のとき' do
it 'ジュースの在庫を減らし、売上を増やす。また、合計金額を減らす。' do
#前提条件
initial_amount = vm.stock[:coke][:amount]
vm.add 500
#購入
vm.purchase :coke
#結果
vm.stock[:coke][:amount].should eq (initial_amount - 1)
vm.sale_amount.should eq vm.stock[:coke][:price]
vm.total.should eq (500 - vm.stock[:coke][:price])
end
end
context '現在の合計金額がジュースの値段未満のとき' do
it 'ジュースの在庫、売上はそのまま。合計金額も変化なし' do
#前提条件
initial_amount = vm.stock[:coke][:amount]
vm.add 100
#購入
vm.purchase :coke
#結果
vm.stock[:coke][:amount].should eq initial_amount
vm.sale_amount.should eq 0
vm.total.should eq 100
end
end
end
end
| true |
59771b8858344ef054e783cf416542f3842f6ec6 | Ruby | Codehoff/Codewars | /take_a_ten_minute_walk.rb | UTF-8 | 125 | 2.953125 | 3 | [] | no_license | def is_valid_walk(walk)
walk.length == 10 && walk.count("s") == walk.count("n") && walk.count("e") == walk.count("w")
end | true |
7528b7e788e6a951334310fc7006c7c9c6b4746d | Ruby | Marisha-Sahay/bitcoin | /app/models/product.rb | UTF-8 | 523 | 2.640625 | 3 | [] | no_license | class Product < ApplicationRecord
has_many :images
has_many :categorized_products
has_many :categories, through: :categorized_products
has_many :carted_products
has_many :orders, through: :carted_products
validates :name, presence: true
validates_numericality_of :price, :greater_than => 0, :less_than => 10000
validates_format_of :price, :with => /\A\d+(?:\.\d{0,2})?\z/
TAXRATE = 0.09
def sale_message
end
def tax
price.to_i * TAXRATE
end
def total
tax + price.to_f
end
end
| true |
40f72b2e28ae457ffb84195a8a5d421bb08ebed8 | Ruby | scmountain/ApiCurious | /app/models/starred_repo.rb | UTF-8 | 455 | 2.734375 | 3 | [] | no_license | class StarredRepo
attr_reader :name, :updated_at, :language, :html_url
def initialize(params)
@name = params["name"]
@updated_at = params["updated_at"]
@language = params["language"]
@html_url = params["html_url"]
end
def self.count
end
def self.all(current_user)
starred_repos_hashes = GithubStarredRepoService.starred(current_user)
starred_repos_hashes.map do |repo|
StarredRepo.new(repo)
end
end
end
| true |
1fddfb65821e8941911f78991d076965ca34dba6 | Ruby | AnaPaulaSousa/estudos_alura | /sistema.rb | UTF-8 | 1,326 | 3.34375 | 3 | [] | no_license | require_relative "livro"
require_relative "estoque"
def livro_para_news_letter(livro)
if livro.ano_lancamento < 1999
puts "NewsLetter/Liquidação"
puts livro.titulo
puts livro.preco
puts livro.possui_reimpressao
end
end
algoritmos = Livro.new("Algoritmos", 100, 1998, true)
arquitetura = Livro.new("Introdução a Arquitetura e Design de Software", 70, 2011, true)
programmer = Livro.new("The Pragmatic Programmer", 100, 1999, true)
ruby = Livro.new("Programming Ruby", 100, 2004, true)
estoque = Estoque.new
estoque << algoritmos
puts estoque.maximo_necessario
estoque << arquitetura
puts estoque.maximo_necessario
estoque << programmer
puts estoque.maximo_necessario
estoque << ruby
puts estoque.maximo_necessario
estoque.remove algoritmos
puts estoque.maximo_necessario
estoque.exporta_csv
baratos = estoque.mais_barato_que(80)
baratos.each do |livro|
puts "#{livro.titulo}"
end
#livro_para_news_letter(algoritmos)
# livro_rails = Livro.new(70, "Agile Web Development with Rails", 2011)
# livro_ruby = Livro.new(60, "Programming Ruby 1.9", 2010)
# def imprime_nota_fiscal(livros)
# livros.each do |livro|
# puts "Título: #{livro.titulo} - #{livro.preco}"
# end
# end
# livros = [livro_rails, livro_ruby]
# imprime_nota_fiscal livros
| true |
599efc89826478611fbc74eee5a31df8b4871991 | Ruby | RadiusNetworks/radius-spec | /benchmarks/bm_setup.rb | UTF-8 | 1,225 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | # frozen_string_literal: true
require 'kalibera'
require 'benchmark/ips'
# Enable and start GC before each job run. Disable GC afterwards.
#
# Inspired by https://www.omniref.com/ruby/2.2.1/symbols/Benchmark/bm?#annotation=4095926&line=182
class GCSuite
def warming(*)
run_gc
end
def running(*)
run_gc
end
def warmup_stats(*)
end
def add_report(*)
end
private
def run_gc
GC.enable
GC.start
GC.disable
end
end
def as_boolean(val, default: nil)
case val.to_s.strip.downcase
when "true", "t", "yes", "y", "on", "1"
true
when "false", "f", "no", "n", "off", "0"
false
else
raise "Unknown boolean value #{val}" if default.nil?
default
end
end
def section(title = nil)
puts "\n#### #{title}" if title
puts "\n```"
GC.start
Benchmark.ips do |bench|
bench.config suite: GCSuite.new if GC_DISABLED
bench.config stats: :bootstrap, confidence: 95
yield bench
bench.compare!
end
puts "```"
end
def display_benchmark_header
puts
puts "### Environment"
puts
puts RUBY_DESCRIPTION
puts "GC Disabled: #{GC_DISABLED}"
puts
puts "### Test Cases"
end
GC_DISABLED = as_boolean(ENV.fetch('GC_DISABLED', nil), default: false)
| true |
f8138b005bb29a345f8f6acaf7975b706e1bab9e | Ruby | geolopigs/traderpogserver | /app/helpers/posts_helper.rb | UTF-8 | 7,483 | 3.078125 | 3 | [] | no_license | module PostsHelper
##
# Get the region that the post is located in
##
def PostsHelper.coordtoregion(latitude, longitude, fraction)
lat_index = PostsHelper.get_index(latitude, fraction, -90, 90)
lon_index = PostsHelper.get_index(longitude, fraction, -180, 180)
(lat_index * 360 * (1.0 / fraction).to_int) + lon_index
end
def PostsHelper.get_index(point, fraction, min_val, max_val)
low_index = 0
hi_index = ((max_val - min_val) * (1.0 / fraction)).to_int - 1
mid_index = (low_index + hi_index) / 2
current_index = -1
rounded_point = point
done = false
if (rounded_point == min_val)
current_index = low_index
else
if (rounded_point == max_val)
current_index = hi_index
else
while !done
left = min_val + (fraction * mid_index)
left = left.round(8)
right = left + fraction
right = right.round(8)
if rounded_point >= left && rounded_point < right
current_index = mid_index
done = true
else
if rounded_point < left
hi_index = mid_index - 1
else
low_index = mid_index + 1
end
mid_index = (low_index + hi_index) / 2
mid_index = mid_index.round(0)
end
end
end
end
# return the current index
current_index
end
def PostsHelper.getsurroundingregions(region, fraction)
regions_array = []
num_cols = ((1.0 / fraction) * 360).round(0)
num_rows = ((1.0 / fraction) * 180).round(0)
first_value_in_last_row = num_cols * (num_rows - 1)
last_value_in_last_row = (num_cols * num_rows) - 1
# general case
if !PostsHelper.IsLeftEdge(region, fraction) && !PostsHelper.IsRightEdge(region, fraction) && !PostsHelper.IsTopRow(region, fraction) && !PostsHelper.IsBottomRow(region, fraction)
regions_array << (region - num_cols - 1)
regions_array << (region - num_cols)
regions_array << (region - num_cols + 1)
regions_array << (region - 1)
regions_array << (region + 1)
regions_array << (region + num_cols - 1)
regions_array << (region + num_cols)
regions_array << (region + num_cols + 1)
end
# top row except for left and right edges (which are corners)
if (regions_array.length == 0) && !PostsHelper.IsLeftEdge(region, fraction) && !PostsHelper.IsRightEdge(region, fraction) && PostsHelper.IsTopRow(region, fraction)
regions_array << (region + first_value_in_last_row - 1)
regions_array << (region + first_value_in_last_row)
regions_array << (region + first_value_in_last_row + 1)
regions_array << (region - 1)
regions_array << (region + 1)
regions_array << (region + num_cols - 1)
regions_array << (region + num_cols)
regions_array << (region + num_cols + 1)
end
# bottom row except for edges (which are corners)
if (regions_array.length == 0) && !PostsHelper.IsLeftEdge(region, fraction) && !PostsHelper.IsRightEdge(region, fraction) && PostsHelper.IsBottomRow(region, fraction)
regions_array << (region - num_cols - 1)
regions_array << (region - num_cols)
regions_array << (region - num_cols + 1)
regions_array << (region - 1)
regions_array << (region + 1)
regions_array << (region - first_value_in_last_row - 1)
regions_array << (region - first_value_in_last_row)
regions_array << (region - first_value_in_last_row + 1)
end
# left edge except for corners. tricky ones are left, upper left, and lower left
if (regions_array.length == 0) && PostsHelper.IsLeftEdge(region, fraction) && !PostsHelper.IsTopRow(region, fraction) && !PostsHelper.IsBottomRow(region, fraction)
regions_array << (region - 1)
regions_array << (region - num_cols)
regions_array << (region - num_cols + 1)
regions_array << (region - 1 + num_cols)
regions_array << (region + 1)
regions_array << (region - 1 + num_cols + num_cols)
regions_array << (region + num_cols)
regions_array << (region + num_cols + 1)
end
# right edge except for corners. tricky ones are right, upper right, lower right
if (regions_array.length == 0) && PostsHelper.IsRightEdge(region, fraction) && !PostsHelper.IsTopRow(region, fraction) && !PostsHelper.IsBottomRow(region, fraction)
regions_array << (region - num_cols - 1)
regions_array << (region - num_cols)
regions_array << (region - num_cols - num_cols + 1)
regions_array << (region - 1)
regions_array << (region - num_cols + 1)
regions_array << (region + num_cols - 1)
regions_array << (region + num_cols)
regions_array << (region + 1)
end
# upper left corner (always sector 0)
if (regions_array.length == 0) && (region == 0)
regions_array << (num_rows * num_cols - 1)
regions_array << first_value_in_last_row
regions_array << first_value_in_last_row + 1
regions_array << (num_cols - 1)
regions_array << 1
regions_array << (num_cols + num_cols - 1)
regions_array << (num_cols)
regions_array << (num_cols + 1)
end
# upper right corner
if (regions_array.length == 0) && PostsHelper.IsRightEdge(region, fraction) && PostsHelper.IsTopRow(region, fraction)
regions_array << (num_rows * num_cols - 2)
regions_array << last_value_in_last_row
regions_array << first_value_in_last_row
regions_array << (region - 1)
regions_array << 0
regions_array << (region + num_cols - 1)
regions_array << (region + num_cols)
regions_array << num_cols
end
# lower left corner (is firstValueInLastRow)
if (regions_array.length == 0) && PostsHelper.IsLeftEdge(region, fraction) && PostsHelper.IsBottomRow(region, fraction)
regions_array << (last_value_in_last_row - num_cols)
regions_array << (region - num_cols)
regions_array << (region - num_cols + 1)
regions_array << last_value_in_last_row
regions_array << (region + 1)
regions_array << (num_cols - 1)
regions_array << 0
regions_array << 1
end
# lower right corner (is lastValueInLastRow)
if (regions_array.length == 0) && PostsHelper.IsRightEdge(region, fraction) && PostsHelper.IsBottomRow(region, fraction)
regions_array << (region - num_cols - 1)
regions_array << (region - num_cols)
regions_array << (first_value_in_last_row - num_cols)
regions_array << (region - 1)
regions_array << first_value_in_last_row
regions_array << (num_cols - 2)
regions_array << (num_cols - 1)
regions_array << 0
end
# return regions_array
regions_array
end
def PostsHelper.IsLeftEdge(region, fraction)
num_cols = ((1.0 / fraction) * 360).round(0)
div = (region % num_cols)
(div == 0)
end
def PostsHelper.IsRightEdge(region, fraction)
PostsHelper.IsLeftEdge(region + 1, fraction)
end
def PostsHelper.IsTopRow(region, fraction)
num_cols = ((1.0 / fraction) * 360).round(0)
(region >= 0 && (region <= (num_cols - 1)))
end
def PostsHelper.IsBottomRow(region, fraction)
num_cols = ((1.0 / fraction) * 360).round(0)
num_rows = ((1.0 / fraction) * 180).round(0)
first_value_in_last_row = num_cols * (num_rows - 1)
last_value_in_last_row = (num_cols * num_rows) - 1
(region >= first_value_in_last_row) && (region <= last_value_in_last_row)
end
end
| true |
c2bfe661db132cbae271d9100efe8c9cd36446ed | Ruby | complikatyed/Whatcha_Reading | /test/test_helper.rb | UTF-8 | 1,011 | 2.75 | 3 | [
"MIT"
] | permissive | ENV["TEST"] = "true"
require 'rubygems'
require 'bundler/setup'
require "minitest/reporters"
require_relative "../lib/environment"
reporter_options = { color: true }
Minitest::Reporters.use! [Minitest::Reporters::DefaultReporter.new(reporter_options)]
require 'minitest/autorun'
class Minitest::Test
def setup
Database.load_structure
Database.execute("DELETE FROM books;")
end
end
def create_book(title)
Database.execute("INSERT INTO books (title) VALUES (?)", title)
end
def exit_from(pipe)
pipe.puts "Exit"
pipe.puts "4"
main_menu + "Go read something!\n"
end
def main_menu
"1. Add a book\n2. Edit book info\n3. View the book list\n4. Exit the program\n"
end
# def actions_menu
# "Would you like to?\n1. Edit the book's title\n2. Edit the book's genre\n3. Go to main menu\n"
# end
# def genres_menu
# "Please choose a genre:\n1. Sci-Fi/Fantasy\n2. 18th-19th century realism\n3. Modern realism\n4. Mystery/Thriller\n5. Poetry\n6. Biography/Memoir\n7. Other non-fiction\n"
# end | true |
b64102fe5cdff3220ea70a3cad98da1834fa02ec | Ruby | dtgit/lftwb | /vendor/plugins/less_monkey_patching/lib/string.rb | UTF-8 | 1,191 | 2.515625 | 3 | [
"MIT"
] | permissive | class String
def strip_xml
self.gsub(/<(.*?)>/, '')
end
def strip_tag_and_contents tag
self.gsub(/<style.*>.*?<\/style>/mi, '')
end
def to_safe_uri
self.strip.downcase.gsub('&', 'and').gsub(' ', '-').gsub(/[^\w-]/,'')
end
def from_safe_uri
self.gsub('-', ' ')
end
def add_param args = {}
self.strip + (self.include?('?') ? '&' : '?') + args.map { |k,v| "#{k}=#{URI.escape(v.to_s)}" }.join('&')
end
def truncate len = 30
return self if size <= len
s = self[0, len - 3].strip
s << '...'
end
def to_formatted_date(format=nil)
begin
converted_date_value = Date.strptime(self.gsub(/\D/, '-').gsub(/-\d\d(\d\d)$/,'-\1'), format.gsub(/[\.\/]/, '-'))
if converted_date_value.year < 1000
converted_date_value = Date.strptime(self.gsub(/\D/, '-'), format.gsub(/[\.\/]/, '-').gsub('%Y', '%y'))
end
rescue
converted_date_value = Chronic.parse(self)
converted_date_value = converted_date_value.to_date unless converted_date_value.blank?
end
return converted_date_value
end
def valid_email?
!(self =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i).nil?
end
end
| true |
8f8a2b99333a104feaeb73a540d01e5d6eaaa638 | Ruby | emilywiegand/ruby-challenges | /first_ruby_object_refactor.rb | UTF-8 | 415 | 3 | 3 | [] | no_license | class Mon_Calamari
attr_writer :name, :job
attr_reader :name, :job
def outburst
return "IT'S A TRAP!"
end
end
this_calamari = Mon_Calamari.new
this_calamari.name = "Admiral Ackbar"
calamariname = this_calamari.name
this_calamari.job = "Military Commander of the Rebel Alliance"
calamarijob = this_calamari.job
puts "#{calamariname}, #{calamarijob}, says '#{this_calamari.outburst}'"
puts this_calamari.inspect
| true |
ffbdb7f2738c21ea2f4d0f83fa39b94778f0bfef | Ruby | emmabeynon/oystercard | /spec/journey_log_spec.rb | UTF-8 | 1,975 | 2.59375 | 3 | [] | no_license | require 'journey_log'
describe JourneyLog do
subject(:journey_log) { described_class.new(journey_klass) }
let(:journey) { double :journey, fare: 6 }
let(:journey_klass) { double :journey_klass, new: journey, exit_station: exit_station}
let(:entry_station) { double :station}
let(:exit_station) { double :station}
describe '#default' do
it "has a an empty list of journeys" do
expect(journey_log.journey_history).to be_empty
end
it 'has no active journey' do
expect(journey_log.journey).to be_nil
end
end
describe '#start_journey' do
before do
journey_log.start_journey(entry_station)
end
it 'creates a new journey' do
expect(journey_log.journey).to eq journey
end
end
describe '#exit_journey' do
before do
allow(journey).to receive(:complete_journey).and_return exit_station
allow(journey).to receive(:exit_station).and_return exit_station
journey_log.start_journey(entry_station)
journey_log.exit_journey(exit_station)
end
it 'should record the journey' do
expect(journey_log.journey_history).to include(journey)
end
it 'should reset journey to nil after completing a journey' do
expect(journey_log.journey).to be_nil
end
end
describe '#journeys' do
it 'returns a list of all previous journeys' do
allow(journey).to receive(:complete_journey).and_return exit_station
journey_log.start_journey(entry_station)
journey_log.exit_journey(exit_station)
expect(journey_log.journey_history).to include(journey)
end
end
describe '#last_journey_fare' do
it 'returns the fare from an completed journey' do
journey_log.start_journey(entry_station)
allow(journey).to receive(:complete_journey).and_return exit_station
allow(journey).to receive(:fare).and_return 1
journey_log.exit_journey(exit_station)
expect(journey_log.last_journey_fare).to eq 1
end
end
end
| true |
01a86d838b2b40dfcb333ee1130a8a2679341de6 | Ruby | danhodge/cfb | /lib/cfb/team.rb | UTF-8 | 723 | 2.734375 | 3 | [
"MIT"
] | permissive | module CFB
Team = Struct.new(:name, :wins, :losses, :ranking, :point_spreads) do
def self.from_json(json)
new(
json["name"],
json["wins"],
json["losses"],
json["ranking"],
json["point_spreads"]
)
end
def attributes
to_h
end
def point_spread
return 'UNKNOWN' if point_spreads.nil? || point_spreads.empty?
sum = point_spreads.reduce(0, :+)
(sum / point_spreads.count).round(1)
end
def merge(team)
merged = attributes.merge(team.attributes) { |_, old_val, new_val| new_val || old_val }
self.class.new(
*merged.values_at(:name, :wins, :losses, :ranking, :point_spreads)
)
end
end
end
| true |
bba508eacd83b10a4510c6134ca74bd5bc191bbd | Ruby | nguyhh/ddd_code_samples_ruby | /claim_test.rb | UTF-8 | 1,453 | 3.03125 | 3 | [] | no_license | require "test/unit"
require 'date'
require_relative './claim'
require_relative './repair_po'
require_relative './line_item'
class ClaimTest < Test::Unit::TestCase
def test_claim_is_setup_correctly
line_item1 = LineItem.new("PARTS", 45.0, "Replacement part for soap dispenser")
line_item2 = LineItem.new("LABOR", 50.0, "1 hour repair")
repair_po = RepairPO.new
repair_po.line_items << line_item1
repair_po.line_items << line_item2
claim = Claim.new(150.0, Date.new(2010, 5, 8))
claim.repair_pos << repair_po
assert_equal 150.0, claim.amount
assert_equal Date.new(2010, 5, 8), claim.date
assert_equal "PARTS", claim.repair_pos[0].line_items[0].type
assert_equal 45.0, claim.repair_pos[0].line_items[0].amount
assert_equal "Replacement part for soap dispenser", claim.repair_pos[0].line_items[0].description
assert_equal "LABOR", claim.repair_pos[0].line_items[1].type
assert_equal 50.0, claim.repair_pos[0].line_items[1].amount
assert_equal "1 hour repair", claim.repair_pos[0].line_items[1].description
end
# entities compare by unique IDs, not properties
def test_claim_equality
claim = Claim.new(150.0, Date.new(2010, 5, 8))
claim_same_id = claim.clone
claim_same_id.repair_pos << RepairPO.new
assert_equal claim, claim_same_id
claim_different_id = Claim.new(150.0, Date.new(2010, 5, 8))
assert_not_equal claim, claim_different_id
end
end
| true |
4f48d710e63f389036f8c5d65ffe2b5cc85c8cec | Ruby | alu0101126692/pract10 | /lib/foodie/menu.rb | UTF-8 | 1,257 | 3.265625 | 3 | [
"MIT"
] | permissive | class Menu
#Nombre del menu
attr_reader :nombre
#lista de platos
attr_accessor :listapl
#lista precios
attr_accessor :listapr
#descripcion del menu
attr_accessor :desc
#precio total
attr_accessor :precios
def initialize(nombre,&block)
@nombre = nombre
@listapl = Listas.new()
@listapr = Listas.new()
@desc = ""
@precio = ""
if block_given?
if block.arity == 1
yield self
else
instance_eval(&block)
end
end
end
def descripcion (text)
@desc = text
end
def preciototal (num)
@precio = num
end
def componente (options = {})
plato = options[:descripcion] if options[:descripcion]
preciopl = options[:precio] if options[:precio]
@listapl.insert_head(plato)
@listapr.insert_head(preciopl)
end
def to_s
output = @nombre
output << "\n#{desc}\n"
output << "Ingredientes\n"
@listapl.zip(@listapr).each do |pl, pr|
output << "#{pl.to_s} "
output << "Precio: #{pr.to_s}\n"
end
output << "Precio total: #{@precio}"
end
end
| true |
9adb97e9cc7cb72d5c9430c0c0365731568cf749 | Ruby | raxoft/form_input | /lib/form_input/types.rb | UTF-8 | 5,015 | 2.96875 | 3 | [
"MIT"
] | permissive | # Common form types.
require 'time'
require 'date'
# Extend forms with arguments for form parameter types which are used often.
class FormInput
# Regular expressions commonly used to validate input arguments.
# Matches names using latin alphabet.
LATIN_NAMES_RE = /\A[\p{Latin}\-\. ]+\z/u
# Matches common email addresses. Note that it doesn't match all addresses allowed by RFC, though.
SIMPLE_EMAIL_RE = /\A[-_.=+%a-z0-9]+@(?:[-_a-z0-9]+\.)+[a-z]{2,4}\z/i
# Matches generic ZIP code. Note that the real format changes for each country.
ZIP_CODE_RE = /\A[A-Z\d]++(?:[- ]?[A-Z\d]+)*+\z/i
# Filter for phone numbers.
PHONE_NUMBER_FILTER = ->{ gsub( /\s*[-\/\.]\s*/, '-' ).gsub( /\s+/, ' ' ).strip }
# Matches generic phone number.
PHONE_NUMBER_RE = /\A\+?\d++(?:[- ]?(?:\d+|\(\d+\)))*+(?:[- ]?[A-Z\d]+)*+\z/i
# Basic types.
# Integer number.
INTEGER_ARGS = {
filter: ->{ ( Integer( self, 10 ) rescue self ) unless empty? },
class: Integer,
}
# Float number.
FLOAT_ARGS = {
filter: ->{ ( Float( self ) rescue self ) unless empty? },
class: Float,
}
# Boolean value, displayed as a select menu.
BOOL_ARGS = {
type: :select,
data: [ [ true, 'Yes' ], [ false, 'No' ] ],
filter: ->{ self == 'true' unless empty? },
class: [ TrueClass, FalseClass ],
}
# Boolean value, displayed as a checkbox.
CHECKBOX_ARGS = {
type: :checkbox,
filter: ->{ not empty? },
format: ->{ self if self },
class: [ TrueClass, FalseClass ],
}
# Address fields.
# Email.
EMAIL_ARGS = {
match: SIMPLE_EMAIL_RE,
}
# Zip code.
ZIP_ARGS = {
match: ZIP_CODE_RE,
}
# Phone number.
PHONE_ARGS = {
filter: PHONE_NUMBER_FILTER,
match: PHONE_NUMBER_RE,
}
# Date and time.
# Full time format.
TIME_FORMAT = "%Y-%m-%d %H:%M:%S".freeze
# Full time format example.
TIME_FORMAT_EXAMPLE = "YYYY-MM-DD HH:MM:SS".freeze
# Full time.
TIME_ARGS = {
placeholder: TIME_FORMAT_EXAMPLE,
filter: ->{ ( FormInput.parse_time!( self, TIME_FORMAT ) rescue self ) unless empty? },
format: ->{ utc.strftime( TIME_FORMAT ) rescue self },
class: Time,
}
# US date format.
US_DATE_FORMAT = "%m/%d/%Y".freeze
# US date format example.
US_DATE_FORMAT_EXAMPLE = "MM/DD/YYYY".freeze
# Time in US date format.
US_DATE_ARGS = {
placeholder: US_DATE_FORMAT_EXAMPLE,
filter: ->{ ( FormInput.parse_time!( self, US_DATE_FORMAT ) rescue self ) unless empty? },
format: ->{ utc.strftime( US_DATE_FORMAT ) rescue self },
class: Time,
}
# UK date format.
UK_DATE_FORMAT = "%d/%m/%Y".freeze
# UK date format example.
UK_DATE_FORMAT_EXAMPLE = "DD/MM/YYYY".freeze
# Time in UK date format.
UK_DATE_ARGS = {
placeholder: UK_DATE_FORMAT_EXAMPLE,
filter: ->{ ( FormInput.parse_time!( self, UK_DATE_FORMAT ) rescue self ) unless empty? },
format: ->{ utc.strftime( UK_DATE_FORMAT ) rescue self },
class: Time,
}
# EU date format.
EU_DATE_FORMAT = "%-d.%-m.%Y".freeze
# EU date format example.
EU_DATE_FORMAT_EXAMPLE = "D.M.YYYY".freeze
# Time in EU date format.
EU_DATE_ARGS = {
placeholder: EU_DATE_FORMAT_EXAMPLE,
filter: ->{ ( FormInput.parse_time!( self, EU_DATE_FORMAT ) rescue self ) unless empty? },
format: ->{ utc.strftime( EU_DATE_FORMAT ) rescue self },
class: Time,
}
# Hours format.
HOURS_FORMAT = "%H:%M".freeze
# Hours format example.
HOURS_FORMAT_EXAMPLE = "HH:MM".freeze
# Seconds since midnight in hours:minutes format.
HOURS_ARGS = {
placeholder: HOURS_FORMAT_EXAMPLE,
filter: ->{ ( FormInput.parse_time( self, HOURS_FORMAT ).to_i % 86400 rescue self ) unless empty? },
format: ->{ Time.at( self ).utc.strftime( HOURS_FORMAT ) rescue self },
class: Integer,
}
# Parse time like Time#strptime but raise on trailing garbage.
# Also ignores -, _ and ^ % modifiers, so the same format can be used for both parsing and formatting.
def self.parse_time( string, format )
format = format.gsub( /%[-_^]?(.)/, '%\1' )
# Rather than using _strptime and checking the leftover field,
# add required trailing character to both the string and format parameters.
suffix = ( string[ -1 ] == "\1" ? "\2" : "\1" )
Time.strptime( "+0000 #{string}#{suffix}", "%z #{format}#{suffix}" ).utc
end
# Like parse_time, but falls back to DateTime.parse heuristics when the date/time can't be parsed.
def self.parse_time!( string, format )
parse_time( string, format )
rescue
DateTime.parse( string ).to_time.utc
end
# Transformation which drops empty values from hashes and arrays and turns empty string into nil.
PRUNED_ARGS = {
transform: ->{
case self
when Array
reject{ |v| v.nil? or ( v.respond_to?( :empty? ) && v.empty? ) }
when Hash
reject{ |k,v| v.nil? or ( v.respond_to?( :empty? ) && v.empty? ) }
when String
self unless empty?
else
self
end
}
}
end
# EOF #
| true |
a1e7d7f1a100f23ab7de8e396def8d09e62bedd6 | Ruby | MichaelSRomero/oo-cash-register-dumbo-web-career-012819 | /lib/cash_register.rb | UTF-8 | 909 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class CashRegister
attr_accessor :total, :discount, :items, :last_transaction
# attr_reader :discount
def initialize(discount = 0)
@total = 0
@discount = discount
@items = []
# @last_transaction = nil
end
def add_item(title, price, quantity = 1)
self.last_transaction = price
quantity.times {self.items << title}
self.total += price * quantity
end
def apply_discount
if self.discount <= 0
return "There is no discount to apply."
else
percentage = self.discount * 0.01
self.total -= (self.total * percentage).to_i
return "After the discount, the total comes to $#{self.total}."
end
end
def void_last_transaction
self.total -= self.last_transaction
end
end
# cash_register = CashRegister.new(20)
# cash_register.add_item("tomato", 1.76)
# puts cash_register.apply_discount
# puts cash_register.void_last_transaction
| true |
d866898be1a7df79327c83483695daabae7ac7c0 | Ruby | evanidul/simpleweed | /lib/simpleweed/timedateutil/timedateservice.rb | UTF-8 | 13,866 | 3.359375 | 3 | [] | no_license | module Simpleweed
module Timedateutil
class Timedateservice
def sayHi
return "timedateservice"
end
#given 0-23 hours as an int, 00-59 minutes as an int, return am/pm string
def formatMilitaryTimeAsAMPM(hours, minutes)
if hours.nil? || minutes.nil?
return
end
ampm = "AM"
h = hours
if h >= 12
h = hours-12;
ampm = "PM"
end
if h == 0
h = 12
end
if minutes == 0
minutes = "00"
end
return h.to_s + ":" + minutes.to_s + " " + ampm
end
# Needs to take 7:00AM and return 7,00. Returns Closed as Closed
def getMilitaryTimeFromAMPMString(datestring)
if !datestring.is_a? String
return nil
end
if datestring == "Closed"
return "Closed"
end
datestring.freeze
# .dup clones a string but unfreezes the cloned one
datestringcopy = datestring.dup
if datestringcopy.include? "pm"
isPm = true
else
isPm = false
end
hoursAndMinutes = datestringcopy.split(':')
hours = hoursAndMinutes[0].strip
minutes = hoursAndMinutes[1].strip
if hours == "12" && !isPm
result = [0, minutes.to_i] # 12:00 AM is 00:00 in military time, to_i drops the pm string
return result
end
if hours == "12" && isPm
result = [12, minutes.to_i] # 12:00 PM is 12:00 in military time
return result
end
hoursAsInt = hours.to_i
if isPm
result = [ hoursAsInt + 12 , minutes.to_i]
return result
else
result = [ hoursAsInt, minutes.to_i]
return result
end
end
# @Tested: rake test test/lib/simpleweed/timedateservice.rb
# need to handle "Closed" case
# def getSecondsSinceMidnight(timestring)
# if !timestring.is_a? String
# return -1
# end
# if timestring == "Closed"
# return -1
# end
# #mutable strings lead to crazy bugs
# timestring.freeze
# # .dup clones a string but unfreezes the cloned one
# timestringcopy = timestring.dup
# # 10:00am - 11:30pm
# if timestringcopy.include? "pm"
# timestringIsPm = true
# else
# timestringIsPm = false
# end
# #delete am and pm
# timestringcopy.sub! 'am' , ''
# timestringcopy.sub! 'pm' , ''
# hoursAndMinutes = timestringcopy.split(':')
# #convert hours into number of seconds
# hoursInSeconds = hoursAndMinutes[0].to_i * 60 * 60
# minutesInSeconds = hoursAndMinutes[1].to_i * 60
# subtotal = hoursInSeconds + minutesInSeconds
# if timestringIsPm
# # if PM, add 12 hours to it.
# if hoursAndMinutes[0].strip == "12" # call .strip because 10:00am - 12:00am leads to " 12"
# return subtotal
# else
# return subtotal + (12* 60 * 60)
# end
# else
# if hoursAndMinutes[0].strip == "12"
# return subtotal - (12 * 60 * 60) # 12 am is midnight, so we should cancel out the 12 hours we added before.
# else
# return subtotal;
# end
# end
# end #getSecondsSinceMidnight
# 0-23 for hours, 0-59 for minutes
def getSecondsSinceMidnightGivenHourAndMinute(hour, minute)
if (!hour.is_a? Integer) || (!minute.is_a? Integer)
#error
return nil;
end
if (hour > 23) || (minute > 59)
return nil;
end
if ( hour < 0 ) || (minute < 0)
return nil
end
hourAsSeconds = hour * 60 *60
minuteAsSeconds = minute * 60
return hourAsSeconds + minuteAsSeconds
end
def isStoreOpen(currenttime, store)
dayint = currenttime.to_date.wday
secondsSinceMidnight = currenttime.seconds_since_midnight()
case dayint
when 0
if store.sundayclosed
if store.saturdayclosed
return false
end
# if store is closed, we still need to call doesTimeOccurDuringBusinessHours with -1,-1 to tell it that
# the store is closed today, but might be open from yesterday (for late closes, 3 am...)
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayopenhour, store.storehourssaturdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayclosehour, store.storehourssaturdaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayopenhour, store.storehourssundayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayclosehour, store.storehourssundaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayopenhour, store.storehourssaturdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayclosehour, store.storehourssaturdaycloseminute)
)
end
when 1
if store.mondayclosed
if store.sundayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayopenhour, store.storehourssundayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayclosehour, store.storehourssundaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayopenhour, store.storehoursmondayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayclosehour, store.storehoursmondaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayopenhour, store.storehourssundayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssundayclosehour, store.storehourssundaycloseminute)
)
end
when 2
if store.tuesdayclosed
if store.mondayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayopenhour, store.storehoursmondayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayclosehour, store.storehoursmondaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayopenhour, store.storehourstuesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayclosehour, store.storehourstuesdaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayopenhour, store.storehoursmondayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursmondayclosehour, store.storehoursmondaycloseminute)
)
end
when 3
if store.wednesdayclosed
if store.tuesdayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayopenhour, store.storehourstuesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayclosehour, store.storehourstuesdaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayopenhour, store.storehourswednesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayclosehour, store.storehourswednesdaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayopenhour, store.storehourstuesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourstuesdayclosehour, store.storehourstuesdaycloseminute)
)
end
when 4
if store.thursdayclosed
if store.wednesdayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayopenhour, store.storehourswednesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayclosehour, store.storehourswednesdaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayopenhour, store.storehoursthursdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayclosehour, store.storehoursthursdaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayopenhour, store.storehourswednesdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourswednesdayclosehour, store.storehourswednesdaycloseminute)
)
end
when 5
if store.fridayclosed
if store.thursdayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayopenhour, store.storehoursthursdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayclosehour, store.storehoursthursdaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayopenhour, store.storehoursfridayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayclosehour, store.storehoursfridaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayopenhour, store.storehoursthursdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursthursdayclosehour, store.storehoursthursdaycloseminute)
)
end
when 6
if store.saturdayclosed
if store.fridayclosed
return false
end
return doesTimeOccurDuringBusinessHours(
-1,
-1,
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayopenhour, store.storehoursfridayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayclosehour, store.storehoursfridaycloseminute)
)
else
return doesTimeOccurDuringBusinessHours(
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayopenhour, store.storehourssaturdayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehourssaturdayclosehour, store.storehourssaturdaycloseminute),
secondsSinceMidnight,
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayopenhour, store.storehoursfridayopenminute),
getSecondsSinceMidnightGivenHourAndMinute(store.storehoursfridayclosehour, store.storehoursfridaycloseminute)
)
end
else
return true #by default, just pretend it's open...
end # case
end #isStoreOpen
# @Tested: rake test test/lib/simpleweed/timedateservice.rb
# open - seconds since midnigtht, open hours
# closed - seconds since midnight
# current time - passed as seconds since midnight
# previousDayOpen - seconds since midnight
# previousDayClose - seconds since midnight
# the store is open 24 hours a day if open and closed are equal, and neither is -1
# the store is closed all day if open and closed are both -1
def doesTimeOccurDuringBusinessHours(open, closed, current, previousDayOpen, previousDayClose)
# if open == closed, this store is open 24 hours a day
if ((open == closed) && !((open == -1) && (closed == -1))) # is the store open 24 hours a day?
return true
end
if ((open == -1) && (closed == -1)) #the store is closed today..but we need to check if it's open from yesterday
# if store was closed yesterday, these values will be nil
if previousDayClose.nil? || previousDayOpen.nil?
return false
end
if previousDayClose < previousDayOpen # .. check and see if the previous day's close is 3AM
#..and that 3 AM is before the open at 5 AM
return current.between?(0, previousDayClose) # if so, the store is still open if the current time is
#between 00:00 and the closing time (3AM)
else
return false
end # if
end # if
if current.between?(0, open) #if the current time is between midnight and the previous day's opening hours..
# if store was closed yesterday, these values will be nil
if previousDayClose.nil? || previousDayOpen.nil?
return false
end
if previousDayClose < previousDayOpen # .. check and see if the previous day's close is 3AM
#..and that 3 AM is before the open at 5 AM
return current.between?(0, previousDayClose) # if so, the store is still open if the current time is
#between 00:00 and the closing time (3AM)
end # if
end # if
if ( closed < open )
return current.between?(open, 86400) # is closed is before open, it's something like 5AM - 3AM, so it's
# open between 5AM and midnight
else
return current.between?(open, closed)
end
end #doesTimeOccurDuringBusinessHours
end #class
end
end | true |
9f0e8ae486b3779232febf8de2ee533f7890d27c | Ruby | rkmathi/two_rank_down | /reopen_class.rb | UTF-8 | 533 | 4.09375 | 4 | [] | no_license | puts 'this is string'
# puts 'this is string'.hoge # `String#hoge`メソッドは存在しないのでエラー
### Stringクラスを再オープンしてhogeメソッドを定義
class String
def hoge
self + ' hogehoge'
end
end
puts 'this is string'.hoge
str = 'fugafuga'
puts str.hoge
### 整数(Fixnum)クラスの+メソッド
puts 2.+(3)
puts 2 + 4
### Fixnumクラスを再オープンしてfugaメソッド(ただの掛け算)を定義
class Fixnum
def fuga(other)
self * other
end
end
puts 2.fuga(5)
| true |
8bab930bb8f99306b127976a50aca137642ab2d5 | Ruby | Osvimil/RubyCourse | /Clase3.rb | UTF-8 | 489 | 3.859375 | 4 | [] | no_license | class Persona
def initialize(nombre,apellido1,apellido2)
@nombre = nombre
@apellido1 = apellido1
@apellido2 = apellido2
end
def mostrar
print("Nombre: "+@nombre+" Ap_paterno: "+@apellido1+" Ap_mat: "+@apellido2)
end
def nombre
@nombre
end
def apellido1
@apellido1
end
def apellido2
@apellido2
end
end
objeto1 = Persona.new("Oswi","Saldivar","Magno\n")
#objeto1.mostrar
puts objeto1.nombre
puts objeto1.apellido1
puts objeto1.apellido2
| true |
b34933b9a3df8a69dbfaa8dbfbf68ce4af8f55de | Ruby | anoam/meeting_schedule | /lib/meeting_deserializer.rb | UTF-8 | 745 | 3.0625 | 3 | [] | no_license | # frozen_string_literal: true
require 'meeting'
require 'invalid_data'
# Provides {Meeting}s deserialization from string
class MeetingDeserializer
MEETING_REGEXP = /(?<title>.+)\s(?<duration>\d+)min/
# Restores collection of meetings from string
# @param source [String] formatted string that contains serialized meetings
# one per line
def restore(source)
return [] if source.nil?
return [] if source.empty?
source.split("\n").map do |text_meeting|
data = MEETING_REGEXP.match(text_meeting)
raise(InvalidData, 'invalid format') if data.nil?
build_meeting(data[:title], data[:duration].to_i)
end
end
private
def build_meeting(title, duration)
Meeting.new(title, duration)
end
end
| true |
733a3441f75c7177295d42e20712495b703a8e88 | Ruby | thracken/mastermind | /mastermind.rb | UTF-8 | 3,552 | 3.515625 | 4 | [] | no_license | module Mastermind
class Game
def initialize
@player = Player.new
@answer = Solution.new.create
@turns = 0
@guesses = Array.new
@all_clues = Array.new
@turn_count = 0
end #initialize
def play
show_board
loop do
take_turn
break if game_over?
end
play_again?
end #play
def take_turn
get_player_guess
@turn_count += 1
show_board
end #take_turn
def get_player_guess
new_guess = Player_Guess.new.get_guess
@guesses.push new_guess
end #get_player_guess
def show_board
if @turn_count > 1 && game_over?
puts " GAME OVER "
puts " #{@answer[0]} | #{@answer[1]} | #{@answer[2]} | #{@answer[3]}"
else
puts " "
puts " X | X | X | X |"
end
puts "---+---+---+---+----"
@guesses.each do |guess|
clue = Feedback.new.analyze(guess, @answer)
@all_clues.push clue
puts " #{guess[0]} | #{guess[1]} | #{guess[2]} | #{guess[3]} | #{clue[0]} #{clue[1]} "
puts " | | | | #{clue[2]} #{clue[3]}"
puts "---+---+---+---+----"
end
end #show_board
def game_over?
last_clue = Feedback.new.analyze(last_guess, @answer)
if last_clue == ["C","C","C","C"]
puts "You Win!"
return true
elsif @turn_count >= 12
return true
else
return false
end
end #game_over?
def last_guess
return @guesses.last
end
def play_again?
loop do
print "Would you like to play again? (Y/N) "
restart = gets.chomp.downcase
if restart == "n"
"Thanks for playing, #{@player.name}!"
return
elsif restart == "y"
Game.new.play
end
end
end #play_again?
end #Game
class Player
attr_reader :name
def initialize
get_name
end
def get_name
print "What's your name? "
@name = gets.chomp
end
end #Player
class Combo
attr_reader :slots
def initialize
@slots = Array.new(4)
end
end #Combo
class Player_Guess < Combo
VALID_NUM = [1,2,3,4,5,6]
def get_guess
puts "Enter 4 numbers (1-6), one at a time:"
@slots.each_with_index do |val, index|
loop do
input = gets.chomp.to_i
if VALID_NUM.include?(input)
@slots[index] = input
break
end
puts "Try again - enter a number from 1-6."
end
end
return @slots
end #get_guess
end #Player_Guess
class Solution < Combo
attr_reader :slots
def create
@slots = 4.times.map { rand(1..6) }
end
end #Solution
class Feedback
attr_reader :clues
def initialize
@clues = Array.new
end
def analyze(combo,solution)
guess = combo.clone
answer = solution.clone
guess.each_with_index do |num, index|
if guess[index] == answer[index]
@clues.push("C")
answer[index] = nil
guess[index] = nil
end
end
(1..6).each do |num|
[guess.count(num), answer.count(num)].min.times do
@clues.push("x")
end
end
@clues.push("-") while @clues.length < 4
return @clues.shuffle
end
end #Feedback
end #Mastermind
include Mastermind
Game.new.play
| true |
f8f7aa572bf50dcb338894deaedfa1b65dcf8718 | Ruby | vanmichael/hrpay | /app/models/commission_sales_person.rb | UTF-8 | 593 | 2.90625 | 3 | [] | no_license | class CommissionSalesPerson < Employee
attr_reader :total_sales, :commission
def initialize(first_name, last_name, base_salary, commission)
super(first_name,last_name,base_salary)
@commission = commission.to_f
get_sales(last_name)
end
def get_sales(last_name)
@total_sales = 0
employee_sales = SaleReader.get_sales('app/models/sales.csv')
employee_sales.each do |sale|
@total_sales += sale.amount.to_f if sale.last_name == last_name
end
end
def gross_salary_per_month
(@base_salary/12) + ((@commission * @total_sales))
end
def net_pay_per_month
super
end
end | true |
220ed259eab720a8a8b3e44e96cb69f7bf38b3e7 | Ruby | david-sawatske/Interview-Cake-Problems | /Problems/2. others_prod_prob.rb | UTF-8 | 408 | 3.96875 | 4 | [] | no_license | # Write a function get_products_of_all_ints_except_at_index() that takes an array
# of integers and returns an array of the products, excluding the integer at
# the current index
# do not use division
# Time
# Space
def others_prod(arr)
end
arr1 = [1, 7, 3, 4]
arr2 = [3, 1, 2, 5, 6, 4]
p others_prod(arr1) == [84, 12, 28, 21]
p others_prod(arr2) == [240, 720, 360, 144, 120, 180]
p others_prod(arr2)
| true |
21a9c1722f8c60751f4e99e2cc1d6bf70f44e181 | Ruby | annielin28815/ruby-hw1 | /0.8.05 - 邏輯判斷與流程控制/09.case-range-02.rb | UTF-8 | 204 | 3.78125 | 4 | [] | no_license | # 用case...when...的寫法1
age = 10
case
when age >= 0 && age <= 3
puts "嬰兒"
when age >= 4 && age <= 10
puts "兒童"
when age >= 11 && age <= 17
puts "青少年"
else
puts "成年"
end | true |
dfbba92e4d397074884a83dd6b49e23b35aca8ff | Ruby | danielnsilva/pullreqs | /bin/comment_stripper.rb | UTF-8 | 1,594 | 2.734375 | 3 | [
"BSD-2-Clause"
] | permissive | #
# (c) 2012 -- 2014 Georgios Gousios <gousiosg@gmail.com>
#
# BSD licensed, see LICENSE in top level dir
#
module CommentStripper
def strip_shell_style_comments(buff)
in_comment = false
out = []
buff.each_byte do |b|
case b
when '#'.getbyte(0)
in_comment = true
when "\r".getbyte(0)
when "\n".getbyte(0)
in_comment = false
unless in_comment
out << b
end
else
unless in_comment
out << b
end
end
end
out.pack('c*')
end
def strip_c_style_comments(buff)
in_ml_comment = in_sl_comment = may_start_comment = may_end_comment = false
out = []
buff.each_byte do |b|
case b
when '/'.getbyte(0)
if may_start_comment
unless in_ml_comment
in_sl_comment = true
end
elsif may_end_comment
in_ml_comment = false
may_end_comment = false
else
may_start_comment = true
end
when '*'.getbyte(0)
if may_start_comment
in_ml_comment = true
may_start_comment = false
else
may_end_comment = true
end
when "\r".getbyte(0)
when "\n".getbyte(0)
in_sl_comment = false
unless in_sl_comment or in_ml_comment
out << b
end
else
unless in_sl_comment or in_ml_comment
out << b
end
may_end_comment = may_start_comment = false
end
end
out.pack('c*')
end
end
| true |
6a16647abf3163bce17aaedf34e088e95eef3680 | Ruby | temi77/hwf-calculator | /app/forms/date_of_birth_form.rb | UTF-8 | 1,152 | 3.171875 | 3 | [] | no_license | # A form object for the date of birth question
# Allows for date's being represented using rails '1i, 2i and 3i' notation.
class DateOfBirthForm < BaseForm
# @!attribute [rw] date_of_birth
# @return [Date] The date of birth of the individual or the eldest in a couple
attribute :date_of_birth, :date
# The type of the form
#
# @return [Symbol] :date_of_birth
def type
:date_of_birth
end
def initialize(inputs = {})
super convert_date_input(inputs)
end
private
# @TODO This method is responsibe for converting from rails's 1i, 2i, 3i format for dates
# - this may well get changed but not focusing on this right now
def convert_date_input(data)
return data unless data.key?('date_of_birth(1i)') &&
data.key?('date_of_birth(2i)') &&
data.key?('date_of_birth(3i)')
inputs = data.dup
date = Date.new inputs.delete('date_of_birth(1i)').to_i,
inputs.delete('date_of_birth(2i)').to_i,
inputs.delete('date_of_birth(3i)').to_i
inputs.merge(date_of_birth: date)
end
def export_params
{
date_of_birth: date_of_birth
}
end
end
| true |
c0d820b8cfe6f8ff362061694b409b6c9bb43137 | Ruby | Jean-Christian-petetin/algoPseudoCode | /algo3ruby.rb | UTF-8 | 181 | 2.5625 | 3 | [] | no_license | #author JesuScript
$word = "anticonstitutionnellement"
$char = "n"
$result = 0
$i = 0
while $i < $word.length
if $word[$i] == $char
$result += 1
end
$i += 1
end
print $result
| true |
faf30a65033a00c59913e2d9b8d6b97386477b9f | Ruby | SugarBowlAcademy/grade-calculator-laurenpalermo10 | /ProjectBegin.rb | UTF-8 | 3,118 | 4.3125 | 4 | [] | no_license | =begin
in this project you will be creating a program that tells people what grade they will need on a test to get a particular overall grade in the class. Look at the pseudocode below as an example of how the the UI is and how the calculation works
=end
=begin
desiredpoints = .9 x total + testworth
pointsontest= desiredpoints - earnedpoints
gradeontest= earnedpoints /testworth
=end
#Example 1
#My current overall grade is 80/100
# my next test is worth 20 points
# I want to know what grade I will need on the test in order to keep a C in the class
# I know that the overall points in the class will be 120
# and that 120*.7 is 84 so I will need a 4/20, or 20% on the next test to maintain a 70% in the class.
#Example 2
# my current grade is 45/50, a 90%
# I want to know how to move to a 95% if my next test is worth 25 points
# I know that my overall grade will be out of 75 points, and .95 of 75 is 71.25
# so the person will need 71.25-45=26.5 points on the next test or 106% to get a 95%
puts "What is your grade in this class out of 100, in decimal format? (50% = .50)" #asks the user this question
overallpercent = gets.to_f #takes information the user enters and stores it
overallpercent = overallpercent*100 #transforms the grade from decimal format to a percentage
puts "What are the total number of points in your class?" #asks the user this question
totalpoints = gets.to_f #takes information the user enters and stores it
gradepoints = totalpoints*overallpercent #takes your grade out of a 100, and multiplys it by the number of points in the class. so if you have a 90 in a class(out of a 100 points), but the class has 200 points, the computer needs to multiply the the total points(200) by the overall percent(.9). This shows that you have 180/200 points in the class.
puts "How many points is the test you took worth?" #asks the user this question
testpoints = gets.to_f #takes information the user enters and stores it
puts "What overall grade do you want in this class as a percent?" #asks the user this question
goalgrade = gets.to_f #takes information the user and stores it
new_class_total = testpoints + totalpoints #the new_class_total equals the worth of the test you took (testpoints) and the total points within your class (totalpoints) added together
goalgrade = goalgrade / 100 * new_class_total #goalgrade(what grade you want in the class) is equal to goalgrade times 100. This makes the decimal into a percent, and then the computer takes this percent and multiplys it by the new_class_total. This number will equal the amount of points that your total grade will need to equal for you to reach the goal grade.
goalgrade= (goalgrade - gradepoints) /testpoints # goalgrade equals your goalgrade minus the gradepoints you already have, to get the difference between the two sets of points. When the computer gets that number, it will divide it by the number of points on the test, to get the percent you will need to get your "goalgrade"
puts "The grade you need on this test is #{goalgrade}" #prints the percent you will need to get on this grade to reach goalgrade.
| true |
a872d155babb32a405ccdbba9d5bd2e6b4e35ff6 | Ruby | hashrocket/localpolitics.in | /vendor/plugins/rspec_expectation_matchers/lib/active_record/validates_uniqueness_of.rb | UTF-8 | 1,596 | 2.515625 | 3 | [
"MIT"
] | permissive | module EdgeCase
module RSpecExpectationMatchers
module ProvidesFor
module ActiveRecord
class ValidatesUniquenessOf < BaseValidationMatcher
def initialize(attribute, options = {})
@attribute = attribute.to_sym
@options = options
@invalid_value = @options[:invalid_value] || nil
@valid_value = @options[:valid_value] || nil
end
def matches?(model)
model.save if model.new_record?
@model = model.class.new(model.attributes)
return !@model.valid? && @model.errors.invalid?(@attribute)
end
def failure_message
message = " - #{@model.class.to_s} does not validates uniqueness of :#{@attribute} as expected."
class_count = @model.class.count
message << "\n There were #{class_count} records present in the database, but none matched your uniqueness validation. Try saving a record with the unique attribute first."
message << print_out_errors(@model)
end
def negative_failure_message
message = " - #{@model.class.to_s} appears to validates uniqueness of :#{@attribute}."
message << print_out_errors(@model)
end
def description
"validate uniqueness of #{@attribute}"
end
end
def validate_uniqueness_of(attr, options = { })
EdgeCase::RSpecExpectationMatchers::ProvidesFor::ActiveRecord::ValidatesUniquenessOf.new(attr, options)
end
end
end
end
end | true |
2222bde8c37c5afb3ef2efaf5c43cd17e198a620 | Ruby | ajLapid718/CodeWars-Problems | /6Kyu Kata/Numerical_Palindrome_Three_Point_Five.rb | UTF-8 | 1,788 | 4.3125 | 4 | [] | no_license | # A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are:
#
# 2332
# 110011
# 54322345
#
# For a given number num, write a function which returns an array of all the numerical palindromes contained within each number. The array should be sorted in ascending order and any duplicates should be removed.
#
# For this kata, single digit numbers and numbers which start and end with 0s (such as 010 and 000) will NOT be considered valid numerical palindromes.
#
# If num contains no valid palindromes, return "No palindromes found". Otherwise, return "Not valid" if the input is not an integer or is less than 0.
#
# palindrome(1221) => [22,1221]
# palindrome(34322122) => [22,212,343,22122]
# palindrome(1001331) => [33,1001,1331]
# palindrome(1294) => "No palindromes found"
# palindrome("1221") => "Not valid"
# Other Kata in this Series:
#
# Numerical Palindrome #1
# Numerical Palindrome #1.5
# Numerical Palindrome #2
# Numerical Palindrome #3
# Numerical Palindrome #3.5
# Numerical Palindrome #4
# Numerical Palindrome #5
def palindrome(num)
return "Not valid" if num.class == String || num < 0
arr = []
num.to_s.chars.each_index do |i|
num.to_s.chars.each_index do |j|
next if i == j
arr << num.to_s[i..j]
end
end
if arr.reject(&:empty?).select { |num| is_palindrome?(num) }.uniq.map(&:to_i).sort.tap { |op| op.delete(0) }.select { |num| is_palindrome?(num) }.empty?
return "No palindromes found"
else
arr.reject(&:empty?).select { |num| is_palindrome?(num) }.uniq.map(&:to_i).sort.tap { |op| op.delete(0) }.select { |num| is_palindrome?(num) }
end
end
def is_palindrome?(num)
(num.to_s == num.to_s.reverse) && (num.to_s.length != 1)
end
| true |
eb9292c2c418c66138eb14bc35c1e4175acd955b | Ruby | rscustom/rocksmith-custom-song-toolkit | /RocksmithToolkitCLI/generalscripts/sng-decrypt-cfb.rb | UTF-8 | 4,279 | 2.796875 | 3 | [] | no_license | require 'openssl'
require 'zlib'
def convert_key(key)
keystr = ''
key.each { |k|
a = k >> 24
b = k >> 16 & 0xff
c = k >> 8 & 0xff
d = k & 0xff
dword = sprintf('%c%c%c%c', d,c,b,a)
keystr += dword
}
return keystr
end
# AES-256-CFB, uninitialized IV
# TOC header key
toc = [ 0x38b23dc5, 0xf7a2a170, 0x0664ae1c, 0x110edd1f,
0xc89d3057, 0xc5d40452, 0x0925dfbf, 0x2c57f20d ]
$tockey = convert_key(toc)
# AES-256-CTR, 16 bytes of IV comes from data
# SNG key - Mac
sngmac = [0x0e332198, 0x701fb934, 0xbd8ca4d0, 0x12935962,
0xa0ce7069, 0xe6c09291, 0xcc76a6cd, 0x9d283898]
$sngmackey = convert_key(sngmac)
$sngwinkey = "\xCB\x64\x8D\xF3\xD1\x2A\x16\xBF\x71\x70\x14\x14\xE6\x96\x19\xEC\x17\x1C\xCA\x5D\x2A\x14\x2E\x3E\x59\xDE\x7A\xDD\xA1\x8A\x3A\x30"
$key = {
'xbox' => nil,
'mac' => $sngmackey,
'win' => $sngwinkey,
}
module AESCrypt
# Decrypts a block of data (encrypted_data) given an encryption key
# and an initialization vector (iv). Keys, iv's, and the data
# returned are all binary strings. Cipher_type should be
# "AES-256-CBC", "AES-256-ECB", or any of the cipher types
# supported by OpenSSL. Pass nil for the iv if the encryption type
# doesn't use iv's (like ECB).
#:return: => String
#:arg: encrypted_data => String
#:arg: key => String
#:arg: iv => String
#:arg: cipher_type => String
def AESCrypt.decrypt(encrypted_data, key, iv=nil, cipher_type="aes-256-cfb")
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.decrypt
aes.key = key
aes.iv = iv if iv != nil
#aes.iv = key[16...32]
aes.update(encrypted_data) + aes.final
end
# Encrypts a block of data given an encryption key and an
# initialization vector (iv). Keys, iv's, and the data returned
# are all binary strings. Cipher_type should be "AES-256-CBC",
# "AES-256-ECB", or any of the cipher types supported by OpenSSL.
# Pass nil for the iv if the encryption type doesn't use iv's (like
# ECB).
#:return: => String
#:arg: data => String
#:arg: key => String
#:arg: iv => String
#:arg: cipher_type => String
def AESCrypt.encrypt(data, key, iv=nil, cipher_type="aes-256-cfb")
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.encrypt
aes.key = key
aes.iv = iv if iv != nil
aes.update(data) + aes.final
end
end
def fread(fn)
return File.open(fn, 'rb').read()
end
def print_b(str, length=nil)
if not length
str.bytes.to_a.each { |x| printf "%02x ", x }
else
str.bytes.to_a[0...length].each { |x| printf "%02x ", x }
end
puts
end
def get_sng_data(data, platform)
payload = data[8...data.bytesize]
if $key[platform]
iv = payload[0...16]
cipher = payload[16...data.bytesize]
decrypted = ''
o = 0
while o < cipher.bytesize do
decrypted << AESCrypt.encrypt(cipher[o...o+16], $key[platform], iv, 'aes-256-cfb')
o += 16
# advance CTR IV
carry = true
j = iv.bytesize - 1;
while j>=0 && carry do
iv[j] = ((iv[j].ord + 1) % 256).chr
carry = (iv[j].ord == 0)? true : false
j -= 1
end
end
zblock = decrypted[4...decrypted.bytesize-56]
else
decrypted = payload
zblock = decrypted[4...decrypted.bytesize]
end
inf = Zlib::Inflate.new()
plain = inf.inflate(zblock)
if platform == 'win' or platform == 'mac'
size = decrypted[0...4].unpack('L')[0]
else
size = decrypted[0...4].unpack('N')[0]
end
if (plain.bytesize != size)
throw "expected size #{size}, got #{plain.bytesize}"
end
return [payload, iv, cipher, decrypted, plain, zblock]
end
def extract_sng(fn, platform, output=nil)
data = fread(fn)
payload, iv, cipher, decrypted, plain, zblock = get_sng_data(data, platform)
out = fn + '.sng'
out = output + File.basename(fn) + '.sng' if output
File.open(out, 'wb') {|f| f.write(plain)}
#puts "DECRYPTED"
#print_b(decrypted, 32)
# puts "ENCRYPTED SIGNATURE 56"
# (data.bytesize-56).upto(data.bytesize-1).each { |x| printf "%02x ", data[x].ord }
# puts "\nPLAIN SIGNATURE 56"
# (decrypted.bytesize-56).upto(decrypted.bytesize-1).each { |x| printf "%02x ", decrypted[x].ord }
# puts
end
if ARGV.length != 2 && ARGV.length != 3
puts "usage: #{$0} <mac/win/xbox> <sng file> [output directory]"
exit(1)
end
platform = ARGV[0]
input = ARGV[1]
output = ARGV[2]
extract_sng(input, platform, output)
| true |
7106b5565a2aab04439d77fce17521f2964b4c55 | Ruby | cunhasb/project-euler-multiples-3-5-web-100817 | /lib/primenumbers.rb | UTF-8 | 140 | 3.484375 | 3 | [] | no_license | require 'pry'
def prime(n)
is_prime = true
(2...n).each do |i|
if n% i == 0
is_prime = false
break
end
end
is_prime
end
| true |
d1c49f2bc6427b6249661719ccf1231da193f4b9 | Ruby | Foreversparce1/Fundamentos-2013 | /TallerPC03/ejecicio01.rb | UTF-8 | 1,605 | 3.546875 | 4 | [] | no_license | =begin
Una persona tiene un dinero que ha heredado. Necesita tomar la decisión de dónde colocarlo para que le rinda una rentabilidad adecuada. Para esto, ha investigado que un banco le puede ofrecer por su dinero en modalidad a Plazo Fijo, una atractiva oferta.
La oferta consiste en tener tasas de interés escalonadas por el tiempo que su dinero estará sin moverlo a una tasa flat (es decir, el interés se calcula por el monto * tasa /100). La tasa inicial ofrecida, se le aumenta un punto porcentual por cada tres meses de permanencia y es con capitalización mensual.
Por ejemplo: con un capital de 1000, una tasa de 10% mensual en 3 meses. Capitalización mensual ganará lo siguiente.
1000 * 0.10 = 100
1100 * 0.10 = 110
1210 * 0.11 = 131.10
343.10 es lo que ganará la persona al cabo de 3 meses
Desarrollar un subprograma que determine el interés total que ganará la persona.
=end
def calcularInteresTotal(meses,monto,tasa)
total = 0
for i in 1..meses
if i % 3 == 0
tasa = tasa + 1
end
interes = monto * tasa / 100
total = total + interes
monto = monto + interes
end
total.round(2)
end
#--- zona de test ----
def test_calcularInteresTotal
print validate(343.10, calcularInteresTotal(3,1000.00,10.0))
print validate(85.13, calcularInteresTotal(5,130.00,10.0))
print validate(182.40, calcularInteresTotal(9,112.10,10.0))
end
def validate (expected, value)
expected == value ? "." : "F"
end
def test
puts "Test de prueba del programa"
puts "---------------------------"
test_calcularInteresTotal
puts " "
end
test
| true |
7f1efaff53515920efbb91a4f3ad899aa11365ed | Ruby | Efutei/atcoder | /ABC100/ringo.rb | UTF-8 | 161 | 2.921875 | 3 | [] | no_license | a,b=gets.chomp.split(" ").map(&:to_i)
if b==100 then
b += 1
end
if a == 0 then
ans = b
elsif a == 1 then
ans = b * 100
else
ans = b * 10000
end
puts ans
| true |
bd63462f25ca4e71f0196ca42265947376d056c6 | Ruby | gaohongwei/ruby_tool | /array.rb | UTF-8 | 219 | 3.15625 | 3 | [] | no_license | These applys to Enumerable and array
########## map ##########
ar.map(&:name)
ar.map{|x|x.name}
########## any?, all? ##########
It takes a block
The default block {|x|x} if no block provided
The block returns a bool
| true |
8b7850a2c7dd306f6929ba01b6e0ed084b2fc09b | Ruby | gively/mdex_client | /lib/mdex_client/mdata/record.rb | UTF-8 | 1,416 | 2.546875 | 3 | [
"MIT"
] | permissive | require 'mdex_client/mdata/node'
module MDEXClient
module MData
class Record < Node
class Attributes < Hash
def initialize(*args)
super(*args)
@dimension_value_ids = {}
@dimension_ids = {}
end
def dimension_value_id(key)
@dimension_value_ids[key]
end
def dimension_id(key)
@dimension_ids[key]
end
def dimension_keys
@dimension_ids.keys
end
def property_keys
keys - dimension_keys
end
def <<(node)
key = node["Key"]
self[key] = node.text
if node.name == "AssignedDimensionValue"
@dimension_value_ids[key] = node["Id"]
@dimension_ids[key] = node["DimensionId"]
end
end
end
attr_accessor :id, :attributes, :snippets
def initialize(element_or_hash=nil)
@attributes = Attributes.new
super(element_or_hash)
end
def initialize_from_element!
@id = @element["Id"]
xpath("mdata:Attributes/mdata:AssignedDimensionValue | mdata:Attributes/mdata:Property").each do |attribute|
@attributes << attribute
end
@snippets = property_list("mdata:Snippets/mdata:Snippet")
end
end
end
end
| true |
417d8f48ea0eb2ec55a6d72e5303a317fac925c1 | Ruby | MariaMancipe/smart-tools | /lib/test_converter.rb | UTF-8 | 1,823 | 2.59375 | 3 | [] | no_license | require 'streamio-ffmpeg'
require 'mysql2'
require 'fileutils'
$original = "#{ENV['VIDEO_ORIGINAL']}"
$converted = "#{ENV['VIDEO_CONVERTED']}"
$upload = "#{ENV['VIDEO_UPLOAD']}"
def convert_to_mp4_five(path)
puts "convert to mp4 #{path}"
movie = FFMPEG::Movie.new(path)
converted = "./public/video/converted/"
new_path = File.basename(path)
new_path = $converted+ new_path[0,new_path.length-4]
movie.transcode("#{new_path}.mp4", %w(-acodec aac -vcodec h264 -strict -2 -threads 5 -threads 5))
end
def convert_to_mp4_ten(path)
puts "convert to mp4 #{path}"
movie = FFMPEG::Movie.new(path)
converted = "./public/video/converted/"
new_path = File.basename(path)
new_path = $converted+ new_path[0,new_path.length-4]
movie.transcode("#{new_path}.mp4", %w(-acodec aac -vcodec h264 -strict -2 -threads 10 -threads 10))
end
def convert_to_mp4_twenty(path)
puts "convert to mp4 #{path}"
movie = FFMPEG::Movie.new(path)
converted = "./public/video/converted/"
new_path = File.basename(path)
new_path = $converted+ new_path[0,new_path.length-4]
movie.transcode("#{new_path}.mp4", %w(-acodec aac -vcodec h264 -strict -2 -threads 20 -threads 20))
end
def search_files
Dir.mkdir($original) unless File.exist?($original)
Dir.mkdir($converted) unless File.exist?($converted)
start = Time.now
Dir.entries($upload).select {|f| convert_to_mp4_five($upload+f) unless File.directory?(f)}
last = Time.now
puts "5 Threads in #{last-start}"
start = Time.now
Dir.entries($upload).select {|f| convert_to_mp4_ten($upload+f) unless File.directory?(f)}
last = Time.now
puts "10 Threads in #{last-start}"
start = Time.now
Dir.entries($upload).select {|f| convert_to_mp4_twenty($upload+f) unless File.directory?(f)}
last = Time.now
puts "20 Threads in #{last-start}"
end
search_files | true |
991ebfa6b7d5d2ef733afd05c3f643cd6d241e12 | Ruby | heroku/configvar | /test/helper.rb | UTF-8 | 495 | 2.734375 | 3 | [
"MIT"
] | permissive | module EnvironmentHelper
# Override an environment variable in the current test.
def set_env(key, value)
overrides[key] = ENV[key] unless overrides.has_key?(key)
ENV[key] = value
end
# Restore the environment back to the state before tests ran.
def teardown
overrides.each do |key, value|
ENV[key] = value
end
super
end
private
# The overridden environment variables to restore when the test finishes.
def overrides
@overrides ||= {}
end
end
| true |
1f66d995b1ede1ec5600614dccdb22432e815d2b | Ruby | pzb/r509 | /lib/r509/openssl/pkey_ecdsa.rb | UTF-8 | 5,903 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | # vim: set sts=2 ts=2 sw=2 et:
if defined?(OpenSSL::PKey::EC) && !defined?(OpenSSL::PKey::EC::UNSUPPORTED)
module OpenSSL::PKey
class ECDSA < OpenSSL::PKey::EC
@initialized = false
def self.generate(arg)
if (arg.kind_of? String) || (arg.kind_of? Symbol)
curve_name = arg.to_s
if !OpenSSL::PKey::EC.builtin_curves.any?{|c|c[0] == curve_name}
raise OpenSSL::PKey::ECError, "unknown curve name (#{curve_name})"
end
group = OpenSSL::PKey::EC::Group.new(curve_name)
elsif arg.kind_of? OpenSSL::PKey::EC::Group
group = arg
else
raise OpenSSL::PKey::ECError, "Must provide group or curve"
end
self.new(group)
end
# Takes two inputs, ec_param and ec_point, as per PKCS#11
def self.from_pkcs11(ec_param, ec_point)
params = OpenSSL::ASN1::Sequence.new([
OpenSSL::ASN1::ObjectId.new("1.2.840.10045.2.1"), # id-ecPublicKey
ec_param
])
# OpenSSL wants a BitString for the point, PKCS#11 gives OctetString
# So decode and rebuild
pubkey = OpenSSL::ASN1::Sequence.new([
params,
OpenSSL::ASN1::BitString.new(OpenSSL::ASN1.decode(ec_point).value)
])
self.new(pubkey.to_der)
end
# trick to track whether arg was passed is from
# http://stackoverflow.com/q/23765914
# Generates or loads an ECDSA keypair.
# If arg is a Group, then it generates a new key using that group
# The second parameter can be a Point, which will make a public key
# If arg is a Point, then it becomes a public key
# If arg is a symbol, then is generates a new key using that as the
# group name
# If arg is a string, then it tries to use that as name of a file
# contain PEM or DER enoded data; failing that it is the literal
# PEM or DER encoded data
def initialize(arg, pass = (no_pass = true; nil))
if arg.kind_of? OpenSSL::PKey::EC::Group
if !pass.nil?
if !pass.kind_of OpenSSL::PKey::EC::Point
raise OpenSSL::PKey::ECError, "only a Point is allowed when supplying group"
elsif !pass.group.eql? arg
raise OpenSSL::PKey::ECError, "Point group does not match requested group"
end
end
super(arg)
if pass.nil?
self.generate_key
else
self.pub_key = pass
end
elsif arg.kind_of? OpenSSL::PKey::EC::Point
# Points have a group, so we have all we need
super(arg.group)
self.pub_key = arg
elsif arg.is_a? OpenSSL::PKey::EC
# "Cast" to ECDSA
if !pass.nil?
raise OpenSSL::PKey::ECError, "password not allowed when supplying key"
end
if !(arg.public_key? || arg.private_key?)
raise OpenSSL::PKey::ECError, "key has not been generated"
end
super(arg.group)
if arg.public_key?
self.pub_key = arg.public_key
end
if arg.private_key?
self.priv_key = arg.private_key
end
elsif arg.kind_of? String
if no_pass
super(arg)
else
super(arg, pass)
end
if !(self.public? || self.private?)
raise OpenSSL::PKey::ECError, "Neither PUB key nor PRIV key found"
end
self.check_key
elsif arg.kind_of? Symbol
if !pass.nil?
raise OpenSSL::PKey::ECError, "password not allowed when supplying curve name"
end
curve_name = arg.to_s
if !OpenSSL::PKey::EC.builtin_curves.any?{|c|c[0] == curve_name}
raise OpenSSL::PKey::ECError, "unknown curve name (#{curve_name})"
end
# Explicitly create the group to ensure EC.new makes the right
# decision on what we are doing (EC::Group.new could still get
# confused)
group = OpenSSL::PKey::EC::Group.new(curve_name)
super(group)
self.generate_key
else
raise OpenSSL::PKey::ECError, "Neither PUB key nor PRIV key"
end
@initialized = true
end
def generate_key
super
self.check_key
end
def group=(*args)
if @initialized
raise OpenSSL::PKey::ECError, "Changing group is not permitted"
end
super(*args)
end
def private?
self.private_key?
end
def public?
self.public_key?
end
# Allow the "raw" public key to be accessed via pub_key
alias_method :pub_key, :public_key
alias_method :priv_key, :private_key
# A point
def pub_key=(arg)
if !arg.kind_of? OpenSSL::PKey::EC::Point
raise OpenSSL::PKey::ECError, "public key must be a Point"
end
if !self.group.eql? arg.group
raise OpenSSL::PKey::ECError, "Point group does not match existing group"
end
if arg.infinity?
raise OpenSSL::PKey::ECError, "Refusing to use point-at-infinity"
end
if !arg.on_curve?
raise OpenSSL::PKey::ECError, "Refusing to use a point not on the curve"
end
self.public_key = arg
self.check_key
self.pub_key
end
def priv_key=(arg)
if !arg.kind_of? OpenSSL::BN
raise OpenSSL::PKey::ECError, "private key must be a BN"
end
self.private_key = arg
self.check_key
self.priv_key
end
def public_key
OpenSSL::PKey::ECDSA.new(self.pub_key)
end
def params
hash = {}
hash["group"] = self.group
hash["pub_key"] = self.pub_key
hash["priv_key"] = self.priv_key
hash
end
end
end
end
| true |
43c686d7d0f5a272e8a43805e08824ee820a0750 | Ruby | gloriasoh/exercises | /hello_world.rb | UTF-8 | 50 | 2.828125 | 3 | [] | no_license | result = 2 + 2
puts "The number is #{result + 4}"
| true |
e8312a0e4c5391ff627ebb7525c3feb20415ed63 | Ruby | ezgiyuksektepe/antfarm | /Meadow.rb | UTF-8 | 4,365 | 3.359375 | 3 | [] | no_license | require 'colorize'
require 'set'
require 'singleton'
require_relative 'Cell'
require_relative 'EventStore'
require_relative 'Queen'
class Meadow
include Singleton
attr_reader :num_cols
attr_reader :num_rows
attr_reader :num_queens
attr_reader :max_ants_per_hill
attr_reader :grid
def initialize
# Meadow configuration
@num_rows = 15
@num_cols = 15
@num_queens = 4
@max_ants_per_hill = @num_rows
@grid = Array.new(@num_rows) {|row| Array.new(@num_cols) {|col| Cell.new(row, col)}}
@queens = Array.new(@num_queens) {|index| Queen.new(self, index)}
# Release all queens so they can build hills
@queens.each {|q| q.release}
end
def getCell(row, col)
if row < 0 || col < 0 || row > @num_rows - 1 || col > @num_cols - 1
raise "Invalid position #{row},#{col}"
end
@grid[row][col]
end
def getRandomCell
row = rand(0...@num_rows)
col = rand(0...@num_cols)
@grid[row][col]
end
def placeFood
cell = getRandomCell
cell.addFood(1)
end
def processTurn
processAnts
processHills
end
def processHills
for row in (0...@num_rows)
for col in (0...@num_cols)
cell = @grid[row][col]
# If there's a hill, let it take the its turn
if cell.hill != nil
cell.hill.processTurn
end
end
end
end
def processAnts
ants_took_turns = Set.new
for row in (0...@num_rows)
for col in (0...@num_cols)
cell = @grid[row][col]
ants_in_cell = cell.getAnts
for ant in ants_in_cell
# If ant has taken turns skip it
next if ants_took_turns.include?(ant)
# Move the ant
move_intent = ant.getMoveIntent
new_row = row + move_intent[0]
new_col = col + move_intent[1]
# Check grid limits
if new_row < 0 || new_row > @num_rows - 1
new_row = row
end
if new_col < 0 || new_col > @num_cols - 1
new_col = col
end
new_cell = @grid[new_row][new_col]
# Remove from the old cell and add it to the new one
ants_in_cell.delete(ant)
new_cell.getAnts.push(ant)
# Update the cell variable in ant
ant.setCurrentCell(new_cell)
# Let ant take its turn
ant.processTurn
ants_took_turns.add(ant)
end
end
end
end
def checkEndStates
num_active_colonies = 0
last_active_colony = nil
for i in (0..@num_queens)
hill = getAnthillForColony(i)
if hill != nil
num_active_colonies += 1
last_active_colony = i
ants = getAntsForColony(i)
if ants.find { |a| a.type == Ant::TYPE_FORAGER } == nil
EventStore.instance.pushEvent "Colony #{i} doesn't have any foragers left."
destroyColony(i)
end
end
end
if num_active_colonies == 1
EventStore.instance.pushEvent "Winning colony is #{Colors.colorizeForColony(last_active_colony, last_active_colony)}!!"
Game.instance.keep_running = false
elsif num_active_colonies < 1
EventStore.instance.pushEvent "All colonies were destroyed!".on_red
Game.instance.keep_running = false
end
end
def destroyColony(colony)
EventStore.instance.pushEvent "Destroying colony #{Colors.colorizeForColony(colony, colony)}"
hill = getAnthillForColony(colony)
ants = getAntsForColony(colony)
hill.destroy
ants.each { |a| a.kill }
end
def getAntsForColony(colony)
results = []
for row in (0...@num_rows)
for col in (0...@num_cols)
cell = @grid[row][col]
ants_in_cell = cell.getAnts
ants = ants_in_cell.select {|ant| ant.colony == colony }
if ants.length != 0
results += ants
end
end
end
results
end
def getAnthillForColony(colony)
for row in (0...@num_rows)
for col in (0...@num_cols)
cell = @grid[row][col]
if cell.hill != nil && cell.hill.colony == colony
return cell.hill
end
end
end
return nil
end
def findCellOfAnt(ant)
for row in (0...@num_rows)
for col in (0...@num_cols)
cell = @grid[row][col]
if cell.getAnts.include?(ant)
return cell
end
end
end
return nil
end
end
| true |
79e388c75ea2654342c6d9bfba1fd2fb3b48245a | Ruby | mymorkkis/ricks-music-stock-app | /specs/album_specs.rb | UTF-8 | 358 | 2.65625 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/rg'
require_relative '../models/album'
class TestAlbums < MiniTest::Test
def setup
@album1 = Album.new('title' => 'The Black Album', 'year' => 2003)
end
def test_album_title
assert_equal('The Black Album', @album1.title)
end
def test_album_year
assert_equal(2003, @album1.year)
end
end | true |
c6641d7a7db5c34e8f2b1c0d1223ea5ff4fafd24 | Ruby | bengler/tilt-jadeite | /benchmarks/benchmarks.rb | UTF-8 | 1,339 | 2.9375 | 3 | [
"MIT"
] | permissive | require 'bundler'
Bundler.require
require 'benchmark'
require 'haml'
require 'tilt-jadeite'
class Scope
def foo(what)
"Foo says #{what}"
end
def play(artist, song)
"Play #{song} from #{artist}"
end
def say_hello
"Hello to you!"
end
def fruity_song
"banana-na-na-na-na-na"
end
def development
true
end
end
proxied = Scope.new
data = {
:foo => proc { |what|
proxied.send(:foo, what)
},
:play => proc { |artist, song|
proxied.send(:play, artist, song)
},
:say_hello => "Hello World",
:fruity_song => proxied.fruity_song,
:development => proxied.development
}
FILES = %w(simple.jade template.jade template.haml template.erb large.jade large.haml large.erb)
def measure(times, title, &blk)
puts
puts "=== #{title} - #{times} times each"
FILES.each do |f|
puts "=> #{f}"
blk.call(times, f, Tilt[f])
puts
end
end
measure 1000, "Initialize + render" do |times, file, template_class|
puts Benchmark.measure {
times.times do
scope = Scope.new
template = template_class.new(file)
template.render(scope, data)
end
}
end
measure 1000, "Render only" do |times, file, template_class|
template = template_class.new(file)
puts Benchmark.measure {
scope = Scope.new
times.times { template.render(scope, data) }
}
end
| true |
7ce199ac0c198dd91ff8e5b74918664094971f35 | Ruby | dorton/tarantino | /app/models/profane_word.rb | UTF-8 | 333 | 3.0625 | 3 | [] | no_license | class ProfaneWord
def initialize(movie)
@movie = movie
end
def all_words
all_words = @movie.datasets.all.map { |a| a.profane_word }
end
def the_words
unique_words_array = all_words.uniq
end
def word_counts
the_words.each do |word|
all_words.select {|a| a == word }.count
end
end
end
| true |
3829ab0f3ebf082e5f1365bb38c52bb25c2aab20 | Ruby | WMudgeEllis/relational_rails | /app/models/book.rb | UTF-8 | 247 | 2.59375 | 3 | [] | no_license | class Book < ApplicationRecord
belongs_to :bookshelf
def self.read_books
Book.where(read: true)
end
def self.alphabetize
Book.order(:name)
end
def self.min_read_time(min)
Book.where("books.read_time > #{min}")
end
end
| true |
cbc4712274dc925f4aaddcadf83746f0da48a472 | Ruby | oconetta/archive.org-getter | /tv_data_analysis.rb | UTF-8 | 886 | 3.34375 | 3 | [] | no_license | require 'rubygems'
require 'json'
require 'pp'
#parse data from JSON files and store in array of hashes
tv_data = JSON.parse(File.read('TVNews_results200.json'))
tv_data += JSON.parse(File.read('TVNews_results400.json'))
tv_data += JSON.parse(File.read('TVNews_results600.json'))
tv_data += JSON.parse(File.read('TVNews_results800.json'))
tv_data += JSON.parse(File.read('TVNews_results1000.json'))
#create empty array to store topics in
topics = []
tv_data.each { |hash| hash["topic"] }.each do |key, value|
key.each do |k, v|
if k == "topic"
topics.push(v)
else
nil
end
end
end
#array of a hash of an array of strings
topics = topics.flatten
frequencies = Hash.new(0)
topics.each { |word| frequencies[word] += 1 }
frequencies = frequencies.sort_by { |a, b| b }
frequencies.reverse!
frequencies.each { |word, frequency| puts word + ": " + frequency.to_s } | true |
d6c210db89f3f9da08b318454c6e986550d306e8 | Ruby | Technici4n/beoi-training-1 | /scripts/json_build_units/json_build_units.rb | UTF-8 | 4,179 | 2.84375 | 3 | [] | no_license | #
# Script to build README.md files from JSON files
# You might need the "json" gem to run it
#
require 'pathname'
unless require 'json'
puts 'You need to install the json gem !'
exit
end
require_relative 'network_util'
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
MAIN_DIR = '../../'
MAIN_README = MAIN_DIR + '/README.md'
# A unit is in its JSON representation, with the "path" member holding the path to the unit
units = {}
# Generally 'README.md', 'README-nl.md' or 'README-fr.md'
filename = '/README.md'
path_filename = ''
# Generally '', '-nl' or '-fr'
lang = ''
# Locale
locale = {}
# Detect all units, and get various information
define_method :build_units do
# Units
dirs = Dir[MAIN_DIR + '*'].select{|f| File.directory? f}.select{|f| File.basename(f)[0..1].is_i?}
puts "Found #{dirs.size} units."
dirs.each do |dir|
if File.exists?(dir + '/unit.json')
unit = JSON.parse(File.open(dir + '/unit.json', 'r:UTF-8', &:read))
unit['path'] = dir
if lang && lang != '' && File.exists?(dir + "/unit#{lang}.json")
unit.merge!(JSON.parse(File.open(dir + "/unit#{lang}.json", 'r:UTF-8', &:read)))
end
units[unit['unit']] = unit
end
end
# Put the result in units.json, so it can be used by other APIs
main_dir_path = Pathname.new(MAIN_DIR)
if lang == ''
File.open(MAIN_DIR + 'units.json', 'w:UTF-8') do |file|
file.write(units.map{|k, v| [k, v['title'], Pathname.new(v['path']).relative_path_from(main_dir_path)]}.to_json)
end
end
end
# Create the README.md file for a unit
define_method :create_unit_readme do |unit|
# Title
header = locale['header'].dup
header['{0}'] = unit['unit'].to_s
header['{1}'] = unit['title']
out = header + "\n"
# Description
out << unit['description'].join("\n") << "\n\n"
# Prerequisites
if unit['prerequisites'] && unit['prerequisites'].class == Array && unit['prerequisites'].size > 0
out << locale['prerequisites'] + "\n"
unit['prerequisites'].each do |u|
utxt = locale['unit'].dup
utxt['{0}'] = u.to_s
utxt['{1}'] = get_unit_path(u, unit['path'])
out << utxt + "\n"
end
out << "\n"
end
# Problems
if unit['problems'] && unit['problems'].class == Array && unit['problems'].size > 0
out << locale['problems'] + "\n"
unit['problems'].each do |p|
base_link = ""
case p[0]
when "uva"
base_link = "- #{NetworkUtil::Uva::get_problem_url p[1]}"
when "codeforces"
base_link = "- #{NetworkUtil::Codeforces::get_problem_url p[1]}"
when "any" # Allow text problems (from previous IOIs for instance)
base_link = "- #{p[1]}"
when "title" # Allow sections
base_link = "\n### #{locale[p[1]] || p[1]}"
end
if p[2]
base_link << " (#{locale[p[2]] || p[2]})"
end
out << "#{base_link}\n"
end
end
# Save file
File.open(unit['path'] + filename, 'w:UTF-8') do |file|
file.write(out)
end
end
# Create the main README.md file
define_method :create_main_readme do
# Header
out = locale['main_readme'].join("\n") + "\n"
# Units
units.each do |k, u|
out << "#{k}. #{get_unit_path(u["unit"], MAIN_DIR)}\n"
end
# Save file
File.open(MAIN_DIR + filename, 'w:UTF-8') do |file|
file.write(out)
end
end
# Get unit path
define_method :get_unit_path do |unit_id, curr_path|
unit = units[unit_id]
if unit
curr = Pathname.new(curr_path)
unit_path = Pathname.new(unit['path'] + path_filename)
out = "[#{unit['title']}](#{unit_path.relative_path_from(curr)})"
if unit['short_description'] != ''
out << " (#{unit['short_description']})"
end
out
else
'<?>'
end
end
#
# MAIN
#
define_method :compile do
build_units
create_main_readme
units.each do |k, u|
create_unit_readme u
end
end
# Problem info
NetworkUtil::Uva::initialize
NetworkUtil::Codeforces::initialize
# Localization
locales = JSON.parse(File.open('locales.json', 'r:UTF-8', &:read))
# General
puts 'Building EN'
locale = locales['en']
compile
# FR
puts 'Building FR'
filename = '/README-fr.md'
path_filename = '/README-fr.md'
lang = '-fr'
locale = locales['fr']
compile
# NL
puts 'Building NL'
filename = '/README-nl.md'
path_filename = '/README-nl.md'
lang = '-nl'
locale = locales['en']
compile
| true |
948371d2f05e57553eff58bb096ca33937f9640c | Ruby | at1as/terminal-rubiks | /printer.rb | UTF-8 | 3,268 | 3.21875 | 3 | [
"MIT"
] | permissive | module Printer
def draw_row(row)
'| ' + row.join(' | ') + ' |'
end
def draw_separator(len, offset = 0)
puts offset + '-' * len
end
def print_cell(cell, offset: 0, top: true, bottom: true)
width = 0
spacing = ' ' * offset
cell.each_with_index do |row, idx|
current_row = draw_row(row)
width = current_row.uncolorize.length
draw_separator(width, spacing) unless idx == 0 && !top
puts spacing + draw_row(row)
end
draw_separator(width, spacing) if bottom
end
def print_cells(cell_blocks)
rows_per_cell = cell_blocks.first.length - 1
seperator = nil
0.upto(rows_per_cell) do |row_num|
seperator = 0
current_row = ['| ']
cell_blocks.each do |face|
current_row << face[row_num].join(' | ') + ' | '
end
seperator = current_row.inject(:+).uncolorize.length
puts '-' * seperator
print current_row.join('') + "\n"
end
puts '-' * seperator
end
def print_current_face
print "\n Current Face: \n"
print_cell(@cube[2])
print "\n"
end
def print_flat_cube
<<-DETAILS
Print a flat 2D rendition of the current Rubiks cube
in the following format:
TOP
LEFTSIDE FRONT RIGHTSIDE BACK
BOTTOM
DETAILS
print_cell(@cube.last, offset: 18, top: true, bottom: false)
print_cells(@cube[1..-2])
print_cell(@cube.first, offset: 18, top: false, bottom: true)
end
def print_flat_cube_vertical
<<-DETAILS
Print a flat 2D rendering of current Rubiks cube
in the following format:
BACK
TOP
LEFTSIDE FRONT RIGHTSIDE
BOTTOM
DETAILS
back = @cube[-2].clone.map { |x| x.reverse }.reverse
print_cell(back, offset: 18, top: true, bottom: false)
print_cell(@cube.last, offset: 18, top: true, bottom: false)
print_cells(@cube[1..-3])
print_cell(@cube.first, offset: 18, top: false, bottom: true)
end
def print_3d_cube
front, side, top = @cube[1], @cube[2], @cube[5]
f = front.flatten
s = side.flatten
t = top.flatten
cube = <<-CUBE
-------------------------- \\
/ #{t[0]} / #{t[1]} / #{t[2]} / |
/ / / / #{s[2]} |
/---------------------- +\\ /|
/ #{t[3]} / #{t[4]} / #{t[5]} / | / |
/ / / / | / |
/-----------------------+ #{s[1]}|/ |
/ #{t[6]} / #{t[7]} / #{t[8]} / | /| #{s[5]}|
/ / / / | / | /|
+----------------------- #{s[0]}/ | / |
| | | | /|#{s[4]} / |
| #{f[0]} | #{f[1]} | #{f[2]} | / | /| |
| | | |/ | / |#{s[8]}|
+-----------------------+ |/ | /
| | | |#{s[3]}/ | /
| #{f[3]} | #{f[4]} | #{f[5]} | /|#{s[7]}|/
| | | | / | /
+-----------------------+/ | /
| | | | | /
| #{f[6]} | #{f[7]} | #{f[8]} |#{s[6]}|/
| | | | /
+-----------------------+ -/
CUBE
puts ?\n + cube + ?\n
end
def inspect_cube
puts @cube.inspect
end
end
| true |
d837c55c695db38c462d291dc31940342d60120d | Ruby | nagerz/SweaterWeather | /app/facades/forecast_facade.rb | UTF-8 | 934 | 2.84375 | 3 | [] | no_license | # frozen_string_literal: true
class ForecastFacade
attr_reader :location, :forecast
def initialize(location)
@location = location
@forecast = make_forecast(search_city(geodata))
end
def geolocation
geocode_service.geocode(@location)
end
def geodata
data = {}
data[:geo_lat] = geolocation[:results][0][:geometry][:location][:lat]
data[:geo_long] = geolocation[:results][0][:geometry][:location][:lng]
data[:geo_city] = geolocation[:results][0][:address_components][0][:long_name]
data[:geo_state] = geolocation[:results][0][:address_components][2][:short_name]
data
end
def search_city(data)
City.find_or_create_by(lat: data[:geo_lat], long: data[:geo_long]) do |city|
city.city = data[:geo_city]
city.state = data[:geo_state]
end
end
def make_forecast(city)
Forecast.new(@location)
end
def geocode_service
GoogleMapsService.new
end
end
| true |
99a4d8a226bcd6a5aec45a5d7a1828bfeeb2bbb3 | Ruby | metalerk/distritos-electorales-mx | /seccion | UTF-8 | 2,554 | 2.6875 | 3 | [] | no_license | #!/usr/bin/env ruby
# encoding: utf-8
require_relative 'lib/common.rb'
require 'ruby-progressbar'
Crawler.max_concurrency = 200
secciones = Crawler::Runner.new URL_SECCIONES
secciones.request_parser = -> (request){
self.method = :post
self.body = {
e: data[:entidad],
q: data[:seccion],
t: 'seccion',
c: 'SECCION',
l: '0'
}
}
secciones.response_parser = -> (body) {
data = body.split('|').last
json = JSON.parse(data, symbolize_names: true)
geom = json[:valores].first[:geom]
geom.scan(%r{\(\(([^\(\)]+)\)\)}).map { |polygon|
polygon[0].split(',').map {|punto| punto.split(' ').map(&:to_f)}
}
}
base_path = File.dirname(__FILE__)
file_distritos = File.expand_path './data/distritos.json', base_path
if !File.exists? file_distritos
puts "Buscando secciones por distrito"
require_relative './distritos'
end
entidades = JSON.parse(File.read(file_distritos), symbolize_names: true)
requests = []
entidad_key = ARGV[0].to_sym
entidad = entidades[entidad_key]
fname = "#{entidad_key.to_s.rjust(2, '0')}-#{entidad[:nombre]}"
entidad[:distritos].each {|id, dto|
requests.concat dto[:secciones].map {|s| {entidad: entidad_key, seccion: s} }
}
file_secciones = File.expand_path "./data/secciones-#{fname}.json", base_path
puts "Buscando geometría de #{requests.count} secciones"
geo = []
pb_opts = {
title: 'Secciones',
starting_at: 0,
total: requests.count,
format: '%t: %c |%B| %f',
throttle_rate: 0.1
}
bar = ProgressBar.create(pb_opts)
begin
puts "Empezando crawl con #{Crawler.max_concurrency} requests simultáneos"
puts ""
secciones.run requests do |request, response|
seccion = {
_id: "#{request.data[:entidad]}-#{request.data[:seccion]}",
entidad: request.data[:entidad].to_s.to_i,
seccion: request.data[:seccion],
coords: {}
}
begin
polygons = response.body
rescue Exception => e
puts e.backtrace.reverse
puts e
exit 1
# return
end
if polygons.count == 1
seccion[:coords] = {
type: 'Polygon',
coordinates: [
[
polygons.first
]
]
}
else
polygons = polygons.map {|pol| [[pol]]}
seccion[:coords] = {
type: 'MultiPolygon',
coordinates: [
polygons
]
}
end
geo << seccion
bar.increment
end
rescue Crawler::Error::HTTP => e
puts e
exit 1
rescue Crawler::Error::Timeout => e
puts e
exit 1
end
File.open file_secciones, 'w' do |f|
f << geo.to_json
end | true |
422d7ab1d2b6af3dde8eade0305b49e0521cdfb8 | Ruby | tmikeschu/yahtzee | /test/yahtzee/getters_test.rb | UTF-8 | 632 | 2.90625 | 3 | [] | no_license | require "minitest/autorun"
require "yahtzee/getters"
module Yahtzee
class TestStore
include Getters
attr_reader :state
def initialize(hands = {})
@state = {hands: hands}
end
end
class GettersTest < Minitest::Test
def test_total_score_returns_0_initially
store = TestStore.new
actual = store.total_score
expected = 0
assert_equal actual, expected
end
def test_total_score_returns_sum_of_values
store = TestStore.new({ones: 3, twos: 2, full_house: nil})
actual = store.total_score
expected = 5
assert_equal actual, expected
end
end
end
| true |
a268970cacdfd9ac78d83ccf274900f174978f2f | Ruby | Nick-Howlett/W2D1 | /chess/display.rb | UTF-8 | 1,580 | 3.34375 | 3 | [] | no_license | require "colorize"
require_relative "cursor"
require_relative "board"
require "byebug"
class Display
attr_accessor :possible_moves, :board
def initialize(board)
@board = board
@cursor = Cursor.new([0,0], board)
@possible_moves = []
end
def render
puts(" " + %w(0 1 2 3 4 5 6 7).join(" "))
cursor.board.grid.each_with_index do |row, i|
print("#{i} ")
row.each_with_index do |el, j|
if [i, j] == cursor.cursor_pos
cursor.selected ? color = :red : color = :yellow
elsif possible_moves.include?([i, j])
color = :red
elsif i % 2 == j % 2
color = :light_blue
else
color = :green
end
string = el.to_s
piece_color = el.color
print " #{string} ".colorize(:color => piece_color, :background => color)
end
puts
end
nil
end
def do_loop
while true
system("clear")
render
pos = cursor.get_input
if pos
@possible_moves += board[pos].moves
else
@possible_moves = []
end
system("clear")
render
end
end
private
attr_reader :cursor
end
if __FILE__ == $PROGRAM_NAME
board = Board.new
display = Display.new(board)
board[[3,3]] = Queen.new([3,3], board, :white)
display.do_loop
end | true |
b0ed34a2286a5165b21f4541869288c7130221cb | Ruby | baseonmars/boffin_tag | /library_tagger.rb | UTF-8 | 982 | 2.734375 | 3 | [] | no_license | require 'rubygems'
require 'id3lib'
require 'sqlite3'
db = SQLite3::Database.new( "LC.db" )
rows = db.execute("SELECT f.id, d.path, f.filename from files f INNER JOIN directories d on f.directory = d.id")
rows.each_with_index do |row,index|
puts "#{index}/#{rows.size} processing file /#{row[1]}#{row[2]}"
filetags = db.execute("SELECT f.id, f.filename, t.name, tt.weight FROM tracktags tt inner join files f on f.id = tt.file join tags t on tt.tag = t.id where f.id = ? order by tt.weight DESC", row[0])
if filetags.size > 0
top_tag = filetags.shift
tag = ID3Lib::Tag.new("/#{row[1]}#{row[2]}")
tag.genre = top_tag[2]
filetags.each do |filetag|
tag.comment = "#{tag.comment}\nlfm:tag:#{filetag[2]}"
end
puts "#{tag.title}: #{top_tag[2]}"
tag.update!
else
puts "not enough tag data"
end
end
# for each file
# load tag
# write primary tag to genre
# write other tags somewhere else
# save tag
# print progress to screen
| true |
e18d104fa2031ed4d0f81e9ea30f85393d143540 | Ruby | wrozka/capybara-angular | /lib/capybara/angular/waiter.rb | UTF-8 | 1,059 | 2.578125 | 3 | [
"MIT"
] | permissive | module Capybara
module Angular
class Waiter
WAITER_JS = IO.read(File.expand_path "../waiter.js", __FILE__)
attr_accessor :page
def initialize(page)
@page = page
end
def wait_until_ready
return unless driver_supports_js?
start = Time.now
until ready?
inject_waiter
timeout! if timeout?(start)
sleep(0.01)
end
end
private
def driver_supports_js?
page.evaluate_script "true"
rescue Capybara::NotSupportedByDriverError
false
end
def timeout?(start)
Time.now - start > Capybara::Angular.default_max_wait_time
end
def timeout!
raise Timeout::Error.new("timeout while waiting for angular")
end
def inject_waiter
return if page.evaluate_script("window.capybaraAngularReady !== undefined")
page.execute_script WAITER_JS
end
def ready?
page.evaluate_script("window.capybaraAngularReady === true")
end
end
end
end
| true |
499ab21e4bbe2a495bf913f34679010cf2ba516d | Ruby | trujillojosh/ruby | /d02/ex06/play_with_arrays.rb | UTF-8 | 110 | 2.921875 | 3 | [] | no_license | #!/usr/bin/env ruby
arr = [2, 8, 9, 48, 8, 22, -12, 2]
p arr
arr.uniq!
new = arr.map{|x| x += 2}
p new[1..4]
| true |
4fae7d90fcb6d34b7e4239820361c5798a3deaf8 | Ruby | MichaelCSlevin/high_school | /models/subject.rb | UTF-8 | 903 | 3.125 | 3 | [] | no_license | require_relative '../db/sql_runner'
class Subject
attr_accessor :id, :name, :teacher
attr_reader :id
def initialize (subject_hash)
@id = subject_hash['id'].to_i if subject_hash ['id']
@name = subject_hash['name']
@teacher = subject_hash['teacher']
end
def save
sql = "INSERT INTO subjects
(
name,
teacher
) VALUES
(
$1, $2
)
RETURNING id"
values = [@name, @teacher]
result = SqlRunner.run(sql, "save_subject", values)
@id = result.first['id'].to_i()
end
def self.all_subjects()
sql = "SELECT * FROM subjects"
values = []
subjects = SqlRunner.run(sql, values)
result = subjects.map {|subject| Subject.new(subject)}
return result
end
def self.delete_all()
sql = "DELETE FROM subjects"
values = []
SqlRunner.run(sql, values)
end
end
| true |
f198f7792d6b9fa71cfe788018b758eb2a2f938e | Ruby | Zahid4960/RoR_office_meal_management_system_backend | /app/services/designation_service.rb | UTF-8 | 699 | 2.515625 | 3 | [] | no_license | class DesignationService
require_relative '../repositories/designation_repository'
require_relative '../models/designation'
@@model = Designation
def index(page, limit)
designation_repo.designation_with_office(page, limit)
end
def create(payload)
designation_repo.save_data(@@model, payload)
end
def show(id)
designation_repo.find_designation_with_office(id)
end
def update(id, payload)
designation_repo.update_data(@@model, id, payload)
end
def destroy(id)
designation_repo.delete_data(@@model, id)
end
def last_inserted
designation_repo.last_inserted(@@model)
end
def designation_repo
@repo = DesignationRepository.new
end
end | true |
4f9a907062a0e1b1f1f3a6beacfe3403499072f8 | Ruby | lindsayhong/ga_itr_final_project_lindsay_hong | /app/helpers/users_helper.rb | UTF-8 | 505 | 3.015625 | 3 | [] | no_license | module UsersHelper
# Calculate fairways and greens in regulation, sandies, and up and downs.
def yes_no_total(array)
array.count { |x| x == "Yes" || x == "No" }
end
def yes_count(array)
array.count("Yes")
end
def total_percentage(array)
calculate_percentage = array.count("Yes").to_f/yes_no_total(array)
if calculate_percentage.to_s == "NaN"
0
else
(calculate_percentage*100).round(2)
end
end
def sum_full_array(array)
array.inject(:+)
end
end
| true |
38b51373484b851f9f275db162ee659ee92c5c82 | Ruby | rex/butler | /lib/utils/helpers.rb | UTF-8 | 342 | 2.90625 | 3 | [
"MIT"
] | permissive | module Utils
class Helpers
def self.header(text)
puts "\n------------\n\n#{text.upcase}\n-------\n"
end
def self.subheader(text)
puts " ---> #{text}\n====="
end
def self.to_object_id(str)
BSON::ObjectId.from_string(str)
end
def self.sanitize(str)
str.chomp.strip.to_s
end
end
end | true |
de5954627c1dba8fa3c663ec1ae019dbc8849739 | Ruby | pedrokp/contador | /contador.rb | UTF-8 | 740 | 3.0625 | 3 | [] | no_license | #Autor: Pedro Kowalski Pereira
#22/09/2017
require 'open-uri'
require 'nokogiri'
@dic = Hash.new(0)
doc = Nokogiri::HTML(open('http://www.threescompany.com/','r:UTF-8',&:read))
doc.css('script').remove
doc.css('style').remove
conteudo = doc.css('body')
def palavras_na_string(string)
string.scan(/[\w']+[^a-zA-Z]/i)
end
def cont_freq(lista)
for palavra in lista
@dic[palavra] += 1
end
@dic
end
conteudo.each do |entrada|
palavras = palavras_na_string(entrada.content)
cont_freq(palavras)
end
puts "SITE: #{doc.title}"
puts "Número de palavras: #{@dic.length} ..."
puts "frequência => palavra"
@dic.sort {|b,a| a[1] <=> b[1]}.each do |key,value|
puts "#{value} => #{key}"
end
puts "Número de palavras: #{@dic.length} ..." | true |
4020aeb1c6722215b2e4871c56459c2888613a04 | Ruby | nakajima/rebound | /spec/rebound_spec.rb | UTF-8 | 2,742 | 2.890625 | 3 | [
"MIT"
] | permissive | require File.join(File.dirname(__FILE__), 'spec_helper')
describe UnboundMethod do
before(:each) do
@a = Class.new { def foo; :bar end }
@b = Class.new { def called?; @called end }
@mod = Module.new { def call; @called = true; end }
@object_a = @a.new
@object_b = @b.new
end
describe "#name" do
it "should return name" do
m = @a.instance_method(:foo)
m.name.should == 'foo'
end
end
describe "#to_s" do
it "should provide source" do
m = @a.instance_method(:foo)
m.to_s(:ruby).should == "def foo()\n :bar\nend"
end
it "should be memoized" do
m = @a.instance_method(:foo)
m.should_receive(:to_ruby).once.and_return(proc { :bar }.to_ruby)
2.times { m.to_s(:ruby) }
end
end
describe "#bind" do
it "should bind method from Class.instance_method to object of different class" do
m = @a.instance_method(:foo)
m.bind(@object_b)
@object_b.foo.should == :bar
end
it "should bind singleton method to object of different class" do
class << @object_a; def greet; :hello end end
m = @object_a.method(:greet).unbind
m.bind(@object_b)
@object_b.greet.should == :hello
end
it "should bind methods that take an argument" do
class << @object_a; def greet(name); "hello #{name}" end end
m = @object_a.method(:greet).unbind
m.bind(@object_b)
@object_b.greet('pat').should == "hello pat"
end
it "should bind methods that take splat of arguments" do
class << @object_a
def add_these(container, *args)
args.each { |a| container << a }
end
end
m = @object_a.method(:add_these).unbind
m.bind(@object_b)
collector = []
@object_b.add_these(collector, 'pat', 'tim', 'drew')
collector.should == ['pat', 'tim', 'drew']
end
it "should bind methods that take block" do
class << @object_a
def append(&block)
res = [:original]
res << yield
res
end
end
m = @object_a.method(:append).unbind
m.bind(@object_b)
@object_b.append { :addition }.should == [:original, :addition]
end
it "should bind module instance method" do
m = @mod.instance_method(:call)
m.bind(@object_b)
@object_b.call
@object_b.should be_called
end
end
describe "#to_proc" do
it "should return proc version" do
m = @a.instance_method(:foo)
m.to_proc.call.should == :bar
end
it "should be memoized" do
m = @a.instance_method(:foo)
m.should_receive(:to_ruby).once.and_return(proc { :bar }.to_ruby)
2.times { m.to_proc }
end
end
end | true |
5cff51f2b2fe8e0da63fda4c04c643295009a364 | Ruby | deatheragetr/playlister-rb | /lib/models/playlister.rb | UTF-8 | 1,410 | 3.09375 | 3 | [] | no_license | require_relative '../concerns/findbyname.rb'
class Artist
extend FindByName
attr_reader :genre
attr_accessor :name, :songs
@@artists = []
def self.count
@@artists.size
end
def self.reset_artists
@@artists = []
end
def self.all
@@artists
end
def self.get_binding
binding()
end
def initialize
@@artists << self
self.songs = []
end
def songs_count
songs.size
end
def add_song(song)
songs << song
add_artist_to_genre(song) if song.genre
end
def add_artist_to_genre(song)
genre = song.genre
genre.artists << self unless genre.artists.include? self
@genre = genre
end
def genres
songs.collect {|song| song.genre}
end
def get_binding
binding()
end
end
class Song
extend FindByName
attr_accessor :name
attr_reader :genre, :artist
@@all = []
def self.all
@@all
end
def initialize
@@all << self
end
def genre=(genre)
genre.songs << self
@genre = genre
end
def artist=(artist)
@artist = artist
end
def get_binding
binding()
end
end
class Genre
extend FindByName
attr_accessor :name, :songs, :artists
@@genres = []
def self.reset_genres
@@genres = []
end
def self.all
@@genres
end
def initialize
@@genres << self
self.songs = []
self.artists = []
end
def get_binding
binding()
end
end
| true |
f711894642aafda8b87808430ad4863b9032703c | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/hamming/eaf59c367c9341b5977235e6398e6df3.rb | UTF-8 | 497 | 3.46875 | 3 | [] | no_license | class Hamming
def self.compute(first,second)
if first.eql?(second)
0
else
self.disparity(first,second)
end
end
def self.disparity(first,second)
disparityLevel=0
shorter=self.shorter(first,second)
(0..shorter).each do |i|
if not first[i].eql?(second[i])
disparityLevel+=1
end
end
disparityLevel
end
def self.shorter(first,second)
if first.length<second.length
first.length-1
else
second.length-1
end
end
end
| true |
56d4891b25e7df2756064a8a5ec527ab6169c2f4 | Ruby | alim/baseballstats | /app/controllers/players_controller.rb | UTF-8 | 5,020 | 2.625 | 3 | [
"MIT"
] | permissive | ########################################################################
# The PlayersController is responsible for managing the
# interaction and updating of Player records. It has all the
# standard CRUD actions plus an action that supports uploading and
# replacing the system's player records from a CSV file.
########################################################################
class PlayersController < ApplicationController
before_action :set_player, only: [:show, :edit, :update, :destroy]
before_action :set_players_menu_active
######################################################################
# GET /players
# GET /players.json
#
# Shows all players sorted by player ID and paginated.
######################################################################
def index
# Get page number from paginate plugin used in view
page = params[:page].nil? ? 1 : params[:page]
@players = Player.order_by([[ :player_id, :asc ]]).paginate(page: page, per_page: PAGE_COUNT)
end
######################################################################
# GET /players/1
# GET /players/1.json
#
# Shows an individual player record.
######################################################################
def show
end
######################################################################
# GET /players/new
#
# Generates a new player record form.
######################################################################
def new
@player = Player.new
end
######################################################################
# GET /players/1/edit
#
# Generates an edit form for the requested player record.
######################################################################
def edit
end
######################################################################
# POST /players
# POST /players.json
#
# Creates a new player record.
######################################################################
def create
@player = Player.new(player_params)
respond_to do |format|
if @player.save
format.html { redirect_to @player, notice: 'Player was successfully created.' }
format.json { render action: 'show', status: :created, location: @player }
else
format.html { render action: 'new' }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
######################################################################
# PATCH/PUT /players/1
# PATCH/PUT /players/1.json
#
# Updates an existing player record.
######################################################################
def update
respond_to do |format|
if @player.update(player_params)
format.html { redirect_to @player, notice: 'Player was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @player.errors, status: :unprocessable_entity }
end
end
end
######################################################################
# DELETE /players/1
# DELETE /players/1.json
#
# Destroys the requested player record.
######################################################################
def destroy
@player.destroy
respond_to do |format|
format.html { redirect_to players_url }
format.json { head :no_content }
end
end
######################################################################
# POST /players/import
#
# The import method allows uploading of a CSV file with batting
# statistics. It uses the Player model import class method
# for uploading the batting statistics.
######################################################################
def import
Player.import(params[:file])
message = "Players imported: #{Player.count} successful and #{Player.skipped} skipped."
redirect_to players_url, notice: message
end
## PRIVATE INSTANCE METHODS ------------------------------------------
private
####################################################################
# Use callbacks to share common setup or constraints between actions.
####################################################################
def set_player
@player = Player.find(params[:id])
end
####################################################################
# Callback to set the Batting Stats menu to active state
####################################################################
def set_players_menu_active
@players_menu_active = 'class=active'
end
####################################################################
# Never trust parameters from the scary internet, only allow the white list through.
####################################################################
def player_params
params.require(:player).permit(:player_id, :birth_year, :first_name, :last_name)
end
end
| true |
c31b3fa00ecce72342130acd228aaabfac387947 | Ruby | bxdn/RubyProjects | /RubyExcercises.rb | UTF-8 | 3,072 | 3.40625 | 3 | [] | no_license | def caesar_cipher(str,rep)
lows = [*('a'..'z')]
ups = [*('A'..'Z')]
output = str.chars.map do |let|
if lows.include?let or ups.include?let
if lows.include?let
ref = lows
else
ref = ups
end
ref[(ref.index(let)+rep)%26]
else
let
end
end
output.join
end
def stock_picker(arr)
buy = 0
sell = 0
maxProf = 0
arr.length.times do |i|
day1 = arr[i]
arr[(i+1)..-1].length.times do |j|
day2 = arr[i+j+1]
prof = day2-day1
if prof>maxProf
maxProf = prof
buy=i
sell=i+j+1
end
end
end
[buy,sell]
end
def in_string(sub, par)
count = 0
par.chars.length.times do |i|
matched = true
sub.chars.length.times do |j|
if par[i+j]!=sub[j]
matched = false
break
end
end
if matched
count += 1
end
end
count
end
def substrings(str, dictionary)
str.downcase!
output = {}
dictionary.each do |sub|
count = in_string(sub,str)
output[sub] = count if count>0
end
output
end
def bubble_sort(arr)
unsorted = true
while unsorted
unsorted = false
arr.length.times do |i|
if arr[i+1]!= nil and arr[i+1]-arr[i]<0
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
unsorted = true
end
end
end
arr
end
def bubble_sort_by(arr)
unsorted = true
while unsorted
unsorted = false
arr.length.times do |i|
if arr[i+1]!= nil and yield(arr[i], arr[i+1])>0
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
unsorted = true
end
end
end
arr
end
def my_each(arr)
arr.length.times do |i|
yield arr[i]
end
end
def my_each_with_index(arr)
arr.length.times do |i|
yield arr[i],i
end
end
def my_select(arr)
out = []
my_each(arr) do |item|
out << item if yield(item)
end
out
end
def my_all(arr)
all = true
my_each(arr) do |item|
all = false unless yield(item)
end
all
end
def my_any(arr)
any = false
my_each(arr) do |item|
any = true if yield(item)
end
any
end
def my_none(arr)
none = true
my_each(arr) do |item|
none = false if yield(item)
end
none
end
def my_count(arr)
count = 0
my_each(arr) do |item|
count += 1 if yield(item)
end
count
end
def my_map(arr,proc=nil)
arr.length.times do |i|
arr[i] = (proc == nil) ? yield(arr[i]) : proc.call(arr[i])
end
arr
end
def my_inject(arr)
arr.length.times do |i|
arr[i] = yield(arr[i-1],arr[i]) if i>0
end
arr[-1]
end
def multiply_els(arr)
my_inject(arr) { |product, n| product * n }
end
| true |
bc4b6fb37b8e6c86ceb5ad318960c82f2bab279b | Ruby | krisswiltshire30/boris-bikes | /spec/docking_station_spec.rb | UTF-8 | 1,670 | 3.15625 | 3 | [] | no_license | require './lib/docking_station'
require './lib/bike'
describe DockingStation do
it { is_expected.to respond_to :release_bike }
it 'has a method dock' do
expect(subject).to respond_to :dock
end
it 'has a method bike that returns a bike' do
expect(subject).to respond_to :bikes
end
it 'returns docked bikes' do
bike = Bike.new
subject.dock(bike)
expect(subject.bikes.last).to eq(bike)
end
describe '#release_bike' do
it 'Releases correct bike' do
bike = Bike.new
subject.dock(bike)
expect( subject.release_bike ).to eq subject.bikes.first
end
it 'raises and error when no bikes are available' do
expect {subject.release_bike}.to raise_error 'No bike available'
end
end
# it { is_expected.to respond_to :full? }
#
# it { is_expected.to respond_to :empty? }
describe '#dock' do
it 'raises an error when a bike is already docked' do
DockingStation::DEFAULT_CAPACITY.times {subject.dock(Bike.new)}
expect { subject.dock(Bike.new) }.to raise_error "Station at full capacity, can't dock bike"
end
end
describe 'Set capacity when create new docking station, default to DEFAULT_CAPACITY' do
it 'capacity set to default when no argument is given' do
docking_station = DockingStation.new()
DockingStation::DEFAULT_CAPACITY.times { docking_station.dock(Bike.new)}
expect{docking_station.dock(Bike.new)}.to raise_error
end
it 'capacity set to 5' do
docking_station = DockingStation.new(5)
5.times { docking_station.dock(Bike.new)}
expect{docking_station.dock(Bike.new)}.to raise_error
end
end
end
| true |
d1a0515d1f41c255045721d082d3799eddd2c71c | Ruby | NoorAlkattan/atm_machine | /app/models/account.rb | UTF-8 | 1,548 | 3 | 3 | [] | no_license | class Account < ActiveRecord::Base
belongs_to :user
has_many :transactions, dependent: :destroy
#validates_presence_of :user_id
attr_accessor :amount
#validates :balance, :numericality => { greater_than_or_equal_to: 0 }
# validates :account_no, :balance, :presence => true
def deposit (amt)
if amt[:amount].to_f <= 0.0 || limit_daily_deposit?(amt[:amount])
errors.add(:amount, "Maximum Daily Desposit $1000")
return false
else
self.balance = self.balance.to_f + amt[:amount].to_f
self.save
return true
end
end
def withdrawal (amt)
if amt[:amount].to_f <= 0.0 || max_withdrawal?(amt[:amount])
errors.add(:amount, "Maximum Daily Withdrawal $500")
return false
else
self.balance = self.balance.to_f - amt[:amount].to_f
self.save
return true
end
end
private
def limit_daily_deposit?(current_amount)
amounts_list = self.transactions.today.where(transaction_type: 1).pluck(:amount)
sum = amounts_list.map(&:to_f).reduce(:+)
new_balance_today = sum.to_f + current_amount.to_f
if new_balance_today > 1000
return true
else
false
end
end
def max_withdrawal?(current_amount)
amounts_list = self.transactions.today.where(transaction_type: 2).pluck(:amount)
sum = amounts_list.map(&:to_f).reduce(:+)
new_balance_today = current_amount.to_f + sum.to_f
if new_balance_today > 500
return true
else
false
end
end
end
| true |
a0130dff988b2e079a356c3e1f21496073904fca | Ruby | YanchWare/GitHubStats | /Report.rb | UTF-8 | 2,153 | 3.375 | 3 | [
"MIT"
] | permissive | =begin
Class representing an user object used in order to hold report data
=end
class User
def initialize(name, firstIssue)
@userName = name
@issuesSolved = [firstIssue]
end
def IssuesSolved
@issuesSolved
end
def UserName
@userName
end
def eql?(other_object)
(self.class.equal?other_object.class and
self.UserName == other_object.UserName and
self.IssuesSolved == other_object.IssuesSolved) or
(self.UserName == other_object)
end
alias == eql?
end
=begin
Class representing an issue object used in order to hold report data
=end
class Issue
def initialize(title, closedBy, closedAt, openedBy)
@title = title
@closedBy = closedBy
@closedAt = closedAt
@openedBy = openedBy
end
def Title
@title
end
def ClosedBy
@closedBy
end
def ClosedAt
@closedAt
end
def OpenedBy
@openedBy
end
end
=begin
Class implementing report behavior
=end
class Report
def initialize(repos, issues)
@usersByUserNames = {}
@issuesClosed = issues
@repositories = repos
@issuesClosed.each do | issue |
userFound = @usersByUserNames[issue.ClosedBy]
if userFound
userFound.IssuesSolved << issue
else
@usersByUserNames[issue.ClosedBy] = User.new(issue.ClosedBy, issue)
end
end
end
def to_s
retS = "\n==========[GitHubStats Report]==========\nAnalyzed #{@repositories.length} repositories:\n"
@repositories.each do |repository|
retS += repository + "\n"
end
retS += "\nFound a total of #{@issuesClosed.length} issues.\n" +
"\n================[Users]================\nUsers found ordered by number of issues solved:\n\n"
@usersByUserNames.sort_by{|k,v| v.IssuesSolved.length}.reverse.each do |userName, userObj|
retS += "----------- #{userName}: #{userObj.IssuesSolved.length} issues solved ----------- \n"
userObj.IssuesSolved.each do |issue|
retS += "Title: #{issue.Title}\nOpened by #{issue.OpenedBy} and closed by #{issue.ClosedBy} at #{issue.ClosedAt}\n\n"
end
end
retS
end
end | true |
bb70a3d2f8d0999f7fcadae4c02a52ff5295c28f | Ruby | blakeynwa/phase-0-tracks | /ruby/gps2_2.rb | UTF-8 | 3,731 | 4.34375 | 4 | [] | no_license | # Method to create a list
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# Get user input - list (use driver code)
# set default quantity. How many items in the list .max
# print the list to the console [can you use one of your other methods here?]
# output: [what data type goes here, array or hash?] Hash
# Method to add an item to a list
# input: list, item name, and optional quantity
# steps:
# Turn array into a hash - list item: Key, quantity: value
# output: Hash
# Method to remove an item from the list
# input: hash[:key]
# steps:
# select item to delete
# output: hash without deleted item
# Method to update the quantity of an item
# input: updated hash
# steps: hash[:item] = 'new item'
# output: hash withou updated item
# Method to print a list and make it look pretty
# input: hash. (print)
# steps:
# access specific keys and values from the hash and print
# output: printed items
def user_list(item)
grocery_list = item.split
quantity_list = {}
grocery_list.each do |item|
quantity_list[item] = 1
end
quantity_list
end
grocery_items = user_list("Carrots Potatoes Milk")
def item_add(list, item, quantity)
list[item] = quantity
list
end
def item_delete(list, item)
list.delete(item)
list
end
def item_updated(list, item, quantity)
list[item] = quantity
list
end
item_add(grocery_items, "Lemonade", 2)
item_add(grocery_items, "Tomatoes", 3)
item_add(grocery_items, "Onions", 1)
item_add(grocery_items, "Ice Cream", 4)
item_delete(grocery_items, "Lemonade")
item_updated(grocery_items, "Ice Cream", 1)
puts "Here's your grocery list:"
grocery_items.each do |item, quantity|
puts "#{item}, #{quantity}"
end
=begin
What did you learn about pseudocode from working on this challenge?
I first thought it would be a good idea to go through and update the pseudo
code as we went along, but now I'm seeing it's a much better idea to have
detailed pseudo code to read through as you start to actually code.
Having detailed pseudo code will lead to more functional actual code.
What are the tradeoffs of using arrays and hashes for this challenge?
At first we were going to use an array, but then realized it would be
pretty difficult to access both the items and the quantities. Using an
array allowed us to use the items as 'keys' and the quantities as 'values',
which made it much easier to access and update the various elements.
What does a method return?
A method returns the result of the last code in the method.
What kind of things can you pass into methods as arguments?
You can pass strings, integers, arrays/hashes
How can you pass information between methods?
As stated at the start of this challenge, one way we could have done this
was with classes. However, we performed this in this challenge by using
the return of previous methods as the argument for new methods. For example,
we defined a method user_list first, which populated a list of grocery items
with a default quantity of 1. The return of that method was a list, which we
used in future methods such as item_add(list, item, quantity). This allowed
us to use the list populated from user_list in all the other methods we
created.
What concepts were solidified in this challenge, and what concepts are still confusing?
Passing information from one method to another was cleared up. It's still
a confusing topic since so much of this information is new to me, but I feel
more confident on passing information from one method to the other moving forward.
It was also nice having additional practice with hashes/arrays, but I definitely
need continued practice to fully wrap my brain around data structures.
end
| true |
a766b87e7f43fd56dcec78556fe1a3debd365495 | Ruby | 3den/hash_delegate | /lib/hash_delegate/accessor.rb | UTF-8 | 537 | 2.6875 | 3 | [
"MIT"
] | permissive | module HashDelegate
class Accessor < Struct.new :klass
def define_getter(key, hash)
define_delegation key do
data = self.send(hash) || {}
data[key.to_s] || data[key.to_sym]
end
end
def define_setter(key, hash)
define_delegation "#{key}=" do |value|
self.send(hash) or self.send("#{hash}=", {})
self.send(hash)[key.to_s] = value
end
end
private
def define_delegation(name, &block)
klass.class_eval { define_method name, &block }
end
end
end
| true |
6487a9b6f52067ca0a7ed619bbcee9fd2c785dd6 | Ruby | bekkopenkurs/railskurs | /spec/ntnu/api/course_parser_spec.rb | UTF-8 | 2,424 | 2.578125 | 3 | [] | no_license | #encoding: utf-8
require 'rspec'
require 'spec_helper'
require 'json'
require 'ntnu/api/parser'
module NTNU
module API
describe CourseParser do
it "should handle requests for invalid courses" do
nonexisting_course = JSON.parse('{ "course": [], "request": { "courseCode": "tdt5110" }}')
expect do
NTNU::API::CourseParser.new(nonexisting_course).parse
end.to raise_exception(NTNU::API::CourseNotFoundException)
end
it "should handle incomplete responses" do
incomplete_response = JSON.parse('{ "course": { "code": 123, "englishName": 0 }}')
expect do
NTNU::API::CourseParser.new(incomplete_response).parse
end.to raise_exception(NTNU::API::CouldNotParseCourseException)
end
subject do
data = <<-EOS
{
"course": {
"code": "TDT4220",
"name": "Ytelsesvurdering",
"englishName": "Computer Systems Performance Evaluation",
"versionCode": "1",
"credit": 7.5,
"creditTypeCode": "SP",
"gradeRule": "30",
"gradeRuleText": "Bokstavkarakterer",
"assessment": [
{"code": "MAPPE-1","codeName": "Mappeevaluering" },
{"code": "MAPPE-2","codeName": "Mappeevaluering" }
],
"mandatoryActivity": [
{ "number": 1, "name": "\u00d8vinger" }
],
"educationalRole": [
{
"code": "Coordinator",
"person": {
"firstName": "Gunnar",
"lastName": "Brataas",
"email": "gunnar.brataas@idi.ntnu.no"
}
}
]
}
}
EOS
CourseParser.new(JSON.parse(data))
end
it "should parse JSON response into a Course" do
subject.parse.should be_a Course
end
it "should parse a Course object" do
subject.parse.code.should eq "TDT4220"
subject.parse.name.should eq "Computer Systems Performance Evaluation"
subject.parse.credit.should eq 7.5
subject.parse.assessments.should eq 2
subject.parse.mandatory_activities.should eq 1
subject.parse.teacher.should eq "Gunnar Brataas"
end
end
end
end | true |
62eedf72841b9371b87766674426f0de1c71d5c4 | Ruby | Malachirwin/malachis_gofish | /lib/card_deck.rb | UTF-8 | 775 | 3.546875 | 4 | [] | no_license | require_relative 'card'
class CardDeck
def initialize
@deck = create_deck
end
def create_deck
suits = ['H', 'D', 'S', 'C']
suits.map do |suit|
13.times.map do |number|
rank = number + 1
Card.new(suit, rank)
end
end.flatten
end
def shuffle
card_deck.shuffle!
end
def cards_left
card_deck.length
end
def deal(deck, *players)
shuffle
players.each do |player_hand|
5.times do
player_hand.player_hand.push(remove_top_card)
end
end
players
end
def remove_top_card
card_deck.shift
end
def remove_all_cards_from_deck
@deck = []
end
def has_cards?
if cards_left > 0
return true
end
end
private
def card_deck
@deck
end
end
| true |
decfb3982d7a98424b0dd9515ab3e3a3f1e6f161 | Ruby | saikrishnagaddipati/rails-interview | /app/models/student.rb | UTF-8 | 785 | 3.015625 | 3 | [] | no_license | class Student < ActiveRecord::Base
# Instance method responsible for showing student's name
def name
# checking duplicate firstname
firstname_count = Student.where(firstname: firstname).count
# we are checking conditions as per duplicate firstname
firstname_count > 1 ? "#{firstname} #{lastname[0]}." : "#{firstname}"
end
# Instance method responsible for showing student's movie
def movie
"#{favoritemovie}"
end
# method for filtering the results with movie
def self.search_by_movie movie
# downcase allowing to search in casesensitive
where('lower(favoritemovie) = ?', movie.downcase)
end
# For fetching the proper student records
def self.fetch_results(movie)
movie.blank? ? self.all : self.search_by_movie(movie)
end
end
| true |
5b4f47d18f668ca07be392b666b96d33eba145c5 | Ruby | mercebc/TicTacToe-ruby | /lib/core/players_factory.rb | UTF-8 | 1,133 | 3.234375 | 3 | [] | no_license | require 'core/players/player_factory'
class PlayersFactory
MODE = {
:HUMAN_VS_HUMAN => 'h',
:HUMAN_VS_EASY_COMPUTER => 'e',
:HUMAN_VS_HARD_COMPUTER => 'i'
}
def initialize(ui)
@ui = ui
end
def build(mode, starting_player_symbol = "X")
new_player = PlayerFactory.new
players = Array.new
case mode
when MODE[:HUMAN_VS_HUMAN]
players << new_player.build(:human,"X",@ui)
players << new_player.build(:human,"O",@ui)
when MODE[:HUMAN_VS_EASY_COMPUTER]
players << new_player.build(:human,"X",@ui)
players << new_player.build(:easy_computer,"O")
when MODE[:HUMAN_VS_HARD_COMPUTER]
players << new_player.build(:human,"X",@ui)
players << new_player.build(:hard_computer,"O")
end
order_players(players, starting_player_symbol)
end
private
def order_players(players, starting_player_symbol)
if players.first.symbol == starting_player_symbol
players
else
swap_players(players)
end
end
def swap_players(players)
players[0], players[1] = players.last, players.first
players
end
end
| true |
33347e1973f37fddbfe1d490e26a38b6df373895 | Ruby | tdevereux/brine | /ruby/lib/brine/step_definitions/assertions.rb | UTF-8 | 1,595 | 2.9375 | 3 | [
"MIT"
] | permissive | # assertions.rb - General assertions to be used with a Selector
Then(/^it is equal to `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| eq v} }
end
Then(/^it is equal to:$/) do |value|
perform { selector.assert_that(value) {|v| eq v} }
end
Then(/^it is matching `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| match v} }
end
Then (/^it is matching:$/) do |value|
perform { selector.assert_that(value) {|v| match v} }
end
Then(/^it is greater than `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| be > v} }
end
Then(/^it is greater than or equal to `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| be >= v} }
end
Then(/^it is less than `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| be < v} }
end
Then(/^it is less than or equal to `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| be <= v} }
end
# Be a little smarter than default.
Then(/^it is empty$/) do
perform { selector.assert_that(nil) do
satisfy{|i| i.nil? || (i.respond_to?(:empty?) && i.empty?) }
end }
end
Then(/^it is including `([^`]*)`$/) do |value|
perform { selector.assert_that(value) {|v| include v } }
end
Then(/^it is including:$/) do |value|
perform { selector.assert_that(value) {|v| include v } }
end
Then(/^it is a valid `([^`]*)`$/) do |type|
perform { selector.assert_that(type) {|t| type_check_for(t) } }
end
Then(/^it is of length `([^`]*)`$/) do |length|
perform { selector.assert_that(length) do |l|
satisfy{|i| i.respond_to?(:length) && i.length == l}
end }
end
| true |
d36afb09a1321f44b354446453cda266253d7a13 | Ruby | rbotafogo/galaaz | /lib/R_interface/rlanguage.rb | UTF-8 | 3,175 | 2.828125 | 3 | [
"BSD-2-Clause"
] | permissive | # -*- coding: utf-8 -*-
##########################################################################################
# @author Rodrigo Botafogo
#
# Copyright © 2018 Rodrigo Botafogo. All Rights Reserved. Permission to use, copy, modify,
# and distribute this software and its documentation, without fee and without a signed
# licensing agreement, is hereby granted, provided that the above copyright notice, this
# paragraph and the following two paragraphs appear in all copies, modifications, and
# distributions.
#
# IN NO EVENT SHALL RODRIGO BOTAFOGO BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL,
# INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF
# THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF RODRIGO BOTAFOGO HAS BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# RODRIGO BOTAFOGO SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
# SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS".
# RODRIGO BOTAFOGO HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS,
# OR MODIFICATIONS.
##########################################################################################
module R
class Language < Object
include BinaryOperators
include LogicalOperators
include ExpBinOp
include IndexedObject
attr_accessor :expression
#--------------------------------------------------------------------------------------
#
#--------------------------------------------------------------------------------------
def self.to_expression(obj)
obj.respond_to?(:expression) ? obj.expression : obj.to_s
end
#--------------------------------------------------------------------------------------
# Builds a call functions with the given arguments.
# @param function_name [String] name of the function to apply: ex: '+'
# @param args [Array] two elements array for the binary function: ex [:a, :b]
# @return call expression. With the above paramenters the result would be:
# .Primitive("+")(a, b)
#--------------------------------------------------------------------------------------
def self.build(function_name, *args)
res = R::Language.new(
R::Support.eval("as.call").
call(R::Support.parse2list(
R::Support.eval(function_name), *args)
))
res.expression = "#{Language.to_expression(args[0])} #{function_name.delete("`")} #{Language.to_expression(args[1])}"
res
end
#--------------------------------------------------------------------------------------
#
#--------------------------------------------------------------------------------------
def assign(expression)
exec_bin_oper("`<-`", expression).eval
end
#--------------------------------------------------------------------------------------
#
#--------------------------------------------------------------------------------------
def i
"I(#{@expression})"
end
end
end
| true |
d7eb31c47546d45788b0eb3c30b17b0122c6bd8e | Ruby | oguzpol/ruby-tutorial | /while_keyword.rb | UTF-8 | 625 | 3.234375 | 3 | [] | no_license | # i = 1
# while i < 10
# puts i
# i += 1
# end
# puts
# p i
# password condition
# status = true
# while status == true
# print "Please enter username : "
# username = gets.chomp.downcase
# print "Plesase enter password : "
# password = gets.chomp.downcase
# if username == "boris" && password == "bestpasswordever"
# puts "Entry granted. The nuclear codes are ..."
# status = false
# elsif username == "quit" || password == "quit"
# puts "Goodbye! Better luck next time !"
# status = false
# else
# puts "Incorrect combination, try again or enter 'quit' and leave."
# end
# end
| true |
faa183eb8a42d654b8ca12197f251d809576928a | Ruby | festinalent3/learn_to_program | /ch09-writing-your-own-methods/old_school_roman_numerals.rb | UTF-8 | 1,295 | 3.828125 | 4 | [] | no_license | def old_roman_numeral num
roman_array = ["I", "V", "X", "L", "C", "D", "M"]
to_roman = ""
to_roman << roman_array[6] * (num / 1000)
to_roman << roman_array[5] * (num % 1000/ 500)
to_roman << roman_array[4] * (num % 500/ 100)
to_roman << roman_array[3] * (num % 100/ 50)
to_roman << roman_array[2] * (num % 50 / 10)
to_roman << roman_array[1] * (num % 10 / 5)
to_roman << roman_array[0] * (num % 5 / 1)
to_roman
end
#MY FIRST SOLUTION BEFORE I SAW THE PATTERN
# def old_roman_numeral num
#
# roman_array = ["I", "V", "X", "L", "C", "D", "M"]
# return_array = []
#
# #Hundreds/Thousands
# return_array << roman_array[6] if num > 999
# return_array << roman_array[5] if num > 499 && num < 999
# return_array << roman_array[4]*(num/100) if num < 500
# num = num -((num/100)*100)
#
# #Tens
# if num > 49
# return_array << roman_array[3]
# num = num -50
# return_array << roman_array[2]*(num/10)
# else
# return_array << roman_array[2]*(num/10)
# end
# num = num -((num/10)*10)
#
# #Ones
# if num > 4
# return_array << roman_array[1]*(num/5)
# num = num-5
# return_array << roman_array[0]*(num)
# elsif num < 5
# return_array << roman_array[0]*(num)
# else
# end
#
#
# return return_array.join()
#
# end
| true |
7bef3d03e446427a3410def07112094dc3dfe3c2 | Ruby | muupan/project_euler | /42/pe42.rb | UTF-8 | 481 | 3.59375 | 4 | [] | no_license | $score_of_a = "A".bytes.to_a[0]
def calc_score_of_char(char)
char.bytes.to_a[0] - $score_of_a + 1
end
def calc_score(word)
return word.split("").inject(0){|sum, c| sum + calc_score_of_char(c)}
end
def is_triangle_number(n)
for i in 1...999 do
return true if i * (i + 1) / 2 == n
return false if i * (i + 1) / 2 > n
end
end
f = open("./words.txt")
str = f.read
words = str.slice(1, str.size - 2).split('","')
p words.count{|word| is_triangle_number(calc_score(word))}
| true |
7b59d12fae1d008f7a56a1d2bfcdc8d6770c62a0 | Ruby | SoftwareWithFriends/forwardable_content_hash_binder | /lib/forwardable_content_hash_binder.rb | UTF-8 | 434 | 2.734375 | 3 | [
"MIT"
] | permissive |
class ForwardableContentHashBinder
attr_reader :content_hash
def initialize(content_hash)
@content_hash = content_hash
end
def method_missing(method, *args)
super(method, args) unless @content_hash[method.to_s]
value = @content_hash[method.to_s]
return value unless value.kind_of? Proc
value.call
end
def []=(key,value)
content_hash[key] = value
end
def get_binding
binding
end
end
| true |
a0ae749782164f1416c4c32e2b560446b268071b | Ruby | edwardkerry/airport_challenge | /lib/airport.rb | UTF-8 | 1,136 | 3.296875 | 3 | [] | no_license | require_relative 'plane'
require_relative 'weather'
class Airport
attr_accessor :capacity
attr_reader :runway
STANDARD_CAPACITY = 10
def initialize(capacity = STANDARD_CAPACITY)
@runway = []
@stormy = Weather.new
@capacity = capacity
end
def land_plane(inbound_plane)
fail "Plane already landed" if already_landed(inbound_plane)
fail "Too stormy to land" if storm_forecast
fail "The airport is full" if reached_capacity
inbound_plane.touch_down
runway << inbound_plane
end
def take_off(departing_plane)
fail "Plane not in this airport" if not_in_airport(departing_plane)
fail "Too stormy to fly" if storm_forecast
departing_plane.in_flight
runway.delete(departing_plane)
end
private
def storm_forecast
@stormy.stormy?
end
def not_in_airport(departing_plane)
!runway.include?(departing_plane)
end
def already_landed(inbound_plane)
runway.include?(inbound_plane)
end
def reached_capacity
runway.count == capacity
end
def in_other_airport(inbound_plane)
inbound_plane.landed && !runway.include?(inbound_plane)
end
end
| true |
ae52d90930e7c3a0a49a8d0689ad29bc6f142e87 | Ruby | freejacque/project_euler | /question_01.rb | UTF-8 | 109 | 2.890625 | 3 | [] | no_license |
selected_numbers = (1..999).find_all { |i| i % 3 == 0 || i % 5 == 0}
answer = selected_numbers.reduce(:+)
| true |
3e92d1bba2891a59481fb82c8b20768fbc973bdf | Ruby | fafafariba/app-academy-projects | /w3d3/URLShortener/app/models/shortened_url.rb | UTF-8 | 1,160 | 2.609375 | 3 | [] | no_license | # require 'secure_random'
# == Schema Information
#
# Table name: shortened_urls
#
# id :integer not null, primary key
# short_url :string
# long_url :string not null
# submitter_id :integer not null
#
class ShortenedUrl < ActiveRecord::Base
validates :short_url, uniqueness: true
validates :long_url, presence: true
validates :submitter_id, presence: true
def self.random_code
begin
url = SecureRandom.urlsafe_base64(16)
raise "already in database" if ShortenedUrl.exists?(short_url: url)
rescue
retry
end
url
end
def self.create_shortened_url(user, long_url)
ShortenedUrl.create!(
submitter_id: user.id,
short_url: ShortenedUrl.random_code,
long_url: long_url
)
end
has_many :visitors,
primary_key: :id,
foreign_key: :shortened_url_id,
class_name: :Visit
belongs_to :submitter,
primary_key: :id,
foreign_key: :submitter_id,
class_name: :User
def num_clicks
self.visitors.count
end
def num_uniques
self.visitors.select(:visitor_id).uniq.count
end
def num_recent_uniques
end
end
| true |
77282b17f39fa8402c1d3dab9c5bc3eb1f477455 | Ruby | nemrow/guess_who | /db/seeds.rb | UTF-8 | 988 | 2.65625 | 3 | [] | no_license | require 'faker'
User.delete_all
Friend.delete_all
Board.delete_all
# Create 200 users
def create_user
id = (1..100).to_a.sample
user = User.create( :first_name => Faker::Name.first_name,
:last_name => Faker::Name.last_name,
:email => Faker::Internet.email,
:fb_id => id,
:fb_access_token => "password" )
return user
end
# Create 200 friends
def create_friend
id = (101..1000).to_a.sample
friend = Friend.create( :first_name => Faker::Name.first_name,
:last_name => Faker::Name.last_name,
:img_url => get_facebook_user_img(id),
:fb_id => id )
return friend
end
# Create 50 boards
50.times do
board = Board.new
2.times do
board.users << create_user
13.times do
board.friends << create_friend
end
end
board.save
end
| true |
9c588ccf2c12e32d0a698369f77a76fc1055821b | Ruby | SpringMT/study | /ruby/reading_meta_ruby/20120405/shared_scope.rb | UTF-8 | 187 | 2.875 | 3 | [] | no_license | #!/usr/bin/env ruby
# encoding: UTF-8
require 'pp'
def my_method
@shared = 0
end
def counter
p @shared
end
def inc(args)
@shared += args
end
my_method
counter
inc(4)
counter
| true |
494db0b0d6ddc4a10cce2809ee17a5479673bae3 | Ruby | trailblazer/reform | /test/changed_test.rb | UTF-8 | 1,100 | 2.6875 | 3 | [
"MIT"
] | permissive | require "test_helper"
require "reform/form/coercion"
class ChangedTest < MiniTest::Spec
Song = Struct.new(:title, :album, :composer)
Album = Struct.new(:name, :songs, :artist)
Artist = Struct.new(:name)
class AlbumForm < TestForm
property :name
collection :songs do
property :title
property :composer do
property :name
end
end
end
let(:song_with_composer) { Song.new("Resist Stance", nil, composer) }
let(:composer) { Artist.new("Greg Graffin") }
let(:album) { Album.new("The Dissent Of Man", [song_with_composer]) }
let(:form) { AlbumForm.new(album) }
# nothing changed after setup.
it do
refute form.changed?(:name)
refute form.songs[0].changed?(:title)
refute form.songs[0].composer.changed?(:name)
end
# after validate, things might have changed.
it do
form.validate("name" => "Out Of Bounds", "songs" => [{"composer" => {"name" => "Ingemar Jansson & Mikael Danielsson"}}])
assert form.changed?(:name)
refute form.songs[0].changed?(:title)
assert form.songs[0].composer.changed?(:name)
end
end
| true |
665c1e191e01e8fa52286bcd3b1d82aa0bec8a03 | Ruby | houndci/hound | /spec/models/commit_spec.rb | UTF-8 | 2,639 | 2.546875 | 3 | [
"MIT"
] | permissive | require "spec_helper"
require "attr_extras"
require "octokit"
require "app/models/commit"
describe Commit do
describe "#file_content" do
context "when content is returned from GitHub" do
it "returns content" do
commit = build_commit("some content")
expect(commit.file_content("test.rb")).to eq "some content"
end
end
context "when file contains special characters" do
it "does not error when linters try writing to disk" do
commit = build_commit("€25.00")
tmp_file = Tempfile.new("foo", encoding: "utf-8")
expect { tmp_file.write(commit.file_content("test.rb")) }.
not_to raise_error
end
end
context "when nothing is returned from GitHub" do
it "returns blank string" do
github = double(:github_api, file_contents: nil)
commit = Commit.new("test/test", "abc", github)
expect(commit.file_content("test.rb")).to eq ""
end
end
context "when content is nil" do
it "returns blank string" do
contents = double(:contents, content: nil)
github = double(:github_api, file_contents: contents)
commit = Commit.new("test/test", "abc", github)
expect(commit.file_content("test.rb")).to eq ""
end
end
context "when error occurs when fetching from GitHub" do
it "returns blank string" do
github = double(:github_api)
commit = Commit.new("test/test", "abc", github)
allow(github).to receive(:file_contents).and_raise(Octokit::NotFound)
expect(commit.file_content("test.rb")).to eq ""
end
end
context "when file too large error is raised" do
it "returns blank" do
github = double(:github_api)
commit = Commit.new("test/test", "abc", github)
error = Octokit::Forbidden.new(body: { errors: [code: "too_large"] })
allow(github).to receive(:file_contents).and_raise(error)
expect(commit.file_content("some/file.rb")).to eq ""
end
end
context "when exception contains no errors" do
it "raises the error" do
github = double("GitHubApi")
commit = Commit.new("test/test", "abc", github)
error = Octokit::Forbidden.new(body: { errors: [] })
allow(github).to receive(:file_contents).and_raise(error)
expect { commit.file_content("some/file.rb") }.to raise_error(error)
end
end
end
def build_commit(content)
file_contents = double(content: Base64.encode64(content))
github = double(:github_api, file_contents: file_contents)
Commit.new("test/test", "abc", github)
end
end
| true |
f1b5469ba70234d44e52e4f983b5d1fb1a826fd0 | Ruby | trevorwhitney/csci446 | /project05/test/unit/author_test.rb | UTF-8 | 1,110 | 2.65625 | 3 | [] | no_license | require 'test_helper'
class AuthorTest < ActiveSupport::TestCase
setup do
@valid_photo = File.new("test/fixtures/onion.jpg")
@invalid_photo = File.new("test/fixtures/lena.bmp")
end
teardown do
@valid_photo.close
@invalid_photo.close
end
test "name_should_not_include_pat" do
author = Author.new name: "Pat"
author.photo = @valid_photo
assert author.invalid?
author.name = "Patrick"
assert author.invalid?
author.name = "John Patrick"
assert author.invalid?
author.name = "Valid Author"
assert author.valid?
end
test "name_should_not_be_blank" do
author = Author.new
assert author.invalid?
author.name = "Author Name"
author.photo = @valid_photo
assert author.valid?
end
test "photo_should_be_present" do
author = Author.new name: "Trevor"
author.photo = @valid_photo
assert author.valid?
end
test "photo_should_be_jpeg_or_png" do
author = Author.new name: "Trevor"
author.photo = @invalid_photo
assert author.invalid?
author.photo = @valid_photo
assert author.valid?
end
end
| true |
8e10efa5e412cf7975f873b1acc979d2b20e26ae | Ruby | andrewmorrismacleod/ruby_project | /models/film.rb | UTF-8 | 1,649 | 3.140625 | 3 | [] | no_license | require_relative( '../db/sql_runner' )
require_relative ('actor')
require 'pry'
class Film
attr_reader :id, :title
def initialize( options )
@id = options['id'].to_i if options['id']
@title = options['title']
end
def save()
sql = "INSERT INTO films
(title)
VALUES
($1)
RETURNING id"
values = [@title]
results = SqlRunner.run(sql, values)
@id = results.first()['id'].to_i
end
def self.all()
sql = "SELECT * FROM films"
results = SqlRunner.run( sql )
return results.map { |film| Film.new( film ) }
end
def self.find(id)
sql = "SELECT * FROM films
WHERE id = $1"
values = [id]
results = SqlRunner.run( sql, values )
return Film.new( results.first )
end
def self.find_by_title(title)
sql = "SELECT * FROM films
WHERE title = $1"
values = [title]
results = SqlRunner.run( sql, values )
if results.first.nil?
return nil
else
return Film.new( results.first )
end
end
def update
sql = "UPDATE films
SET title = $1
WHERE id = $2"
values = [@title, @id]
SqlRunner.run(sql, values)
end
def self.delete_all()
sql = "DELETE FROM films"
SqlRunner.run( sql )
end
def self.delete(id)
sql = "DELETE FROM films
WHERE id = $1"
values = [id]
SqlRunner.run( sql, values )
end
def actors
sql = "SELECT actors.* FROM actors
INNER JOIN castings
ON actors.id = castings.actor_id
WHERE castings.film_id = $1"
values = [@id]
results = SqlRunner.run(sql, values)
return results.map { |actor| Actor.new( actor ) }
end
end
| true |
4a9d6305457abeba162ab3105c3cccfa1cae9e80 | Ruby | bruadarach/ruby-study-note | /114_rubyiestNotesStyle.rb | UTF-8 | 1,835 | 4.34375 | 4 | [] | no_license | ##### IMPLICIT RETURNS #####
# Less Preferred
def get_avg(num_1, num_2)
return (num_1 + num_2) / 2
end
puts get_avg(4, 6) #=> 5
# Preferred by a Rubyist
def get_avg(num1, num2)
(num1 + num2) / 2
end
puts get_avg(2, 6) #=> 4
##### OMMITTING PARENTHESES FOR METHOD CALLS WITH NO ARGUMENTS #####
# Less preferred
def say_hi
"hi"
end
puts say_hi() #=> hid
# Preferred by a Rubyist
def say_hi
"hi"
end
puts say_hi #=> hi
##### USE SINGLE LINE CONDITIONALS WHEN POSSIBLE #####
# Less preferred
raining = true
if raining
puts "don't forget an umbrella!"
end
# Preferred by a Rubyist
raining = true
puts "don't forget an unbrella!" if raining
##### USE BUILT-IN METHODS: .even? #####
# Less preferred
num = 6
puts num % 2 == 0 #=> true
# Preferred by a Rubyiest
num = 6
puts num.even? #=> true
##### USE BUILT-IN METHODS: .last #####
# Less preferred
people = ["Suji", "Minji", "Lucky"]
puts people[people.length-1] #= Lucky>
# Preferred by a Rubyist
people = ["Suji", "Minji", "Lucky"]
puts people[-1] #= Lucky>
puts people.last #= Lucky>
##### USE ENUMERABLES TO ITERATE: .times { puts " "} #####
# Less preferred
def repeat_hi(num)
i = 0
while i < num
puts "hi"
i += 1
end
end
repeat_hi(3)
# hi
# hi
# hi
# Preferred by a Rubyist
def repeat_hi(num)
num.times { puts "hi" }
end
repeat_hi(3)
# hi
# hi
# hi
##### USE ENUMERABLES TO ITERATE: .all? { |num| num.even? } #####
# Less preferred
def all_numbers_even?(nums)
nums.each do |num|
return false if num % 2 != 0
end
true
end
puts all_numbers_even?([2,3,4,5])
# false
puts all_numbers_even?([2,4,6,8])
# true
# Preferred by a Rubyist
def all_numbers_even?(nums)
nums.all? { |num| num.even? }
end
puts all_numbers_even?([2,3,4,5])
# false
puts all_numbers_even?([2,4,6,8])
# true
| true |
74cc4eb63d8c8f29009a85b1fe559a6ea2f63020 | Ruby | lassebunk/shortie | /lib/shortie/service.rb | UTF-8 | 783 | 3.265625 | 3 | [] | no_license | module Shortie
class Service
@@services = []
# Register a new service by key, name, and shortener, e.g. register("bitly", "bit.ly", Bitly).
def self.register(key, name, shortener)
@@services << Service.new(key, name, shortener)
end
# Get a list of all services.
def self.all
@@services
end
# Find a service by key, e.g. 'bitly'.
def self.find_by_key(key)
@@services.find { |s| s.key == key }
end
attr_accessor :key, :name, :shortener
def initialize(key, name, shortener)
self.key, self.name, self.shortener = key, name, shortener
end
# Shorten a URL. This calls the shorten(url) method on the shortener.
def shorten(url)
shortener.shorten(url)
end
end
end | true |
f2edbd1e2475be1d1bd666834b6af4b7ad1f8a4a | Ruby | harrim91/airport_challenge | /lib/airport.rb | UTF-8 | 1,416 | 3.46875 | 3 | [] | no_license | require_relative "weather"
class Airport
include Weather
DEFAULT_CAPACITY = 1
STORM_ERR = "The weather is stormy"
ACCEPT_ERR = "Plane already at an airport"
RELEASE_ERR = "Plane not at this airport"
FULL_ERR = "Airport is full"
def initialize capacity=DEFAULT_CAPACITY
@planes = []
@capacity = capacity
end
def accept plane
abort_landing plane unless ok_to_land? plane
tell_to_land plane
store_plane plane
end
def release plane
abort_take_off plane unless ok_to_take_off? plane
tell_to_take_off plane
remove_plane plane
end
private
attr_reader :planes, :capacity
def plane_flying? plane
plane.flying?
end
def full?
planes.count == capacity
end
def ok_to_land? plane
(plane_flying? plane) && !full? && !stormy?
end
def abort_landing plane
fail ACCEPT_ERR unless plane_flying? plane
fail FULL_ERR if full?
fail STORM_ERR if stormy?
end
def tell_to_land plane
plane.land
end
def store_plane plane
@planes << plane
end
def plane_in_airport? plane
planes.include? plane
end
def ok_to_take_off? plane
(plane_in_airport? plane) && !stormy?
end
def abort_take_off plane
fail RELEASE_ERR unless plane_in_airport? plane
fail STORM_ERR if stormy?
end
def tell_to_take_off plane
plane.take_off
end
def remove_plane plane
@planes.delete plane
end
end
| true |
4d9896f55c94623abc437ba180d1d881f4d84de3 | Ruby | Krishna312/test | /calculator.rb | UTF-8 | 893 | 4.1875 | 4 | [] | no_license | def add(a,b)
result = a + b
# put your code here
end
def subtract(a,b)
result = a - b
# put your code here
end
def multiply(a,b)
result = a * b
# put your code here
end
def divide(a,b)
result = a / b
# put your code here
end
puts "Welcome to RubyCalc"
print "Enter first number: "
a = gets.chomp
print "Enter second number: "
b = gets.chomp
# enter your code here
# enter your code here
print "Enter operation (+, -, *, /): "
c = gets.chomp
# enter your code here
# # do calculation
if c == "+"
result = a.to_i + b.to_i
elsif c == "-"
result = a.to_i - b.to_i
elsif c == "*"
result = a.to_i * b.to_i
elsif c == "*"
result = a.to_i / b.to_i
# elsif number == 2
# puts def subtract(a,b)
# elsif number == 3
# puts def multiply(a,b)
# elsif number == 4
# puts def divide(a,b)
else
puts "New Number"
#
end
puts "The result is: #{result}"
| true |
76ec221623e45cdccb3debd2dbac4144c77ec3a9 | Ruby | koiralakiran0/ruby-calisthenics | /lib/cartesian_product.rb | UTF-8 | 381 | 3.703125 | 4 | [] | no_license | class CartesianProduct
include Enumerable
# YOUR CODE HERE
def initialize(arr1, arr2)
@array1 = arr1
@array2 = arr2
end
def each
# ret = []
@array1.each { |x|
#temp = [x]
@array2.each { |y|
#temp.push(y)
yield [x,y]
}
# ret.push(temp)
}
#return ret
end
end
#check
#CartesianProduct.new([1,2,3],['a','b']) | true |
de9911625514571012473de83a0985fbf4eb807f | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/hamming/c8cb0105340244edb5f91e4b184cb4a9.rb | UTF-8 | 255 | 2.765625 | 3 | [] | no_license | class Hamming
def self.compute dna_strand_a, dna_strand_b
merged_dna = dna_strand_b.split('').zip dna_strand_b.split('')
merged_dna.reduce(0) do |differences, joint|
differences += 1 if joint.uniq == 2
differences
end
end
end
| true |
2539f359e91a91bbeb09f17cfe5b7b5fc28eeebe | Ruby | Maha-Magdy/Custom-HTML-Linter | /bin/main.rb | UTF-8 | 2,015 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'open-uri'
require 'colorize'
require 'tty-box'
require 'ruby-progressbar'
require_relative '../lib/file_reader'
require_relative '../lib/reviewer'
system 'clear'
system 'cls'
if ARGV[0].nil?
puts TTY::Box.warn('There is no file passed to check.')
else
progressbar = ProgressBar.create(format: "%a %b\u{15E7}%i %p%% %t",
progress_mark: ' ',
remainder_mark: "\u{FF65}",
starting_at: 0)
checking_file = FileReader.new(ARGV[0])
if checking_file.error_message.empty?
# rubocop:disable Style/Semicolon
10.times { progressbar.increment; sleep 0.02 }
Reviewer.proper_structure(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.declare_correct_doctype(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.close_tags(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.avoid_inline_style(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.check_alt_attribute_with_images(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.check_external_style_sheets_place(checking_file)
10.times { progressbar.increment; sleep 0.02 }
Reviewer.use_lowercase_tag_names(checking_file)
10.times { progressbar.increment; sleep 0.02 }
if checking_file.error_message.any?
20.times { progressbar.increment; sleep 0.02 }
errors_status = "× Found #{checking_file.error_message.length} error."\
"Try to fix it to have clean code \n\n#{checking_file.error_message.join("\n\n")}"
puts TTY::Box.error(errors_status, padding: 1)
else
20.times { progressbar.increment; sleep 0.05 }
puts TTY::Box.success('No offenses detected')
end
else
100.times { progressbar.increment; sleep 0.025 }
# rubocop:enable Style/Semicolon
puts TTY::Box.warn(checking_file.error_message.join.to_s)
end
end
| true |
7a0e9343b64ec0ed6871de67dfee3fc892bf39af | Ruby | forgotera/BMSTU_PROG_WEB_3SEM | /lab6_3/lambdaMain6_3.rb | UTF-8 | 297 | 3.796875 | 4 | [] | no_license | require './logical6_3'
def main(n)
puts "enter #{n} coordinate x y "
(0...n).each do |i|
puts "#{i+1} coordinate"
x = gets.to_f
y = gets.to_f
yield x, y
end
end
puts 'how much coordinate do you want to enter?'
n = gets.to_i
block = ->(x, y) { neibr x, y }
main(n, &block)
| true |
9ef2b01949350738e994db862f0709ab9fab8bae | Ruby | pombreda/NounNews | /lib/noun_identifier/override.rb | UTF-8 | 760 | 3.296875 | 3 | [] | no_license | module NounIdentifier
class Override
def initialize(identifier)
@identifier = identifier
@nouns = File.read('data/override/nouns.txt').split.map(&:downcase)
@not_nouns = File.read('data/override/not_nouns.txt').split.map(&:downcase)
end
def is_noun?(word)
# no posessives
return false if word =~ /'/
# nothing with a number in it is a noun
return false if word =~ /\d/
# nothing with a hyphen in it is a noun
return false if word =~ /-/
# all uppercase acronyms are nouns
return true if word =~ /^[A-Z]{2,}$/
return true if @nouns.include?(word.downcase)
return false if @not_nouns.include?(word.downcase)
@identifier.is_noun?(word)
end
end
end
| true |
661ff51e5fd8a375f11e0e32243b4801c37f0f98 | Ruby | Matt808/Challenge-F | /Banger.rb | UTF-8 | 456 | 2.953125 | 3 | [] | no_license | # Use this variable to speed up, then slow down the sample
x = 1
# Use this variable to store the long file path of your sample
banger = "C:/Users/matthew_marin/Downloads/challenge_f/this_is_a_banger.wav"
sample banger
sleep 3
4.times do
x = x - 0.1
sample banger, rate: x
sleep 3
print x
end
4.times do
x = x + 0.1
sample banger, rate: x
sleep 3
print x
end
with_fx :reverb do
sample banger, rate: 1.5
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.