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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
edb92fa17bcd4c1a6c08aad6c3ed695cd882ed2a | Ruby | kcmills/mutiny | /spec/unit/tests/test_set/filterable_spec.rb | UTF-8 | 2,004 | 2.640625 | 3 | [
"MIT"
] | permissive | module Mutiny
module Tests
class TestSet
describe Filterable do
context "for" do
let(:subjects) { subject_set_for("Max", "Min") }
let(:test_set) { test_set_for("Min", "Min#run", subjects: subjects) }
it "should return only those tests that are relevant to the subject" do
expected = test_set_for("Min", "Min#run", subjects: subjects)
expect(test_set.for(subjects["Min"])).to eq(expected)
end
it "should return no tests if none are relevant to the subject" do
expect(test_set.for(subjects["Max"])).to eq(TestSet.empty)
end
end
context "for all" do
let(:subjects) { subject_set_for("Max", "Min") }
let(:test_set) { test_set_for("Min", "Min#run", subjects: subjects) }
it "should remove irrelevant tests" do
expected = test_set.subset { |t| t.name != "Subtract" }
expect(test_set.for_all(subjects)).to eq(expected)
end
it "should return all relevant tests" do
expected = test_set.subset { |t| t.name.start_with?("Min") }
expect(test_set.for_all(subjects)).to eq(expected)
end
it "should return no tests when there are no tests" do
expect(TestSet.empty.filterable(subjects).for_all(subjects)).to eq(TestSet.empty)
end
end
def subject_set_for(*names)
Subjects::SubjectSet.new(names.map { |n| Subjects::Subject.new(name: n) })
end
def test_set_for(*expressions, subjects:)
TestSet.new(tests_for(*expressions))
.filterable(subjects, filtering_strategy: DummyStrategy)
end
def tests_for(*names)
names.map { |name| Test.new(name: name) }
end
class DummyStrategy < Filter
def related?(subject_name:, test_name:)
test_name.start_with?(subject_name)
end
end
end
end
end
end
| true |
1ab098b117999d04d7ff8e732fe41cad190d8de8 | Ruby | ClaudiaPfeil/schwab-auber | /cloth_app/vendor/plugins/cp_utils/lib/model_methods.rb | UTF-8 | 674 | 2.765625 | 3 | [
"MIT"
] | permissive | # To change this template, choose Tools | Templates
# and open the template in the editor.
module ModelMethods
def self.build_attribute_accessor(attributes)
method_symbols = ""
method_symbols << ":" << attributes.map { |value| '%s%s' % value}.join(',:') unless attributes.nil?
#method_symbols
end
def self.attr_accessor(*method_symbols)
method_symbols = method_symbols.to_s.gsub(":", "").gsub(" ", "").gsub("-", "_").split(/,/)
method_symbols.each { | method |
module_eval("def #{method.downcase}; return @#{method.downcase}; end")
}
end
def translate(collection)
collection.map { |word| I18n.t(word.to_sym)}
end
end
| true |
1c97d0f90e80143c1b186e906dbf2791316399ac | Ruby | Witchrist/nivelamento-aluno | /06-exercicio.rb | UTF-8 | 3,231 | 3.78125 | 4 | [] | no_license | def valida_parametros(vacinacao, transmissao, leitos)
if vacinacao<0.0 || vacinacao>1.0
validacao = "Dado inválido: vacinação "+vacinacao.to_s
elsif transmissao<0.0
validacao = "Dado inválido: transmissão "+transmissao.to_s
elsif leitos<0.0 || leitos>1.0
validacao = "Dado inválido: leitos "+leitos.to_s
else
validacao = nil
end
return validacao
end
def fase_pandemica(vacinacao, transmissao, leitos)
if valida_parametros(vacinacao, transmissao, leitos)!=nil
fase = "Por favor, ajuste os valores inseridos..."
elsif vacinacao>0.8
fase = "AZUL"
elsif leitos<=0.5 && transmissao<1
fase = "VERDE"
elsif leitos<=0.65 && transmissao<1
fase = "AMARELO"
elsif leitos<=0.8 && transmissao<1
fase = "LARANJA"
elsif leitos<=0.9 || transmissao>=1
fase = "VERMELHO"
else
fase = "ROXA"
end
return fase
end
print "Insira a taxa de vacinação: "
vacinacao = gets.to_f
print "Insira o fator de transmissão: "
transmissao = gets.to_f
print "Insira a taxa de ocupação de leitos: "
leitos = gets.to_f
puts valida_parametros(vacinacao, transmissao, leitos)
puts fase_pandemica(vacinacao, transmissao, leitos)
# Estamos vivendo uma pandemia e o governador pediu um sistema para indicar qual a cor da fase
# pandêmica em que está o Estado.
# A cor da fase pandêmica é definida baseada em três valores:
# 1) A taxa de vacinação da população.
# 2) O fator de transmissão do vírus.
# 3) A taxa de ocupação dos leitos de UTI.
# As regras para definição de cada fase são as seguintes:
# - FASE AZUL: quando que a taxa de vacinação estiver acima de 80% (percentual de imunização coletiva)
# - FASE VERDE: quando a taxa de ocupação de leitos estiver abaixo ou igual a 50%,
# porém com fator de transmissão menor que 1.
# - FASE AMARELA: quando a taxa de ocupação de leitos estiver acima de 50%,
# porém com fator de transmissão menor que 1.
# - FASE LARANJA: quando a taxa de ocupação de leitos estiver acima de 65%,
# porém com fator de transmissão menor que 1.
# - FASE VERMELHA: quando a taxa de ocupação de leitos estiver acima de 80%
# ou quando o fator de transmissão for maior ou igual a 1.
# - FASE ROXA: quando a taxa de ocupação de leitos estiver acima de 90%.
# Para atender o sistema, defina uma função chamada 'fase_pandemica' que deve
# receber três parâmetros (taxa de vacinação, fator de transmissão e taxa de ocupação de leitos)
# e baseado nas regras descritas acima, retornar uma string com o nome da cor da fase da pandemia.
# Ex.: ao executar o seguinte comando:
# fase_pandemica(0.1, 0.7, 0.5)
# Deve retornar a string "VERDE".
# Obs.: validar os parâmetros, considerando as seguintes regras:
# - taxa de vacinação deve ser um número entre 0.0 e 1.0 (1.0 = 100%)
# - fator de transmissão dever ser um número maior ou igual a zero
# - taxa de ocupação de leitos deve ser um número entre 0.0 e 1.0 (1.0 = 100%)
# Se houver alguma invalidação nas regras acima, retornar uma string que descreva a regra
# que foi invalidada.
# Obs. 2: escreva testes para demonstrar que o sistema está funcionando. | true |
dd1a146811a31a6de8620983e788eaa4a92da3ff | Ruby | barsoom/attr_extras | /spec/attr_extras/method_object_spec.rb | UTF-8 | 901 | 3 | 3 | [
"MIT"
] | permissive | require "spec_helper"
describe Object, ".method_object" do
it "creates a .call class method that instantiates and runs the #call instance method" do
klass = Class.new do
method_object :foo
def call
foo
end
end
assert klass.call(true)
refute klass.call(false)
end
it "doesn't require attributes" do
klass = Class.new do
method_object
def call
true
end
end
assert klass.call
end
it "accepts a block for initialization" do
klass = Class.new do
method_object :value do
@copy = @value
end
attr_reader :copy
end
example = klass.new("expected")
_(example.copy).must_equal "expected"
end
it "passes along any block" do
klass = Class.new do
method_object
def call
yield
end
end
assert klass.call { :foo } == :foo
end
end
| true |
903ee3ad365bcf5c5fce90ea659a0accbbdbd941 | Ruby | jonathanpberger/pairtrix | /app/models/pair.rb | UTF-8 | 1,043 | 2.71875 | 3 | [
"MIT"
] | permissive | class Pair < ActiveRecord::Base
belongs_to :pairing_day
has_many :pair_memberships, inverse_of: :pair
has_many :team_memberships, through: :pair_memberships
has_many :employees, through: :team_memberships
validates_presence_of :pairing_day
validate :validate_team_membership_count
def validate_team_membership_count
errors.add(:base, "You must include two team members.") if team_memberships.size < 2
end
def name
pair_memberships.map(&:name).join("-")
end
def employee_one
pair_memberships[0].name
end
def employee_two
pair_memberships[1].name
end
def memberships_active?(active_memberships)
team_memberships.all? { |team_membership| active_memberships.include?(team_membership) }
end
def has_membership?(membership)
team_memberships.detect { |team_membership| team_membership.employee_id == membership.employee_id }
end
def other_membership(membership)
team_memberships.detect { |team_membership| team_membership.employee_id != membership.employee_id }
end
end
| true |
9316b8245d053720abd1fb14de2ff9f4c5186cf6 | Ruby | clm1403/Intro-to-programming | /loops_and_iterators/exercise_2.rb | UTF-8 | 232 | 3.171875 | 3 | [] | no_license | looping = "Let's go looping ... "
puts looping
user_answer = gets.chomp
still_looping = ''
while still_looping != "STOP" do
puts looping
puts "Still looping here ..."
still_looping = gets.chomp
end
puts "Thanks for playing." | true |
49a5e1b8d208c113296b1cfadae4588563ffd13e | Ruby | SteveBirtles/RubyMetaprogramming | /Example3.rb | UTF-8 | 307 | 2.90625 | 3 | [] | no_license | class CarModel
attr_accessor :engine_info, :engine_price,
:wheel_info, :wheel_price,
:airbag_info, :airbag_price,
:alarm_info, :alarm_price,
:stereo_info, :stereo_price
end
car = CarModel.new()
car.stereo_price = 4
puts car.stereo_price
| true |
66270cbde7d972e657b9f817d2db33dc561125d3 | Ruby | AugustoPresto/LP-Database | /app/views/lps_view.rb | UTF-8 | 278 | 2.953125 | 3 | [] | no_license | class LpsView
def index(lps)
puts ""
puts "Listing all your LPs..."
lps.each do |lp|
puts "#{lp.id}. #{lp.artist} - #{lp.title} - #{lp.year} - R$ #{lp.price}"
end
end
def ask_for(string)
puts "#{string}?"
print "> "
gets.chomp
end
end
| true |
a48734fcd11b89e504f75d8fcaec979ecbfd9b19 | Ruby | chubberlisk/tic-tac-toe | /lib/user_interface/presenter.rb | UTF-8 | 796 | 2.734375 | 3 | [] | no_license | # frozen_string_literal: true
class UserInterface::Presenter
def initialize(start_new_game:, evaluate_game:, take_turn:, user_interface:)
@start_new_game = start_new_game
@evaluate_game = evaluate_game
@take_turn = take_turn
@ui = user_interface
end
def execute(*)
first_player = @ui.ask_user_for_first_player
start_new_game_response = @start_new_game.execute(first_player: first_player)
@ui.display_turn(start_new_game_response)
while @evaluate_game.execute[:outcome] == :continue
position = @ui.ask_user_for_position
take_turn_response = @take_turn.execute(position: position)
@ui.display_turn(take_turn_response)
end
evaluate_game_response = @evaluate_game.execute
@ui.display_game_over(evaluate_game_response)
end
end
| true |
877635a33bdc517c19dfe79335e449e7bd035b30 | Ruby | bunmiaj/CodeAcademy | /Web-Development/Ruby/5- Loops & Iterators/3.rb | UTF-8 | 692 | 4.71875 | 5 | [] | no_license | # The 'Until' Loop
# The complement to the while loop is the until loop. It's sort of like a backwards while:
# i = 0
# until i == 6
# i += 1
# end
# puts i
# In the example above, we first create a variable i and set it to zero.
# Then we execute a block of code until i is equal to 6. That block of code increments i.
# When i is equal to 6, the block ends.
# Finally, we print 6, the value of i, to the console.
# Instructions
# On line 2, fill in the __ blank so that the loop breaks when counter is greater than 10.
# On line 5, increment counter like we do in the example above.
counter = 1
until counter > 10
puts counter
# Add code to update 'counter' here!
counter += 1
end | true |
74501f7e9e8ef8c07aa8ed852bff8fa1ad9d5db4 | Ruby | DFE-Digital/get-help-to-retrain | /spec/models/job_vacancy_spec.rb | UTF-8 | 4,652 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'rails_helper'
RSpec.describe JobVacancy do
describe '#title' do
it 'returns the title from a parsed body' do
body = { 'title' => 'Some title' }
expect(described_class.new(body).title).to eq('Some title')
end
it 'returns nil if title missing' do
body = {}
expect(described_class.new(body).title).to be_nil
end
end
describe '#url' do
it 'returns the url from a parsed body' do
body = { 'url' => 'https://example.com' }
expect(described_class.new(body).url).to eq('https://example.com')
end
it 'returns nil if url is missing' do
body = {}
expect(described_class.new(body).url).to be_nil
end
end
describe '#closing_date' do
it 'returns the closing date from a parsed body' do
body = { 'closing' => '2019-10-11T18:56:40' }
expect(described_class.new(body).closing_date).to eq('2019-10-11T18:56:40')
end
it 'returns nil if closing date is empty' do
body = { 'closing' => '' }
expect(described_class.new(body).closing_date).to be_nil
end
it 'returns nil if closing date is missing' do
body = {}
expect(described_class.new(body).closing_date).to be_nil
end
end
describe '#date_posted' do
it 'returns the posted date from a parsed body' do
body = { 'posted' => '2019-10-11T18:56:40' }
expect(described_class.new(body).date_posted).to eq('2019-10-11T18:56:40')
end
it 'returns nil if posted date is empty' do
body = { 'posted' => '' }
expect(described_class.new(body).date_posted).to be_nil
end
it 'returns nil if posted date is missing' do
body = {}
expect(described_class.new(body).date_posted).to be_nil
end
end
describe '#company' do
it 'returns the company from a parsed body' do
body = { 'company' => 'University College London' }
expect(described_class.new(body).company)
.to eq('University College London')
end
it 'returns nil if the company is empty' do
body = { 'company' => '' }
expect(described_class.new(body).company).to be_nil
end
it 'returns nil if company is missing' do
body = {}
expect(described_class.new(body).company).to be_nil
end
end
describe '#location' do
it 'returns the location from a parsed body' do
body = { 'location' => 'London, UK' }
expect(described_class.new(body).location).to eq('London, UK')
end
it 'returns nil if the location is empty' do
body = { 'location' => '' }
expect(described_class.new(body).location).to be_nil
end
it 'returns nil if location is missing' do
body = {}
expect(described_class.new(body).location).to be_nil
end
end
describe '#salary' do
it 'returns the salary from a parsed body' do
body = { 'salary' => '£21 to £22 per hour' }
expect(described_class.new(body).salary).to eq('£21 to £22 per hour')
end
it 'returns nil if the salary is empty' do
body = { 'salary' => '' }
expect(described_class.new(body).salary).to be_nil
end
it 'returns nil if salary is missing' do
body = {}
expect(described_class.new(body).salary).to be_nil
end
end
describe '#description' do
it 'returns the description from a parsed body' do
body = { 'description' => 'Division Information Services Division' }
expect(described_class.new(body).description).to eq('Division Information Services Division')
end
it 'returns truncated description if text longer than 260 characters' do
body = {
'description' => 'UCL Department / Division Information Services Division Specific unit \
Sub department Shared Services / Resource Pool Location of position London Grade 8 Hours \
Full Time Salary (inclusive of London allowance) Competitve Duties and Responsibilities \
Are you a Development Manager looking to manage a large team of developers or a Team Lead'
}
expect(described_class.new(body).description).to eq(
'UCL Department / Division Information Services Division Specific unit \
Sub department Shared Services / Resource Pool Location of position London Grade 8 Hours \
Full Time Salary (inclusive of London allowance) Competitve Duties and Respons...'
)
end
it 'returns nil if description is empty' do
body = { 'description' => '' }
expect(described_class.new(body).description).to be_nil
end
it 'returns nil if description is missing' do
body = {}
expect(described_class.new(body).description).to be_nil
end
end
end
| true |
a48fa928ca3e3cd50827126a6559dad3c537e0de | Ruby | AlanGabbianelli/oystercard-2 | /lib/oystercard.rb | UTF-8 | 665 | 3.203125 | 3 | [] | no_license | require_relative 'journey'
class Oystercard
attr_reader :balance, :journey
MAX_BALANCE = 50
MIN_LIMIT = 0
def initialize(journey_klass = Journey)
@balance = 0
@journey = journey_klass
end
def top_up(amount)
fail "Max balance #{MAX_BALANCE} reached" if @balance + amount > MAX_BALANCE
@balance += amount
end
def touch_in(entry_station)
@journey = @journey.new(entry_station)
fail 'Insuffient funds' if @balance < Journey::MIN_FARE
end
def touch_out(exit_station)
journey.end_at(exit_station)
deduct(@journey.fare)
@journey = Journey
end
private
def deduct(amount)
@balance -= amount
end
end
| true |
e28099d6bd374a63550257f716a60646d4feb0ca | Ruby | dajia/RubyTraining | /namexample.rb | UTF-8 | 1,017 | 3.375 | 3 | [] | no_license | puts 'what is you firts name?'
name = gets.chomp
puts 'what is your middle name?'
name2=gets.chomp
puts 'what is you last name?'
name3=gets.chomp
puts "Greetings " + name + ' '+ name2+ ' ' + name3 + '!' + ' Who is you favorite number?'
number=gets.chomp
number2 = number.to_i + 1.to_i
puts 'well' + ' ' + name + ' '+ name2+ ' ' + name3 +' I guess that ' + number2.to_s + ' is bigger and favorite number!'
puts 'what is you firts name?'
name = gets.chomp
puts 'what is your middle name?'
name2=gets.chomp
puts 'what is you last name?'
name3=gets.chomp
puts "Greetings " + name + ' '+ name2+ ' ' + name3 + '!' + ' Who is you favorite number?'
number=gets.chomp
number.to_s
number2 = number + '1'
puts 'well' + ' ' + name + ' '+ name2+ ' ' + name3 +' I guess that ' + number2 + ' is bigger and favorite number!'
puts self | true |
61dba878447915a18c25f9b05d1efe64378bf4b4 | Ruby | karlwitek/launch_school_rb130 | /ruby_challenges/easy/word_count.rb | UTF-8 | 1,219 | 4.28125 | 4 | [] | no_license | # Write a program that given a phrase can count the occurences of each word in that phrase.
class Phrase
attr_reader :phrase
def initialize(phrase)
@phrase = phrase
end
def clean_up_phrase
# remove punctuation (except apostrophes, numbers)
# normalize case here? tests: hash includes all lowercase words
# arr = phrase.split(%r{,\s*})
# arr = phrase.split(/[,]/).join.split(' ')
arr = phrase.split(',')
p arr
arr = arr.map { |e| e.split(' ') }.flatten
p arr
b = arr.map { |word| word.gsub(/[^0-9a-zA-Z']/, '')}.map { |word| word.downcase }
b.select { |el| el != '' }
end
def word_count
hash = Hash.new(0)
arr = clean_up_phrase
arr.each do |word|
num = arr.count(word)
hash[word] = num unless hash.has_key?(word)
end
hash
end
end
# phrase = Phrase.new('testing, 1, 2 testing')
#phrase = Phrase.new('testing,1,2 testing')
# p phrase.word_count
# counts = { 'testing' => 2, '1' => 1, '2' => 1 }
#phrase = Phrase.new('one,two,three')
phrase = Phrase.new("Joe can't tell between 'large' and large.")
p phrase.word_count
# counts = { 'one' => 1, 'two' => 1, 'three' => 1 } | true |
8d249fe21c2699c8075c209cdfdc0f018d010cf9 | Ruby | samk826/todo-ruby-basics-online-web-prework | /lib/ruby_basics.rb | UTF-8 | 362 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def division(num1, num2)
12/2
end
def assign_variable(value)
value
end
def argue(phrase)
phrase
end
def greeting(greeting,name)
puts "#{greeting} ejcbecb #{name}"
end
def return_a_value
(return_a_value="Nice")
end
def last_evaluated_value
last_evaluated_value="expert"
end
def pizza_party(choice="cheese")
puts choice
pizza_party=choice
end
| true |
487876e58cebb801887bf34c86bd3eb9d0a1bb5b | Ruby | MargaretLzy/programming-univbasics-2-statement-repetition-with-while-yale-web-yss-051721 | /lib/count_down.rb | UTF-8 | 103 | 3.21875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # Write your code here
count = 10
while (count>0) do
puts count
count-=1
end
puts "Happy New Year!" | true |
018267e602349fdc13cf61aadfd3d107fe7825d9 | Ruby | brandnewlink/noteblock | /app/services/aes.rb | UTF-8 | 795 | 2.875 | 3 | [] | no_license | require 'openssl'
module AES
extend self
def encrypt(string, key)
Base64.urlsafe_encode64(aes(key, string))
end
def decrypt(string, key)
aes_decrypt(key, Base64.urlsafe_decode64(string))
end
def aes(key,string)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
cipher.key = Digest::SHA256.digest(key)
cipher.iv = initialization_vector = cipher.random_iv
cipher_text = cipher.update(string)
cipher_text << cipher.final
return initialization_vector + cipher_text
end
def aes_decrypt(key, encrypted)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = Digest::SHA256.digest(key)
cipher.iv = encrypted.slice!(0,16)
d = cipher.update(encrypted)
d << cipher.final
end
end
| true |
66615a9da454f5ec8268a0ad7f1bd8e536171c7f | Ruby | johndillon773/101_109_small_problems | /medium_2/9.rb | UTF-8 | 475 | 4 | 4 | [] | no_license | # bubble sort
def bubble_sort!(arr)
n = arr.length
loop do
newn = 0
1.upto(n-1) do |i|
if arr[i-1] > arr[i]
arr[i-1], arr[i] = arr[i], arr[i-1]
newn = i
end
end
n = newn
break if n == 0
end
end
array = [5, 3]
bubble_sort!(array)
p array == [3, 5]
array = [6, 2, 7, 1, 4]
bubble_sort!(array)
p array == [1, 2, 4, 6, 7]
array = %w(Sue Pete Alice Tyler Rachel Kim Bonnie)
bubble_sort!(array)
p array == %w(Alice Bonnie Kim Pete Rachel Sue Tyler)
| true |
788109843009c184439fd2e61ae39fc03fb64c6c | Ruby | WozniakMac/penalty_game | /tests/game_list_test.rb | UTF-8 | 484 | 2.515625 | 3 | [] | no_license | require_relative '../lib/game_list'
require 'test/unit'
# tests/game_list_test.rb
class TestGameList < Test::Unit::TestCase
def test_creating_game
game = GameList.instance.create
assert_instance_of(Game, game)
game2 = GameList.instance.find(game.id)
assert_instance_of(Game, game2)
end
def test_game
game = GameList.instance.create
assert_equal(GameList.instance.game?(game.id), true)
assert_equal(GameList.instance.game?('adam'), false)
end
end
| true |
6ca204a77bd4e73b6cdac025cd49b68a296a738d | Ruby | wudip/need-not-to-speed | /lib/view/painters/background.rb | UTF-8 | 463 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'view/painters/painter'
module NeedNotToSpeed
module View
# Background of a game (image of surface on which car moves)
class Background < Painter
PATH_TEMPLATE = 'lib/images/map/map_%<level>s.png'.freeze
def initialize(world, level)
super(world)
path = format(PATH_TEMPLATE, level: level)
@image = Gosu::Image.new(path)
end
def draw
draw_img(@image, 0, 0, 0)
end
end
end
end
| true |
7b8154e30713c239905f5732c77bae0614a4eb69 | Ruby | yhk1038/facebook_page_manager | /app/helpers/application_helper.rb | UTF-8 | 1,565 | 2.515625 | 3 | [] | no_license | require 'rails_autolink'
module ApplicationHelper
# Facebook Scope request parameters and lists
def scope_parameters
'?scope='+scope_list.join(',')
end
def scope_list
%w(pages_show_list manage_pages publish_pages read_page_mailboxes pages_messaging read_insights)
end
# Flash message
def bootstrap_class_for(flash_type)
case flash_type
when "success"
"alert-success" # Green
when "error"
"alert-danger" # Red
when "alert"
"alert-warning" # Yellow
when "notice"
"alert-info" # Blue
else
flash_type.to_s
end
end
def time_parse_stringify(raw_time)
date, time = raw_time.split('T')
time = time.split('+')[0]
year = date.split('-')[0]
month = date.split('-')[1]
day = date.split('-')[2]
hour = time.split(':')[0]
minute = time.split(':')[1]
sec = time.split(':')[2]
ut = DateTime.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, sec.to_i) + 9.hour
noon = '오후'
noon = '오전' if ut.hour < 12
_hour = ut.hour
_hour = ut.hour - 12 if ut.hour > 12
hour_ = _hour.to_s
hour_ = '0'+_hour.to_s if _hour < 10
min_ = ut.min.to_s
min_ = '0'+ut.min.to_s if ut.min < 10
str = "#{ut.year}년 #{ut.month}월 #{ut.day}일 #{noon} #{hour_}:#{min_}"
# 2017년 3월 10일 오전 11:41
str
end
end
| true |
ce46a257a6761281dbddfb72967b1c22a0f97cde | Ruby | scroniser/learn_ruby | /02_calculator/calculator.rb | UTF-8 | 407 | 3.796875 | 4 | [] | no_license | def add(v1, v2)
v1 + v2
end
def subtract(v1, v2)
v1 - v2
end
def sum(array)
array.inject(0){|running_total, item| running_total + item }
end
def multiply(array)
array.inject(1){|running_total, item| running_total * item }
end
def power(v1, v2)
v1**v2
end
def factorial(num)
if num > 0
total = 1
for n in 1..num
total *= n
end
return total
else
return 0
end
end | true |
c193dbd4882403a5b096d213c22136aab44b6534 | Ruby | doniexun/furnace | /lib/furnace/ssa/constant.rb | UTF-8 | 834 | 3.125 | 3 | [
"MIT"
] | permissive | module Furnace
class SSA::Constant < SSA::Value
attr_reader :type
attr_reader :value
def initialize(type, value)
@value = value
@type = type.to_type
super()
end
def type=(type)
@type = type.to_type
SSA.instrument(self)
end
def value=(value)
@value = value
SSA.instrument(self)
end
def constant?
true
end
def ==(other)
if other.respond_to? :to_value
other_value = other.to_value
other_value.constant? &&
other_value.type == type &&
other_value.value == value
else
false
end
end
def awesome_print_as_value(p=AwesomePrinter.new)
type.awesome_print(p)
p.text @value.inspect
p
end
def inspect
awesome_print
end
end
end
| true |
83cd1664cea4d987ade0c531727ae7be20037605 | Ruby | celinero/ruby-order-picker | /group.rb | UTF-8 | 1,033 | 3.328125 | 3 | [] | no_license | require_relative "methods"
class Group
attr_reader :name, :names_array
def initialize(group_name, file_path)
@name = group_name
@path = file_path
@names_array = self.path_to_array
end
def randomise_order
@names_array.shuffle
end
def output_random_array
randomise_order.each_with_index do |name, index|
puts "#{index + 1}. #{capitalize_multi_word_string(name)}".colorize
end
puts "\n"
end
def add_name(name)
@names_array.push(name)
end
def path_to_array
begin
array = File.readlines(get_file_path).map {|name| name.}
rescue
puts "invalid path, creating file"
File.open(get_file_path, "w") do |file|
file.write("")
end
array = []
end
return array
end
def save
File.open(@path, "w+") do |file|
file.puts(@names_array)
end
end
private
def get_file_path
@path
end
end
test_group = Group.new("test group", "./groups/test-group.txt")
test_group.add_name("Bob Smith")
test_group.save | true |
2122c6de042e942c8fb3c2beba6860b3b8ffe3cd | Ruby | acareaga/headcount | /lib/enrollment.rb | UTF-8 | 3,663 | 3.109375 | 3 | [] | no_license | require_relative 'district'
require_relative 'formatting'
class Enrollment
attr_reader :district_data, :name, :dropout_rate_by_year
def initialize(name, enrollment_data)
@dropout_rate_by_year = enrollment_data.fetch(:dropout_rates)
@graduation_rates = enrollment_data.fetch(:graduation_rates)
@participation_by_year = enrollment_data.fetch(:pupil_enrollment)
@kindergarten_participation = enrollment_data.fetch(:kindergarten_participation)
@online_participation = enrollment_data.fetch(:online_participation)
@pupil_enrollment_by_race_ethnicity = enrollment_data.fetch(:pupil_enrollment_by_race_ethnicity)
@special_education = enrollment_data.fetch(:special_education)
@remediation= enrollment_data.fetch(:remediation)
end
def dropout_rate_in_year(year)
dropout_rate_by_year[:"all students"][year]
end
def dropout_rate_by_gender_in_year(year)
{ :female => dropout_rate_by_year[:"female students"][year],
:male => dropout_rate_by_year[:"male students"][year] }
end
def dropout_rate_by_race_in_year(year)
{ :asian => dropout_rate_by_year[:"asian students"][year],
:black => dropout_rate_by_year[:"black students"][year],
:hispanic => dropout_rate_by_year[:"hispanic students"][year],
:white => dropout_rate_by_year[:"white students"][year],
:native_american => dropout_rate_by_year[:"native american students"][year],
:pacific_islander => dropout_rate_by_year[:"native hawaiian or other pacific islander"][year],
:two_or_more => dropout_rate_by_year[:"two or more races"][year]
}
end
def dropout_rate_for_race_or_ethnicity(race)
race = race.to_s + " students"
dropout_rate_by_year[race.to_sym]
end
def dropout_rate_for_race_or_ethnicity_in_year(race, year)
dropout_rate_by_race_in_year(year)[race]
end
def graduation_rate_by_year
@graduation_rates
end
def graduation_rate_in_year(year)
@graduation_rates.values_at(year).pop
end
def kindergarten_participation_by_year
@kindergarten_participation
end
def kindergarten_participation_in_year(year)
@kindergarten_participation.values_at(year).pop
end
def online_participation_by_year
@online_participation
end
def online_participation_in_year(year)
@online_participation.values_at(year).pop
end
def participation_by_year
@participation_by_year
end
def participation_in_year(year)
@participation_by_year.values_at(year).pop
end
def participation_by_race_or_ethnicity(race)
race = race.to_s + " students"
hash = @pupil_enrollment_by_race_ethnicity[race.to_sym]
if hash == nil
UnknownRaceError
else
hash
end
end
def participation_by_race_or_ethnicity_in_year(year)
{ :asian => @pupil_enrollment_by_race_ethnicity[:"asian students"][year],
:black => @pupil_enrollment_by_race_ethnicity[:"black students"][year],
:hispanic => @pupil_enrollment_by_race_ethnicity[:"hispanic students"][year],
:white => @pupil_enrollment_by_race_ethnicity[:"white students"][year],
:native_american => @pupil_enrollment_by_race_ethnicity[:"american indian students"][year],
:pacific_islander => @pupil_enrollment_by_race_ethnicity[:"native hawaiian or other pacific islander"][year],
:two_or_more => @pupil_enrollment_by_race_ethnicity[:"two or more races"][year]
}
end
def special_education_by_year
@special_education
end
def special_education_in_year(year)
@special_education.values_at(year).pop
end
def remediation_by_year
@remediation
end
def remediation_in_year(year)
@remediation.values_at(year).pop
end
end
| true |
8d7960e036116d00638556668ae3509eb55ac56f | Ruby | amangautamberyl/training_and_learning | /ruby/ruby_multiarray.rb | UTF-8 | 634 | 3.328125 | 3 | [] | no_license | class ArrayExample
def multidim_array
@str_details = Array['id','firstname', 'lastname', 'Company' ],[1,'Aman', 'Gautam','Beryl'],['2', 'Anand', 'Kumar', 'Beryl']
#@empty_array = Array.new #blank array
puts "#{@str_details[0][0]} \t #{@str_details[0][1]} \t #{@str_details[0][2]} \t #{@str_details[0][3]}"
puts "#{@str_details[1][0]} \t #{@str_details[1][1]} \t \t #{@str_details[1][2]} \t #{@str_details[1][3]} "
puts "#{@str_details[2][0]} \t #{@str_details[2][1]} \t \t #{@str_details[2][2]} \t \t #{@str_details[2][3]} "
#puts "#{@empty_array}"
end
end
ob=ArrayExample.new
ob.multidim_array()
| true |
2967bc3add49102e1da3691170b8483da25f2578 | Ruby | kulraj-singh/ruby | /4palindrome.rb | UTF-8 | 350 | 3.796875 | 4 | [] | no_license | class String
def palindrome?
# compare string with its reverse in ignore case mode. casecmp returns zero if they match
casecmp(reverse) == 0
end
end
puts "enter the string to check. enter q to quit"
while
string = gets.chomp
break if string.match(/^q$/i)
puts (string.palindrome?) ? "it is palindrome" : "it is not palindrome"
end
| true |
267e90c15fc726057bbaf41018d2653bc4884be5 | Ruby | doches/corncob | /scripts/get_words_rmc.rb | UTF-8 | 471 | 2.828125 | 3 | [] | no_license | prefix = ARGV[0]
words_f = IO.readlines("#{prefix}.wordmap").map { |x| x.strip.split(" ") }
words = {}
words_f.each { |pair| words[pair[0].to_i] = pair[1] }
counts = IO.readlines("#{prefix}.counts").map { |x| x.strip.split(" ").map { |x| x.to_i } }
counts.each_with_index { |x,x_i| x.each_with_index { |w_c, w_i| counts[x_i][w_i] = [w_c,w_i] } }
counts.map! { |x| x.sort { |a,b| b[0] <=> a[0] } }
counts.each do |category|
p category[0..9].map { |x| words[x[1]] }
end
| true |
262897b70972a633a1b41cddbe923a5b702677e3 | Ruby | DouglasAllen/code-The_Book_of_Ruby | /code/ch06/if_else_alt.rb | UTF-8 | 371 | 4.53125 | 5 | [] | no_license | # ch06 The Book of Ruby - http://www.sapphiresteel.com
def dayIs(aDay)
(aDay == 'Saturday' || aDay == 'Sunday') ?
daytype = 'weekend' :
daytype = 'weekday'
daytype
end
x = 11
x == 10 ? puts("it's 10") : puts("it's some other number")
day1 = 'Monday'
day2 = 'Saturday'
print(day1 + ' is a ' + dayIs(day1) + "\n")
print(day2 + ' is a ' + dayIs(day2) + "\n")
| true |
94def714521e31c58a2ed366bf1f9816d1989af7 | Ruby | seattlerb/sexp_processor | /lib/sexp_matcher.rb | UTF-8 | 23,830 | 3.0625 | 3 | [
"MIT"
] | permissive | class Sexp #:nodoc:
##
# Verifies that +pattern+ is a Matcher and then dispatches to its
# #=~ method.
#
# See Matcher.=~
def =~ pattern
raise ArgumentError, "Not a pattern: %p" % [pattern] unless Matcher === pattern
pattern =~ self
end
##
# Verifies that +pattern+ is a Matcher and then dispatches to its
# #satisfy? method.
#
# TODO: rename match?
def satisfy? pattern
raise ArgumentError, "Not a pattern: %p" % [pattern] unless Matcher === pattern
pattern.satisfy? self
end
##
# Verifies that +pattern+ is a Matcher and then dispatches to its #/
# method.
#
# TODO: rename grep? match_all ? find_all ?
def / pattern
raise ArgumentError, "Not a pattern: %p" % [pattern] unless Matcher === pattern
pattern / self
end
##
# Recursively searches for the +pattern+ yielding the matches.
def search_each pattern, &block # TODO: rename to grep?
raise ArgumentError, "Needs a pattern" unless pattern.kind_of? Matcher
return enum_for(:search_each, pattern) unless block_given?
if pattern.satisfy? self then
yield self
end
self.each_sexp do |subset|
subset.search_each pattern, &block
end
end
##
# Recursively searches for the +pattern+ yielding each match, and
# replacing it with the result of the block.
#
def replace_sexp pattern, &block # TODO: rename to gsub?
raise ArgumentError, "Needs a pattern" unless pattern.kind_of? Matcher
return yield self if pattern.satisfy? self
# TODO: Needs #new_from(*new_body) to copy file/line/comment
self.class.new(*self.map { |subset|
case subset
when Sexp then
subset.replace_sexp pattern, &block
else
subset
end
})
end
##
# Matches an S-Expression.
#
# See Matcher for examples.
def self.q *args
Matcher.new(*args)
end
def self.s *args
where = caller.first.split(/:/, 3).first(2).join ":"
warn "DEPRECATED: use Sexp.q(...) instead. From %s" % [where]
q(*args)
end
##
# Matches any single item.
#
# See Wild for examples.
def self._
Wild.new
end
# TODO: reorder factory methods and classes to match
##
# Matches all remaining input.
#
# See Remaining for examples.
def self.___
Remaining.new
end
##
# Matches an expression or any expression that includes the child.
#
# See Include for examples.
def self.include child # TODO: rename, name is generic ruby
Include.new(child)
end
##
# Matches any atom.
#
# See Atom for examples.
def self.atom
Atom.new
end
##
# Matches when any of the sub-expressions match.
#
# This is also available via Matcher#|.
#
# See Any for examples.
def self.any *args
Any.new(*args)
end
##
# Matches only when all sub-expressions match.
#
# This is also available via Matcher#&.
#
# See All for examples.
def self.all *args
All.new(*args)
end
##
# Matches when sub-expression does not match.
#
# This is also available via Matcher#-@.
#
# See Not for examples.
def self.not? arg
Not.new arg
end
class << self
alias - not?
end
# TODO: add Sibling factory method?
##
# Matches anything that has a child matching the sub-expression.
#
# See Child for examples.
def self.child child
Child.new child
end
##
# Matches anything having the same sexp_type, which is the first
# value in a Sexp.
#
# See Type for examples.
def self.t name
Type.new name
end
##
# Matches any atom who's string representation matches the patterns
# passed in.
#
# See Pattern for examples.
def self.m *values
res = values.map { |value|
case value
when Regexp then
value
else
re = Regexp.escape value.to_s
Regexp.new "\\A%s\\Z" % re
end
}
Pattern.new Regexp.union(*res)
end
##
# Matches an atom of the specified +klass+ (or module).
#
# See Pattern for examples.
def self.k klass
Klass.new klass
end
##
# Defines a family of objects that can be used to match sexps to
# certain types of patterns, much like regexps can be used on
# strings. Generally you won't use this class directly.
#
# You would normally create a matcher using the top-level #s method,
# but with a block, calling into the Sexp factory methods. For example:
#
# s{ s(:class, m(/^Test/), _, ___) }
#
# This creates a matcher for classes whose names start with "Test".
# It uses Sexp.m to create a Sexp::Matcher::Pattern matcher, Sexp._
# to create a Sexp::Matcher::Wild matcher, and Sexp.___ to create a
# Sexp::Matcher::Remaining matcher. It works like this:
#
# s{ # start to create a pattern
# s( # create a sexp matcher
# :class. # for class nodes
# m(/^Test/), # matching name slots that start with "Test"
# _, # any superclass value
# ___ # and whatever is in the class
# )
# }
#
# Then you can use that with #=~, #/, Sexp#replace_sexp, and others.
#
# For more examples, see the various Sexp class methods, the examples,
# and the tests supplied with Sexp.
#
# * For pattern creation, see factory methods: Sexp::_, Sexp::___, etc.
# * For matching returning truthy/falsey results, see Sexp#=~.
# * For case expressions, see Matcher#===.
# * For getting all subtree matches, see Sexp#/.
#
# If rdoc didn't suck, these would all be links.
class Matcher < Sexp
##
# Should #=~ match sub-trees?
def self.match_subs?
@@match_subs
end
##
# Setter for +match_subs?+.
def self.match_subs= o
@@match_subs = o
end
self.match_subs = true
##
# Does this matcher actually match +o+? Returns falsey if +o+ is
# not a Sexp or if any sub-tree of +o+ is not satisfied by or
# equal to its corresponding sub-matcher.
#
#--
# TODO: push this up to Sexp and make this the workhorse
# TODO: do the same with ===/satisfy?
def satisfy? o
return unless o.kind_of?(Sexp) &&
(length == o.length || Matcher === last && last.greedy?)
each_with_index.all? { |child, i|
sexp = o.at i
if Sexp === child then # TODO: when will this NOT be a matcher?
sexp = o.sexp_body i if child.respond_to?(:greedy?) && child.greedy?
child.satisfy? sexp
else
child == sexp
end
}
end
##
# Tree equivalent to String#=~, returns true if +self+ matches
# +sexp+ as a whole or in a sub-tree (if +match_subs?+).
#
# TODO: maybe this should NOT be aliased to === ?
#
# TODO: example
def =~ sexp
raise ArgumentError, "Can't both be matchers: %p" % [sexp] if Matcher === sexp
self.satisfy?(sexp) ||
(self.class.match_subs? && sexp.each_sexp.any? { |sub| self =~ sub })
end
alias === =~ # TODO?: alias === satisfy?
##
# Searches through +sexp+ for all sub-trees that match this
# matcher and returns a MatchCollection for each match.
#
# TODO: redirect?
# Example:
# Q{ s(:b) } / s(:a, s(:b)) => [s(:b)]
def / sexp
raise ArgumentError, "can't both be matchers" if Matcher === sexp
# TODO: move search_each into matcher?
MatchCollection.new sexp.search_each(self).to_a
end
##
# Combines the Matcher with another Matcher, the resulting one will
# be satisfied if either Matcher would be satisfied.
#
# TODO: redirect
# Example:
# s(:a) | s(:b)
def | other
Any.new self, other
end
##
# Combines the Matcher with another Matcher, the resulting one will
# be satisfied only if both Matchers would be satisfied.
#
# TODO: redirect
# Example:
# t(:a) & include(:b)
def & other
All.new self, other
end
##
# Returns a Matcher that matches whenever this Matcher would not have matched
#
# Example:
# -s(:a)
def -@
Not.new self
end
##
# Returns a Matcher that matches if this has a sibling +o+
#
# Example:
# s(:a) >> s(:b)
def >> other
Sibling.new self, other
end
##
# Is this matcher greedy? Defaults to false.
def greedy?
false
end
def inspect # :nodoc:
s = super
s[0] = "q"
s
end
def pretty_print q # :nodoc:
q.group 1, "q(", ")" do
q.seplist self do |v|
q.pp v
end
end
end
##
# Parse a lispy string representation of a matcher into a Matcher.
# See +Parser+.
def self.parse s
Parser.new(s).parse
end
##
# Converts from a lispy string to Sexp matchers in a safe manner.
#
# "(a 42 _ (c) [t x] ___)" => s{ s(:a, 42, _, s(:c), t(:x), ___) }
class Parser
##
# The stream of tokens to parse. See #lex.
attr_accessor :tokens
##
# Create a new Parser instance on +s+
def initialize s
self.tokens = lex s
end
##
# Converts +s+ into a stream of tokens and adds them to +tokens+.
def lex s
s.scan %r%[()\[\]]|\"[^"]*\"|/[^/]*/|:?[\w?!=~-]+%
end
##
# Returns the next token and removes it from the stream or raises if empty.
def next_token
raise SyntaxError, "unbalanced input" if tokens.empty?
tokens.shift
end
##
# Returns the next token without removing it from the stream.
def peek_token
tokens.first
end
##
# Parses tokens and returns a +Matcher+ instance.
def parse
result = parse_sexp until tokens.empty?
result
end
##
# Parses a string into a sexp matcher:
#
# SEXP : "(" SEXP:args* ")" => Sexp.q(*args)
# | "[" CMD:cmd sexp:args* "]" => Sexp.cmd(*args)
# | "nil" => nil
# | /\d+/:n => n.to_i
# | "___" => Sexp.___
# | "_" => Sexp._
# | /^\/(.*)\/$/:re => Regexp.new re[0]
# | /^"(.*)"$/:s => String.new s[0]
# | UP_NAME:name => Object.const_get name
# | NAME:name => name.to_sym
# UP_NAME: /[A-Z]\w*/
# NAME : /:?[\w?!=~-]+/
# CMD : t | k | m | atom | not? | - | any | child | include
def parse_sexp
token = next_token
case token
when "(" then
parse_list
when "[" then
parse_cmd
when "nil" then
nil
when /^\d+$/ then
token.to_i
when "___" then
Sexp.___
when "_" then
Sexp._
when %r%^/(.*)/$% then
re = $1
raise SyntaxError, "Not allowed: /%p/" % [re] unless
re =~ /\A([\w()|.*+^$]+)\z/
Regexp.new re
when /^"(.*)"$/ then
$1
when /^([A-Z]\w*)$/ then
Object.const_get $1
when /^:?([\w?!=~-]+)$/ then
$1.to_sym
else
raise SyntaxError, "unhandled token: %p" % [token]
end
end
##
# Parses a balanced list of expressions and returns the
# equivalent matcher.
def parse_list
result = []
result << parse_sexp while peek_token && peek_token != ")"
next_token # pop off ")"
Sexp.q(*result)
end
##
# A collection of allowed commands to convert into matchers.
ALLOWED = [:t, :m, :k, :atom, :not?, :-, :any, :child, :include].freeze
##
# Parses a balanced command. A command is denoted by square
# brackets and must conform to a whitelisted set of allowed
# commands (see +ALLOWED+).
def parse_cmd
args = []
args << parse_sexp while peek_token && peek_token != "]"
next_token # pop off "]"
cmd = args.shift
args = Sexp.q(*args)
raise SyntaxError, "bad cmd: %p" % [cmd] unless ALLOWED.include? cmd
result = Sexp.send cmd, *args
result
end
end # class Parser
end # class Matcher
##
# Matches any single item.
#
# examples:
#
# s(:a) / s{ _ } #=> [s(:a)]
# s(:a, s(s(:b))) / s{ s(_) } #=> [s(s(:b))]
class Wild < Matcher
##
# Matches any single element.
def satisfy? o
true
end
def inspect # :nodoc:
"_"
end
def pretty_print q # :nodoc:
q.text "_"
end
end
##
# Matches all remaining input. If remaining comes before any other
# matchers, they will be ignored.
#
# examples:
#
# s(:a) / s{ s(:a, ___ ) } #=> [s(:a)]
# s(:a, :b, :c) / s{ s(:a, ___ ) } #=> [s(:a, :b, :c)]
class Remaining < Matcher
##
# Always satisfied once this is reached. Think of it as a var arg.
def satisfy? o
true
end
def greedy?
true
end
def inspect # :nodoc:
"___"
end
def pretty_print q # :nodoc:
q.text "___"
end
end
##
# Matches when any of the sub-expressions match.
#
# This is also available via Matcher#|.
#
# examples:
#
# s(:a) / s{ any(s(:a), s(:b)) } #=> [s(:a)]
# s(:a) / s{ s(:a) | s(:b) } #=> [s(:a)] # same thing via |
# s(:a) / s{ any(s(:b), s(:c)) } #=> []
class Any < Matcher
##
# The collection of sub-matchers to match against.
attr_reader :options
##
# Create an Any matcher which will match any of the +options+.
def initialize *options
@options = options
end
##
# Satisfied when any sub expressions match +o+
def satisfy? o
options.any? { |exp|
Sexp === exp && exp.satisfy?(o) || exp == o
}
end
def == o # :nodoc:
super && self.options == o.options
end
def inspect # :nodoc:
options.map(&:inspect).join(" | ")
end
def pretty_print q # :nodoc:
q.group 1, "any(", ")" do
q.seplist options do |v|
q.pp v
end
end
end
end
##
# Matches only when all sub-expressions match.
#
# This is also available via Matcher#&.
#
# examples:
#
# s(:a) / s{ all(s(:a), s(:b)) } #=> []
# s(:a, :b) / s{ t(:a) & include(:b)) } #=> [s(:a, :b)]
class All < Matcher
##
# The collection of sub-matchers to match against.
attr_reader :options
##
# Create an All matcher which will match all of the +options+.
def initialize *options
@options = options
end
##
# Satisfied when all sub expressions match +o+
def satisfy? o
options.all? { |exp|
exp.kind_of?(Sexp) ? exp.satisfy?(o) : exp == o
}
end
def == o # :nodoc:
super && self.options == o.options
end
def inspect # :nodoc:
options.map(&:inspect).join(" & ")
end
def pretty_print q # :nodoc:
q.group 1, "all(", ")" do
q.seplist options do |v|
q.pp v
end
end
end
end
##
# Matches when sub-expression does not match.
#
# This is also available via Matcher#-@.
#
# examples:
#
# s(:a) / s{ not?(s(:b)) } #=> [s(:a)]
# s(:a) / s{ -s(:b) } #=> [s(:a)]
# s(:a) / s{ s(not? :a) } #=> []
class Not < Matcher
##
# The value to negate in the match.
attr_reader :value
##
# Creates a Matcher which will match any Sexp that does not match the +value+
def initialize value
@value = value
end
def == o # :nodoc:
super && self.value == o.value
end
##
# Satisfied if a +o+ does not match the +value+
def satisfy? o
!(value.kind_of?(Sexp) ? value.satisfy?(o) : value == o)
end
def inspect # :nodoc:
"not?(%p)" % [value]
end
def pretty_print q # :nodoc:
q.group 1, "not?(", ")" do
q.pp value
end
end
end
##
# Matches anything that has a child matching the sub-expression
#
# example:
#
# s(s(s(s(s(:a))))) / s{ child(s(:a)) } #=> [s(s(s(s(s(:a))))),
# s(s(s(s(:a)))),
# s(s(s(:a))),
# s(s(:a)),
# s(:a)]
class Child < Matcher
##
# The child to match.
attr_reader :child
##
# Create a Child matcher which will match anything having a
# descendant matching +child+.
def initialize child
@child = child
end
##
# Satisfied if matches +child+ or +o+ has a descendant matching
# +child+.
def satisfy? o
child.satisfy?(o) ||
(o.kind_of?(Sexp) && o.search_each(child).any?)
end
def == o # :nodoc:
super && self.child == o.child
end
def inspect # :nodoc:
"child(%p)" % [child]
end
def pretty_print q # :nodoc:
q.group 1, "child(", ")" do
q.pp child
end
end
end
##
# Matches any atom (non-Sexp).
#
# examples:
#
# s(:a) / s{ s(atom) } #=> [s(:a)]
# s(:a, s(:b)) / s{ s(atom) } #=> [s(:b)]
class Atom < Matcher
##
# Satisfied when +o+ is an atom.
def satisfy? o
!(o.kind_of? Sexp)
end
def inspect #:nodoc:
"atom"
end
def pretty_print q # :nodoc:
q.text "atom"
end
end
##
# Matches any atom who's string representation matches the patterns
# passed in.
#
# examples:
#
# s(:a) / s{ m('a') } #=> [s(:a)]
# s(:a) / s{ m(/\w/,/\d/) } #=> [s(:a)]
# s(:tests, s(s(:test_a), s(:test_b))) / s{ m(/test_\w/) } #=> [s(:test_a),
#
# TODO: maybe don't require non-sexps? This does respond to =~ now.
class Pattern < Matcher
##
# The regexp to match for the pattern.
attr_reader :pattern
def == o # :nodoc:
super && self.pattern == o.pattern
end
##
# Create a Patten matcher which will match any atom that either
# matches the input +pattern+.
def initialize pattern
@pattern = pattern
end
##
# Satisfied if +o+ is an atom, and +o+ matches +pattern+
def satisfy? o
!o.kind_of?(Sexp) && o.to_s =~ pattern # TODO: question to_s
end
def inspect # :nodoc:
"m(%p)" % pattern
end
def pretty_print q # :nodoc:
q.group 1, "m(", ")" do
q.pp pattern
end
end
def eql? o
super and self.pattern.eql? o.pattern
end
def hash
[super, pattern].hash
end
end
##
# Matches any atom that is an instance of the specified class or module.
#
# examples:
#
# s(:lit, 6.28) / s{ q(:lit, k(Float)) } #=> [s(:lit, 6.28)]
class Klass < Pattern
def satisfy? o
o.kind_of? self.pattern
end
def inspect # :nodoc:
"k(%p)" % pattern
end
def pretty_print q # :nodoc:
q.group 1, "k(", ")" do
q.pp pattern
end
end
end
##
# Matches anything having the same sexp_type, which is the first
# value in a Sexp.
#
# examples:
#
# s(:a, :b) / s{ t(:a) } #=> [s(:a, :b)]
# s(:a, :b) / s{ t(:b) } #=> []
# s(:a, s(:b, :c)) / s{ t(:b) } #=> [s(:b, :c)]
class Type < Matcher
attr_reader :sexp_type
##
# Creates a Matcher which will match any Sexp who's type is +type+, where a type is
# the first element in the Sexp.
def initialize type
@sexp_type = type
end
def == o # :nodoc:
super && self.sexp_type == o.sexp_type
end
##
# Satisfied if the sexp_type of +o+ is +type+.
def satisfy? o
o.kind_of?(Sexp) && o.sexp_type == sexp_type
end
def inspect # :nodoc:
"t(%p)" % sexp_type
end
def pretty_print q # :nodoc:
q.group 1, "t(", ")" do
q.pp sexp_type
end
end
end
##
# Matches an expression or any expression that includes the child.
#
# examples:
#
# s(:a, :b) / s{ include(:b) } #=> [s(:a, :b)]
# s(s(s(:a))) / s{ include(:a) } #=> [s(:a)]
class Include < Matcher
##
# The value that should be included in the match.
attr_reader :value
##
# Creates a Matcher which will match any Sexp that contains the
# +value+.
def initialize value
@value = value
end
##
# Satisfied if a +o+ is a Sexp and one of +o+'s elements matches
# value
def satisfy? o
Sexp === o && o.any? { |c|
# TODO: switch to respond_to??
Sexp === value ? value.satisfy?(c) : value == c
}
end
def == o # :nodoc:
super && self.value == o.value
end
def inspect # :nodoc:
"include(%p)" % [value]
end
def pretty_print q # :nodoc:
q.group 1, "include(", ")" do
q.pp value
end
end
end
##
# See Matcher for sibling relations: <,<<,>>,>
class Sibling < Matcher
##
# The LHS of the matcher.
attr_reader :subject
##
# The RHS of the matcher.
attr_reader :sibling
##
# An optional distance requirement for the matcher.
attr_reader :distance
##
# Creates a Matcher which will match any pair of Sexps that are siblings.
# Defaults to matching the immediate following sibling.
def initialize subject, sibling, distance = nil
@subject = subject
@sibling = sibling
@distance = distance
end
##
# Satisfied if o contains +subject+ followed by +sibling+
def satisfy? o
# Future optimizations:
# * Shortcut matching sibling
subject_matches = index_matches(subject, o)
return nil if subject_matches.empty?
sibling_matches = index_matches(sibling, o)
return nil if sibling_matches.empty?
subject_matches.any? { |i1, _data_1|
sibling_matches.any? { |i2, _data_2|
distance ? (i2-i1 == distance) : i2 > i1
}
}
end
def == o # :nodoc:
super &&
self.subject == o.subject &&
self.sibling == o.sibling &&
self.distance == o.distance
end
def inspect # :nodoc:
"%p >> %p" % [subject, sibling]
end
def pretty_print q # :nodoc:
if distance then
q.group 1, "sibling(", ")" do
q.seplist [subject, sibling, distance] do |v|
q.pp v
end
end
else
q.group 1 do
q.pp subject
q.text " >> "
q.pp sibling
end
end
end
private
def index_matches pattern, o
indexes = []
return indexes unless o.kind_of? Sexp
o.each_with_index do |e, i|
data = {}
if pattern.kind_of?(Sexp) ? pattern.satisfy?(e) : pattern == o[i]
indexes << [i, data]
end
end
indexes
end
end # class Sibling
##
# Wraps the results of a Sexp query. MatchCollection defines
# MatchCollection#/ so that you can chain queries.
#
# For instance:
# res = s(:a, s(:b)) / s{ s(:a,_) } / s{ s(:b) }
class MatchCollection < Array
##
# See Traverse#search
def / pattern
inject(self.class.new) { |result, match|
result.concat match / pattern
}
end
def inspect # :nodoc:
"MatchCollection.new(%s)" % self.to_a.inspect[1..-2]
end
alias :to_s :inspect # :nodoc:
def pretty_print q # :nodoc:
q.group 1, "MatchCollection.new(", ")" do
q.seplist(self) {|v| q.pp v }
end
end
end # class MatchCollection
end # class Sexp
| true |
fd1ce43611ff164bc3e145b709ee341ff97d4b3c | Ruby | SadTreeFriends/DanmakuHunter | /danmaku_hunter.rb | UTF-8 | 1,295 | 2.90625 | 3 | [] | no_license | class DanmakuHunter
require 'nokogiri'
f = File.open('danmaku.xml')
@doc = Nokogiri::XML(f).slop! do |option|
option.strict.nonet
end
f.close
@danmaku_storage = Array.new
class Danmaku
attr_accessor :font,:time,:color,:type, :content
def initialize(font,time,color,type,content)
@font = font_formatter font
@time = time_formatter time
@color = color_formatter color
@type = type_formatter type
@content = content
end
def time_formatter time
hour, residue = time.to_f.divmod(3600)
minute, second = residue.divmod(60)
readable_time = ["%02d" % hour, "%02d" % minute, "%2.2f" % second].join(':')
end
def font_formatter font
font.to_i > 19 ? "BIG": "SMALL"
end
def color_formatter(color)
"%06X" % color
end
def type_formatter(type)
case type
when "1"
"R -> L Danmaku"
when "4"
"StationaryBottomDanmaku"
when "5"
"StationaryTopDanmaku"
else
"ExceptionalDanmaku"
end
end
end
@doc.i.d.each do |line|
attr = line["p"].split(",")
@danmaku_storage << Danmaku.new(attr[2],attr[0],attr[3],attr[1],line.content)
end
@danmaku_storage.each do |element|
p element
end
end | true |
4b2fd531ba119fd7dd78768f4c565856234ad671 | Ruby | thread314/teaching_app_v1 | /scratch.rb | UTF-8 | 867 | 2.9375 | 3 | [] | no_license | @user = User.last
#Determine how many new cards need to be added
#This isn't working, if there are any existing new cards in the users cardstates, it enters every single card to their cardstates for some reason. Non-essential feature, can fix later
newcardsneeded = 6
@user.cardstates.each do |card|
if card.due.nil?
newcardsneeded = newcardsneeded - 1
end
end
if newcardsneeded < 0
newcardsneeded = 0
end
puts "here tis- #{newcardsneeded}"
currentcardsarray = []
@user.cardstates.each do |card|
currentcardsarray.push(card.card_id)
end
allcardsarray = []
Card.all.each do |card|
allcardsarray.push(card.id)
end
unreviewedcards = []
unreviewedcards = allcardsarray - currentcardsarray
newcardstoadd = unreviewedcards.shuffle[0..newcardsneeded]
puts newcardstoadd
| true |
84536a64f79cef5cf508c24ab1b8db761ad0b54f | Ruby | crystalwilliams/tts-ruby | /092517/question_4.rb | UTF-8 | 314 | 4.25 | 4 | [] | no_license | # ask user for a sentence
puts "Write a sentence."
sentence = gets.chomp.to_s
# ask favorite word in sentence
puts "What is your favorite word in the sentence?"
fav_word = gets.chomp.to_s
# tell user what index favorite word starts at
index = sentence.index(fav_word)
puts "Your favorite word starts at #{index}." | true |
b7fae332258e28334f00a2d038dd6e9018161c16 | Ruby | sllee/activerecord_jr | /test.rb | UTF-8 | 696 | 2.6875 | 3 | [] | no_license | require_relative 'app'
cohort = Cohort.find(1)
p cohort
cohort[:name] = 'What Cohort'
cohort.save
puts "--------------"
p cohort
p Student.all.size
p Cohort.all.size
p Student.create(:cohort_id => 4, :first_name => 'ping', :last_name => 'pong', :email => 'dingdong@gmail.com', :gender => 'f', :birthdate => '1982-12-24')
p Cohort.create(:name => 'KittyCat')
p Student.where('first_name = ?','Kobe')
p Cohort.where('name = ?','KittyCat').first
p Student.find(2001)
p Cohort.find(10)
p Cohort.create(:name => 'Olanda')
p Student.create(:cohort_id => 13, :first_name => 'holand', :last_name => 'dao', :email => 'dingdong@gmail.com', :gender => 'f', :birthdate => '1982-12-24')
p Cohort.all
p "hahahah"
p "lol" | true |
328e34659dbc9ce0769d79c097dbc82f021770d8 | Ruby | memetibryan/Shoe-Distribution-Ruby | /lib/brand.rb | UTF-8 | 411 | 2.65625 | 3 | [] | no_license | class Brand < ActiveRecord::Base
has_many :stores_shoes
has_many :stores, through: :stores_shoes #creating many to many relationship
#Active Record Validations making sure the form is not submitted blank
validates(:name, :presence => true)
#changes the input to Title_Case
before_save(:titlecase_name)
private
define_method(:titlecase_name) do
self.name = (name().titlecase())
end
end | true |
735302171078c3951b34adc7b7109f914150d65f | Ruby | marvelousNinja/porse | /spec/lib/porse/url_generator_spec.rb | UTF-8 | 1,957 | 2.9375 | 3 | [] | no_license | module Porse
describe 'UrlGenerator' do
let(:starting_url) { 'google.com' }
let(:param_name) { 'p' }
let(:url_generator) { UrlGenerator.new(starting_url, param_name) }
describe '#initialize' do
it 'sets up starting url and name of the parameter' do
expect(url_generator.starting_url).to eq(starting_url)
expect(url_generator.param_name).to eq(param_name)
end
it 'sets generator to initial state' do
expect_any_instance_of(UrlGenerator).to receive(:rewind)
url_generator
end
end
describe '#rewind' do
it 'sets current uri to parsed starting url' do
expect(URI).to receive(:parse).with(starting_url).and_call_original
expect(url_generator.current_uri).to be_kind_of(URI)
end
end
describe '#next_url' do
it 'returns absolute URL' do
url = url_generator.next_url
expect(URI.parse(url).absolute?).to be(true)
end
it 'it starts with 1 and increments parameter value' do
values = 3.times.map do
url = url_generator.next_url
value = url.scan(/#{param_name}=([^&]+)/)[0][0].to_i
end
expect(values).to be_eql([1,2,3])
end
it 'replaces parameter value' do
urls = 3.times.map { url_generator.next_url }
urls.last.scan(/#{param_name}=([^&]+)/).count
end
end
describe '#to_enum' do
let(:enumerator) { url_generator.to_enum }
it 'returns Enumerator' do
expect(enumerator).to be_kind_of(Enumerator)
end
it 'provides enumerator for next urls' do
expect(url_generator).to receive(:next_url).exactly(3).times
enumerator.take(3)
end
it 'provides enumerator which can be reset' do
url = enumerator.take(3).last
enumerator.rewind
url_after_reset = enumerator.take(3).last
expect(url).to eq(url_after_reset)
end
end
end
end
| true |
63d3cb65b9ca7862787c9f9ca3a7c4f67db24f89 | Ruby | sreemudunuri/module-one-final-project-guidelines-nyc-web-060418 | /lib/user_interactions.rb | UTF-8 | 6,506 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'colorize'
def login_process
puts "enter a username, or enter \".exit\" to return to main menu".colorize(:red)
user_command = gets.chomp
if user_command == '.exit' then exit_to_main end
login_name = user_command
if User.find_user(login_name) == nil
puts "User doesn't exist!".colorize(:red)
login_process
else
user_help_menu
app_flow_after_user_created(login_name)
end
end
def create_account_process
puts "Enter a username to create your account, or enter \".exit\" to return to main menu".colorize(:red)
user_command = gets.chomp
if user_command == '.exit' then exit_to_main end
user_name = user_command
if User.find_user(user_name) == nil
User.create(name: user_name)
puts " "
puts "User Created!!".colorize(:light_blue)
user_help_menu
app_flow_after_user_created(user_name)
else
puts "Username taken, please enter another name".colorize(:red)
create_account_process
end
end
def companies_in_list
puts "Companies listed in database".colorize(:green)
puts "----------------------------"
Company.all.each do |company_instance|
puts "#{company_instance.name}"
end
puts "----------------------------"
end
def add_a_company_process
puts "Enter company name, or enter \".list\" for company listing. Enter \".exit\" to return to account menu".colorize(:red)
input = gets.chomp
case input
when ".list"
companies_in_list
add_a_company_process
when ".exit"
exit_to_account
end
company_name_input = input
if Company.all.find_by(name:company_name_input) == nil
puts "\nCompany not found, check for case sestivity, or create a new company entry from your account screen\n".colorize(:red)
companies_in_list
add_a_company_process
elsif @logged_in_user.companies.find_by(name:company_name_input) != nil
puts "\nCompany is already in your portfolio\n".colorize(:red)
companies_in_list
add_a_company_process
else
puts "\nCompany added to your portfolio\n".colorize(:light_blue)
@logged_in_user.add_a_company_from_the_list(company_name_input)
exit_to_account
end
end
def create_a_company_process
puts "Enter company name, or enter \".exit\" to return to account menu".colorize(:red)
given_company_name = gets.chomp
if given_company_name == '.exit' then exit_to_account end
puts "Enter company ticker_symbol".colorize(:red)
given_ticker_symbol = gets.upcase.chomp
if given_ticker_symbol.downcase == '.exit' then exit_to_account end
if @logged_in_user.companies.find_by(name:given_company_name) == nil
@logged_in_user.create_and_add_new_company_to_user(given_company_name, given_ticker_symbol)
puts "Company Added To You List".colorize(:blue)
user_menu
else
puts "Company Already Exists!"
companies_in_list
user_menu
end
end
def delete_a_company_process
puts @logged_in_user.list_portfolio_companies
puts "Enter company name to delete it from your portfolio, or enter \".list\" to view your portfolio. Enter \".exit\" to return to account menu".colorize(:red)
input = gets.chomp
case input
when ".list"
puts @logged_in_user.list_portfolio_companies
delete_a_company_process
when ".exit"
exit_to_account
end
given_company_name = input
if @logged_in_user.companies.find_by(name:given_company_name) != nil
@logged_in_user.delete_a_company_from_users_list(given_company_name)
puts "Company Deleted".colorize(:red)
exit_to_account
else @logged_in_user.companies.find_by(name:given_company_name) == nil
puts "Company doesn't exist in Your portfolio".colorize(:red)
puts "Check your list".colorize(:red)
puts @logged_in_user.list_portfolio_companies
delete_a_company_process
end
end
def exit_to_main
main_help_menu
main_menu
end
def exit_to_account
user_help_menu
user_menu
end
def add_a_analyst_process
puts "Enter analyst name, or enter \".list\" for analyst listing. Enter \".exit\" to return to account menu".colorize(:red)
input = gets.chomp
case input
when ".list"
analysts_in_list
add_a_analyst_process
when ".exit"
exit_to_account
end
analyst_name_input = input
if Analyst.all.find_by(name:analyst_name_input) == nil
puts "\nAnalyst not found, check for case sestivity, or create a new analyst entry from your account screen\n".colorize(:red)
analysts_in_list
add_a_analyst_process
elsif @logged_in_user.analysts.find_by(name:analyst_name_input) != nil
puts "\nAnalyst is already in your portfolio\n".colorize(:red)
analysts_in_list
add_a_analyst_process
else
puts "\nAnalyst added to your list\n".colorize(:light_blue)
@logged_in_user.add_a_analyst_from_the_list(analyst_name_input)
exit_to_account
end
end
def analysts_in_list
puts "Analysts listed in database".colorize(:green)
puts "----------------------------"
Analyst.all.each do |analyst_instance|
puts "#{analyst_instance.name}"
end
puts "----------------------------"
end
def create_a_analyst_process
puts "Enter analyst name, or enter \".exit\" to return to account menu".colorize(:red)
given_analyst_name = gets.chomp
if given_analyst_name == '.exit' then exit_to_account end
puts "Enter Analyst twitter_id".colorize(:red)
given_twitter_id = gets.chomp
if given_twitter_id.downcase == '.exit' then exit_to_account end
if @logged_in_user.analysts.find_by(name:given_analyst_name) == nil
@logged_in_user.create_and_add_new_analyst_to_user(given_analyst_name, given_twitter_id)
puts "Analyst Added To You List".colorize(:blue)
user_menu
else
puts "Analyst Already Exists!"
analysts_in_list
user_menu
end
end
def delete_a_analyst_process
puts @logged_in_user.list_analysts
puts "Enter analyst name to delete it from your portfolio, or enter \".list\" to view your portfolio. Enter \".exit\" to return to account menu".colorize(:red)
input = gets.chomp
case input
when ".list"
puts @logged_in_user.list_analysts
delete_a_analyst_process
when ".exit"
exit_to_account
end
given_analyst_name = input
if @logged_in_user.analysts.find_by(name:given_analyst_name) != nil
@logged_in_user.delete_a_analyst_from_users_list(given_analyst_name)
exit_to_account
else @logged_in_user.analysts.find_by(name:given_analyst_name) == nil
puts "Analyst doesn't exist in Your portfolio".colorize(:red)
puts "Check your list".colorize(:red)
puts @logged_in_user.list_analysts
delete_a_analyst_process
end
end
| true |
20c727bb81c1ef2f7a4aba9f79fe1af68c6008b4 | Ruby | alexandre-h/drivy | /level5/main.rb | UTF-8 | 2,903 | 3.328125 | 3 | [] | no_license | require 'json'
require 'date'
FILE = File.open('data.json').read
class Pricing
def initialize(data)
@data = JSON.parse(data)
@cars = @data['cars']
@rentals_cars = {}
@data['rentals'].map do |rental|
@rentals_cars[rental['id']] = rental.merge!(@cars.find { |e| e['id'] == rental['car_id'] })
end
end
def define_price
res = []
@rentals_cars.each do |car|
duration = (Date.parse(car[1]['end_date']) -
Date.parse(car[1]['start_date'])).to_i + 1
price_per_day = reduction(duration, car[1]['price_per_day'])
total_price = price_per_day + car[1]['distance'] * car[1]['price_per_km']
actions = format(car[1]['deductible_reduction'], duration, total_price)
res.push(id: car[0], actions: actions)
end
JSON.pretty_generate(rentals: res)
end
def reduction(duration, base_price)
price_reduct = 0
for days in 1..duration
price_reduct += case
when days > 10
base_price * 0.5
when days > 4
base_price * 0.7
when days > 1
base_price * 0.9
else
base_price
end
end
price_reduct
end
def deductible(is_deductible, duration)
is_deductible ? (duration * 4) * 100 : 0
end
def driver(is_deductible, duration, price)
deductible = is_deductible ? (duration * 4) * 100 : 0
(price + deductible).to_i
end
def owner(price)
commission_price = price * 0.3
(price - commission_price).to_i
end
def insurance(price)
commission_price = price * 0.3
(commission_price * 0.5).to_i
end
def assistance(duration)
duration * 100
end
def drivy(duration, price, is_deductible)
commission_price = price * 0.3
insurance = insurance(price)
assistance = assistance(duration)
deductible = deductible(is_deductible, duration)
((commission_price - (insurance + assistance)) + deductible).to_i
end
def format_json(who, type, amount)
{ who: who, type: type, amount: amount }
end
def format(is_deductible, duration, price)
driver = format_json('driver', 'debit', driver(is_deductible,
duration, price))
owner = format_json('owner', 'credit', owner(price))
insurance = format_json('insurance', 'credit', insurance(price))
assistance = format_json('assistance', 'credit', assistance(duration))
drivy = format_json('drivy', 'credit', drivy(duration,
price, is_deductible))
res = []
res.push(driver, owner, insurance, assistance, drivy)
end
end
result_data = Pricing.new(FILE).define_price.to_json
converted_result = JSON.parse(result_data)
File.open('output.json', 'w') { |file| file.write(converted_result) }
| true |
45ef91319eb2de1476efba22db504faa3e1052ce | Ruby | surekrishna/RubyOnRailsPractise | /main.rb | UTF-8 | 71 | 2.671875 | 3 | [] | no_license | numbers = [1,2,3,4,5,6,7,8,9]
p numbers
p numbers[4]
p numbers.reverse! | true |
65fe39eae9ff9ed64f454110ae0b79da9dbb12c6 | Ruby | zengjk/tsvm | /select.rb | UTF-8 | 463 | 2.859375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
input = ARGV.first
num = ARGV[2] || 1000
name = "#{input}.#{num}"
train_file = name
test_file = "#{name}.t"
#
# select N random instances as train data
# a bit of a memory hog, sorry
#
File.open(input) do |f|
lines = f.readlines
train_lines = lines.sample(num)
test_lines = lines - train_lines
File.open(train_file,'w') { |out| out << train_lines.join("") }
File.open(test_file,'w') { |out| out << test_lines.join("") }
end
| true |
cfc8096f09e90354c7bdf811ddbcda8ca19f2484 | Ruby | terhechte/appventure.me-codebase | /_plugins/global_filters.rb | UTF-8 | 2,317 | 2.796875 | 3 | [] | no_license | module Jekyll
module Filters
def list_of_month_years(posts = nil)
array = {}
checkarray = []
if posts
# break down into January, 2011 | etc, return
posts.each { |element|
date_string = element.date.strftime('%B %Y')
if not checkarray.include?(date_string)
checkarray.push(date_string)
array.push([date_string, element.date.strftime('%Y/%m/')])
end
}
return array
end
return []
end
def excerpt(post = nil)
content = post['content']
if content.include?('<!-- more -->')
"#{content.split('<!-- more -->').first} #{read_more_link post['url']}"
else
content
end
end
def read_more_link(url = "")
"<p class=\"continue\"><a href=\"#{url}\">Continue reading this post <span>→</span></a></p>"
end
def parameterize(text = "")
text.gsub(/[^a-z0-9\-_]+/, '-').split('-').delete_if(&:empty?).join('-')
end
def date_to_words(input = Date.today)
input.strftime('%B %e, %Y')
end
def categories_to_sentence(input = [])
case input.length
when 0
""
when 1
link_to_category input[0].to_s
when 2
"#{link_to_category input[0]} and #{link_to_category input[1]}"
else
"#{input[0...-1].map(&:link_to_category).join(', ')} and #{link_to_category input[-1]}"
end
end
def pager_links(pager)
if pager['previous_page'] || pager['next_page']
html = '<div class="pager">'
if pager['previous_page']
if pager['previous_page'] == 1
html << "<div class=\"previous\"><p><a href=\"//\">Newer posts →</a></p></div>"
else
html << "<div class=\"previous\"><p><a href=\"/page#{pager['previous_page']}\">Newer posts →</a></p></div>"
end
end
if pager['next_page']
html << "<div class=\"next\"><p><a href=\"/page#{pager['next_page']}\">← Older posts</a></p></div>"
end
html << '</div>'
html
end
end
def mail_to(address = '', text = nil)
"<a class=\"mailto\" href=\"#{address.to_s.tr("A-Za-z", "N-ZA-Mn-za-m")}\">#{!text ? address.tr("A-Za-z", "N-ZA-Mn-za-m") : text}</a>"
end
end
end | true |
a3cea09540106144c3cdeca4b0aabfa78806ea6a | Ruby | thyagobr/pylon | /lib/pylon.rb | UTF-8 | 3,821 | 2.734375 | 3 | [] | no_license | require 'ostruct'
require 'rss'
require 'open-uri'
require 'action_view'
require 'pylon/tracer'
module Pylon
class General
# Displays all the associations on a Rails app.
#
# It works by retrieving all files on the app/models folder,
# trying to turn the file names into classes (which will probably fail in namespaced models...),
# and calling ActiveRecord.reflect_on_all_associations method on them and parsing the response.
def self.reflect_on_all_associations
all_model_classes = Dir[Rails.root.join('app', 'models', '*.rb')].map { |model| model.split("/")[-1].split(".")[0] }
constantized_model_classes = all_model_classes.map { |model_name| model_name.camelize.constantize }
active_model_classes = constantized_model_classes.select { |model| model.respond_to?(:reflect_on_all_associations) }
active_model_classes.each do |model|
model.reflect_on_all_associations.each do |assoc|
assoc_name = derive_association_name_from_class(assoc)
puts "#{model} [#{assoc_name}] #{assoc.name.to_s.camelize}"
end
end
true
end
# Receives an ActiveRecord::Reflection's inherited class, parses its name and spits out a String
# that represents the association.
#
# i.e. ActiveRecord::Reflection::BelongsToReflection returns "belongs_to"
#
# It's been built to be used by `self.reflect_on_all_associations`
def self.derive_association_name_from_class(klass)
klass.class.to_s.split("::")[-1].gsub("Reflection","").underscore
end
def self.set_trace
sequence_tracer = []
trace = TracePoint.new(:call, :return) do |tp|
if tp.path.include?(Rails.root.to_s)
sequence_tracer << [tp.defined_class, tp.method_id, tp.event]
#puts "#{sequence_tracer[-1][0]} -- #{sequence_tracer[-1][1]} -- #{sequence_tracer[-1][2]}"
end
end
trace.enable
yield
trace.disable
File.open("sequence_trace.txt", "w") do |file|
last_call = sequence_tracer[0]
last_call[0] = parse_class_name(last_call[0])
return_stack = [{ class: last_call[0], method: last_call[1] }]
file.puts "actor System"
file.puts "System->#{last_call[0]}:#{last_call[1]}"
sequence_tracer[1..-1].each do |method_call|
method_call[0] = parse_class_name(method_call[0])
if method_call[2] == :return
return_to = return_stack.find { |call| call[:class] == method_call[0] && call[:method] == method_call[1] }
next if return_to.nil?
return_to_class = return_to&.fetch(:class)
return_to_method = return_to&.fetch(:method)
# Let's skip the return arrow if the call is to the class itself, it's unnecessary
if return_to_class != method_call[0]
file.puts "#{return_to_class}<--#{method_call[0]}:#{method_call[1]}"
end
else
return_stack << { class: method_call[0], method: method_call[1] }
file.puts "#{last_call[0]}->#{method_call[0]}:#{method_call[1]}"
end
last_call = method_call
end
end
end
def self.parse_class_name(klass)
class_name = klass.to_s
# Sometimes the class is returned in the format: #<Class:NameOfTheClass>
class_name = if class_name.starts_with?("#")
class_name.gsub("#<Class:","").gsub(">","")
else
class_name.to_s
end
class_name = class_name.gsub("::","_")
# ActiveRecord models seem to bring with them the attributes in paranthesis.
# As in User(id: integer, name: string)
# We want to remove the parenthesis part
class_name = class_name.split("(")[0]
class_name
end
end
end
| true |
196676a8fa326e6c242e19469476959605b16679 | Ruby | msloekito/flow_control | /exercise3.rb | UTF-8 | 272 | 4.15625 | 4 | [] | no_license | puts "what is the number?"
number = gets.to_i
if (number > 100)
puts "it's above 100"
elsif (number > 50 && number <= 100)
puts "it's between 51 and 100"
elsif (number <= 50 && number >= 0)
puts "it's between 0 and 50"
else
puts "it's outside tested range"
end | true |
71cf0f49ea6e1551a53c50fd3b9f0a91acf9fcdb | Ruby | shawnmne/week-03-library-project | /lib/book.rb | UTF-8 | 598 | 2.796875 | 3 | [] | no_license | #this is class that create a book object
#
#+title - string: title of the book
#+author - string: author of the book
#+isbn - integer: isbn of the book
#+library_id - integer: primary key of the libary
# where the book is available
# will be nil if checked out
#+parton_id - integer: primary key of the patron
# who has the book checked out, nil if not checked out
class Book < ActiveRecord::Base
validates :title, presence: true
validates :author, presence: true
validates :isbn, presence: true
validates :library_id, presence: true
belongs_to :library
belongs_to :patron
end | true |
a0888e8615d8d35b48731501a9355bc4501a5794 | Ruby | monkeygq/ruby_demo | /method_argument_and_parameter.rb | UTF-8 | 817 | 4.09375 | 4 | [] | no_license | class Myclass
def method_missing(method, *args)
puts "you called undefined method : #{method}(#{args.join(',')})"
end
end
Myclass.new.mymethod(2,3,4) #=> you called undefined method : mymethod(2,3,4)
#==============================================================================>
# parameter and argument : *
def mytest(para1, *para2)
puts "para1=#{para1}"
para2.each {|i| puts "para2=#{i}"}
end
arr = ["yes", "no", "233"]
mytest(arr) #=> para1=["yes", "no", "233"]
mytest(*arr) #=> para1=yes
#=> para2=no
#=> para2=233
#==============================================================================>
# parameter and argument : &
def mytest2(a,b,&p)
p.(a,b)
end
mytest2(2,3) { |x,y| puts x+y } #=> 5
myproc = Proc.new{ |x,y| puts x+y }
mytest2(2,3,&myproc) #=> 5
| true |
4c0aa20c86463a47be81d8b9b767c7934d4ef663 | Ruby | proxygear/exo_cms | /app/services/ckeditor_railser.rb | UTF-8 | 2,148 | 2.609375 | 3 | [
"MIT"
] | permissive | class CkeditorRailser
RAILS_STRUCTURE = {
rails_assets: {
javascripts: /\.js\z/,
stylesheets: /\.css\z/,
images: /\.(png|jpg|jpeg)\z/,
otheres: nil
}
}
attr_accessor :base_path, :actions
def process path=nil
self.base_path = path || '.'
raise "base path #{base_path} does not exist" unless Pathname.new(base_path).exist?
init_structure
railsing!
end
protected
def init_structure
puts " ! Init structure"
rails_assets_path = File.join base_path, 'rails_assets'
if Pathname.new(rails_assets_path).exist?
puts " - #{rails_assets_path}/*"
FileUtils.rm_rf rails_assets_path
end
self.actions = {}
init_recursivly base_path, RAILS_STRUCTURE do |path, action|
self.actions[action] = path
end
end
def init_recursivly path, structure_hash, ®ister
structure_hash.each do |_folder, action|
folder = _folder.to_s
folder_path = File.join(path, folder)
puts " + #{folder_path}"
Dir.mkdir folder_path
if action.kind_of?(Hash)
init_recursivly folder_path, action, ®ister
else
puts " > #{action} -> #{_folder}"
register.call folder_path, action
end
end
end
def railsing!
puts " ! Railsing"
Dir[File.join(base_path, '**', '*')].each do |path|
next if Pathname.new(path).directory?
actions.each do |regexp, group_path|
next unless regexp =~ path
copy_file path, group_path
break
end
end
end
def copy_file file_path, group_path
rel_path = file_path[base_path.size..-1]
folder_destination = group_path
rel_path.split('/')[0..-2].each do |folder|
folder_destination = File.join folder_destination, folder
next if Pathname.new(folder_destination).exist?
puts " + #{folder_destination} f"
Dir.mkdir folder_destination
end
destination_path = File.join group_path, rel_path
puts " + #{destination_path}"
File.open(file_path, 'r') do |source|
File.open(destination_path, 'w') do |destination|
destination.write source.read
end
end
end
end | true |
29a6a8acf53d6e8fa62424928ba8b6e620196ca1 | Ruby | sena-ji/app-academy-open | /software_engineering_foundations_curriculum/blocks_project/lib/part_2.rb | UTF-8 | 486 | 3.25 | 3 | [] | no_license | def all_words_capitalized?(array)
array.all? { |word| word == word.capitalize}
end
def no_valid_url?(array)
valid_urls = [".com", ".net", ".io", ".org"]
array.none? do |url|
index = url.index(".")
url_ending = url[index..-1]
valid_urls.include?(url_ending)
end
end
def any_passing_students?(students)
students.any? do |student|
avg_grade = student[:grades].sum / (student[:grades].length * 1.0)
avg_grade >= 75
end
end | true |
387d88302ba4c97ba6a2c6a9dbb501c101894910 | Ruby | Slouch07/Intro_to_Ruby | /Basics/ex_5.rb | UTF-8 | 166 | 3.015625 | 3 | [] | no_license | five = 5 * 4 * 3 * 2 * 1
six = 6 * 5 * 4 * 3 * 2 * 1
seven = 7 * 6 * 5 * 4 * 3 * 2 * 1
eight = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
puts five
puts six
puts seven
puts eight | true |
e8331405ff55ea7ffa90a38a51e23c8ed5c69340 | Ruby | mrkamel/significance | /lib/significance.rb | UTF-8 | 1,046 | 3.109375 | 3 | [] | no_license |
require "significance/version"
require "complex"
module Significance
LANCZOS_COEF = [
0.99999999999980993,
676.5203681218851,
-1259.1392167224028,
771.32342877765313,
-176.61502916214059,
12.507343278686905,
-0.13857109526572012,
9.9843695780195716e-6,
1.5056327351493116e-7
]
def self.gamma(z)
g = 7
if z.real < 0.5
Math::PI / (sin(Math::PI * z) * gamma(1 - z))
else
z -= 1
x = LANCZOS_COEF[0]
for i in 1 .. g + 1
x += LANCZOS_COEF[i] / (z + i)
end
t = z + g + 0.5
Math.sqrt(2 * Math::PI) * t ** (z + 0.5) * Math.exp(-t) * x
end
end
def self.factorial(z)
return nil if z < 0
gamma(z + 1)
end
def self.calculate(a, b, k, n)
l = a.to_f * b / n
return nil if k.zero?
return nil if (k + 1.0) / l <= 2.5
if k <= 10
(l - k * Math.log10(l) + factorial(Math.log10(k))) / Math.log10(n)
else
(k * (Math.log10(k) - Math.log10(l) - 1.0)) / Math.log10(n)
end
end
end
| true |
7f0b6c4bfe56585325513b39cc03352b52b68146 | Ruby | rshiva/MyDocuments | /01-notes-programming /04-ruby+rails/ruby1.9/samples/tutcontainers_42.rb | UTF-8 | 556 | 3.3125 | 3 | [] | no_license | #---
# Excerpted from "Programming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information.
#---
a = [ 1, 3, "cat" ]
h = { dog: "canine", fox: "lupine" }
# Create Enumerators
enum_a = a.to_enum
enum_h = h.to_enum
enum_a.next
enum_h.next
enum_a.next
enum_h.next
| true |
7f4e2701c3b8581ed1f050058949fea48b74edec | Ruby | JuliaPrussia/BlackJack | /card.rb | UTF-8 | 275 | 3.625 | 4 | [] | no_license | class Card
attr_reader :suit,
:value
def initialize (suit, value)
@suit = suit
@value = value
end
def score
if @value.to_i > 0
@value.to_i
elsif @value == 'A'
@value
else
10
end
end
end
| true |
848da8bf392e99aee869764bd930a2a9c06f135c | Ruby | aks/easy_time | /lib/easy_time.rb | UTF-8 | 15,682 | 3.09375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'time'
require 'date'
require 'active_support'
require 'active_support/duration'
require 'active_support/time_with_zone'
require 'active_support/core_ext/numeric/time'
require 'easy_time/version'
require 'easy_time/convert'
# Are you tired of having to deal with many kinds of date and time objects?
#
# Are you frustrated that comparing timestamps from different systems yields
# incorrect results? _(Were you surprised to learn that, despite really good
# time sync sources, many systems aren't actually synced all that closely in
# time?)_
#
# Well, then, give EasyTime a try!
#
# `EasyTime` accepts most of the well-known date and time objects, including
# `RFC2822`, `HTTPDate`, `XMLSchema`, and `ISO8601` strings and provides
# comparisons that have an adjustable tolerance. With `EasyTime` methods, you
# can reliably compare two timestamps and determine which one is "newer", "older"
# or the "same" withing a configurable tolerance.
#
# The default comparison tolerance is 1 second. This means that if a local
# object is created at time t1 and then transferred across the network and used
# to create a corresponding object in a 3rd-party system, eg: AWS S3, at time
# t2, then if `(t1 - t2).abs` is < 1.second the two times would be logicall the
# same.
#
# In other words, if you have a time-stamp from an `ActiveRecord` object that
# is a few milliseconds different from a related object obtained from a
# 3rd-party system, (eg: AWS S3), then logically, from an application
# perspective, these two objects could be considered having the "same"
# time-stamp.
#
# This is quite useful when one is trying to keep state synchronized between
# different systems. How does one know if an object is "newer" or "older" than
# that from another system? If the system time from the connected systems
# varies by a few or more seconds, then comparisons needs to have some
# tolerance.
#
# Having a tolerant comparison makes "newness" and "oldness" checks easier to
# manage across systems with possibly varying time sources.
#
# However, it is also important to keep the tolerance as small as possible in
# order to avoid causing more problems, such as false equivalences when objects
# really were created at different moments in time.
#
# `EasyTime` objects are just like Time objects, except:
#
# - they auto-convert most time objects, including strings, to Time objects
# - they provide configurable tolerant comparisons between two time objects
#
# Even if you decide to set the configurable comparison tolerance to zero
# _(which disables it)_, the auto-type conversion of most date and time objects
# makes time and date comparisons and arithmetic very easy.
#
# Finally, this module adds an new instance method to the familiar date and
# time classes, to easily convert from the object to the corresponding
# `EasyTime` object:
#
# time.easy_time
#
# The conversion to an `EasyTime` can also be provided with a tolerance value:
#
# time.easy_time(tolerance: 2.seconds)
#
# These are the currently known date and time classes the values of which will
# be automatically converted to an `EasyTime` value with tolerant comparisons:
#
# Date
# Time
# EasyTime
# DateTime
# ActiveSupport::Duration
# ActiveSupport::TimeWithZone
# String
#
# The String values are examined and parsed into a `Time` value. If a string
# cannot be parsed, the `new` and `convert` methods return a nil.
#
class EasyTime
include Comparable
# we define a default tolerance below. This causes time value differences
# less than this to be considered "equal". This allows for time comparisons
# between values from different systems where the clock sync might not be
# very accurate.
#
# If this default tolerance is not desired, it can be overridden with an
# explicit tolerance setting in the singleton class instance:
#
# EasyTime.comparison_tolerance = 0
DEFAULT_TIME_COMPARISON_TOLERANCE = 1.second
class << self
# @example These comparison methods observe the comparison tolerance
#
# EasyTime.newer?(t1, t2, tolerance: nil) # => true if t1 > t2
# EasyTime.older?(t1, t2, tolerance: nil) # => true if t1 < t2
# EasyTime.same?(t1, t2, tolerance: nil) # => true if t1 == t2
# EasyTime.compare(t1, t2, tolerance: nil) # => -1, 0, 1 (or nil)
#
# By default, the `tolerance` is nil, which means that any previously
# configured instance comparison tolerance value is used, if it is set,
# otherwise, the class comparison tolerance is used, if it set, otherwise
# the default `DEFAULT_TIME_COMPARISON_TOLERANCE` is used.
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param time2 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] another time value
# @param tolerance [Integer] seconds of tolerance _(optional)_
# @return [Boolean] true if `time1` > `time2`, using a tolerant comparison
def newer?(time1, time2, tolerance: nil)
compare(time1, time2, tolerance: tolerance).positive?
end
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param time2 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] another time value
# @param tolerance [Integer] seconds of tolerance _(optional)_
# @return [Boolean] true if `time1` > `time2`, using a tolerant comparison
def older?(time1, time2, tolerance: nil)
compare(time1, time2, tolerance: tolerance).negative?
end
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param time2 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] another time value
# @param tolerance [Integer] seconds of tolerance _(optional)_
# @return [Boolean] true if `time1` > `time2`, using a tolerant comparison
def same?(time1, time2, tolerance: nil)
compare(time1, time2, tolerance: tolerance).zero?
end
# @overload between?(time1, t_min, t_max, tolerance: nil)
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param t_min [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] the minimum time
# @param t_max [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] the maximum time
# @return [Boolean] true if `t_min <= time1 <= t_max`, using tolerant comparisons
#
# @overload between?(time1, time_range, tolerance: nil)
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param time_range [Range] a range `(t_min..t_max)` of time values
# @return [Boolean] true if `time_range.min <= time1 <= time_range.max`, using tolerant comparisons
def between?(time1, t_arg, t_max=nil, tolerance: nil)
if t_arg.is_a?(Range)
t_min = t_arg.min
t_max = t_arg.max
else
t_min = t_arg
end
compare(time1, t_min, tolerance: tolerance) >= 0 &&
compare(time1, t_max, tolerance: tolerance) <= 0
end
# @param time1 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] a time value
# @param time2 [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] another time value
# @param tolerance [Integer] seconds of tolerance _(optional)_
# @return [Integer] one of [-1, 0, 1] if `time1` <, ==, or > than `time2`,
# or nil if `time2` cannot be converted to a `Time` value.
def compare(time1, time2, tolerance: nil)
new(time1, tolerance: tolerance) <=> time2
end
# These methods make it easy to add or subtract dates and durations
# EasyTime.add(time, duration, tolerance: nil)
# EasyTime.subtract(time, time_or_duration, tolerance: nil)
# @param time [Time,DateTime,ActiveSupport::TimeWithZone,Date,String,Integer,Array<Integer>] a time value
# @param duration [ActiveSupport::Duration,Integer,Float] a duration value
# @return [EasyTime] the `time` with the `duration` added
def add(time, duration)
EasyTime.new(time) + duration
end
# @param time [Time,DateTime,ActiveSupport::TimeWithZone,Date,String,Integer,Array<Integer>] a time value
# @param time_or_duration [Time,DateTime,ActiveSupport::Duration,Integer,Float] a time or duration value
# @return [EasyTime,Duration] an `EasyTime` value, when a duration is subtracted from a time, or
# a duration _(Integer)_ value, when one time is subtracted from another time.
def subtract(time, time_or_duration)
EasyTime.new(time) - time_or_duration
end
attr_writer :comparison_tolerance
# Class methods to set the class-level comparison tolerance
#
# @example
# EasyTime.comparison_tolerance = 0 # turns off any tolerance
# EasyTime.comparison_tolerance = 5.seconds # makes times within 5 seconds the "same"
# EasyTime.comparison_tolerance = 1.minute # the default
# @return [Integer] the number of seconds of tolerance to use for "equality" tests
def comparison_tolerance
@tolerance || DEFAULT_TIME_COMPARISON_TOLERANCE
end
# @param time_string [String] a time string in one of the many known Time string formats
# @return [EasyTime]
def parse(time_string)
new(parse_string(time_string))
end
def method_missing(symbol, *args, &block)
if Time.respond_to?(symbol)
value = Time.send(symbol, *args, &block)
is_a_time?(value) ? new(value) : value
else
super(symbol, *args, &block)
end
end
def respond_to_missing?(symbol, include_all=false)
Time.respond_to?(symbol, include_all)
end
# @param value [Anything] value to test as a time-like object
# @return [Boolean] true if value is one the known Time classes, or responds to :acts_like_time?
def is_a_time?(value)
case value
when Integer, ActiveSupport::Duration
false
when Date, Time, DateTime, ActiveSupport::TimeWithZone, EasyTime
true
else
value.respond_to?(:acts_like_time?) && value.acts_like_time?
end
end
end
attr_accessor :time
attr_reader :other_time
attr_writer :comparison_tolerance
delegate :to_s, :inspect, to: :time
def initialize(*time, tolerance: nil)
@time = time.presence && convert(time.size == 1 ? time.first : time)
@comparison_tolerance = tolerance
end
# if there is no instance value, default to the class value
def comparison_tolerance
@comparison_tolerance || self.class.comparison_tolerance
end
# returns a _new_ EasyTime value with the tolerance set to value
#
# @example Example:
#
# t1 = EasyTime.new(some_time)
# t1.with_tolerance(2.seconds) <= some_other_time
#
# @param value [Integer] a number of seconds to use as the comparison tolerance
# @return [EasyTime] a new EasyTime value with the given tolerance
def with_tolerance(value)
dup.tap { |time| time.comparison_tolerance = value }
end
# @example Comparison examples
# time1 = EasyTime.new(a_time, tolerance: nil)
# time1.newer?(time2)
# time1.older?(time2)
# time1.same?(time2)
# time1.compare(time2) # => -1, 0, 1
# @param time2 [String,Date,Time,DateTime,Duration,Array<Integer>] another time value
# @return [Boolean] true if `self` > `time2`
def newer?(time2)
self > time2
end
# @param time2 [String,Date,Time,DateTime,Duration,Array<Integer>] another time value
# @return [Boolean] true if `self` < `time2`
def older?(time2)
self < time2
end
# @param time2 [String,Date,Time,DateTime,Duration,Array<Integer>] another time value
# @return [Boolean] true if `self` == `time2`
def same?(time2)
self == time2
end
alias eql? same?
# @param time2 [String,Date,Time,DateTime,Duration,Array<Integer>] another time value
# @return [Boolean] true if `self` != `time2`
def different?(time2)
self != time2
end
# @param time2 [String,Date,Time,DateTime,Duration,Array<Integer>] another time value
# @return [Integer] one of the values: [-1, 0, 1] if `self` [<, ==, >] `time2`,
# or nil if `time2` cannot be converted to a `Time` value
def compare(time2, tolerance: nil)
self.comparison_tolerance = tolerance if tolerance
self <=> time2
end
# compare with automatic type-conversion and tolerance
# @return [Integer] one of [-1, 0, 1] or nil
def <=>(other)
diff = self - other # note: this has a side-effect of setting @other_time
if diff && diff.to_i.abs <= comparison_tolerance.to_i
0
elsif diff
time <=> other_time
end
end
# compare a time against a min and max date pair, or against a time Range value.
# @overload between?(t_min, t_max, tolerance: nil)
# @param t_min [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] the minimum time
# @param t_max [Date,Time,DateTime,EasyTime,Duration,String,Array<Integer>] the maximum time
# @param tolerance [Integer] the optional amount of seconds of tolerance to use in the comparison
# @return [Boolean] true if `t_min <= self.time <= t_max`, using tolerant comparisons
#
# @overload between?(time_range, tolerance: nil)
# @param time_range [Range] a range `(t_min..t_max)` of time values
# @param tolerance [Integer] the optional amount of seconds of tolerance to use in the comparison
# @return [Boolean] true if `time_range.min <= self.time <= time_range.max`, using tolerant comparisons
def between?(t_arg, t_max = nil)
if t_arg.is_a?(Range)
t_min = t_arg.min
t_max = t_arg.max
else
t_min = t_arg
end
compare(t_min) >= 0 && compare(t_max) <= 0
end
# @param duration [Integer] seconds to add to the EasyTime value
# @return [EasyTime] updated date and time value
def +(duration)
dup.tap { |eztime| eztime.time += duration }
end
# Subtract a value from an EasyTime. If the value is an integer, it is treated
# as seconds. If the value is any of the Date, DateTime, Time, EasyTime, or a String-
# formatted date/time, it is subtracted from the EasyTime value resulting in an integer
# duration.
# @param other [Date,Time,DateTime,EasyTime,Duration,String,Integer]
# a date/time value, a duration, or an Integer
# @return [EasyTime,Integer] updated time _(time - duration)_ or duration _(time - time)_
def -(other)
@other_time = convert(other, false)
if is_a_time?(other_time)
time - other_time
elsif other_time
dup.tap { |eztime| eztime.time -= other_time }
end
end
def acts_like_time?
true
end
private
def convert(datetime, coerce = true)
self.class.convert(datetime, coerce)
end
# intercept any time methods so they can wrap the time-like result in a new EasyTime object.
def method_missing(symbol, *args, &block)
if time.respond_to?(symbol)
value = time.send(symbol, *args, &block)
is_a_time?(value) ? dup.tap { |eztime| eztime.time = value } : value
else
super(symbol, *args, &block)
end
end
def respond_to_missing?(symbol, include_all=false)
time.respond_to?(symbol, include_all)
end
def is_a_time?(value)
self.class.is_a_time?(value)
end
end
# Extend the known date and time classes _(including EasyTime itself!)_
module EasyTimeExtensions
def easy_time(tolerance: nil)
EasyTime.new(self, tolerance: tolerance)
end
end
[EasyTime, Date, Time, DateTime, ActiveSupport::Duration, ActiveSupport::TimeWithZone, String].each do |klass|
klass.include(EasyTimeExtensions)
end
# end of EasyTime
| true |
dd65acf0cb420d8a28d4f39b43a0d3c44bf3450b | Ruby | vlezya/my_study_projects | /hero_dragon_game/c_3/engine.rb | UTF-8 | 2,147 | 3.671875 | 4 | [] | no_license | require_relative "game_config"
require_relative "char"
require_relative "hero"
require_relative "dragon"
class Engine
attr_reader :game_config
def initialize(file = "game_options.yaml")
@game_config = GameConfig.new(file). # => instance of GameConfig
load_config # => Hash from YAML file
@dragon = Dragon.new @game_config
@hero = Hero.new @game_config
@whose_turn = true
end
def next_turn
while @hero.current_hp.positive? && @dragon.current_hp.positive?
@whose_turn ? player_turn : dragon_turn
end
if @hero.current_hp.positive?
puts "Победил - ГЕРОЙ!"
puts "Здоровье героя - #{@hero.current_hp}"
else
puts "Победил ДРАКОН"
puts "Здоровье Дракона - #{@dragon.current_hp}"
end
end
private
def dragon_turn
sleep 2
puts "\n!!!! Атакует Дракон !!!!!\n"
sleep 1
received_dmg = @hero.receive_damage(@dragon)
sleep 1
puts "\nДракон нанес: #{received_dmg} единиц ущерба!"
puts "Здоровье героя: #{@hero.current_hp}"
@whose_turn = true
end
def player_turn
action_hero = nil
loop do
puts "\n!!!!! Ход героя !!!!! (attack / heal)"
action_hero = gets.chomp.downcase
if @hero.current_potions.zero? && action_hero == "heal"
puts "\nЗелье закончилось. Вы можете только атаковать!"
elsif action_hero == "heal"
@hero.drink_potion
puts "\nГерой излечился.Здоровье героя равно: #{@hero.current_hp} - единиц"
puts "Зелий осталось #{@hero.current_potions}\n"
break
elsif action_hero == "attack"
received_dmg = @dragon.receive_damage(@hero)
sleep 1
puts "\nГерой нанес: #{received_dmg} единиц ущерба!"
puts "Здоровье дракона: #{@dragon.current_hp}"
break
else
puts "\nНеизвестная команда"
end
end
@whose_turn = false
end
end
| true |
de20a0aef1812eb5a9805cdc1d25248f0a52fbcc | Ruby | camnpr/studentinsights | /app/charts/student_profile_chart.rb | UTF-8 | 2,366 | 2.5625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | class StudentProfileChart < Struct.new :student
def percentile_ranks_to_highcharts(star_results)
return nil unless star_results
star_results.select(:id, :date_taken, :percentile_rank, :grade_equivalent, :total_time)
end
def interventions_to_highcharts
return if student.interventions.blank?
student.interventions.with_start_and_end_dates.map do |intervention|
intervention.to_highcharts
end
end
def growth_percentiles_to_highcharts(student_assessments)
return if student_assessments.blank?
student_assessments.map do |s|
[s.date_taken.year, s.date_taken.month, s.date_taken.day, s.growth_percentile]
end
end
def scale_scores_to_highcharts(student_assessments)
return if student_assessments.blank?
student_assessments.map do |s|
[s.date_taken.year, s.date_taken.month, s.date_taken.day, s.scale_score]
end
end
def chart_data
data = serialize_student_for_profile_chart(student)
{
star_series_math_percentile: percentile_ranks_to_highcharts(data[:star_math_results]),
star_series_reading_percentile: percentile_ranks_to_highcharts(data[:star_reading_results]),
next_gen_mcas_mathematics_scaled: scale_scores_to_highcharts(data[:next_gen_mcas_mathematics_results]),
next_gen_mcas_ela_scaled: scale_scores_to_highcharts(data[:next_gen_mcas_ela_results]),
mcas_series_math_scaled: scale_scores_to_highcharts(data[:mcas_mathematics_results]),
mcas_series_ela_scaled: scale_scores_to_highcharts(data[:mcas_ela_results]),
mcas_series_math_growth: growth_percentiles_to_highcharts(data[:mcas_mathematics_results]),
mcas_series_ela_growth: growth_percentiles_to_highcharts(data[:mcas_ela_results]),
interventions: interventions_to_highcharts
}
end
def serialize_student_for_profile_chart(student)
{
student: student,
student_assessments: student.student_assessments,
star_math_results: student.star_math_results,
star_reading_results: student.star_reading_results,
mcas_mathematics_results: student.mcas_mathematics_results,
mcas_ela_results: student.mcas_ela_results,
next_gen_mcas_mathematics_results: student.next_gen_mcas_mathematics_results,
next_gen_mcas_ela_results: student.next_gen_mcas_ela_results,
interventions: student.interventions
}
end
end
| true |
073140d66ba1d45508b2ef12dd01ec6057582569 | Ruby | amfazlani/phase-1 | /week-7/gps6/my_solution.rb | UTF-8 | 8,722 | 3.25 | 3 | [
"MIT"
] | permissive | # Virus Predictor
# I worked on this challenge [by myself, with: ].
# We spent [#] hours on this challenge.
# EXPLANATION OF require_relative
#
#
# require_relative 'state_data'
# require is a file call necessary for this program to run. The relative part means that look in the relative directory to the program. Require literally takes the file and pastes it on the line where it is called. Require uses knowledge of the path variable in the shell (as compared to require_relative).
#population density is number of people per square mile as of 2012
#this data is updated every year with estimates from a 10 year census
# STATE_DATA is a hash, that contains inner hashes. The first syntax is a hash rocket, and the second one is a colon. When you put a colon after after a key, it turns it into a symbol. As such, a proper noun like a state would be better as string with a hash rocket. People tend to want to use symbol keys over strings because of string degradation (used to be in Ruby that every time a string variable was called, it would have to be called every single).
# STATE_DATA is a constant, it is not a global variable, but constants have a global scope. Bad practice to change constants.
STATE_DATA = {
"Alabama" => {population_density: 94.65, population: 4822023},
"Alaska" => {population_density: 1.1111, population: 731449},
"Arizona" => {population_density: 57.05, population: 6553255},
"Arkansas" => {population_density: 56.43, population: 2949131},
"California" => {population_density: 244.2, population: 38041430},
"Colorado" => {population_density: 49.33, population: 5187582},
"Connecticut" => {population_density: 741.4, population: 3590347},
"Delaware" => {population_density: 470.7, population: 917092},
"Florida" => {population_density: 360.2, population: 19317568},
"Georgia" => {population_density: 172.5, population: 9919945},
"Hawaii" => {population_density: 216.8, population: 1392313},
"Idaho" => {population_density: 19.15, population: 1595728},
"Illinois" => {population_density: 231.9, population: 12875255},
"Indiana" => {population_density: 182.5, population: 6537334},
"Iowa" => {population_density: 54.81, population: 3074186},
"Kansas" => {population_density: 35.09, population: 2885905},
"Kentucky" => {population_density: 110.0, population: 4380415},
"Louisiana" => {population_density: 105.0, population: 4601893},
"Maine" => {population_density: 43.04, population: 1329192},
"Maryland" => {population_density: 606.2, population: 5884563},
"Massachusetts" => {population_density: 852.1, population: 6646144},
"Michigan" => {population_density: 174.8, population: 9883360},
"Minnesota" => {population_density: 67.14, population: 5379139},
"Mississippi" => {population_density: 63.50, population: 2984926},
"Missouri" => {population_density: 87.26, population: 6021988},
"Montana" => {population_density: 6.86, population: 1005141},
"Nebraska" => {population_density: 23.97, population: 1855525},
"Nevada" => {population_density: 24.8, population: 2758931},
"New Hampshire" => {population_density: 147.0, population: 1320718},
"New Jersey" => {population_density: 1205, population: 8864590},
"New Mexico" => {population_density: 17.16, population: 2085538},
"New York" => {population_density: 415.3, population: 19570261},
"North Carolina" => {population_density: 200.6, population: 9752073},
"North Dakota" => {population_density: 9.92, population: 699628},
"Ohio" => {population_density: 282.5, population: 11544225},
"Oklahoma" => {population_density: 55.22, population: 3814820},
"Oregon" => {population_density: 40.33, population: 3899353},
"Pennsylvania" => {population_density: 285.3, population: 12763536},
"Rhode Island" => {population_density: 1016, population: 1050292},
"South Carolina" => {population_density: 157.1, population: 4723723},
"South Dakota" => {population_density: 10.86, population: 833354},
"Tennessee" => {population_density: 156.6, population: 6456243},
"Texas" => {population_density: 98.07, population: 26059203},
"Utah" => {population_density: 34.3, population: 2855287},
"Vermont" => {population_density: 67.73, population: 626011},
"Virginia" => {population_density: 207.3, population: 8185867},
"Washington" => {population_density: 102.6, population: 6724540},
"Washington,D.C."=> {population_density: 10357, population: 632323},
"West Virginia" => {population_density: 77.06, population: 1855413},
"Wisconsin" => {population_density: 105.2, population: 5726398},
"Wyoming" => {population_density: 5.851, population: 576412}
}
# Declare a class
class VirusPredictor
# Establishing all the arugments as instances
def initialize(state_of_origin, population_density, population)
@state = state_of_origin
@population = population
@population_density = population_density
end
# Calls on two internal methods within the class
def virus_effects
predicted_deaths(@population_density, @population, @state)
speed_of_spread(@population_density, @state)
end
private
#only the items in the class would be able to access it aka can't be accessed by anything outside of the class/object.
# Function accepts 3 arguments and puts the population through an
# if statement that takes the population density and multiplies it
# through a defined quotient. The higher density the higher the instance of the death rate.
def predicted_deaths(population_density, population, state)
# predicted deaths is solely based on population density
if @population_density >= 200
number_of_deaths = (@population * 0.4).floor
elsif @population_density >= 150
number_of_deaths = (@population * 0.3).floor
elsif @population_density >= 100
number_of_deaths = (@population * 0.2).floor
elsif @population_density >= 50
number_of_deaths = (@population * 0.1).floor
else
number_of_deaths = (@population * 0.05).floor
end
print "#{@state} will lose #{number_of_deaths} people in this outbreak"
end
# This method accepts two arguments and puts the values through an
# if statement that defines the variable speed and outputs that to
# the user.
def speed_of_spread(population_density, state) #in months
# We are still perfecting our formula here. The speed is also affected
# by additional factors we haven't added into this functionality.
speed = 0.0
if @population_density >= 200
speed += 0.5
elsif @population_density >= 150
speed += 1
elsif @population_density >= 100
speed += 1.5
elsif @population_density >= 50
speed += 2
else
speed += 2.5
end
puts " and will spread across the state in #{speed} months.\n\n"
end
end
#=======================================================================
# DRIVER CODE
# initialize VirusPredictor for each state
# VirusPredictor.new takes 3 arguments of these types
# - String
# - Float
# - Integer
# Output is a string with the inputs listed
STATE_DATA.each do |state, data|
VirusPredictor.new(state, data[:population_density], data[:population]).virus_effects
end
# e.g., state == "Alabama"
# e.g., STATE_DATA[state] == data
# alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population])
# alabama.virus_effects
# jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population])
# jersey.virus_effects
# california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population])
# california.virus_effects
# alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population])
# alaska.virus_effects
#=======================================================================
# Reflection Section
# One is a hash rocket, and allows for a string to be set as a key, and the other is a colon which allows for the key to be set as symbol. Apparently
# Require and require_relative both call in a separate file into the program for use - it literally pastes the entire file at that line in the code. The difference comes from how it accesses that file - require will take the file path from the path variable, whereas require_relative will use a relative file path given.
# Can pretty much use an iteration method to iterate through a hash. Just depends if you want to iterate through the keys, values, or indexes.
# Nothing really stood about the variables per se.
# How classes operate and the use of private were really cemented in this challenge.
#
#
#
#
#
#
#
| true |
19dec6ec0cf8317669faabcfe8ca92dac43151e0 | Ruby | hyperloop-rails/static-analyzer | /applications/jobsworth/helpers/cache_helper.rb | UTF-8 | 1,177 | 2.90625 | 3 | [] | no_license | # Using expire_fragment with a regular expression is PITA as it makes Rails iterate over all the cache keys which is too slow.
# Additionally, some cache strategies don't support iterating over keys, making it non-trivial to drop multiple cache entries.
#
# This helper makes it possible to group together multiple cache entries, making it easier to drop all grouped cache entries together.
# It works by assigning a prefix to all cache entries in a group. To delete all the cache entries of a group,
# it simply renames the prefix for that group, making all cache entries to be re-generated on request, while old entries are
# garbage collected by the backend cache store.
#
# Original idea from http://quickleft.com/blog/faking-regex-based-cache-keys-in-rails
module CacheHelper
CACHE_KEY_PREFIX = "group_cache_index_for"
def grouped_cache_key group_key, sub_key
"#{group_key}/#{group_cache_index(group_key)}/#{sub_key}"
end
def reset_group_cache! group_key
Rails.cache.delete("#{CACHE_KEY_PREFIX}/#{group_key}")
end
private
def group_cache_index group_key
Rails.cache.fetch("#{CACHE_KEY_PREFIX}/#{group_key}") { rand(10**8).to_s }
end
end
| true |
fe7ea91c242e30d551c1d9b22bcce9c5db6e3477 | Ruby | kasumi8pon/nlp100 | /04.rb | UTF-8 | 339 | 3.203125 | 3 | [] | no_license | sentence = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
words = sentence.split(/\W+/)
one_char = [1, 5, 6, 7, 8, 9, 15, 16, 19]
hash = {}
words.each.with_index(1) do |word, i|
key = one_char.include?(i) ? word[0] : word[0..1]
hash[key] = i
end
puts hash
| true |
b9a27c53a5d587eef72d28de3e398d455a99e7e3 | Ruby | Alonsorozco/desafiosopcionales | /opcional1.rb | UTF-8 | 176 | 3.71875 | 4 | [] | no_license | a = [1, 9 ,2, 10, 3, 7, 4, 6]
puts a.map(&:to_f)
puts a.select {|num| num<=5 }
puts a.inject(:+)
# ejemplo [3, 6, 10, 13]
# (((3 + 6) + 10) + 13) => 32
puts a.count {|x| x<5} | true |
c19c3838e22de77d2a3f2d71f39f7bd5e677126d | Ruby | pkordel/oss_analyzer | /app/helpers/application_helper.rb | UTF-8 | 869 | 2.625 | 3 | [] | no_license | # Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
# Return a link for use in layout navigation.
def nav_link(text, controller, action='index')
link_to_unless_current text, :id => nil,
:controller => controller,
:action => action
end
def truncate_string(myString = nil, length = 50)
return myString if myString.length <= length
myString.slice(0...length) << "..." unless myString.nil?
end
def display_date(date=nil)
date.strftime("%Y-%m-%d") unless date.nil?
end
def swedish_currency(amount)
number_to_currency(amount, :delimiter => " ",
:separator => ",",
:unit => "",
:precision => 0)
end
end
| true |
9d1355ad7e8c238ae14623f5e6103f362d8557a8 | Ruby | ghiculescu/sorbet | /test/testdata/lsp/rename/method_attr.rb | UTF-8 | 406 | 2.703125 | 3 | [
"Apache-2.0"
] | permissive | # typed: true
# frozen_string_literal: true
class Foo
attr_reader :foo
# ^ apply-rename: [A] invalid: true
attr_writer :bar
# ^ apply-rename: [C] invalid: true
attr_accessor :baz
# ^ apply-rename: [D] invalid: true
end
f = Foo.new
f.foo
# ^ apply-rename: [B] newName: bar invalid: true expectedErrorMessage: Sorbet does not support renaming `attr_reader`s
| true |
62b99433c0f72c1fd42f290212647624f0784319 | Ruby | otegami/cherry | /spec/effects_spec.rb | UTF-8 | 951 | 3.28125 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe "Effects" do
describe "Reverse" do
it "makes words to reverse" do
effect = Effects.reverse
expect(effect.call('Ruby is fun!')).to eq('ybuR si !nuf')
end
end
describe "Echo" do
context "makes words to echo" do
it "is twice" do
effect = Effects.echo(2)
expect(effect.call('Ruby is fun!')).to eq('RRuubbyy iiss ffuunn!!')
end
it "is three times" do
effect = Effects.echo(3)
expect(effect.call('Ruby is fun!')).to eq('RRRuuubbbyyy iiisss fffuuunnn!!!')
end
end
end
describe "Loud" do
context "make words be loud" do
it "is twice" do
effect = Effects.loud(2)
expect(effect.call('Ruby is fun!')).to eq('RUBY!! IS!! FUN!!!')
end
it "is three times" do
effect = Effects.loud(3)
expect(effect.call('Ruby is fun!')).to eq('RUBY!!! IS!!! FUN!!!!')
end
end
end
end
| true |
2bbc96c6f1044f6bfa38dbacada56720bff70a5e | Ruby | CCCQ2/Euler | /problem62-solved.rb | UTF-8 | 949 | 3.375 | 3 | [] | no_license | #The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube.
solution = []
lookup = (1..1E4).to_a.map{|n| n**3}
cube = lookup.sort_by{|c| c.to_s.size}.map{|n| n.to_s.split(//).sort!.join.to_s}
digits = cube.inject(Hash.new(0)){|sums,x| sums[x] += 1; sums}.sort_by{|n| n[1]}.select{|n| n[1] == 5}.map{|digits| digits.first}
puts "Selected: #{digits.inspect}"
digits.each do |x|
lookup.each do |y|
solution << y if x.split(//).sort == y.to_s.split(//).sort
end
end
puts solution.sort
#Solution propre
puts "-" * 50
M = 5
N = 10000
hash = Hash.new {|hash, key| hash[key] = []}
(1..N).each do |n| i = n**3
arr = i.to_s.split(//).sort
hash[arr] << i
puts hash[arr] or break if hash[arr].size >= M
end | true |
0e372cc8e1793aae8e718a9212d7423cd7000082 | Ruby | agarun/homeworks | /classwork/W3D2/bonus_refactor_WIP/reply.rb | UTF-8 | 1,879 | 2.796875 | 3 | [] | no_license | require_relative 'dbconnection'
require_relative 'user'
require_relative 'question'
class Reply < ModelBase
attr_accessor :body, :user_id, :question_id, :reply_id
attr_reader :id
def initialize(options)
@id = options['id']
@body = options['body']
@reply_id = options['reply_id']
@question_id = options['question_id']
@user_id = options['user_id']
end
def self.find_by_user_id(user_id)
reply = QuestionsDBConnection.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
replies
WHERE
user_id = ?
SQL
return nil if reply.empty?
reply.map { |reply| Reply.new(reply) }
end
def self.find_by_question_id(question_id)
reply = QuestionsDBConnection.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
question_id = ?
SQL
return nil if reply.empty?
reply.map { |reply| Reply.new(reply) }
end
def author
User.find_by_id(self.user_id)
end
def question
Question.find_by_id(self.question_id)
end
def parent_reply
Reply.find_by_id(self.reply_id)
end
def child_replies
reply = QuestionsDBConnection.instance.execute(<<-SQL, self.id)
SELECT
*
FROM
replies
WHERE
reply_id = ?
SQL
return nil if reply.empty?
reply.map { |reply| Reply.new(reply) }
end
private
def insert
QuestionsDBConnection.instance.execute(<<-SQL, body, question_id, reply_id, user_id)
INSERT INTO
replies (body, question_id, reply_id, user_id)
VALUES
(?, ?, ?, ?)
SQL
end
def update
QuestionsDBConnection.instance.execute(<<-SQL, body, question_id, reply_id, user_id, id)
UPDATE
replies
SET
body = ?, question_id = ?, reply_id = ?, user_id = ?
WHERE
id = ?
SQL
end
end
| true |
645ac5c8843048310571dc497686de8559636b8f | Ruby | travis-ci/travis-scheduler | /lib/travis/support/registry.rb | UTF-8 | 1,835 | 2.75 | 3 | [
"MIT"
] | permissive | module Travis
module Registry
class Registry
def []=(key, object)
objects[key.to_sym] = object
end
def [](key)
key && objects[key.to_sym] || fail("can not use unregistered object #{key.inspect}. known objects are: #{objects.keys.inspect}")
end
def objects
@objects ||= {}
end
end
class << self
def included(base)
base.send(:extend, ClassMethods)
base.send(:include, InstanceMethods)
end
def [](key)
registries[key] ||= Registry.new
end
def registries
@registries ||= {}
end
end
module ClassMethods
attr_reader :registry_key
def [](key)
key && registry[key.to_sym] || fail("can not use unregistered object #{key.inspect}. known objects are: #{registry.keys.inspect}")
end
def register(*args)
key, namespace = *args.reverse
registry = namespace ? Travis::Registry[namespace] : self.registry
registry[key] = self
@registry_key = key
@registry_namespace = namespace
end
def registry
Travis::Registry[registry_namespace]
end
def registry_full_key
@registry_full_key ||= [registry_namespace, registry_key].join('.')
end
def registry_namespace
@registry_namespace ||= underscore(self.class.name.split('::').last)
end
def underscore(string)
string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
downcase
end
end
module InstanceMethods
def registry_key
self.class.registry_key
end
def registry_full_key
self.class.registry_full_key
end
def registry_namespace
self.class.registry_namespace
end
end
end
end
| true |
1922f32bb25b397bed17e3e4b868316150f3b28b | Ruby | tgrosch91/debugging-with-pry-v-000 | /lib/pry_debugging.rb | UTF-8 | 38 | 3.171875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def plus_two(num)
sum=num+2
sum
end
| true |
438a51d81a735537d2416db65d9d10f41c26c782 | Ruby | beltrachi/automatic_dictionary | /test/integration/lib/interactor/snapshooter.rb | UTF-8 | 1,381 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'interactor/shared'
require 'tempfile'
require 'fileutils'
module Interactor
module Snapshooter
class << self
include Shared
def create_screenshot
file = tmp_file.path
# NOTE: we are using jpg because imagemagick png can last as much as 12s
# when converting images. Jpg is 1s. Increased quality be less lossy.
run("import -window root -quality 99% #{file}")
store_a_copy_for_debugging(file)
file
end
private
def store_a_copy_for_debugging(img)
return unless Interactor.debug?
log_screenshot(img)
end
def local_tmp
File.join(Interactor.root, 'tmp')
end
def log_screenshot(img)
Dir.mkdir(local_tmp) unless Dir.exist?(local_tmp)
target_path = File.join(local_tmp, File.basename(img))
FileUtils.cp(img, target_path)
logger.info("Copied screenshot to #{target_path}")
end
def tmp_file
# We need to keep tempfile in memory to not be garbage collected.
# When garbage collected file gets removed. We want this to
# happen when ruby process ends.
@@tmp_files ||= []
timestamp = Time.now.strftime('%Y%m%d-%H%M%S')
Tempfile.new(["screenshot-#{timestamp}", '.jpg']).tap do |file|
@@tmp_files << file
end
end
end
end
end
| true |
2a8209409512cdae4b4886615a551683f244338d | Ruby | billbell73/Week-4-test | /inject_method/lib/array.rb | UTF-8 | 513 | 3.3125 | 3 | [] | no_license | class Array
def new_inject
first, *rest = self
accumulator = first
rest.each do |value|
accumulator = yield accumulator, value
end
accumulator
end
def new_inject_with_arg(initial)
accumulator = initial
self.each do |value|
accumulator = yield accumulator, value
end
accumulator
end
# inject_3(2){ |v| print "#{v} " }
# def inject_3(&block)
# accumulator = 0
# self.each do |val|
# yield accumulator
# end
# accumulator
# end
end | true |
7dfd6e2f08dc860232c66dba9cae4b550c608b0c | Ruby | enspirit/bmg | /lib/bmg/sql/ext/predicate/expr.rb | UTF-8 | 362 | 2.546875 | 3 | [
"MIT"
] | permissive | class Predicate
module Expr
def to_sql_literal(buffer, value)
case value
when TrueClass
buffer << Sql::Expr::TRUE
when FalseClass
buffer << Sql::Expr::FALSE
when Integer, Float
buffer << value.to_s
else
buffer << Sql::Expr::QUOTE << value.to_s << Sql::Expr::QUOTE
end
end
end
end
| true |
7db50d6cf7036cf8bbc41bc2abb1891e0a9fb4cc | Ruby | dvandersluis/number_muncher | /spec/number_muncher/parser_spec.rb | UTF-8 | 3,897 | 3.140625 | 3 | [] | no_license | RSpec.describe NumberMuncher::Parser do
subject { described_class }
describe '.call' do
let(:options) { { thousands_separator: '.', decimal_separator: ',' } }
context 'when given invalid input' do
it 'raises an exception' do
expect { described_class.new('a').call }.to raise_error(NumberMuncher::InvalidNumber)
expect { described_class.new('a/2').call }.to raise_error(NumberMuncher::InvalidNumber)
expect { described_class.new('1/2 abc').call }.to raise_error(NumberMuncher::InvalidNumber)
expect { described_class.new('abc 1/2').call }.to raise_error(NumberMuncher::InvalidNumber)
expect { described_class.new('1/0').call }.to raise_error(NumberMuncher::InvalidNumber)
end
end
context 'when given a Rational' do
it 'passes it through' do
expect(1/2r).to parse_to(1/2r)
end
end
context 'when given a Float' do
it 'passes it through' do
expect(Math::PI).to parse_to(Math::PI)
end
end
context 'when given a Numeric' do
let(:numeric) { NumberMuncher::Numeric.new(5) }
it 'passes it through' do
expect(numeric).to parse_to(numeric)
end
end
context 'when given a phrase' do
it 'raises an exception' do
expect { described_class.new('1 2').call }.to raise_error(NumberMuncher::InvalidParseExpression)
end
end
context 'when given a single fraction' do
it 'parses it' do
expect('1/2').to parse_to(1/2r)
end
it 'handles negative fractions' do
expect('-3/8').to parse_to(-3/8r)
end
it 'ignores extra whitespace' do
expect('3 / 8').to parse_to(3/8r)
end
end
context 'when given a mixed fraction' do
it 'parses it' do
expect('1 7/8').to parse_to(15/8r)
end
it 'handles negative fractions' do
expect('-3 1/2').to parse_to(-7/2r)
end
it 'ignores repeated whitespace' do
expect('9 3/7').to parse_to(66/7r)
expect('9 3 / 7').to parse_to(66/7r)
end
it 'handles separators' do
expect('1,000 1/2').to parse_to(2001/2r)
end
it 'when the thousands separator is different' do
expect('1.000 1/2').to parse_to(2001/2r).with_options(options)
end
end
context 'when given a decimal' do
it 'parses it' do
expect('3.75').to parse_to(15/4r)
end
it 'handles separators' do
expect('1,000.5').to parse_to(2001/2r)
end
it 'handles negative decimals' do
expect('-3.8').to parse_to(-19/5r)
end
it 'parses a decimal without leading 0' do
expect('.5').to parse_to(1/2r)
end
it 'when the separators are different' do
expect('1.000,5').to parse_to(2001/2r).with_options(options)
end
end
context 'when given unicode fractions' do
it 'converts them' do # rubocop:disable RSpec/ExampleLength
expect('½').to parse_to(1/2r)
expect('⅓').to parse_to(1/3r)
expect('⅔').to parse_to(2/3r)
expect('¼').to parse_to(1/4r)
expect('¾').to parse_to(3/4r)
expect('⅕').to parse_to(1/5r)
expect('⅖').to parse_to(2/5r)
expect('⅗').to parse_to(3/5r)
expect('⅘').to parse_to(4/5r)
expect('⅙').to parse_to(1/6r)
expect('⅚').to parse_to(5/6r)
expect('⅐').to parse_to(1/7r)
expect('⅛').to parse_to(1/8r)
expect('⅜').to parse_to(3/8r)
expect('⅝').to parse_to(5/8r)
expect('⅞').to parse_to(7/8r)
expect('⅑').to parse_to(1/9r)
expect('⅒').to parse_to(1/10r)
end
it 'handles negative fractions' do
expect('-⅙').to parse_to(-1/6r)
end
it 'converts mixed fractions' do
expect('1½').to parse_to(3/2r)
end
end
end
end
| true |
9a0eaf0efff164c9e766bc6eb715579428ae7d93 | Ruby | MaggieHibberd/card_game | /spec/deck_spec.rb | UTF-8 | 611 | 3.25 | 3 | [] | no_license | require 'deck'
describe Deck do
context 'Class starts with a full deck of cards of which you can apply methods to' do
it 'initializes with a deck of cards' do
deck = Deck.new
sample = deck.check_deck.sample
expect(deck.check_deck).to include sample
end
it 'allows you to shuffle a deck' do
deck = Deck.new
deck.stub(:shuffle).and_return("2 spades")
deck.shuffle.should eq("2 spades")
end
it 'can deal a card from the deck if the deck is not empty' do
deck = Deck.new
deck.stub(:deal).and_return("2 spades")
deck.deal.should eq("2 spades")
end
end
end
| true |
1f160202494e49c72dd2e1308edef054fffb3bfa | Ruby | aantix/email_finder | /lib/email_finder/email_pattern_resolver.rb | UTF-8 | 2,439 | 3.359375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'erb'
require 'email_finder/utils'
module EmailFinder
class EmailPatternResolver
include Utils
attr_reader :username
FIRST_NAMES = "data/first_names.txt"
LAST_NAMES = "data/last_names.txt"
def initialize(username)
@username = username.downcase
end
def pattern
email_template = username.dup
temp_username = username.dup
last_name = scan_and_replace(username, email_template, temp_username,
'last_name', last_names)
first_name = scan_and_replace(temp_username, email_template, temp_username,
'first_name', first_names)
remove_delimiters(temp_username)
# Any remaining chars?
if temp_username.size > 0
if last_name && !first_name
email_template.gsub!(temp_username, "<%= first_name[0..#{temp_username.size - 1}] %>")
elsif !last_name && first_name
email_template.gsub!(temp_username, "<%= last_name[0..#{temp_username.size - 1}] %>")
else
return nil # extraneous chars that aren't equal to a first or last name
# can't extract a general email pattern with an example like that
# e.g. jjones857@aantix.com (not everyone would have an 857)
end
end
email_template
end
def self.name_for(first_name, last_name, template)
ERB.new(template).result(binding)
end
def first_name?
find_name(username, first_names).present?
end
def last_name?
find_name(username, last_names).present?
end
private
def read_names(filename, min)
File.readlines(File.join([root, "..", filename]), "\r")
.collect(&:chomp!)
.find_all{|n| n && n.size >= min}
.collect(&:downcase)
end
def first_names
@first_names||=read_names(FIRST_NAMES, 3)
end
def last_names
@last_names||=read_names(LAST_NAMES, 5)
end
def find_name(username, names)
names.find { |name| username =~ /#{name.chomp}/ }
end
def remove_delimiters(temp_username)
['.', '_', '-'].each { |c| temp_username.gsub!(c, '') }
end
def scan_and_replace(username, email_template, temp_username, placeholder, names)
name = find_name(username, names)
if name
email_template.gsub!(name, "<%= #{placeholder} %>")
temp_username.gsub!(name, '')
end
name
end
end
end
| true |
d53812f0d76a2805fa09a3f7f12073508547ea59 | Ruby | jaredianmills/nyc-web-062518 | /19-rails-forms-rest-validations-bagel-shop/app/controllers/bagels_controller.rb | UTF-8 | 1,263 | 2.6875 | 3 | [] | no_license | class BagelsController < ApplicationController
# rails will infer i want to render index when at /bagels
# show ALL bagels
def index
@bagels = Bagel.all
render :index
end
# show form to create a new bagel
def new
@bagel = Bagel.new
render :new
end
# POST request from our new bagel form
def create
# pass in return value of private bagel_params method, which is a hash of whitelisted attributes
@bagel = Bagel.new(bagel_params)
# checking validations; method is provided by ActiveRecord
if @bagel.valid?
# if bagel is valid, save to database
@bagel.save
redirect_to(bagels_path)
else # if bagel is not valid
# rails provides a method for sending data across multiple requests
# we can access this via flash[:KEY] hash syntax
flash[:errors] = @bagel.errors.full_messages
# display error message
# because I am not redirecting, instance var @bagel maintains the attributes from the form
render(:new) # render DOES NOT TRIGGER NEW GET REQUEST
end
end
#everything below private keyword is private
private
def bagel_params
# return a hash of whitelisted attributes from params
params.require(:bagel).permit(:name, :price, :tasty)
end
end
| true |
b78a8b88613d58556db91a11d7b0353eaf44d70f | Ruby | kushwahdeepak/deepak_cardinal | /lib/tasks/update_intake_batch_person.rake | UTF-8 | 939 | 2.5625 | 3 | [] | no_license | require 'csv'
namespace :scheduled do
task :update_person, [:name] => [:environment] do |task, args|
puts "starting intake batches"
load_csv = iterate_input_rows args[:name]
end
def load_csv_file file
file_read = File.read(file)
CSV.parse file_read, {
headers: true,
skip_blanks: true,
converters: :date,
skip_lines: /^(?:,\s*)+$/,
encoding: 'windows-1251:utf-8'
}
end
def iterate_input_rows name
file = Rails.root.join("public", name)
csv = load_csv_file file #downloads file back from the cloud
csv.each do |row|
params = row.to_hash.transform_keys{ |key| key.to_s.downcase.to_sym }.compact
update_person params
end
end
def update_person params
person = Person.find_by(email_address: params[:email_address])
begin
person.update! params
rescue => exception
puts "No data available to update"
end
end
end
| true |
7653b056701fe7eea647ac795688c40fc074bc66 | Ruby | kevthunder/pawa | /lib/pawa/operations/replace_operation.rb | UTF-8 | 2,267 | 2.515625 | 3 | [
"MIT"
] | permissive | module Pawa
module Operations
class ReplaceOperation < Operation
def findable?
true
end
def parser()
super.tap do |parser|
parser.flags.push 'word'
end
end
def start_reg
if listedParams.first.is_a?(String)
Regexp.new(Regexp.escape(listedParams.first))
else
Regexp.new(listedParams.first)
end
end
def search
start_reg
end
def replace
listedParams[1]
end
def reparse?(instance = nil)
return true if replace.empty?
super
end
def valid?(instance)
instance.my_match =~ start_reg
end
def alter_text(txt)
alts = Alterations.new(txt,search)
multi_param(:alter).each do |args|
alts.new_group(args)
end
txt.sub(search,alts.process_replace(replace))
end
def exec(instance)
instance.alter_remaining_text do |txt|
alter_text(txt)
end
end
class Alterations
def initialize(txt,search)
@txt, @search = txt,search
@altered_groups = []
end
attr_accessor :altered_groups, :txt, :search
def new_group(args)
AlteredGroup.new(args,self)
end
def process_replace(replace)
replace = replace.gsub(/\$(\d+)/,'\\\\\1')
altered_groups.each do |g|
replace = g.apply(replace)
end
replace
end
end
class AlteredGroup
def initialize(args,alts)
@alts = alts
@from, @name, @search, @replace = args
@from = alts.process_replace(from)
@replace = alts.process_replace(replace)
alts.altered_groups.push(self)
end
attr_accessor :alts, :from, :name, :search, :replace
def subject
alts.txt.match(alts.search)[0].sub(alts.search,from)
end
def result
subject.gsub(search,replace)
end
def apply(txt)
txt.gsub("${#{name}}",result)
end
end
end
end
end | true |
1a31b88ad5334f92792271f5b771e575ae67e648 | Ruby | celluloid/celluloid | /lib/celluloid/internals/handlers.rb | UTF-8 | 859 | 2.921875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require "set"
module Celluloid
module Internals
class Handlers
def initialize
@handlers = Set.new
end
def handle(*patterns, &block)
patterns.each do |pattern|
handler = Handler.new pattern, block
@handlers << handler
end
end
# Handle incoming messages
def handle_message(message)
handler = @handlers.find { |h| h.match(message) }
handler.call(message) if handler
handler
end
end
# Methods blocking on a call to receive
class Handler
def initialize(pattern, block)
@pattern = pattern
@block = block
end
# Match a message with this receiver's block
def match(message)
@pattern === message
end
def call(message)
@block.call message
end
end
end
end
| true |
ca716b334510a725573d83c396ee2e1f8bbf640e | Ruby | b-studios/doc.js | /lib/dom/node.rb | UTF-8 | 11,664 | 3.453125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require_relative 'dom'
require_relative 'exceptions'
module Dom
# Node can be seen as an **aspect** or feature of another Object. Therefore it can be mixed in to
# add node-functionality to a class.
# Such functionality is used by {CodeObject::Base code-objects} and {Document::Document documents}.
#
# Instance Variables
# ------------------
# The following instance-variables will be set while including Dom::Node into your class:
#
# - `@name` (should be already set in your including class)
# - `@parent`
# - `@children`
#
# @example
# class MyObject
# include Dom::Node
#
# # The contructor of MyObject should call init_node
# def initialize(name)
# super
# @name = name
# end
# end
#
# # MyObject can now be used as a node within our Domtree
# @baz = MyObject.new 'Baz'
# @baz.add_node(MyObject.new 'foo')
# @baz.add_node(MyObject.new 'bar')
#
# # These Nodes get inserted into Dom, so it looks like
# Dom.print_tree
# #=>
# #-Baz
# # -foo
# # -bar
#
# @note including Class should set instance-variable @name
# @see CodeObject::Base
# @see Document::Document
# @see Dom
module Node
NS_SEP_STRING = '.'
NS_SEP = /#{Regexp.escape(NS_SEP_STRING)}/
NODENAME = /[0-9a-zA-Z$_]+/
LEAF = /^#{NS_SEP}(?<name>#{NODENAME})$/
ABSOLUTE = /^(?<first>#{NODENAME})(?<rest>(#{NS_SEP}#{NODENAME})*)$/
RELATIVE = /^#{NS_SEP}(?<first>#{NODENAME})(?<rest>(#{NS_SEP}#{NODENAME})*)$/
# @group Initialization
# The 'constructor' of {Dom::Node}. It initializes all required instance-variables.
# (see {Dom::Node above}).
def initialize
super
@children, @parent = {}, nil
@name ||= "" # should be written by including class
end
# @group Traversing
# `node.parent` returns the parent {Dom::Node node}, if there is one. If no parent exists `nil`
# is returned. In this case `node` can be considered either as loose leave or root of the {Dom}.
#
# @return [Dom::Node] the parent node, if one exists
def parent
@parent
end
# searches all parents recursivly and returns an array, starting with the highest order parent
# (excluding the {Dom.root}) and ending with the immediate parent.
#
# @example
# o1 = CodeObject::Base.new :foo
# o2 = CodeObject::Base.new :bar, o1
# o3 = CodeObject::Base.new :baz, o2
#
# # no parents
# o1.parents #=> []
#
# # all parents
# o3.parents #=> [#<CodeObject::Base:foo>, #<CodeObject::Base:bar>]
#
# @return [Array<Dom::Node>] the associated parents
def parents
return [] if @parent.nil? or @parent.parent.nil?
@parent.parents << @parent
end
# Returns all immediately associated children of this `node`
#
# @return [Hash<Symbol, Dom::Node>]
def children
@children
end
# Get's the child of this node, which is identified by `path`. Returns `nil? , if no matching
# child was found.
#
# @example childname
# Dom[:Core] #=> #<CodeObject::Object:Core @parent=__ROOT__ …>
# Dom['Core'] #=> #<CodeObject::Object:Core @parent=__ROOT__ …>
#
# @example path
# Dom['Core.logger.log'] #=> #<CodeObject::Function:log @parent=logger …>
#
# @overload [](childname)
# @param [String, Symbol] childname
# @return [Dom::Node, nil]
#
# @overload [](path)
# @param [String] path The path to the desired node
# @return [Dom::Node, nil]
def [](path)
return @children[path] if path.is_a? Symbol
return @children[path.to_sym] if path.split(NS_SEP_STRING).size == 1
path = path.split(NS_SEP_STRING)
child = @children[path.shift.to_sym]
return nil if child.nil?
# decend recursive
child[path.join(NS_SEP_STRING)]
end
# Alias for bracket-access
# @see #[]
def find(path)
self[path]
end
# Returns if the current node is a leaf or not.
#
# @return [Boolean]
def has_children?
not (@children.nil? or @children.size == 0)
end
# Finds all siblings of the current node. If there is no parent, it will return `nil`.
#
# @return [Array<Dom::Node>, nil]
def siblings
return nil if parent.nil?
@parent.children
end
# Resolves `nodename` in the current context and tries to find a matching
# {Dom::Node}. If `nodename` is not the current name and further cannot be found in the list of
# **children** the parent will be asked for resolution.
#
# Given the following example, each query (except `.log`) can be resolved without ambiguity.
#
# # -Core
# # -extend
# # -extensions
# # -logger
# # -log
# # -properties
# # -log
#
# Dom[:Core][:logger].resolve '.log'
# #=> #<CodeObject::Function:log @parent=logger @children=[]>
#
# Dom[:Core][:logger][:log].resolve '.log'
# #=> #<CodeObject::Function:log @parent=logger @children=[]>
#
# Dom[:Core][:logger][:log].resolve '.logger'
# #=> #<CodeObject::Object:logger @parent=Core @children=[]>
#
# Dom[:Core].resolve '.log'
# #=> #<CodeObject::Function:log @parent=Core @children=[]>
#
# Dom[:Core][:properties].resolve '.log'
# #=> #<CodeObject::Function:extend @parent=Core @children=[]>
#
# Dom[:Core][:logger].resolve 'foo'
# #=> nil
#
# @param [String] nodename
#
# @return [Dom::Node, nil]
def resolve(nodename)
return self if nodename == @name
return nil if @children.nil? and @parent.nil?
path = RELATIVE.match(nodename)
if path
first, rest = path.captures
# we did find the first part in our list of children
if not @children.nil? and @children.has_key? first.to_sym
# we have to continue our search
if rest != ""
@children[first.to_sym].resolve rest
# Finish
else
@children[first.to_sym]
end
else
@parent.resolve nodename unless @parent.nil?
end
# It's absolute?
elsif ABSOLUTE.match nodename
Dom.root.find nodename
end
end
# Iterates recursivly over all children of this node and applies `block` to them
#
# @param [Block] block
def each_child(&block)
@children.values.each do |child|
yield(child)
child.each_child(&block)
end
end
# @group Manipulation
# There are three different cases
#
# 1. Last Childnode i.e. ".foo"
# -> Append node as child
# 2. absolute path i.e. "Foo"
# -> delegate path resolution to Dom.root
# 3. relative path i.e. ".bar.foo"
# a. if there is a matching child for first element, delegate
# adding to this node
# b. create NoDoc node and delegate rest to this NoDoc
#
#
# @overload add_node(path, node)
# @param [String] path
# @param [Dom::Node] node
#
# @overload add_node(node)
# @param [Dom::Node] node
#
def add_node(*args)
# Grabbing right overload
if args.count == 2
node = args[1]
path = args[0]
elsif args.count == 1
node = args[0]
path = '.'+node.name
raise NoPathGiven.new("#{node} has no path.") if path.nil?
else
raise ArgumentError.new "Wrong number of arguments #{args.count} for 1 or 2"
end
leaf = LEAF.match path
if leaf
# node found, lets insert it
add_child(leaf[:name], node)
else
matches = RELATIVE.match path
if matches
name = matches[:first].to_s
# node not found, what to do?
add_child(name, NoDoc.new(name)) if self[name].nil?
# everything fixed, continue with rest
self[name].add_node(matches[:rest], node)
else
# has to be an absolute path or something totally strange
raise WrongPath.new(path) unless ABSOLUTE.match path
# begin at top, if absolute
Dom.add_node '.' + path, node
end
end
end
# @group Name- and Path-Handling
# Like {#qualified_name} it finds the absolute path.
# But in contrast to qualified_name it will not include the current node.
#
# @example
# my_node.qualified_name #=> "Core.logger.log"
# my_node.namespace #=> "Core.logger"
#
# @see #qualified_name
# @return [String]
def namespace
parents.map{|p| p.name}.join NS_SEP_STRING
end
# The **Qualified Name** equals the **Absolute Path** starting from the
# root-node of the Dom.
#
# @example
# my_node.qualified_name #=> "Core.logger.log"
#
# @return [String]
def qualified_name
parents.push(self).map{|p| p.name}.join NS_SEP_STRING
end
# Generates a text-output on console, representing the **subtree-structure**
# of the current node. The current node is **not** being printed.
#
# @example example output
# -Core
# -extend
# -extensions
# -logger
# -log
# -properties
#
# @return [nil]
def print_tree
# Because parent = nil and parent = Dom.root are handled the same at #parents
# we need to make a difference here
if @parent.nil?
level = 0
else
level = parents.count + 1
end
@children.each do |name, child|
puts "#{" " * level}-#{name.to_s}#{' (NoDoc)' if child.is_a? NoDoc}"
child.print_tree
end
nil
end
protected
def add_child(name, node)
name = name.to_sym
if self[name].nil?
self[name] = node
# If child is a NoDoc: replace NoDoc with node and move all children from
# NoDoc to node using node.add_child
elsif self[name].is_a? NoDoc
self[name].children.each do |name, childnode|
node.add_child(name, childnode)
end
self[name] = node
else
raise NodeAlreadyExists.new(name)
end
self[name].parent = self
end
# @note unimplemented
def remove_child(name) end
def parent=(node)
@parent = node
end
# setting a children of this node
def []=(name, value)
@children[name.to_sym] = value
end
# path can be absolute like `Foo.bar`, `Foo` or it can be relative like
# `.foo`, `.foo.bar`.
# in both cases we need to extract the name from the string and save it
# as name. After doing this we can use the path to save to dom.
#
# @example absolute path
# Node.extract_name_from("Foo.bar.baz") #=> 'baz'
# Node.extract_name_from("Foo.bar.baz") #=> 'baz'
#
# @param [String] path relative or absolute path of node
# @return [String] the extracted name
def extract_name_from(path)
name = path.split(NS_SEP_STRING).last
raise NoNameInPath.new(path) if name.nil?
return name
end
end
end
| true |
0d8580344403e9f51ce1e6258a66baa0bc481de2 | Ruby | sadeeshkumarv/simple_record | /test/my_child_model.rb | UTF-8 | 538 | 2.59375 | 3 | [] | no_license | require File.expand_path(File.dirname(__FILE__) + "/../lib/simple_record")
require 'my_model'
class MyChildModel < SimpleRecord::Base
belongs_to :my_model
has_attributes :name
end
#
#
#puts 'word'
#
#mm = MyModel.new
#puts 'word2'
#
#mcm = MyChildModel.new
#
#puts 'mcm instance methods=' + MyChildModel.instance_methods(true).inspect
##puts 'mcm=' + mcm.instance_methods(false)
#puts 'mcm class vars = ' + mcm.class.class_variables.inspect
#puts mcm.class == MyChildModel
#puts 'saved? ' + mm.save.to_s
#puts mm.errors.inspect
| true |
0c782102302376a5238ae929b835dc2f4634ab94 | Ruby | weavery/clarc | /Rakefile | UTF-8 | 2,077 | 2.640625 | 3 | [
"Unlicense"
] | permissive | # This is free and unencumbered software released into the public domain.
require 'yaml'
require 'active_support/core_ext/hash' # `gem install activesupport`
def parse_examples(filepath, type)
examples = {}
File.open(filepath) do |file|
name = nil
file.readline; file.readline # skip URL
file.read.split("\n\n").each do |section|
case section
when / \$ clarc/
examples[name][:ok] += 1 if section.include?('STOP')
examples[name][:err] += 1 if section.include?('clarc:')
when /^([^:]+):\s?(.*)/
examples[name = $1] = {type: type, ok: 0, err: 0, notes: $2.strip}
else abort "unknown section: #{section}"
end
end
end
examples
end
def each_feature(&block)
features = {}
features.merge!(parse_examples('test/literals.t', 'literal'))
features.merge!(parse_examples('test/keywords.t', 'keyword'))
features.merge!(parse_examples('test/operators.t', 'operator'))
features.merge!(parse_examples('test/functions.t', 'function'))
#features.each { |k, v| p [k, v] }; exit
features.keys.sort.each do |feature|
block.call(feature, features[feature])
end
end
task default: %w(README.md)
file "README.md" => %w(test/literals.t test/keywords.t test/operators.t test/functions.t) do |t|
head = File.read(t.name).split("### Supported Clarity features\n", 2).first
File.open(t.name, 'w') do |file|
file.puts head
file.puts "### Supported Clarity features"
file.puts
file.puts ["Feature", "Type", "Status", "Notes"].join(' | ')
file.puts ["-------", "----", "------", "-----"].join(' | ')
each_feature do |feature, feature_info|
file.puts [
"`#{feature}`",
feature_info[:type],
feature_info[:notes] == "Not supported." || feature_info[:notes] == "Not implemented yet." ? "❌" :
(feature_info[:ok] > 0 ? "✅" : "🚧"),
feature_info[:notes],
].join(' | ').strip
end
file.puts
file.puts "**Legend**: ❌ = not supported. 🚧 = work in progress. ✅ = supported."
end
end
| true |
ffbcc2bafe0dcfa3fdcdc7b75f9acf8741720864 | Ruby | Augustus-Gabe/ruby_stuff | /condicionais.rb | UTF-8 | 263 | 3.5 | 4 | [] | no_license | puts"insira um numero"
numero = gets.to_i
puts "insira outro numero"
oto_numero = gets.to_i
if numero == oto_numero then
puts "Os numeros #{numero} e #{oto_numero} foram testados"
puts "os numeros sao iguais"
else
puts"os numeros são diferentes"
end
| true |
769dceebac3f3dbb00f0b8fe0bc69c20dbdd328d | Ruby | ryuchan00/Miscellaneous | /paiza/D.rb | UTF-8 | 1,012 | 3.546875 | 4 | [] | no_license | # input_lines = gets
# p gets.to_i
# p gets.to_i
# p input_lines
# words = []
# while s = gets
# words << s.chomp.to_i
# end
# p words.sort
# p gets.to_i
# p gets.to_i
# p input_lines
gets
words = []
while s = gets
words << s.chomp.to_i
end
# p words.sort
words.sort.each { |v| puts v.to_s + "\n" }
# a,b = gets.chomp.split(",")
# p a
# p b
# p " "
# p gets.chomp
# s = input_lines.split(" ")
# # print "hello = ", s[0], " , world = ", s[1], "\n"
# s.each do |word|
# # p word
# if words.has_key?(word.to_s)
# words[word.to_s] += 1
# else
# words[word.to_s] = 1
# end
# end
# }
# words.each { |k, v|
# puts k.to_s + " " + v.to_s
# }
# a,b = gets.chomp.split(",")
# p a
# p b
# p " "
# p gets.chomp
# s = input_lines.split(" ")
# # print "hello = ", s[0], " , world = ", s[1], "\n"
# s.each do |word|
# # p word
# if words.has_key?(word.to_s)
# words[word.to_s] += 1
# else
# words[word.to_s] = 1
# end
# end
# }
# words.each { |k, v|
# puts k.to_s + " " + v.to_s
# }
| true |
539d71261bc390786ed5ec7322f52e36127b93ff | Ruby | abicky/typed_data | /lib/typed_data/schema/enum_type.rb | UTF-8 | 315 | 2.5625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module TypedData
class Schema
class EnumType < Type
def initialize(name, symbols)
@name = name
@symbols = symbols
end
def primitive?
false
end
def match?(value)
@symbols.include?(value)
end
end
end
end
| true |
600261e48a9023e90b81993e633088a0c5ba71c4 | Ruby | meganemura/private_please | /lib/private_please/methods_calls_tracker.rb | UTF-8 | 772 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'private_please/tracking/trace_point_processor'
module PrivatePlease
class MethodsCallsTracker
def self.instance
@instance ||= new(Config.new)
end
def self.reset
@instance = nil
end
# -----
attr_reader :config
def initialize(config)
@config = config
@trace_point_processor = Tracking::TracePointProcessor.new(config)
end
private_class_method :new
def start_tracking
tracer.enable
end
def stop_tracking
tracer.disable
end
def result
@trace_point_processor.result
end
private
def tracer
@_tracer ||= begin
TracePoint.new do |tp|
@trace_point_processor.process(tp)
end
end
end
end
end
| true |
e2864184accae9377f8bfa87044d093f9152fd79 | Ruby | olsi2984/Ruby_projects | /Tic_Tac_Toe/tic_tac_toe.rb | UTF-8 | 3,329 | 4.0625 | 4 | [] | no_license | class Game
@@message = "It's a tie" # updated from check_winner
def initalize(board)
@board = board
end
def show_board(board)
puts row1 = "#{board[0]}"" | ""#{board[1]}"" | ""#{board[2]}"
puts separator = "---------"
puts row2 = "#{board[3]}"" | ""#{board[4]}"" | ""#{board[5]}"
puts separator
puts row3 = "#{board[6]}"" | ""#{board[7]}"" | ""#{board[8]}"
end
def valid_move?(board, p)
if p.between?(1, 9) == false
puts "Please type a valid input"
false
elsif board[p-1] != " "
puts "Sorry that cell is taken"
false
else
true
end
end
def taken_cells(board)
taken = 0
board.each do |n|
if n == "x" || n == "o"
taken +=1
end
end
return taken
end
def current_player(board)
player = nil
if taken_cells(board) % 2 == 0
player = "Player 1"
else
player = "Player 2"
end
return player
end
def put_mark(board, p)
if current_player(board) === "Player 1"
board[p-1] = "x"
else
board[p-1] = "o"
end
end
def position
p = nil
end
def turn(board)
puts "#{current_player(board)} please type a number from 1 to 9 where do you want to put your mark"
p = gets.chomp.to_i
if valid_move?(board, p)
put_mark(board, p)
show_board(board)
else
turn(board)
end
end
def play_game(board)
until
taken_cells(board) == 9
turn(board)
check_winner(board)
return if @@message == "Player 1 wins" || @@message == "Player 2 wins"
end
puts @@message
end
def check_winner(board)
puts @@message = "Player 1 wins" if board[0] == "x" && board[1] == "x" && board[2] == "x"
puts @@message = "Player 2 wins" if board[0] == "o" && board[1] == "o" && board[2] == "o"
puts @@message = "Player 1 wins" if board[3] == "x" && board[4] == "x" && board[5] == "x"
puts @@message = "Player 2 wins" if board[3] == "o" && board[4] == "o" && board[5] == "o"
puts @@message = "Player 1 wins" if board[6] == "x" && board[7] == "x" && board[8] == "x"
puts @@message = "Player 2 wins" if board[6] == "o" && board[7] == "o" && board[8] == "o"
puts @@message = "Player 1 wins" if board[0] == "x" && board[3] == "x" && board[6] == "x"
puts @@message = "Player 2 wins" if board[0] == "o" && board[3] == "o" && board[6] == "o"
puts @@message = "Player 1 wins" if board[1] == "x" && board[4] == "x" && board[7] == "x"
puts @@message = "Player 2 wins" if board[1] == "o" && board[4] == "o" && board[7] == "o"
puts @@message = "Player 1 wins" if board[2] == "x" && board[5] == "x" && board[8] == "x"
puts @@message = "Player 2 wins" if board[2] == "o" && board[5] == "o" && board[8] == "o"
puts @@message = "Player 1 wins" if board[0] == "x" && board[4] == "x" && board[8] == "x"
puts @@message = "Player 2 wins" if board[0] == "o" && board[4] == "o" && board[8] == "o"
puts @@message = "Player 1 wins" if board[2] == "x" && board[4] == "x" && board[6] == "x"
puts @@message = "Player 2 wins" if board[2] == "o" && board[4] == "o" && board[6] == "o"
end
end
ttt = Game.new
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ttt.show_board(board)
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
ttt.play_game(board)
| true |
13e7964b7df57a2bc43a4161f31888bd6e810ff8 | Ruby | ivanvanderbyl/cloudist | /examples/sandwich_worker_with_class.rb | UTF-8 | 1,355 | 2.734375 | 3 | [
"MIT"
] | permissive | # Cloudst Example: Sandwich Worker
#
# This example demonstrates receiving a job and sending back events to the client to let it know we've started and finsihed
# making a sandwich. From here you could dispatch an eat.sandwich event.
#
# Be sure to update the Cloudist connection settings if they differ from defaults:
# user: guest
# pass: guest
# port: 5672
# host: localhost
# vhost: /
#
$:.unshift File.dirname(__FILE__) + '/../lib'
require "rubygems"
require "cloudist"
class SandwichWorker < Cloudist::Worker
def process
log.info("Processing #{queue.name} job: #{id}")
# This will trigger the start event
# Appending ! to the end of a method will trigger an
# event reply with its name
#
# e.g. job.working!
#
job.started!
(1..5).each do |i|
# This sends a progress reply, you could use this to
# update a progress bar in your UI
#
# usage: #progress([INTEGER 0 - 100])
job.progress(i * 20)
# Work hard!
sleep(1)
# Uncomment this to test error handling in Listener
# raise ArgumentError, "NOT GOOD!" if i == 4
end
# Trigger finished event
job.finished!
end
end
Cloudist.signal_trap!
Cloudist.start(:logging => false, :worker_prefetch => 2) {
Cloudist.handle('make.sandwich').with(SandwichWorker)
}
| true |
4629e1e286821ce4c6af800526a492404e4c7b9a | Ruby | mattgfisch/phase-0-tracks | /ruby/santa.rb | UTF-8 | 2,045 | 4 | 4 | [] | no_license | # ----- SANTA CLASS DEFINITION
class Santa
attr_reader :ethnicity
attr_accessor :gender, :age
def initialize(gender, ethnicity)
puts "Initializing Santa instance..."
@gender = gender
@ethnicity = ethnicity
@reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
@age = 0
end
def speak
puts "Ho, ho, ho! Haaaappy holidays!"
end
def eat_milk_and_cookies(cookie_type)
p "That was a good #{cookie_type} cookie!"
end
#Attribute changing methods
def celebrate_birthday
@age += 1
end
def get_mad_at(reindeer)
@reindeer_ranking.delete(reindeer)
@reindeer_ranking << reindeer
end
end
# ----- TEST CODE
# happy = Santa.new("male", "white")
# happy.speak
# happy.eat_milk_and_cookies("snickerdoodle")
#Create array of santas
santas = []
#Establish test arguments
test_genders = ["agender", "female", "bigender", "male", "gender fluid", "N/A"]
test_ethnicities = ["black", "white", "chinese", "east-african", "aborigine", "N/A"]
#Loop through test arguments and shovel into a new santa in santas array
test_genders.length.times do |i|
santas << Santa.new(test_genders[i], test_ethnicities[i])
end
# #Should print data for 6th santa
# p santas[5]
p santas[4].celebrate_birthday
p santas[4].get_mad_at("Dancer")
p santas[5].gender = "Male"
p santas[4].age
p santas[3].ethnicity
# ----- BUILDING SANTAS
# Get how many santas you want to build (n)
puts "How many santas would you like to build?"
n = gets.chomp.to_i
# Loop n times, creating new santas with random gender and ethnicity
n.times do
# Randomly select gender and ethnicity
santa = Santa.new(test_genders.sample, test_ethnicities.sample)
# Randomly set age between 0 and 140
rand_age = Random.new
santa.age = rand_age.rand(141)
#Print attributes of newly built santa
puts "-"*10 + "NEW SANTA ATTRIBUTES" + "-"*10
puts "Age: #{santa.age}"
puts "Gender: #{santa.gender}"
puts "Ethnicity: #{santa.ethnicity}"
puts "-"*40
end
| true |
972dc83c1af574f985c04355997b294abe5185ea | Ruby | banyanbbt/Multi-Trust-Connector | /cloud/app/models/util/token.rb | UTF-8 | 708 | 2.9375 | 3 | [
"MIT"
] | permissive | module Util
class Token
class << self
def friendly_token(length=16)
SecureRandom.base64(length).tr('+/=lIO0', 'xmhesch')
end
def generate_password(password, salt)
pwd_str = password + "mtc" + salt
Digest::MD5.hexdigest(pwd_str)
end
def numeric_code(length=6)
chars = '012356789'
str = ''
length.times { str << chars[rand(chars.size)] }
str
end
def random_char(length=4)
chars = 'abcdefghjkmnpqrstuvwxyz'
str = ''
length.times { str << chars[rand(chars.size)] }
str
end
def random_name
"#{random_char}#{numeric_code}"
end
end
end
end | true |
05cc5f676c07a3951747223b797821d374eafc19 | Ruby | taiak/ruby_denemelerim | /Problemler/kok_bulma/kok_bul.rb | UTF-8 | 1,542 | 3.265625 | 3 | [] | no_license | def islem (x)
func = x**10 - 1
return func
end
def tablo_bas (alt, ust, adim, xR, hata_payi)
print "#{adim}\t#{alt.round(4)}\t#{ust.round(4)}\t"
print "#{xR.round(4)}\t#{islem(alt).round(4)}\t"
print "#{islem(ust).round(4)}\t#{islem(xR).round(4)}\t"
puts "#{hata_payi.round(6)}"
end
def kok_bas (xR)
puts "Kök: #{xR}"
end
def xr_bul (alt, ust, yontem = 1)
if (yontem == 0) # yontem 0'sa dogrusal yöntem çalışacak
xR = ust - ((islem(ust) * (alt-ust))/(islem(alt) - islem(ust)))
elsif (yontem == 1) # yontem 1'se ikiye bölme yöntemi çalışacak
xR = (alt + ust) / 2.0
end
return xR
end
def hata_payi_bul (xR, xR_eski)
return ((xR - xR_eski) / xR).abs * 100
end
def kok_bul (yontem, ust, alt=0, hata_siniri=0, xR_eski=0, adim=0)
if (islem(alt) * islem(ust) < 0 ) # adim1
adim, flag = adim + 1 , 0
xR = xr_bul(alt, ust, yontem) #adim 2
hata_payi = hata_payi_bul(xR, xR_eski)
tablo_bas(alt, ust, adim, xR, hata_payi)
if(hata_payi > hata_siniri)
sonuc = islem(xR) * islem(alt)
if(islem(xR) * islem(alt) < 0)
kok_bul( yontem, alt, xR, hata_siniri, xR, adim)
elsif(islem(xR) * islem(alt) > 0)
kok_bul( yontem, xR, ust, hata_siniri, xR, adim)
else
flag = 1
end
else
flag = 1
end
kok_bas(xR) if (flag == 1)
end
end
puts "Doğrusal Yaklaşımla Çözüm"
puts "Adım\tXa\tXü\tXr\tf(Xa)\tf(Xü)\tf(Xr)\tHata Payı"
kok_bul(0, 1.3, 0, 0.01)
puts "\nAralığı İkiye Bölme Yöntemiyle"
puts "Adım\tXa\tXü\tXr\tf(Xa)\tf(Xü)\tf(Xr)\tHata Payı"
kok_bul(1, 1.3, 0, 0.01)
| true |
8c0fb3d51a42c25c7df5da977f53d1d671a86e53 | Ruby | Adedee/ruby | /Exercise12/bin/main.rb | UTF-8 | 204 | 3.578125 | 4 | [] | no_license | require_relative('../lib/CharacterClass.rb')
puts "Please enter text"
text = gets.chomp
if text.nil?
puts "Please enter a number"
else
characters = CharacterClass.new(text)
puts characters.to_s
end | true |
233aa40c4de13aab861c1a7cfc85fbcaec8dc399 | Ruby | akatz/check_internet | /check_internet.rb | UTF-8 | 525 | 2.75 | 3 | [] | no_license | #!/usr/bin/ruby
require 'rubygems'
require 'curb'
unless ARGV.size == 2
puts "Usage: \n #{$0} url delay"
exit
end
url = ARGV[0]
delay = ARGV[1]
puts "Checking " + url + " every " + delay + " seconds"
while 1
time = Time.now
# url = URI.parse('http://www.google.com')
begin
p = Curl::Easy.perform(url).response_code
elapsed_time = Time.now - time
puts "Time " + elapsed_time.to_s + " response " + p.to_s
rescue Curl::Err::HostResolutionError
puts "Not Connected"
end
sleep delay.to_i
end | true |
72c2d76aebb594118e1abd5d4d965c05abfb78ff | Ruby | ozfortress/serveme | /app/services/ftp_zip_file_creator.rb | UTF-8 | 787 | 2.640625 | 3 | [] | no_license | # frozen_string_literal: true
class FtpZipFileCreator < ZipFileCreator
def create_zip
tmp_dir = Dir.mktmpdir
begin
reservation.status_update("Downloading logs and demos from FTP")
server.copy_from_server(files_to_zip, tmp_dir)
zip(tmp_dir)
chmod
ensure
FileUtils.remove_entry tmp_dir
end
end
def zip(tmp_dir)
reservation.status_update("Zipping logs and demos")
Zip::File.open(zipfile_name_and_path, Zip::File::CREATE) do |zipfile|
files_to_zip_in_dir(tmp_dir).each do |filename_with_path|
filename_without_path = File.basename(filename_with_path)
zipfile.add(filename_without_path, filename_with_path)
end
end
end
def files_to_zip_in_dir(dir)
Dir.glob(File.join(dir, "*"))
end
end
| true |
8edf90ca170eb15bb12c8f91d6ff78583832ab18 | Ruby | Automatic365/module_3_diagnostic | /app/models/station.rb | UTF-8 | 292 | 2.671875 | 3 | [] | no_license | class Station < OpenStruct
def self.service
StationService.new
end
def self.search_locations_by_zipcode(params)
raw_stations = service.search_locations_by_zipcode(params)
raw_stations["fuel_stations"].map do |raw_station|
Station.new(raw_station)
end
end
end
| true |
c99e621c1a8ad82b8da2c6592a1e141d6ebd635d | Ruby | khotta/simple_rotate | /lib/simple_rotate/internal/process_sync.rb | UTF-8 | 3,492 | 2.53125 | 3 | [
"MIT"
] | permissive | require_relative "./process_sync_mixin"
class SimpleRotate
class ProcessSync
include ProcessSyncMixin
ProcessSyncMixin.instance_methods.each do |method_name|
method = instance_method(method_name)
define_method(method_name) do |*args|
# common execution
return nil if !@enable
# -------------------
method.bind(self).call(*args)
end
end
def initialize(sr)
@sr = sr
@enable = sr.instance_variable_defined?(:@is_psync) ? sr.instance_variable_get(:@is_psync) : nil
file_name = sr.instance_variable_defined?(:@file_name) ? sr.instance_variable_get(:@file_name) : nil
# #init not called
return self if file_name == nil
@try_limit = 3
@@tempf_name = File.dirname(file_name) + File::SEPARATOR + ".simple_rotate_tempfile_#{File.basename($0)}"
# replace whitespaces
@@tempf_name.gsub!(/\s/, '_')
create_tempfile if @enable && !@@scheduled_del_lockfile
end
# Create the temp file for locking
private
def create_tempfile
begin
if tempf_exists?
set_delete_tempfile
else
@@tempf = File.open(@@tempf_name, File::RDWR|File::CREAT|File::EXCL)
set_delete_tempfile
end
rescue
SimpleRotate::Error.warning("Failed to create temp file => #{@@tempf_name}")
end
end
private
def tempf_exists?
return File.exist?(@@tempf_name)
end
# Delete the lock file at the end of the script
private
def set_delete_tempfile
return true if @@scheduled_del_lockfile
if tempf_exists?
# is it empty?
if File.size(@@tempf_name) == 0
delete_at_end
else
# it is not empty
msg = "File is not empty => #{@@tempf_name}#{$-0}"
msg += "Skip to delete temp file!"
SimpleRotate::Error.warning(msg)
end
end
@@scheduled_del_lockfile = true
end
private
def delete_at_end
at_exit do
begin
File.delete(@@tempf_name)
rescue
SimpleRotate::Error.warning("Failed to delete temp file => #{@@tempf_name}")
end
end
end
private
def reopen_temp_file
close_temp_file
open_temp_file
end
private
def open_temp_file
if @@tempf.is_a?(IO) && @@tempf.closed? || !@@tempf.is_a?(IO)
begin
@@tempf = File.open(@@tempf_name, File::RDWR|File::CREAT|File::APPEND)
rescue
SimpleRotate::Error.warning("Failed to open temp file => #{@@tempf_name}")
end
end
end
private
def close_temp_file
if @@tempf.is_a?(IO) && !@@tempf.closed?
begin
@@tempf.close
rescue
SimpleRotate::Error.warning("Couldn't close temp file => #{@@tempf_name}")
end
end
end
end
end
| true |
e50cc699cbd052455f374f978cc49286ec49650e | Ruby | Brandan-Hummell/blocipedia | /db/seeds.rb | UTF-8 | 464 | 2.5625 | 3 | [] | no_license | require 'faker'
5.times do
User.create!(
email: Faker::Internet.unique.email,
password: Faker::Internet.password(6, 10),
role: :standard
)
end
users = User.all
20.times do
Wiki.create!(
title: Faker::Witcher.character,
body: Faker::Witcher.quote,
user: users.sample,
private: false
)
end
wikis = Wiki.all
puts "Created #{users.count} Users"
puts "Created #{wikis.count} Wikis" | true |
3bf1fd6132499fc1077558cb1d13faf006bd60d3 | Ruby | ossert/ossert | /lib/ossert/classifiers.rb | UTF-8 | 3,216 | 3.046875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'ossert/classifiers/base'
require 'ossert/classifiers/decision_tree'
require 'ossert/classifiers/growing'
require 'ossert/classifiers/cluster'
require 'ossert/classifiers/check'
module Ossert
module Classifiers
module_function
# The list of available data sections.
SECTIONS = %i[agility community].freeze
# The list of available data periods.
PERIODS = %i[total quarter last_year].freeze
# The list of available classifiers.
# It is calculated from all combinations of SECTIONS and PERIODS.
CLASSIFIERS = SECTIONS.product(PERIODS).map { |s, p| "#{s}_#{p}".to_sym }
# The list of available grades for a project and its metrics.
GRADES = %w[ClassA ClassB ClassC ClassD ClassE].freeze
# The map of available grades to its reversed version.
REVERSED_GRADES = GRADES.zip(GRADES.reverse).to_h.freeze
# Public: Prepare classifiers.
# It warms up classifiers upon existing data.
def train
Growing.new.train
Cluster.current.train
# Stale. Very untrusty
DecisionTree.new(Project.projects_by_reference).train
end
# Helper class for threshold value to range conversion
class ThresholdToRange
def initialize(metric, value, grade, reversed: ->(_) { false })
@metric = metric
@value = value
@grade = grade
@reversed = reversed
end
# @return [Range] for the given instance
def range
if reversed?(@metric)
Reversed.new(@value, @grade).range
else
Base.new(@value, @grade).range
end
end
# Check the metric if it reversed.
#
# @param metric_name [String] to check.
# @return [true, false] check result.
def reversed?(metric_name)
@reversed.call(metric_name)
end
# Class for base threshold to range behavior
class Base
def initialize(value, grade)
@value = value.to_f
@grade = grade
end
# @return [Range] for current instance state
def range
start_value...end_value
end
private
# @return [true, false] if current value is the worst one.
def worst_value?
@grade == worst_grade
end
# @return [one of GRADES] which to treat as the worst one.
def worst_grade
GRADES.last
end
# @return [Float] where to start the result range
def start_value
return -Float::INFINITY if worst_value?
@value
end
# @return [Float] where to end the result range
def end_value
Float::INFINITY
end
end
# Class for reversed threshold to range behavior
class Reversed < Base
# @return [one of GRADES] which to treat as the worst one.
def worst_grade
GRADES.first
end
# @return [Float] where to start the result range
def start_value
-Float::INFINITY
end
# @return [Float] where to end the result range
def end_value
return Float::INFINITY if worst_value?
@value
end
end
end
end
end
| true |
243d48ab596ff1ccf040011e581d71ac8728fdb4 | Ruby | menor/dbc_flashcards_and_todos | /part4_ruby-todos-2-additional-features-challenge/solutions/sample_19.rb | UTF-8 | 4,053 | 3.421875 | 3 | [] | no_license | require 'csv'
require 'date'
class CSVParser
def self.load
test = []
CSV.foreach('todo3.csv', { headers: true, header_converters: :symbol }) do |row|
test << Task.new(row.to_hash)
end
test
end
end
class Task
attr_reader :todo, :index, :completion_date, :creation_date, :tags
attr_accessor :status
def initialize(args)
@index = args[:index]
@status = args[:status]
@todo = args[:todo]
@creation_date = args[:creation_date]
@completion_date = args[:completion_date]
@tags = args[:tags]
end
def complete!
@status = 'complete'
@completion_date = Date.today.to_s
end
def tag!(tags)
@tags = tags
end
def incomplete?
status == 'incomplete'
end
def completed?
status == 'complete'
end
def to_a
[@index, @status, @todo, @creation_date, @completion_date, @tags]
end
end
module Output
def welcome
puts "Your Todo List"
puts "========================================================================"
end
def clear_screen
print "\e[2J"
print "\e[H"
end
end
class TodoList
attr_reader :list
def initialize(args)
@list = args
end
def save
CSV.open('todo3.csv', "w") do |csv|
csv << ['index', 'status', 'todo', 'creation_date', 'completion_date', 'tags']
list.each { |todo| csv << todo.to_a }
end
end
def convert_to_hash(task)
{:index => list.last.index.to_i+1, :status => 'incomplete', :todo => task, :creation_date => Date.today.to_s, :completion_date => nil, :tags => nil}
end
def display
list
end
def add(task)
@list << Task.new(convert_to_hash(task))
save
end
def find_at(index)
task = list.find do |task|
task.index == index.to_s
end
task
end
def delete_at(index)
puts "deleting at #{index}"
list.delete(find_at(index))
save
end
def created_first
list.sort_by do |task|
task.creation_date
end
end
def outstanding #Add formatting when outputting
created_first.select do |task|
task.incomplete?
end
end
def completed_first
list.select { |task| task.completion_date != nil }.sort_by do |task|
task.completion_date
end.reverse
end
def completed
completed_first.select do |task|
task.completed?
end
end
def complete_at(index)
find_at(index).complete!
save
end
def tag(index, tags)
find_at(index).tag!(tags)
save
end
def filter(tag)
list.select { |task| task.tags.include?(tag) }
end
end
class UI
include Output
attr_reader :command, :argument, :tags, :list
def initialize
@list = TodoList.new(CSVParser.load)
end
def x_bracket(task)
task.completed? ? '[X]' : '[ ]'
end
def pretty_print(array)
array.each do |task|
puts "#{task.index}. #{x_bracket(task)} #{task.todo} - Completed: #{task.completion_date} - Created: #{task.creation_date} - Tags: #{task.tags}"
end
end
def start(input)
clear_screen
welcome
parse_input(input)
case command
when "list"
if argument == "outstanding"
pretty_print(list.outstanding)
elsif argument == "completed"
pretty_print(list.completed)
else
pretty_print(list.display)
end
when "add"
list.add(argument)
pretty_print(list.display)
when "delete"
list.delete_at(argument)
pretty_print(list.display)
when "complete"
list.complete_at(argument)
pretty_print(list.display)
when "filter"
pretty_print(list.filter(argument))
when "tag"
list.tag(argument, tags)
pretty_print(list.display)
end
end
def parse_input(input)
if input[0].include?(':')
@command = input[0].split(':')[0]
@argument = input[0].split(':')[1]
elsif input[0].include?('add')
@command = ARGV.shift
@argument = ARGV.join(" ").chomp
else
@command = ARGV.shift
@argument = ARGV.shift
@tags = ARGV.join(" ")
end
end
end
app = UI.new
app.start(ARGV)
| true |
355ced9d1b46d49c6582b867bc688141ec06e9a0 | Ruby | ecmerchant/Somali | /app/models/product.rb | UTF-8 | 10,432 | 2.578125 | 3 | [] | no_license | class Product < ApplicationRecord
require 'uri'
require 'open-uri'
require 'nokogiri'
require 'date'
def collect(user, data)
logger.debug("====== Collect ========")
asin = data[0]
logger.debug(asin)
check1 = data[9].to_s
check2 = data[14].to_s
check3 = data[18].to_s
logger.debug(check1)
logger.debug(check2)
logger.debug(check3)
url = 'https://delta-tracer.com/item/chart_html/jp/' + asin
charset = nil
begin
html = open(url) do |f|
charset = f.charset
f.read # htmlを読み込んで変数htmlに渡す
end
rescue OpenURI::HTTPError => error
logger.debug("===== ERROR =====")
logger.debug(error)
hit = Product.where(user: user).find_or_create_by(asin: asin)
result = {
asin: asin,
new_sale1: 0,
new_sale2: 0,
new_sale3: 0,
used_sale1: 0,
used_sale2: 0,
used_sale3: 0,
new_avg3: 0,
used_avg3: 0,
check1: check1,
cart_price: 0,
cart_income: 0,
used_price: 0,
used_income: 0,
check2: check2,
title: "※該当商品なし",
mpn: "",
item_image: "",
check3: check3,
new_bid_price: 0,
used_bid_price: 0,
new_negotiate_price: 0,
used_negotiate_price: 0
}
hit.update(result)
return result
end
json = html.match(/JSON.parse\('([\s\S]*?)'/)[1]
rawdata = JSON.parse(json)
timestamp = rawdata['timestamp']
new_count = rawdata['data']['new_count']
used_count = rawdata['data']['used_count']
sales_rank = rawdata['data']['sales_rank']
new_counter1 = 0
new_counter2 = 0
new_counter3 = 0
used_counter1 = 0
used_counter2 = 0
used_counter3 = 0
counter1 = 0
counter2 = 0
counter3 = 0
d1 = 1.months.ago.to_i * 1000
d2 = 2.months.ago.to_i * 1000
d3 = 3.months.ago.to_i * 1000
timestamp.each.with_index(1) do |tt, j|
diff = sales_rank[j].to_i - sales_rank[j-1].to_i
new_diff = new_count[j].to_i - new_count[j-1].to_i
used_diff = used_count[j].to_i - used_count[j-1].to_i
if diff < (sales_rank[j-1].to_i*0.05*(-1)) then
if tt > d3 then
if new_diff < 0 then
new_counter3 += 1
end
if used_diff < 0 then
used_counter3 += 1
end
counter3 += 1
if tt > d2 then
if new_diff < 0 then
new_counter2 += 1
end
if used_diff < 0 then
used_counter2 += 1
end
counter2 += 1
if tt > d1 then
if new_diff < 0 then
new_counter1 += 1
end
if used_diff < 0 then
used_counter1 += 1
end
counter1 += 1
end
end
end
end
end
avg_new = (new_counter3) / 3
if new_counter3 > 0 && avg_new == 0 then
avg_new = 1
end
avg_used = (used_counter3) / 3
puts '===== VALUES ======'
puts "avg_new=" + avg_new.to_s
puts "avg_used=" + avg_used.to_s
puts "new_counter1=" + new_counter1.to_s
puts "new_counter2=" + new_counter2.to_s
puts "new_counter3=" + new_counter3.to_s
puts "used_counter1=" + used_counter1.to_s
puts "used_counter2=" + used_counter2.to_s
puts "used_counter3=" + used_counter3.to_s
puts '===== END ======'
if avg_new == 0 && avg_used == 0 then
puts '===== NO DATA ======'
hit = Product.where(user: user).find_or_create_by(asin: asin)
result = {
asin: asin,
new_sale1: 0,
new_sale2: 0,
new_sale3: 0,
used_sale1: 0,
used_sale2: 0,
used_sale3: 0,
new_avg3: 0,
used_avg3: 0,
check1: check1,
cart_price: 0,
cart_income: 0,
used_price: 0,
used_income: 0,
check2: check2,
title: "※該当データなし",
mpn: "",
item_image: "",
check3: check3,
new_bid_price: 0,
used_bid_price: 0,
new_negotiate_price: 0,
used_negotiate_price: 0
}
hit.update(result)
return result
end
url = "https://delta-tracer.com/item/detail/jp/" + asin
charset = nil
html = nil
begin
html = open(url) do |f|
charset = f.charset
f.read # htmlを読み込んで変数htmlに渡す
end
rescue OpenURI::HTTPError => error
logger.debug("===== ERROR =====")
logger.debug(error)
end
cart = html.match(/新品カート<\/strong>([\s\S]*?)<\/tr>/)
if cart != nil then
cart = cart[1]
cart = cart.scan(/<strong>([\s\S]*?)<\/strong>/)
if cart != nil then
if cart[0] != nil then
cart_price = cart[0][0].gsub(",","").to_i
if cart[1] != nil then
cart_profit = cart[1][0].gsub(",","").to_i
else
cart_profit = 0
end
else
cart_price = 0
cart_profit = 0
end
else
cart_price = 0
cart_profit = 0
end
else
cart_price = 0
cart_profit = 0
end
used = html.match(/中古<\/strong>([\s\S]*?)<\/tr>/)
if used != nil then
used = used[1]
used = used.scan(/<strong>([\s\S]*?)<\/strong>/)
if used != nil then
if used[0] != nil then
used_price = used[0][0].gsub(",","").to_i
if used[1] != nil then
used_profit = used[1][0].gsub(",","").to_i
else
used_profit = 0
end
else
used_price = 0
used_profit = 0
end
else
used_price = 0
used_profit = 0
end
else
used_price = 0
used_profit = 0
end
title = html.match(/<strong style="word-break:break-all;">([\s\S]*?)<\/strong>/)
if title != nil then
title = title[1]
mpn = html.match(/<strong>規格番号:<\/strong><input class="selectable" value="([\s\S]*?)"/)
if mpn != nil then
mpn = mpn[1]
else
mpn = ""
end
temp = html.match(/<table class="table-itemlist"([\s\S]*?)td>/)
if temp != nil then
temp = temp[1]
image = temp.match(/src="([\s\S]*?)"/)
if image != nil then
image = image[1]
else
image = ""
end
else
image = ""
end
if check1 == "true" then
cart_price = data[11].to_i
cart_profit = data[12].to_i
used_price = data[13].to_i
used_profit = data[14].to_i
end
logger.debug(cart_price)
logger.debug(cart_profit)
logger.debug(used_price)
logger.debug(used_profit)
#計算
tuser = Account.find_by(user: user)
profit_rate = (tuser.profit_rate.to_f / 100.to_f).to_f
used_profit_rate = (tuser.used_profit_rate.to_f / 100.to_f).to_f
shipping = tuser.shipping
puts profit_rate
puts shipping
if cart_price != 0 then
new_bid_price = cart_profit.to_f - shipping.to_f - (cart_price.to_f * profit_rate).to_f
new_bid_price = new_bid_price.round(-2)
if cart_profit * (1.to_f - profit_rate).to_f < 10000 then
temp = cart_profit.to_f * (1.to_f - profit_rate).to_f
new_negotiate_price = (temp.to_i / 500.to_i) * 500
else
temp = cart_profit.to_f * (1.to_f - profit_rate).to_f
new_negotiate_price = (temp.to_i / 1000.to_i) * 1000
end
else
new_bid_price = 0
new_negotiate_price = 0
end
if used_price != 0 then
used_bid_price = used_profit.to_f - shipping.to_f - (used_price.to_f * used_profit_rate).to_f
used_bid_price = used_bid_price.round(-2)
if used_profit * (1.to_f - used_profit_rate).to_f < 10000 then
temp = used_profit.to_f * (1.to_f - used_profit_rate).to_f
used_negotiate_price = (temp.to_i / 500.to_i) * 500
else
temp = used_profit.to_f * (1.to_f - used_profit_rate).to_f
used_negotiate_price = (temp.to_i / 1000.to_i) * 1000
end
else
used_bid_price = 0
used_negotiate_price = 0
end
else
title = ""
mpn = ""
image = ""
end
puts '===== VALUES ======'
puts "title=" + title.to_s
puts "mpn=" + mpn.to_s
puts "image=" + image.to_s
puts "cart_price=" + cart_price.to_s
puts "cart_profit=" + cart_profit.to_s
puts "used_price=" + used_price.to_s
puts "used_profit=" + used_profit.to_s
puts '===== END ======'
hit = Product.where(user: user).find_or_create_by(asin: asin)
if check1 == "true" then
logger.debug("check1")
cart_price = data[10].to_i
cart_income = data[11].to_i
used_price = data[12].to_i
used_income = data[13].to_i
end
if check2 == "true" then
logger.debug("check2")
title = data[15].to_s
mpn = data[16].to_s
image = /src="([\s\S]*?)"/.match(data[17])[1]
end
if check3 == "true" then
logger.debug("check3")
new_bid_price = data[19].to_i
used_bid_price = data[20].to_i
new_negotiate_price = data[21].to_i
used_negotiate_price = data[22].to_i
end
used_counter3 = used_counter3 - used_counter2
used_counter2 = used_counter2 - used_counter1
new_counter3 = counter3 - counter2 - used_counter3
new_counter2 = counter2 - counter1 - used_counter2
new_counter1 = counter1 - used_counter1
avg_new = (new_counter3 + new_counter2 + new_counter1) / 3
result = {
asin: asin,
new_sale1: new_counter1,
new_sale2: new_counter2,
new_sale3: new_counter3,
used_sale1: used_counter1,
used_sale2: used_counter2,
used_sale3: used_counter3,
new_avg3: avg_new,
used_avg3: avg_used,
check1: check1,
cart_price: cart_price,
cart_income: cart_profit,
used_price: used_price,
used_income: used_profit,
check2: check2,
title: title,
mpn: mpn,
item_image: image,
check3: check3,
new_bid_price: new_bid_price,
used_bid_price: used_bid_price,
new_negotiate_price: new_negotiate_price,
used_negotiate_price: used_negotiate_price
}
hit.update(result)
return result
end
end
| true |
5bc9c843a76ed724c34c78a9c8958f63f0d0e56e | Ruby | k-kibi/codeiq_solutions | /1621/1621.rb | UTF-8 | 717 | 3.640625 | 4 | [] | no_license | require 'pp'
def count_prime(num)
# 0〜numのindexを持つ配列を作る
list = Array.new(num+1)
2.upto(num/2) do |i|
list[i*2] = 1
end
prime = 3
while prime * prime < num
#puts "prime: #{prime}"
prime.step(num/prime, 2) do |i|
list[i*prime] = 1
end
#list.each_with_index do |n, i|
# print "#{i} " if n.nil?
#end
#print "\n"
prime += 1
until list[prime].nil?
prime += 1
end
end
#list.each_with_index do |n, i|
# puts "list[#{i}]: #{n.nil?}"
#end
result = 0
# i=0,1 を除去
list.shift 2
# i=num を除去
list.pop
list.map{ |i| result += 1 if i.nil? }
result
end
while str = STDIN.gets
puts count_prime(str.to_i)
end
| true |
9878e3c98c84837745545848996d3cc7498ed102 | Ruby | AnnaGulstine/ruby_exercises | /calc_3.rb | UTF-8 | 1,440 | 4.5 | 4 | [] | no_license | # In this example, we have THREE calculators, the two included in the previous
# exercises as well as Whiz Bang Calculator that can even calculate the
# hypotenuse of a triangle if given the length of the other two sides. Figure
# out how to DRY up all the code below - there shouldn't be a single method
# duplicated between any two classes.
module Utilities # :nodoc:
def add(first_number, second_number)
first_number + second_number
end
def subtract(first_number, second_number)
first_number - second_number
end
def multiply(first_number, second_number)
first_number * second_number
end
def divide(first_number, second_number)
first_number / second_number
end
end
class SimpleCalculator # :nodoc:
include Utilities
end
class FancyCalculator # :nodoc:
include Utilities
def square_root(number)
Math.sqrt(number)
end
end
class WhizBangCalculator < FancyCalculator # :nodoc:
def hypotenuse(first_number, second_number)
Math.hypot(first_number, second_number)
end
def exponent(first_number, exponent_number)
total = 1
exponent_number.times { total = multiply(total, first_number) }
total
end
end
# Copy your driver code from the previous exercise and more below:
calc = WhizBangCalculator.new
puts calc.add(4, 3)
puts calc.subtract(4, 3)
puts calc.multiply(4, 3)
puts calc.divide(6, 3)
puts calc.square_root(4)
puts calc.hypotenuse(3, 4)
puts calc.exponent(2, 2)
| true |
6fa7bea059cf34ce278f81bb1aafeb976f1fdbfa | Ruby | oveja87/D3_crossfilter_movie_connection_demo | /app/workers/filmography_scanner_worker.rb | UTF-8 | 1,947 | 2.625 | 3 | [] | no_license | # encoding: UTF-8
class FilmographyScannerWorker
include Sidekiq::Worker
sidekiq_options :queue => :filmography
def perform(imdb_id)
imdb_id = imdb_id.pop
doc = PersonCrawler.person_data(imdb_id)
f = doc.at('#filmography')
if f && (f.at('div[data-category="actor"]') || f.at('div[data-category="actress"]'))
div_pos = nil
i = 0
f.search('div.head').each do |r|
if r['data-category']=='actor' || r['data-category']=='actress'
div_pos = i
end
i+=1
end
if div_pos
row_bodies = f.search('div.filmo-category-section')
if row_bodies.length > 0
actor_rows = row_bodies[div_pos].search('div.filmo-row')
else
actor_rows = []
end
end
if actor_rows.length > 0
movie = {}
actor_rows.each do |row|
# Ignore TV-Series
next if row.to_s.match(/.*\s+\(TV\s+Series\).*/)
next if row.to_s.match(/.*\s+\(Video\s+Game\).*/)
if row.at('b/a')
movie[:title] = row.at('b/a').inner_text.strip
movie[:imdb_id] = row.at('b/a')['href'].gsub(/.*\/(tt[^\/]+).*/, "\\1")
# Ignore movies we already found
next if File.read('/Users/christoph/Desktop/found_imdb_ids.txt').split(/\n/).include? movie[:imdb_id]
end
if row.at('.year_column')
movie[:year] = row.at('.year_column').inner_text.gsub(/.*(\d{4}).*/m, "\\1").to_i
end
if movie[:imdb_id]
File.open('/Users/christoph/Desktop/found_imdb_ids.txt', 'a'){|f| f.write("#{movie[:imdb_id]}\n")}
if movie[:year] >= 2000
puts movie.inspect
MovieInformationWorker.perform_async movie[:imdb_id]
end
else
raise "IMdB ID not found!"
end
end
end
end
end
end | true |
9caeb94791350682c0bd6c842e14f50b520e39ee | Ruby | ja-laporte/launch-school | /LS_Prep/More_Stuff/more_stuff_exercises/ex3.rb | UTF-8 | 698 | 3.625 | 4 | [] | no_license | # what_is_exception_handling.rb
# My answer:
<<-HERE
Exception handling is the process by which a programmer can "catch" error instances and trace them back to their origin in hopes of trying to determine the cause of the error. It solves having to dig around in your code with no idea where an issue may have occurred - instead it leaves a trail and some details of what has happened.
HERE
# My answer was incorrect. What I described was stack tracing.
# Tutorial answer:
<<-HERE
Exception handling is a structure used to handle the possibility of an error occurring in a program. It is a way of handling the error by changing the flow of control without exiting the program entirely.
HERE | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.