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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
33a5002cfdf3ba05766e89390d7991133a276325 | Ruby | richardTowers/fixingVerify | /lib/pki.rb | UTF-8 | 752 | 2.53125 | 3 | [] | no_license | require 'base64'
def create_private_key(key)
puts key.filename
pem_path = key.path.sub(/\.pk8$/, '.pem')
Dir.chdir("#{__dir__}/..") do
`openssl genrsa -out '#{pem_path}' 2048`
`openssl pkcs8 -topk8 -inform PEM -outform DER -in '#{pem_path}' -out '#{key.path}' -nocrypt`
end
end
def create_certificate(certificate, private_key_path)
puts certificate.filename
pem_path = private_key_path.sub(/\.pk8$/, '.pem')
Dir.chdir("#{__dir__}/..") do
`openssl req -batch -new -subj '/CN=#{certificate.variable}' -key '#{pem_path}' | openssl x509 -req -sha256 -signkey '#{pem_path}' -out '#{certificate.path}'`
end
end
def read_as_base64(path)
Dir.chdir("#{__dir__}/..") do
Base64.strict_encode64(IO.binread(path))
end
end
| true |
1bbdeeeb577c914a73062f718af8dae9501cf2b7 | Ruby | akax/akax.github.com | /newpost.rb | UTF-8 | 2,015 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env ruby
# *********************************************
# Jekyll Post Generator Awesomeness
# by Cody Krieger (http://codykrieger.com)
# edited by Akax (http://blog.uytor.info)
# *********************************************
# Usage:
# % ./newpost.rb POST NAME
if ARGV.empty? or ARGV[0].downcase == "--help" or ARGV[0].downcase == "-h"
puts <<-USAGE
Usage:
% ./newpost.rb POST NAME
USAGE
exit (ARGV.empty? ? 1 : 0)
end
#from http://www.java2s.com/Code/Ruby/Time/Converttimetotimezone.htm
class Time
def convert_zone(to_zone)
original_zone = ENV["TZ"]
utc_time = dup.gmtime
ENV["TZ"] = to_zone
to_zone_time = utc_time.localtime
ENV["TZ"] = original_zone
return to_zone_time
end
end
class String
# from ruby on rails (https://github.com/rails/rails)
# activesupport/lib/active_support/inflector/transliterate.rb
def parameterize(sep = '-')
# replace accented chars with their ascii equivalents
parameterized_string = self.dup
# Turn unwanted chars into the separator
parameterized_string.gsub!(/[^a-z0-9\-_]+/i, sep)
unless sep.nil? || sep.empty?
re_sep = Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/i, '')
end
parameterized_string.downcase
end
end
TEMPLATE = "template.markdown"
POSTS_DIR = "_posts"
# Get the title and use it to derive the new filename
t = Time.now
t.convert_zone("US/Eastern")
title = ARGV.join(" ")
filename = "#{t.strftime('%Y-%m-%d')}-#{title.parameterize}.markdown"
filepath = File.join(POSTS_DIR, filename)
# Load in the template and set the title
post_text = File.read(TEMPLATE)
post_text.gsub!('%%TITLE%%', title)
post_text.gsub!('%%DATE%%', "#{t.strftime('%Y-%m-%d %H:%M:%S')}")
# Write out the post
post_file = File.open(filepath, 'w')
post_file.puts post_text
post_file.close
system("subl #{filepath}")
| true |
71b5837189c32b65ada4e539357f66faf260c72e | Ruby | marcelodanieldm/projectsAndPracticeRB | /helloname.rb | UTF-8 | 69 | 3.40625 | 3 | [] | no_license | print "Write your name: "
name = gets.chomp
puts
puts "Hi #{name}!"
| true |
fe0ef2cb0e695a6dcb99d7bdcd0756bcc06bf9ef | Ruby | fuzzySi/sonicPi | /shepardTone.rb | UTF-8 | 936 | 2.640625 | 3 | [] | no_license | # Shephard tone
tempo = 120
maxAmp = 0.5
layers = 5
use_synth :sine
notes = chord:c3, :m, num_octaves: 4
len = notes.length
vols = []
fade = len / 4 # proportion of loop affected by fade
incr = maxAmp.to_f / fade # or # maxAmp.fdiv(fade)
threads = []
for i in 0...layers
threads[i] = len / layers * i # sorts out where multiple ribbons are along scale
end
for i in 0...fade # attribute fade volumes
vols[i] = incr * (i + 1)
end
for i in fade...(len - fade)
vols[i] = maxAmp
end
for i in (len - fade)...(len)
vols[i] = incr * (len - i)
end
live_loop :scale do
use_bpm tempo
for i in 0...len
for j in 0...layers
k = i + threads[j]
if k >= len then
k = k - len
end
# puts notes[k], vols[k], (k.fdiv(len)* 2)-1
play notes[k], amp: vols[k], attack: 1, release: 1.5-i.fdiv(len), pan: (k.fdiv(len)* 2)-1 #, cutoff: (k * 50 / len) + 50
sleep (0.5 / layers)
end
end
end
| true |
4ced585a5f2d44783810ec3b7e858d2ae7f6a2ac | Ruby | ho-tonym/my-select-nyc-web-051418 | /lib/my_select.rb | UTF-8 | 417 | 3.515625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_select(collection)
if collection.length <= 0
"This block should not run!"
else
counter = 0
new_array = Array.new
while counter < collection.length
if yield(collection[counter]) == true
new_array << (collection[counter])
end
counter +=1
end
end
return new_array
=begin
collection.select do |number|
number.even?
end
=end
end
| true |
7e1579694792f130103b7b35d0e43373c5d8666e | Ruby | jlee-r7/raptor-io | /lib/raptor-io/support/struct2/c_struct_template.rb | UTF-8 | 900 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: binary -*-
# RaptorIO::Support::Struct2
module RaptorIO::Support
module Struct2
class CStructTemplate
require 'raptor-io/support/struct2/c_struct'
attr_reader :template, :template_create_restraints, :template_apply_restraint
attr_writer :template, :template_create_restraints, :template_apply_restraint
def initialize(*tem)
self.template = tem
self.template_create_restraints = [ ]
self.template_apply_restraint = [ ]
end
def create_restraints(*ress)
self.template_create_restraints = ress
return self
end
def apply_restraint(*ress)
self.template_apply_restraint = ress
return self
end
def make_struct
RaptorIO::Support::Struct2::CStruct.new(*self.template).
create_restraints(*self.template_create_restraints).
apply_restraint(*self.template_apply_restraint)
end
end
# end RaptorIO::Support::Struct2
end
end
| true |
4b54cb14cb24034a814d3d85c3b9f9c5adffb6e1 | Ruby | mcleary03/homework | /W3D1/plays_demo/playwright.rb | UTF-8 | 1,294 | 2.890625 | 3 | [] | no_license | require 'sqlite3'
require 'singleton'
class PlaywrightDBConnection < SQLite3::Database
include Singleton
def initailize
super('playwright.db')
self.type_translation = true
self.results_as_hash = true
end
end
class Playwright
attr_accessor :name, :plays
def self.all
data = PlaywrightDBConnection.instance.execute("SELECT * FROM playwright")
data.map { |datum| PlaywrightDBConnection.new(datum) }
end
def self.find_by_name(name)
PlaywrightDBConnection.instance.execute("SELECT * FROM playwright WHERE name = #{name}")
end
def new(options)
@id = options['id']
@name = options['name']
@plays = options['plays']
end
def create
raise "#{self} already in database" if @id
PlaywrightDBConnection.instance.execute(<<-SQL, @name, @plays)
INSERT INTO
playwright (name, plays)
VALUES
(?, ?, ?)
SQL
@id = PlaywrightDBConnection.instance.last_insert_row_id
end
def update
raise "#{self} not in database" unless @id
PlaywrightDBConnection.instance.execute(<<-SQL, @name, @plays, @id)
UPDATE
name = ?, plays = ?
WHERE
id = ?
SQL
end
def get_plays
PlaywrightDBConnection.instance.execute("SELECT * FROM playwright WHERE name = #{name}")
end
end
| true |
d9c75ae5873669974dcaa3e3744fb468905b1b93 | Ruby | KateWilkinson/takeaway-challenge | /spec/takeaway_spec.rb | UTF-8 | 2,169 | 3 | 3 | [] | no_license | require 'takeaway'
describe Takeaway do
it { is_expected.to respond_to :check_menu }
it { is_expected.to respond_to(:add_to_order).with(2).arguments }
it 'should be initialised with a default menu' do
expect(subject.menu).to eq Takeaway::MENU
end
describe 'check' do
it 'should print out the list of dishes and prices' do
expect(subject.check_menu).to eq Takeaway::MENU
end
end
describe 'add_to_order' do
it 'should raise an error message if the dish does not match an item in the menu' do
expect { subject.add_to_order(1, :pizza) }.to raise_error "Sorry! That's not on the menu!"
end
it 'should add the price of the ordered dish to a running total of costs' do
subject.add_to_order(1, :prawn_toast)
subject.add_to_order(2, :spring_rolls)
expect(subject.total_cost).to eq 6.50
end
it 'should add the ordered item and total price for the item(s) to the order summary' do
subject.add_to_order(2, :prawn_toast)
expect(subject.order_summary).to include :prawn_toast => 5.0
end
end
describe 'check_order_summary' do
# Really struggled with this test! I wanted to check that the method printed everything out correctly - it does in irb but can't think of a way to test it here..
xit 'should print your order summary and the total cost of your order' do
end
end
describe 'pay' do
before(:each)do
subject.add_to_order(3, :spring_rolls)
end
it 'should raise an error message if you try to pay the wrong amount' do
expect { subject.pay 4 }.to raise_error "Sorry, you need to pay the exact total - £6.00"
end
it 'should confirm your payment has been accepted once you pay the correct amount' do
expect(subject.pay 6).to eq "Thanks for your order - delivery time will be confirmed by text message"
end
it 'should clear your order summary once you pay the correct amount' do
subject.pay 6
expect(subject.order_summary).to be_empty
end
it 'should return total_cost to 0 once you pay the correct amount' do
subject.pay 6
expect(subject.total_cost).to eq 0
end
end
end
| true |
6c8357e9b3d261807441a58cf910816bb9f6e262 | Ruby | Lean-GNU/EjerciciosRuby | /Metodos/ejercicio-metodos-retorno4.rb | UTF-8 | 430 | 4.03125 | 4 | [] | no_license | =begin
Elaborar un método que reciba tres enteros y nos retorne el valor promedio de los mismos.
=end
def promedio(v1, v2, v3)
sum = v1 + v2 + v3
prom = sum/3
end
#bloque principal
print "Ingrese valor 1: "
value1 = (gets.chomp).to_i
print "Ingrese valor 2: "
value2 = (gets.chomp).to_i
print "Ingrese valor 3: "
value3 = (gets.chomp).to_i
puts "El promedio de los 3 valores es #{promedio(value1, value2, value3)}"
| true |
9adc85360d416646e5628565b5e8ed37f9eee5d4 | Ruby | Ramez-/Gamification-Achievement-Platform | /Game_Tracking_System/lib/rule.rb | UTF-8 | 141 | 2.546875 | 3 | [] | no_license | class Rule
attr_accessor :metric_id,:value,:operation
def initialize
@metric_id = 1
@value = '32'
@operation='>'
end
end | true |
6d1ef44cec1cb0cae78729d103a6e4aeb8c5e866 | Ruby | Zkalish/alchemy_cms | /lib/alchemy/mount_point.rb | UTF-8 | 572 | 2.5625 | 3 | [
"BSD-3-Clause"
] | permissive | module Alchemy
# Returns alchemys mount point in current rails app.
# Pass false to not return a leading slash on empty mount point.
def self.mount_point(remove_leading_slash_if_blank = true)
alchemy_routes = Rails.application.routes.named_routes[:alchemy]
raise "Alchemy not mounted! Please mount Alchemy::Engine in your config/routes.rb file." if alchemy_routes.nil?
mount_point = alchemy_routes.path.spec.to_s
if remove_leading_slash_if_blank && mount_point == "/"
mount_point.gsub(/^\/$/, '')
else
mount_point
end
end
end
| true |
70923b684e897cc835d3c64d66a9f670e38f96f5 | Ruby | emomax/AdventOfCode2015 | /dec12/task1/main.rb | UTF-8 | 1,019 | 3.5 | 4 | [] | no_license | #################
# Pieslicer #
# 2015 #
#################
## --- Day 12: JSAbacusFramework.io ---
# Santa's Accounting-Elves need help balancing
# the books after a recent order. Unfortunately,
# their accounting software uses a peculiar
# storage format. That's where you come in.
# They have a JSON document which contains a
# variety of things: arrays ([1,2,3]), objects
# ({"a":1, "b":2}), numbers, and strings. Your
# first job is to simply find all of the numbers
# throughout the document and add them together.
# You will not encounter any strings containing
# numbers.
# What is the sum of all numbers in the document?
# ****** FUNCTIONS ****** #
def parseRow(row)
sum = 0
stuff = row.scan /-?\d+/
stuff.each do |digit|
sum += digit.to_i
end
return sum
end
# *** GLOBAL VARIABLES ** #
$sum = 0
# ******** BODY ********* #
file = File.new('input.txt', 'r')
while row = file.gets
row.strip!
$sum += parseRow(row)
end
puts 'All numbers in input combined is: ' + $sum.to_s
| true |
0a4cece042baa98dea9adf9036d769e03a3a15cb | Ruby | Matts966/ruby_files | /1bitDemultiplexer.rb | UTF-8 | 457 | 3.28125 | 3 | [] | no_license | def demultiplexer(i)
r = {"o0" => false, "o1" => false}
r["o0"] = (!i["x"] & i["s"]) |\
(i["y"] & !i["s"])
r["o1"] = (i["x"] & i["s"]) |\
(!i["y"] & !i["s"])
return r
end
begin
print ("=====Testing demultiplexer===== \n")
input = {"x" => true, "s" => false}
output = {"o0" => false, "o1" => false}
output = demultiplexer(input)
print("demultiplexer input: ", input, "\n")
print("demultiplexer output: ", output, "\n")
end | true |
17c9cea35d285de5e4d51a48ed8359b2efb65bb7 | Ruby | fuji-nakahara/nlp100 | /src/04.rb | UTF-8 | 788 | 3.9375 | 4 | [
"MIT"
] | permissive | # "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."
# という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,
# 取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.
sentence = 'Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'
res = sentence.split.map.with_index(1) do |word, i|
str = if [1, 5, 6, 7, 8, 9, 15, 16, 19].include?(i)
word[0]
else
word[0..1]
end
[str, i]
end.to_h
puts res
| true |
4235af2ba7a46d24a449178979aef1f752d19f6d | Ruby | Rinbo/fizzbuzz | /lib/fizz_buzz.rb | UTF-8 | 419 | 4.40625 | 4 | [] | no_license |
def fizz_buzz(number)
if number % 5 == 0
if number % 3 == 0
return "fizzbuzz"
else
return "buzz"
end
elsif number % 3 == 0
return "fizz"
else
return number
end
end
while true
print "Write a number: "
number = gets.chomp.to_i
puts number > 0 ? fizz_buzz(number) : "Invalid number. Try again"
end | true |
86752431dd7a3831851e20f0bd0c70f1233ae4a2 | Ruby | Chucheen/Leaderboard | /lib/db_seed_populator.rb | UTF-8 | 280 | 2.5625 | 3 | [] | no_license | class DbSeedPopulator
def initialize(populator_class, rows)
@populator = populator_class.new(rows)
end
def record_block
@populator.record_block
end
def prepare
@populator.try(:prepare)
end
end
Dir["db_seed_populators/*.rb"].each {|file| require file } | true |
a4d68b12fb5c855ea2fc543d67217abf41996262 | Ruby | aditilonhari/wwcsf-backend-study-group | /designpatterns/src/main/ruby/designpatterns/behavioral/observer/ObserverB.rb | UTF-8 | 384 | 3.046875 | 3 | [] | no_license | require_relative 'ObserverInterface'
# Concrete Observers react to the updates issued by the Publisher they had been attached to.
class ObserverB
include ObserverInterface
# @param [Publisher] publisher
def update(publisher)
return unless publisher.state.zero? || publisher.state >= 2
puts 'ObserverB: Reacted to the event'
end
def to_s
'ObserverB'
end
end | true |
9c34f4abc74e361f20157b13fe83a33d9fdab9b3 | Ruby | Maxih/classwork | /W2D3/poker/lib/player.rb | UTF-8 | 1,109 | 3.609375 | 4 | [] | no_license | require_relative 'hand'
class Player
attr_accessor :name, :pot, :hand, :fold
def initialize(name, pot)
@name = name
@pot = pot
@hand = Hand.new
@fold = false
end
def discard_card(card)
@hand.discard_card(card)
end
def recieve_card(card)
@hand.add_card(card)
end
def render_hand
self.hand.render_cards
end
def setup_new_round
@fold = false
@hand = Hand.new
end
def play_turn
system('clear')
puts self.render_hand
puts "It's #{name}'s turn"
get_turn
end
def get_turn
move = gets.chomp
case move
when ""
puts "Ends turn"
return
when "fold"
@fold = true
puts "#{name} Folds"
when "check"
puts "Checks"
when "raise"
puts "How much?"
value = gets.chomp.to_i
raise_pot(value)
puts "#{name} raises $#{value}"
else
move = move.split(",").map(&:chomp)
move.each do |card|
discard_card(@hand.card_from_face_value(card))
end
end
end
def raise_pot(value)
self.pot -= value if self.pot - value >= 0
end
end
| true |
b58ad57c195e435ef9583a887acfc2a4d8f683f5 | Ruby | avrilanne/ruby | /synaps-weighin-challenge/db/seeds.rb | UTF-8 | 2,405 | 2.84375 | 3 | [] | no_license | # # This file should contain all the record creation needed to seed the database with its default values.
# # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
# require 'csv'
# participants_csv_text = File.read(Rails.root.join('lib', 'seeds', 'participants.csv'))
# csv = CSV.parse(participants_csv_text, :headers => true, :encoding => 'ISO-8859-1')
# csv.each do |row|
# p = Person.find_or_create_by!(name: row[0])
# e = Event.find_or_create_by!(name: row[1])
# l = League.find_or_create_by!(name: row[2])
# p.update_attributes(league_id: l.id)
# end
# weigh_ins_csv_text = File.read(Rails.root.join('lib', 'seeds', 'weighins.csv'))
# csv = CSV.parse(weigh_ins_csv_text, :headers => true, :encoding => 'ISO-8859-1')
# csv.each do |row|
# CreateCheckin.call(Person.find_or_create_by!(name: row[0]), Event.find_or_create_by(name: row[2]), row[1].to_i, nil)
# end
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
require 'csv'
csv_text = File.read(Rails.root.join('lib', 'seeds', 'participants.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
participant_name = row[0]
participant_event = row[1]
participant_league = row[2]
unless Person.pluck(:name).include?(participant_name)
p = Person.new
p.name = participant_name
p.save
end
unless Event.pluck(:name).include?(participant_event)
e = Event.new
e.name = participant_event
e.save
end
unless League.pluck(:name).include?(participant_league)
l = League.new
l.name = participant_league
l.save
p.league_id = l.id
p.save
end
end
puts "There are now #{Person.count} rows in the people table"
puts "There are now #{Event.count} rows in the event table"
puts "There are now #{League.count} rows in the league table"
csv_text = File.read(Rails.root.join('lib', 'seeds', 'weighins.csv'))
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
csv.each do |row|
checkin_name = row[0]
checkin_weight = row[1].to_i
checkin_event = row[2]
CreateCheckin.call(Person.find_by(name: checkin_name), Event.find_by(name: checkin_event), checkin_weight, nil)
end
puts "There are now #{Checkin.count} rows in the checkin table"
| true |
292ec2076ffe948803a2e73991fcf5ae534a80da | Ruby | muffatruffa/RB101-RB109-Small-Problems | /easy_8/middle_character.rb | UTF-8 | 727 | 4.21875 | 4 | [] | no_license | # returns the middle character or characters of the argument. If the argument has an odd length,
# you should return exactly one character. If the argument has an even length,
# you should return exactly two characters.
def center_of_bk(str)
size = str.size
size.even? ? str[size / 2 - 1] + str[size / 2] : str[size / 2]
end
def center_of(str)
if str.size == 1 || str.size == 2
str
else
center_of(str[1..-2])
end
end
p center_of('I love ruby') == 'e'
p center_of('Launch School') == ' '
p center_of('Launch') == 'un'
p center_of('Launchschool') == 'hs'
p center_of('x') == 'x'
p center_of('I love ruby')
p center_of('Launch School')
p center_of('Launch')
p center_of('Launchschool')
p center_of('x')
| true |
d4ca9dbcc5377d31586d73c39a12cfb7b32a9750 | Ruby | Giagnus64/OO-Art-Gallery-dumbo-web-071519 | /tools/console.rb | UTF-8 | 616 | 2.875 | 3 | [] | no_license | require_relative '../config/environment.rb'
a1 = Artist.new("foo", 8)
a2 = Artist.new("bar", 2)
a3 = Artist.new("baz", 1)
g1 = Gallery.new("alpha", "Vegas")
g2 = Gallery.new("beta", "Ohio")
g3 = Gallery.new("gamma", "Chicago")
g4 = Gallery.new("psi", "Brklyn")
g5 = Gallery.new("omega", "Nyc")
p1 = Painting.new("butt", 4000, a1, g1)
p2 = Painting.new("fart", 20000, a2, g1)
p3 = Painting.new("gross", 70000, a3, g1)
p4 = Painting.new("blah", 8000, a1, g2)
p5 = Painting.new("deomd", 4000, a2, g2)
p6 = Painting.new("dalsji", 45000, a2, g3)
p7 = Painting.new("siwudh", 36000, a3, g4)
binding.pry
puts "Bob Ross rules."
| true |
33ed19603d2b7ac8a1cf013c7d0ccb214834cf05 | Ruby | GermanFilipp/Codebreaker | /lib/code_breaker/gamer.rb | UTF-8 | 806 | 3.078125 | 3 | [
"MIT"
] | permissive | require 'yaml'
module CodeBreaker
class Gamer
FILE = "./code_breaker/users_data.yaml"
attr_accessor :gamers
def initialize
@gamers = []
end
def add obj
@gamers.push obj
end
def create_table_score
@gamers.each do |f|
puts "Name: #{f.name} Turns: #{f.turns}"
end
end
def save_data
return "file not found" unless File.exist? FILE
File.open(FILE, "w" ) do |f|
f.write(YAML::dump(@gamers))
f.close
end
end
def load_data
return "file not found" unless File.exist? FILE
data = File.read(FILE)
new_obj = YAML::load(data)
unless new_obj.nil?
new_obj.each do |f|
@gamers.push User.new(name: f.name, turns: f.turns)
end
end
end
end
end
| true |
d79175b8b8a1b3d89d451267e10648f6f072007b | Ruby | xritqa/tst | /power.rb | UTF-8 | 303 | 3.53125 | 4 | [] | no_license | #! /usr/bin/env ruby
def power(x,y)
if (y == 0)
return 1
elsif (y == 1)
return x
else
res = x
end
for i in 1..y-1 do
res = res * x
end
return res
end
print 'power(10,0) '
puts power(10,0)
print 'power(10,1) '
puts power(10,1)
print 'power(10,2) '
puts power(10,2)
| true |
2fb9413df30c023816a500403110b5d193b35061 | Ruby | maltize/nkbook | /app/models/spot.rb | UTF-8 | 989 | 2.515625 | 3 | [] | no_license | # == Schema Information
#
# Table name: spots
#
# id :integer not null, primary key
# profile_id :integer
# duration :integer
# position :integer
# valid_from :datetime
# valid_to :datetime
# status :integer
# created_at :datetime
# updated_at :datetime
#
class Spot < ActiveRecord::Base
belongs_to :profile
validates_presence_of :duration, :position
validates_inclusion_of :position, :in => 0..999
validate :is_uniq_spot, :on => :create
before_create :set_interval
named_scope :valid, lambda { { :conditions => ["valid_from <= ? AND valid_to > ?", Time.now, Time.now], :joins => :profile } }
named_scope :with_url, lambda { |url| { :conditions => ["profiles.url = ?", url], :joins => :profile } }
private
def set_interval
self.valid_from = Time.now
self.valid_to = duration.days.from_now
end
def is_uniq_spot
errors.add_to_base("To miejsce jest już zajęte!") if Spot.valid.find_by_position(position)
end
end
| true |
6c86eb1644a6a0f4c1061198120bc310f48ec2d5 | Ruby | Corn-cloud/programming-univbasics-nds-nds-to-insight-understand-lab-houston-web-012720 | /lib/nds_explore.rb | UTF-8 | 487 | 2.890625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | $LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
# Call the method directors_database to retrieve the NDS
def pretty_print_nds(nds)
require 'pp'
pp nds
# Change the code below to pretty print the nds with pp
nil
end
def print_first_directors_movie_titles
index = 0
spilberg_movies = directors_database[0][:movies]
while index < spilberg_movies.length do
titles = spilberg_movies[index][:title]
puts titles
index += 1
end
end
| true |
8154c1c804d0535d2e59b0309d6744df5fb0755c | Ruby | rocky/rb-trepanning | /test/unit/test-proc-frame.rb | UTF-8 | 2,155 | 2.546875 | 3 | [
"BSD-2-Clause"
] | permissive | #!/usr/bin/env ruby
require 'test/unit'
require_relative '../../processor'
require_relative '../../processor/frame'
require_relative '../../app/mock'
$errors = []
$msgs = []
# Test Trepan::CmdProcessor Frame portion
class TestCmdProcessorFrame < Test::Unit::TestCase
def setup
$errors = []
$msgs = []
@proc = Trepan::CmdProcessor.new(Trepan::MockCore.new())
@proc.frame_index = 0
@proc.frame_initialize
class << @proc
def msg(msg)
$msgs << msg
end
def errmsg(msg)
$errors << msg
end
def print_location
# $msgs << "#{@frame.source_container} #{@frame.source_location[0]}"
$msgs << "#{@frame.source_container} "
# puts $msgs
end
end
end
# See that we have can load up commands
def test_basic
@proc.frame_setup(RubyVM::Frame.get)
# Test absolute positioning. Should all be okay
0.upto(@proc.top_frame.stack_size-1) do |i|
@proc.adjust_frame(i, true)
assert_equal(0, $errors.size)
assert_equal(true, $msgs.size >= i+1)
end
# Test absolute before the beginning fo the stack
frame_index = @proc.frame_index
@proc.adjust_frame(-1, true)
assert_equal(0, $errors.size)
assert_equal(frame_index, @proc.frame_index)
@proc.adjust_frame(-@proc.top_frame.stack_size-1, true)
assert_equal(1, $errors.size, $errors)
assert_equal(frame_index, @proc.frame_index)
setup
@proc.top_frame = @proc.frame = RubyVM::Frame.get
@proc.adjust_frame(0, true)
@proc.top_frame.stack_size-1.times do
frame_index = @proc.frame_index
@proc.adjust_frame(1, false)
assert_equal(0, $errors.size)
assert_not_equal(frame_index, @proc.frame_index,
'@proc.frame_index should have moved')
end
# FIXME: bug in threadframe top_frame.stack_size?
# # Adjust relative beyond the end
# @proc.adjust_frame(1, false)
# assert_equal(1, $errors.size)
# Should have stayed at the end
# proc.adjust_frame(proc.top_frame.stack_size-1, true)
# proc.top_frame.stack_size.times { proc.adjust_frame(-1, false) }
end
end
| true |
97f357737f27fa707ff25df439dddc93b3c2eab7 | Ruby | givmo/couch_record | /lib/couch_record/trackable_container.rb | UTF-8 | 6,393 | 2.640625 | 3 | [] | no_license | module CouchRecord
module TrackableContainer
attr_accessor :parent_record
attr_accessor :parent_attr
def _track_change(key = nil, value = nil)
if self.is_a?(CouchRecord::Base)
self.attribute_will_change_to!(key, value)
else
# passing nil here works because the current value must be non nil for self to exist
self.parent_record.attribute_will_change_to!(self.parent_attr, nil)
end
end
def _make_trackable(value, attr = nil)
newly_trackable = false
if value.is_a?(Array) && !value.is_a?(TrackableContainer)
value.extend TrackableArray
newly_trackable = true
elsif value.is_a?(Hash) && !value.is_a?(TrackableContainer)
value.extend TrackableHash
newly_trackable = true
end
if value.is_a? TrackableContainer
if self.is_a?(CouchRecord::Base)
value.parent_record = self
value.parent_attr = attr && attr.to_sym
else
value.parent_record = self.parent_record
value.parent_attr = self.parent_attr
end
_make_children_trackable(value) if newly_trackable
end
end
def _make_children_trackable(value = self)
if value.is_a?(Array)
value.each { |subvalue| value._make_trackable(subvalue, self.parent_attr) }
elsif value.is_a?(Hash)
value.each_value { |subvalue| value._make_trackable(subvalue, self.parent_attr) }
end
end
module TrackableArray
include TrackableContainer
def []=(*args)
value = args.last
index = args.length == 2 ? args[0] : args[0..1]
_make_trackable(value)
if (index.is_a?(Array) && self[index[0], index[1]] != value) ||
(!index.is_a?(Array) && self[index] != value)
_track_change
end
super
end
def <<(value)
_make_trackable(value)
_track_change
super
end
def clear()
_track_change unless self.empty?
super
end
def delete_at(index)
_track_change if (0..self.length-1).include? index
super
end
def insert(*args)
_track_change
super
_make_children_trackable
end
def map!
block_given? or return enum_for(__method__)
each_with_index { |v, i| self[i] = yield(v) }
self
end
alias :collect! :map!
def compact!
result = super
_track_change unless result.nil?
result
end
def delete(value)
result = super
_track_change unless result.nil?
result
end
def delete_if(&block)
block_given? or return enum_for(__method__)
reject! &block
self
end
def reject!(&block)
block_given? or return enum_for(__method__)
delete_indexes = []
each_with_index { |v, i| delete_indexes << i if yield(v) }
delete_indexes.reverse_each { |i| self.delete_at(i)}
delete_indexes.empty? ? self : nil
end
def fill(*args)
old = self.clone
super
_track_change unless old == self
_make_children_trackable
end
def flatten!(*args)
result = super
_track_change unless result.nil?
result
end
def replace(*args)
old = self.clone
super
_track_change unless old == self
_make_children_trackable
end
def keep_if
block_given? or return enum_for(__method__)
each_with_index { |v, i| delete_at(i) unless yield(v) }
self
end
def select!
block_given? or return enum_for(__method__)
l = self.length
each_with_index { |v, i| delete_at(i) unless yield(v) }
l == self.length ? nil : self
end
def pop(*args)
_track_change unless self.empty?
super
end
def push(obj, *smth)
_track_change
super
_make_trackable obj
_make_trackable smth
end
def reverse!(*args)
_track_change
super
end
def rotate!(*args)
_track_change
super
end
def shuffle!(*args)
_track_change
super
end
def slice!(*args)
result = super
_track_change unless result.nil? || result.empty?
result
end
def sort!
old = self.clone
super
_track_change unless old == self
end
def sort_by!
old = self.clone
super
_track_change unless old == self
end
def uniq!
result = super
_track_change unless result.nil?
result
end
def unshift(obj, *smth)
_track_change
super
_make_trackable obj
_make_trackable smth
end
end
module TrackableHash
include TrackableContainer
def []=(key, value)
_make_trackable(value, key)
_track_change(key, value) unless value == self[key]
super
end
alias :store :[]=
def clear
_track_change unless self.empty?
super
end
def delete(key)
_track_change(key) if self.has_key? key
super
end
def delete_if
block_given? or return enum_for(__method__)
self.each_pair { |key, value| self.delete(key) if yield(key, value) }
self
end
def reject!
block_given? or return enum_for(__method__)
n = size
delete_if { |key, value| yield(key, value) }
size == n ? nil : self
end
def replace(other_hash)
_track_change
super
_make_children_trackable
end
def keep_if
block_given? or return enum_for(__method__)
self.each_pair { |key, value| self.delete(key) unless yield(key, value) }
self
end
def select!
block_given? or return enum_for(__method__)
n = size
keep_if { |key, value| yield(key, value) }
size == n ? nil : self
end
def merge!(other_hash)
self.each_pair do |key, value|
if other_hash.has_key? key
new_value = block_given? ? yield(key, value, other_hash[key]) : other_hash[key]
self[key] = new_value
end
end
self
end
end
end
end | true |
1da338c37e673a15aa2ed526d977f6aa58f48a23 | Ruby | mrphishxxx/api-snippets | /tools/snippet-testing/error_logger.rb | UTF-8 | 478 | 3.046875 | 3 | [
"MIT"
] | permissive | require 'singleton'
require 'colorize'
class ErrorLogger
include Singleton
def initialize
@errors = []
end
def add_error(error)
errors.push(error)
end
def build_failed?
!errors.empty?
end
def print_errors
puts "\n\n\n###############################################################\n"\
"#############There were errors on these files:#################\n".red
errors.each { |error| puts error.red }
end
attr_reader :errors
end | true |
8df66fb3cadad1d8f90c11ff053e8019178cfb66 | Ruby | pajkicdj/princess-krofne | /prep.rb | UTF-8 | 1,873 | 4.03125 | 4 | [] | no_license | # FizzBuzz Assignment
def fizzbuzz
ii = ""
for x in 1..100
if (x%3 == 0) && (x%5 == 0)
ii += "FizzBuzz "
elsif (x%5 == 0)
ii += "Buzz "
elsif (x%3 == 0)
ii += "Fizz "
else
ii += ""
end
end
print ii
end
fizzbuzz
# Build A Calculator
class Calculator
def add(a, b)
a + b
end
def subtract(a, b)
a - b
end
end
# Array of String Lengths
def length_finder(input_array)
input_array.map {|i| i.length}
end
#Non-Duplicate Values in an Array
def non_duplicated_values(values)
values.delete_if {|value| values.count(value) > 1}
end
#Ruby Warrior Game:
#Level 1
class Player
def play_turn(warrior)
warrior.walk!
end
end
#Level 2
class Player
def play_turn(warrior)
if warrior.feel.empty?
warrior.walk!
else
warrior.attack!
end
end
end
#Level 3
class Player
def play_turn(warrior)
if warrior.feel.empty?
if warrior.health < 20
warrior.rest!
else
warrior.walk!
end
else
warrior.attack!
end
end
end
#Level 4
class Player
def play_turn(warrior)
@health ||= warrior.health
under_attack = warrior.health < @health
if (warrior.feel.empty?)
if (warrior.health >= 20) || (under_attack)
warrior.walk!
else
warrior.rest!
end
else
warrior.attack!
end
@health = warrior.health
end
end
#Level 5
class Player
def play_turn(warrior)
@health = warrior.health if @health.nil?
under_attack = warrior.health < @health
if (warrior.feel.empty?)
if (warrior.health >= 20) || (under_attack)
warrior.walk!
else
warrior.rest!
end
else
if warrior.feel.captive?
warrior.rescue!
else
warrior.attack!
end
end
@health = warrior.health
end
end | true |
bdbd062381c8b2ca53682e616096f4a6453a11e9 | Ruby | ne-ha/wage_slave | /lib/wage_slave/aba.rb | UTF-8 | 1,749 | 2.765625 | 3 | [
"MIT"
] | permissive | module WageSlave
class ABA
attr_reader :descriptive_record, :details
def initialize(transactions = [])
@descriptive_record = WageSlave::ABA::DescriptiveRecord.new
@details = WageSlave::ABA::DetailCollection.new(transactions)
end
##
# This method was adapted from https://github.com/andrba/aba which is released under MIT.
# See /LICENSE.txt for details.
def to_s
output = @descriptive_record.to_s + "\r\n"
output += @details.to_s + "\r\n"
# Record Type
# Size: 1
# Char position: 1
# Must be 7
output += "7"
# BSB format filler
# Size: 7
# Char position: 2-8
# Must be 999-999
output += "999-999"
# Reserved
# Size: 12
# Char position: 9-20
# Blank filled
output += " " * 12
# Net total amount
# Size: 10
# Char position: 21-30
# Right justified, zero filled.
output += @details.net_total.abs.to_s.rjust(10, "0")
# Credit total amount
# Size: 10
# Char position: 31-40
# Right justified, zero filled.
output += @details.credit_total.abs.to_s.rjust(10, "0")
# Debit total amount
# Size: 10
# Char position: 41-50
# Right justified, zero filled.
output += @details.debit_total.abs.to_s.rjust(10, "0")
# Reserved
# Size: 24
# Char position: 51-74
# Blank filled
output += " " * 24
# Count of Type 1 records
# Size: 6
# Char position: 75-80
# Right justified, zero filled.
output += @details.size.to_s.rjust(6, "0")
# Reserved
# Size: 40
# Char position: 81-120
# Blank filled
output += " " * 40
end
end
end
| true |
a24dfd1c8b9769fa3197225913bb7ee24640b00a | Ruby | Andreautama/ElectivesLite | /Final-Project/models/category.rb | UTF-8 | 2,707 | 3.0625 | 3 | [] | no_license | require './db/mysql_client.rb'
require './models/item.rb'
class Categories
attr_accessor :category_name, :category_id, :item
def initialize(param)
@category_name = param[:category_name]
@category_id = param[:category_id]
@item = []
end
def self.get_categories
client = create_db_client
raw_data = client.query("SELECT * from categories")
categories = Array.new
raw_data.each do |data|
category = Categories.new({
category_name: data['category_name'],
category_id: data['category_id'],
})
categories.push(category)
end
categories
end
def self.get_category_by_category_id(category_id)
client = create_db_client
raw_data = client.query("Select ca.category_id, ca.category_name, Count(i_c.item_id) item_included from categories ca Left join item_category i_c
on ca.category_id = i_c.category_id where ca.category_id = #{category_id} group by ca.category_id, ca.category_name;")
categories = Array.new
raw_data.each do |data|
category = Categories.new({
category_name: data['category_name'],
category_id: data['category_id'],
item: data['item_included']
})
categories.push(category)
end
categories
end
def save
return false unless valid?
client = create_db_client
client.query("insert into categories(category_name) values('#{category_name}')")
end
def valid?
return false if @category_name.nil?
true
end
def self.update_category(category_id, category_name)
client = create_db_client
client.query("update categories set category_name = '#{category_name}' where category_id = #{category_id}")
end
def self.get_items_by_category_id(category_id)
client = create_db_client
raw_data = client.query("select i.item_id, i.name, i.price from items i join item_category i_c on i.item_id = i_c.item_id where i_c.category_id = #{category_id}")
items_by_category = Array.new
raw_data.each do |data|
item = Item.new({
name: data['name'],
price: data['price'],
item_id: data['item_id']})
items_by_category.push(item)
end
items_by_category
end
def self.delete_category(category_id)
client = create_db_client
client.query("delete from item_category where category_id = #{category_id}")
client.query("delete from categories where category_id = #{category_id}")
end
end
| true |
da464beb3660ad9bbafb55c95a8cf5c117b7396c | Ruby | DrDhoom/RMVXA-Script-Repository | /Himeworks/Enemy Reinforcements.rb | UTF-8 | 7,602 | 3.40625 | 3 | [
"MIT"
] | permissive | =begin
#===============================================================================
Title: Enemy Reinforcements
Author: Hime
Date: Sep 23, 2016
--------------------------------------------------------------------------------
** Change log
Aug 31, 2016
- add_member should return the actual enemy added
Sep 23, 2015
- corrected order that sprites are inserted
Jan 2, 2015
- added support for checking if a troop is in the battle
Feb 13, 2014
- standardized all enemy removal using a "remove_enemy" method
Jan 4, 2014
- fixed bug with yanfly visual battler add-on
Oct 14, 2013
- improved new enemy drawing
Jun 20, 2013
- updated to support yanfly's visual battlers
Mar 8, 2013
- fixed bug where enemy battle window did display all of the enemies
when new enemies were added
Jul 8, 2012
- added "remove troop" feature
- Initial release
--------------------------------------------------------------------------------
** Terms of Use
* Free to use in non-commercial projects
* Contact me for commercial use
* No real support. The script is provided as-is
* Will do bug fixes, but no compatibility patches
* Features may be requested but no guarantees, especially if it is non-trivial
* Credits to Hime Works in your project
* Preserve this header
--------------------------------------------------------------------------------
** Description
This script allows you to create "enemy reinforcements" by specifying
which troop an enemy should be fetched from
Enemy reinforcements are just new enemies that enter the battle.
The enemies are selected from existing Troops from the troop editor and
basically copies them over into the current battle.
This means that the position and appearance of the sprite can be
set in the editor.
--------------------------------------------------------------------------------
** Usage
There are two ways to add new enemies
-add one enemy
-add an entire troop
To add a new enemy to the battle, use the script call
add_enemy(troop_id, index)
where the troop_id is the ID of the troop that the enemy is in, and
the index is the order that they were added in the editor.
You may need to test it a few times to get the right index
To add an entire troop, use the script call
add_troop(troop_id)
And the entire troop will be copied over.
It is also possible to remove an entire troop from battle.
All members of that troop will disappear when this script is called
remove_troop(troop_id)
You can check whether a certain troop is in the battle using the script call
troop_exists?(troop_id)
Which returns true if there exists an enemy with the specified troop ID and
is alive.
--------------------------------------------------------------------------------
Credits to Victor Sant for coming up with the idea of using troops
to specify positions of sprites
#===============================================================================
=end
$imported = {} if $imported.nil?
$imported[:TH_EnemyReinforcements] = true
#===============================================================================
# ** Configuration
#===============================================================================
module TH
module Enemy_Reinforcements
end
end
#===============================================================================
# ** Rest of the script
#===============================================================================
class Spriteset_Battle
#-----------------------------------------------------------------------------
# New. Update the enemy sprites
#-----------------------------------------------------------------------------
def refresh_new_enemies
battlers = @enemy_sprites.collect {|spr| spr.battler }
new_battlers = $game_troop.members - battlers
new_battlers.each do |enemy|
@enemy_sprites.insert(0, Sprite_Battler.new(@viewport1, enemy))
end
end
end
class Game_Interpreter
#-----------------------------------------------------------------------------
# Adds the enemy from the specified troop ID, by index
#-----------------------------------------------------------------------------
def add_enemy(troop_id, index)
$game_troop.add_enemy(troop_id, index)
end
#-----------------------------------------------------------------------------
# Adds the selected troop to the battle
#-----------------------------------------------------------------------------
def add_troop(troop_id)
$game_troop.add_troop(troop_id)
end
#-----------------------------------------------------------------------------
# Removes the selected troop from battle. Enemies do not "die" they just
# disappear
#-----------------------------------------------------------------------------
def remove_troop(troop_id)
$game_troop.remove_troop(troop_id)
end
#-----------------------------------------------------------------------------
# Returns true if there's an enemy in the troop with the specified troop
# ID and is alive.
#-----------------------------------------------------------------------------
def troop_exists?(troop_id)
$game_troop.alive_members.any? {|mem| mem.troop_id == troop_id }
end
end
class Game_Enemy < Game_Battler
attr_accessor :troop_id #NEW: stores which troop the enemy is in
# opposite of `appear
def disappear
@hidden = true
end
end
class Game_Troop < Game_Unit
alias :th_enemy_reinforcements_setup :setup
def setup(troop_id)
th_enemy_reinforcements_setup(troop_id)
setup_troop_ids(troop_id)
end
def setup_troop_ids(troop_id)
@enemies.each {|enemy| enemy.troop_id = troop_id}
end
def add_member(member, troop_id)
enemy = Game_Enemy.new(@enemies[-1].index + 1, member.enemy_id)
enemy.hide if member.hidden
enemy.screen_x = member.x
enemy.screen_y = member.y
enemy.troop_id = troop_id
@enemies.push(enemy)
make_unique_names
return enemy
end
def add_enemy(troop_id, index)
member = $data_troops[troop_id].members[index - 1]
return unless member
add_member(member, troop_id)
SceneManager.scene.refresh_enemies
end
def remove_enemy(enemy)
enemy.hide
end
def add_troop(troop_id)
$data_troops[troop_id].members.each { |member|
next unless member
add_member(member, troop_id)
}
SceneManager.scene.refresh_enemies
end
def remove_troop(troop_id)
@enemies.each {|enemy|
remove_enemy(enemy) if enemy.troop_id == troop_id
}
end
end
class Window_BattleEnemy < Window_Selectable
# update to display all enemies, not just 8 of them
def contents_height
line_height * item_max
end
alias :th_enemy_reinforcements_refresh :refresh
def refresh
create_contents
th_enemy_reinforcements_refresh
end
end
class Scene_Battle < Scene_Base
# refresh sprites on screen
def refresh_enemies
@spriteset.refresh_new_enemies
@enemy_window.refresh
end
end
#-------------------------------------------------------------------------------
# Compatibility with yanfly's visual battlers
#-------------------------------------------------------------------------------
if $imported["YEA-VisualBattlers"]
class Game_Troop < Game_Unit
alias :add_enemy_vb :add_enemy
def add_enemy(troop_id, index)
add_enemy_vb(troop_id, index)
set_coordinates
end
alias :add_troop_vb :add_troop
def add_troop(troop_id)
add_troop_vb(troop_id)
set_coordinates
end
end
end | true |
2d9a8b280465ce4c657a867938658458cd8bba6e | Ruby | pureawesome/advent2016 | /fourteen.rb | UTF-8 | 1,606 | 3.046875 | 3 | [] | no_license | require 'digest'
input = 'ngcjuoqr'
test_input = 'abc'
@sets = Hash.new(Float::INFINITY)
@stretches = Hash.new(Float::INFINITY)
@md5 = Digest::MD5.new
def get_hexdigest(input)
@sets[input] = @md5.hexdigest(input) if @sets[input] == Float::INFINITY
@sets[input]
end
def key?(character, count, raw_input)
status = (0..1000).to_a.map.with_index do |iter|
check = count - 1001 + iter
next if check < 0
input = raw_input + check.to_s
# part 1
# first = get_hexdigest(input).scan(/(.)\1\1/)
# part 2
first = get_stretch_hex(input, get_hexdigest(input)).scan(/(.)\1\1/)
#
next if first.empty?
# part 1
# check if character == first[0][0]
# Part 2
check if get_stretch_hex(input, get_hexdigest(input)) =~ /(#{character})\1\1/
#
end
# p status
status.compact
end
def get_stretch_hex(input, hash)
@stretches[input] if @stretches[input] != Float::INFINITY
2016.times { hash = get_hexdigest(hash.downcase) }
@stretches[input] = hash
hash
end
def run(raw_input)
keys = []
count = 0
# until keys.size > 64
until count > 23_000
input = raw_input + count.to_s
hex = get_hexdigest(input)
# part 2
hex = get_stretch_hex(input.downcase, hex.downcase)
#
if index = hex =~ /(.)\1{4}/
key = key?(hex[index], count, raw_input)
p "input #{input}" if key
p "key #{key}" if key
keys += key if key
keys.uniq!
end
count += 1
end
keys.sort!
end
start_time = Time.now
p run(input)
# p run(test_input)
end_time = Time.now
puts "Time elapsed #{(end_time - start_time)} seconds"
| true |
1285c9ed1345e65e03478fc3c07f02cac28f848c | Ruby | n00dl3nate/Homework_week02_day_01 | /Homework_exercise_1/student.rb | UTF-8 | 313 | 3.1875 | 3 | [] | no_license | class Student
attr_accessor :name, :cohort
def initialize(name, cohort)
@name = name
@cohort = cohort
end
def get_name
return @name
end
def get_cohort
return @cohort
end
def talk()
return "I can talk"
end
def say_favourite_language(language)
return "I love #{language}"
end
end
| true |
419cddec46445fb93d3053c650ba521c575b9871 | Ruby | uoysip/reglex | /lib/conversion_tests.rb | UTF-8 | 492 | 3.046875 | 3 | [
"MIT"
] | permissive | require_relative "helper"
require_relative "../src/main"
@total = 0
@pass = 0
def assert(message, test)
@total = @total + 1
if test then
@pass = @pass + 1
puts "success: " + message
else
puts "failed: " + message
end
end
@total = 0
@pass = 0
test_case = "(.(|LD)D(|LD(.DQ)))"
assert("can handle (.(|LD)D(|LD(.DQ)))",
TreeHolder.new(PrefixToTree.new(test_case).to_tree).to_s == test_case)
puts @pass.to_s + " passed out of " + @total.to_s + " tests."
| true |
f297660902a8173a62ddf9b4129f554b39b55b83 | Ruby | pilarcormo/SNP_distribution_method | /Cluster/SDM/model_genome.rb | UTF-8 | 1,786 | 3.03125 | 3 | [] | no_license | #encoding: utf-8
require_relative 'lib/model_genome'
require_relative 'lib/write_it'
require_relative 'lib/reform_ratio'
name = ARGV[0]
contig_size = ARGV[1].to_i
fasta_file = "TAIR10_chr1.fasta"
genome_length = ReformRatio::genome_length(fasta_file)
genome_length.to_i
snp = genome_length/3000
snp_2 = snp*2
size_2 = genome_length/2
# make the directory to put data files into
Dir.mkdir(File.join(Dir.home, "SDM/genomes/#{name}"))
hm_r = "hm <- rnorm(#{snp}, #{size_2}, #{snp_2})" # Causative SNP at/near 10000
ht_r = "ht <- runif(#{snp}, 1, #{genome_length})" # Genome length of 10000
hm, ht = ModelGenome::get_snps(hm_r, ht_r)
arabidopsis_c1 = ModelGenome::fasta_to_char_array(fasta_file)
puts "There are #{hm.length} homozygous SNPs"
puts "There are #{ht.length} heterozygous SNPs"
snp_pos = [hm, ht].flatten
puts "...and generating the fragments"
genome_length.to_i
frags = ModelGenome::get_frags(arabidopsis_c1, contig_size)
puts "Small genome length: #{genome_length.length} bases"
puts "You have created #{frags.length} fragments of sizes #{contig_size}-#{contig_size*2}"
# Get the positions of the SNPs on fragments
pos_on_frags, snp_pos_all = ModelGenome::pos_each_frag(snp_pos, frags)
fastaformat_array = ModelGenome::fasta_array(frags)
fastaformat_array_shuf = fastaformat_array.shuffle
vcf = ModelGenome::vcf_array(frags, pos_on_frags, snp_pos_all, hm, ht)
WriteIt::write_data("genomes/#{name}/frags.fasta", fastaformat_array)
WriteIt::write_data("genomes/#{name}/snps.vcf", vcf)
WriteIt::write_data("genomes/#{name}/frags_shuffled.fasta", fastaformat_array_shuf)
WriteIt::write_txt("genomes/#{name}/info", [hm_r, ht_r, "Contig size = #{contig_size}"])
WriteIt::write_txt("genomes/#{name}/hm_snps", hm)
WriteIt::write_txt("genomes/#{name}/ht_snps", ht) | true |
dc8f46e5e1f1bda4b5ebdaa9c1b44fa6858747a8 | Ruby | etdev/algorithms | /0_code_wars/trimming_a_string.rb | UTF-8 | 299 | 3.546875 | 4 | [
"MIT"
] | permissive | # http://www.codewars.com/kata/563fb342f47611dae800003c
# --- iteration 1 ---
def trim(str, size)
if str.size < 3
return "#{str.slice(0...size)}..."
elsif str.size <= size
return str
else
new_sz = (size > 3 ? (size-3).abs : size)
return "#{str.slice(0...new_sz)}..."
end
end
| true |
ac00963d15323e65252b21f74afbb30d4e40a757 | Ruby | ryuichi7/cancan_lab-v-000 | /app/models/note.rb | UTF-8 | 662 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Note < ActiveRecord::Base
belongs_to :user
has_many :viewers
has_many :readers, through: :viewers, source: :user
before_save :add_user_to_readers
def visible_to=(users)
self.reader_ids = users.split(",").map { |name| User.find_or_create_by(name: name.strip).id }
# user_ids = []
# users.split(",").each do |name|
# if name.present?
# user = User.find_or_create_by(name: name.strip)
# user_ids << user.id
# end
# end
# self.reader_ids = user_ids
end
def visible_to
readers.collect { |r| r.name }.join(", ")
end
private
def add_user_to_readers
if user && !readers.include?(user)
readers << user
end
end
end
| true |
b6a6d950e21601c77d723801d157a2750add3839 | Ruby | rondall/ruby_book | /exercises/5.rb | UTF-8 | 121 | 3.265625 | 3 | [] | no_license | array = [1,2,3,4,5,6,7,8,9,10]
array.push(11)
array.unshift(0)
p array
array.pop #answer
array << 3 #answer
p array | true |
4cca698e02438c216dba843067e3e37f42550d56 | Ruby | nickhillwd/Ruby-CodeClan-week2-day2-homework-classes | /library.rb | UTF-8 | 1,266 | 3.5625 | 4 | [] | no_license | class Library
attr_reader :name, :books, :people
def initialize(name)
@name = name
@books = {}
@people = {}
end
def add_book(book)
@books[book.title] = book
end
def list_all_books
if @books.empty?
"There are currently no books in the library"
else
book_strings = @books.map do
|key, book|
book.pretty_string
end
book_strings.join("\n")
end
end
def add_person(person)
@people[person.name] = person
end
def list_people
if @people.empty?
"No people here!"
else
people_strings = @people.map do |key, person|
person.pretty_string
end
people_strings.join("\n")
end
end
def lend (person_name, book_title)
person = @people[person_name]
book = @books.delete(book_title)
person.borrow(book)
end
def return_book_to_library(person_name, book_title)
person = @people[person_name]
book = @people[person_name].books[book_title]
person.return_book(book_title)
self.add_book(book)
end
def list_borrowed_books
loan_books_list = @people.map { |key, person| person.books unless person.books.empty? }.compact
loan_books_list.each { |key, value| puts key }
end
end
| true |
b58a35539265b967b1b7df54e72b2a08328177e8 | Ruby | amandaungco/api-muncher | /test/lib/recipe_test.rb | UTF-8 | 750 | 2.703125 | 3 | [] | no_license | require "test_helper"
describe Recipe do
it "Cannot be initialized with less than 6 parameters" do
expect {
Recipe.new
}.must_raise ArgumentError
expect {
Recipe.new "Name"
}.must_raise ArgumentError
end
it "Must initialize parameters properly" do
recipe = Recipe.new("chicken", "308423948", "picture.jpeg", "recipe.com", ["Dairy-Free", "Soy-Free"], ["Coconutmilk", "Sugar"])
expect(recipe.label).must_equal "chicken"
expect(recipe.uri).must_equal "308423948"
expect(recipe.image_url).must_equal "picture.jpeg"
expect(recipe.recipe_url).must_equal "recipe.com"
expect(recipe.dietaryinformation[0]).must_equal "Dairy-Free"
expect(recipe.ingredients[1]).must_equal "Sugar"
end
end
| true |
f8393b866dbc21689a75f7471c17308e999cc6ea | Ruby | rhq-project/samples | /rest-api/ruby/get_status.rb | UTF-8 | 399 | 2.71875 | 3 | [] | no_license | #
# Sample script to read the status from the server and print on stdout
# Heiko W. Rupp
#
require 'rest_client'
require 'JSON'
load 'RHQ_config.rb'
config = RHQ_config.new('rhqadmin', 'rhqadmin')
base_url = config.base_url
response = RestClient.get base_url + 'status.json'
data = JSON.parse(response)
values = data['values']
values.each do |key,value|
print key.to_s + ': ' +value.to_s + "\n"
end | true |
cfd74660f8163499b48ac1f60c8a8fa488e5dc09 | Ruby | woodie/coding_challenges | /dump_neighbors.rb | UTF-8 | 1,565 | 4.03125 | 4 | [] | no_license | #!/usr/bin/env ruby
class NeighborNode
attr_accessor :label, :neighbors
def initialize(label, neighbors=[])
self.label = label
self.neighbors = neighbors
end
# 1-2-3 (1,0)→ [] • return any suitable datatype
# \| | (1,1)→ [2,4] • order doesn't matter
# 4-5-6 (1,2)→ [1,2,3,4,5] • results should be unique
def self.get_neighborhood(node, depth=0)
neighborhood = {}
queue = node.neighbors
depth.times do
queue.each {|z| neighborhood[z.label] = z}
queue = []
neighborhood.values.each do |s|
s.neighbors.each do |z|
queue << z unless neighborhood.has_key? z.label
end
end
end
neighborhood.values.sort_by {|e| e.label}
end
def print_neighborhood(depth)
puts "#{self.label},#{depth} → #{
NeighborNode.get_neighborhood(self, depth).map(&:label).inspect}"
end
def self.print_nodelist(nodes)
nodes.each do |n|
puts "#{n.label} → #{n.neighbors.map(&:label).inspect}"
end
end
end
# 1-2-3
# \| |
# 4-5-6
nodes = 0.upto(6).map {|i| NeighborNode.new(i)}
nodes[1].neighbors = [nodes[2], nodes[4]]
nodes[2].neighbors = [nodes[1], nodes[3], nodes[4]]
nodes[3].neighbors = [nodes[2], nodes[4], nodes[5]]
nodes[4].neighbors = [nodes[1], nodes[2], nodes[5]]
nodes[5].neighbors = [nodes[3], nodes[4], nodes[6]]
# NeighborNode.print_nodelist(nodes)
nodes[1].print_neighborhood(0)
nodes[1].print_neighborhood(1)
nodes[1].print_neighborhood(2)
__END__
1,0 → []
1,1 → [2, 4]
1,2 → [1, 2, 3, 4, 5]
| true |
d4612cb79dbd689c255a9047a3364fd3c9319915 | Ruby | stanvandepoll/exercises-launch-ruby-intro | /loops/ex2.rb | UTF-8 | 97 | 3.21875 | 3 | [] | no_license | input = 'start'
while input != 'STOP'
puts 'What do you want to do?'
input = gets.chomp
end
| true |
eb7bb0aab40f50e109d67e517f664ee9ecffddc1 | Ruby | walidwahed/ls | /100-program-prep/rubyintro/5-arrays/timestwo.rb | UTF-8 | 143 | 3.546875 | 4 | [] | no_license | def timestwo(array)
arrtwo = []
array.each do |element|
arrtwo << element * 2
end
p array
p arrtwo
end
timestwo([5,10,12,13,14]) | true |
ddd62800524c3940bb2fe7f8843389c13a6e5728 | Ruby | shanebdavis/Babel-Bridge | /lib/babel_bridge/nodes/non_terminal_node.rb | UTF-8 | 761 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | =begin
Copyright 2011 Shane Brinkman-Davis
See README for licence information.
http://babel-bridge.rubyforge.org/
=end
module BabelBridge
# rule node
# subclassed automatically by parser.rule for each unique non-terminal
class NonTerminalNode < Node
def update_match_length
@match_length = last_match ? last_match.offset_after_match - offset : 0
end
#*****************************
# Array interface implementation
#*****************************
def matches
@matches ||= []
end
def last_match
matches[-1]
end
include Enumerable
def length
matches.length
end
def add_match(node)
return if !node || node.kind_of?(EmptyNode) || node == self
node.tap do
matches << node
update_match_length
end
end
end
end
| true |
b2d0f8a0adfeee08385c7dc34376fe6793efe988 | Ruby | cclausen/petri_net | /test/reachability_graph/tc_graph.rb | UTF-8 | 10,765 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'rubygems'
require 'logger'
require 'test/unit'
class TestPetriNetReachabilityGraph < Test::Unit::TestCase
def setup
@net = PetriNet::Net.new(:name => 'Water', :description => 'Creation of water from base elements.')
@net.logger = Logger.new(STDOUT)
end
def fill_net
@net << PetriNet::Place.new(:name => "testplace")
@net << PetriNet::Transition.new(:name => "testtrans")
arc = PetriNet::Arc.new do |a|
a.name = 'testarc'
a.weight = 2
a.add_source(@net.get_place 'testplace')
a.add_destination(@net.get_transition 'testtrans')
end
@net << arc
end
def teardown
@net.reset
end
def test_trivial_generate_reachability_graph
assert_equal "Reachability Graph [Water]
----------------------------
Description:
Filename:
Nodes
----------------------------
1: Node1 ([])
Edges
----------------------------
", @net.generate_reachability_graph().to_s, "Simple Reachability Graph with only one reachable state"
end
def test_generate_reachability_graph
fill_net
assert_equal "Reachability Graph [Water]
----------------------------
Description:
Filename:
Nodes
----------------------------
4: Node4 ([0])
Edges
----------------------------
", @net.generate_reachability_graph().to_s, "Reachability Graph of sample net"
end
def test_to_gv
fill_net
# @net.generate_reachability_graph().to_gv
end
def test_simple_net_1
@net = PetriNet::Net.new(:name => 'SimpleNet1', :description => 'PTP')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Transition.new(name:'T')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T'))
@net << PetriNet::Arc.new(source:@net.get_transition('T'), destination:@net.get_place('B'))
@net.get_place('A').add_marking
rn = @net.generate_reachability_graph
assert_equal "Reachability Graph [SimpleNet1]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n6: Node6 ([1, 0])\n7: Node7 ([0, 1])\n\nEdges\n----------------------------\n8: Edge8 6: Node6 ([1, 0]) -> 7: Node7 ([0, 1]) )\n\n", rn.to_s
end
def test_simple_net_2
@net = PetriNet::Net.new(:name => 'SimpleNet2', :description => 'PTTPP')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Place.new(name: 'C')
@net << PetriNet::Transition.new(name:'T1')
@net << PetriNet::Transition.new(name:'T2')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T1'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T2'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('C'))
@net.get_place('A').add_marking
rn = @net.generate_reachability_graph
assert_equal "Reachability Graph [SimpleNet2]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n10: Node10 ([1, 0, 0])\n11: Node11 ([0, 1, 0])\n13: Node13 ([0, 0, 1])\n\nEdges\n----------------------------\n12: Edge12 10: Node10 ([1, 0, 0]) -> 11: Node11 ([0, 1, 0]) )\n14: Edge14 10: Node10 ([1, 0, 0]) -> 13: Node13 ([0, 0, 1]) )\n\n", rn.to_s
end
def test_simple_net_3
@net = PetriNet::Net.new(:name => 'SimpleNet3', :description => 'PTPPinf')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Transition.new(name:'T')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T'))
@net << PetriNet::Arc.new(source:@net.get_transition('T'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_transition('T'), destination:@net.get_place('A'))
@net.get_place('A').add_marking
rn = @net.generate_reachability_graph
assert_equal "Reachability Graph [SimpleNet3]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n7: Node7 ([1, 0])\n8: Node8 ([1, 1])\n10: Node10 ([Infinity])\n\nEdges\n----------------------------\n9: Edge9 7: Node7 ([1, 0]) -> 8: Node8 ([1, 1]) )\n11: Edge11 8: Node8 ([1, 1]) -> 10: Node10 ([Infinity]) )\n\n", rn.to_s
end
def test_simple_net_4
@net = PetriNet::Net.new(:name => 'SimpleNet4', :description => 'PTPPinf')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Transition.new(name:'T1')
@net << PetriNet::Transition.new(name:'T2')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T1'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('A'))
@net << PetriNet::Arc.new(source:@net.get_place('B'), destination:@net.get_transition('T2'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('A'))
@net.get_place('A').add_marking
rn = @net.generate_reachability_graph
assert_equal "Reachability Graph [SimpleNet4]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n10: Node10 ([1, 0])\n11: Node11 ([1, 1])\n13: Node13 ([Infinity])\n15: Node15 ([2, 0])\n17: Node17 ([Infinity])\n\nEdges\n----------------------------\n12: Edge12 10: Node10 ([1, 0]) -> 11: Node11 ([1, 1]) )\n14: Edge14 11: Node11 ([1, 1]) -> 13: Node13 ([Infinity]) )\n16: Edge16 10: Node10 ([1, 0]) -> 15: Node15 ([2, 0]) )\n18: Edge18 15: Node15 ([2, 0]) -> 17: Node17 ([Infinity]) )\n\n", rn.to_s
end
def test_simple_net_5
@net = PetriNet::Net.new(:name => 'SimpleNet5', :description => 'PTPTP')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Transition.new(name:'T1')
@net << PetriNet::Transition.new(name:'T2')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T1'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_place('B'), destination:@net.get_transition('T2'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('A'))
@net.get_place('A').add_marking
@net.to_gv
rn = @net.generate_reachability_graph
assert_equal "Reachability Graph [SimpleNet5]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n9: Node9 ([1, 0])\n10: Node10 ([0, 1])\n\nEdges\n----------------------------\n11: Edge11 9: Node9 ([1, 0]) -> 10: Node10 ([0, 1]) )\n13: Edge13 10: Node10 ([0, 1]) -> 9: Node9 ([1, 0]) )\n\n", rn.to_s
rn.to_gv
end
def test_real_net_1
@net = PetriNet::Net.new(:name => 'RealNet1', :description => 'Failed in real situation')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Place.new(name: 'C')
@net << PetriNet::Place.new(name: 'D')
@net << PetriNet::Transition.new(name:'T1')
@net << PetriNet::Transition.new(name:'T2')
@net << PetriNet::Transition.new(name:'T3')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T1'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('D'))
@net << PetriNet::Arc.new(source:@net.get_place('B'), destination:@net.get_transition('T2'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('C'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('D'))
@net << PetriNet::Arc.new(source:@net.get_place('D'), destination:@net.get_transition('T3'))
@net << PetriNet::Arc.new(source:@net.get_transition('T3'), destination:@net.get_place('A'))
@net.get_place('A').add_marking
@net.to_gv
rg = @net.generate_reachability_graph
rg.to_gv
#TODO assert_equal "", rg.to_s
end
def test_empty_net1
@net = PetriNet::Net.new(:name => 'EmptyNet1', :description => 'Should be boring')
@net.generate_reachability_graph # Don't know what to test here, bit this crashed with an Error before...
end
def test_empty_net2
@net = PetriNet::Net.new(:name => 'EmptyNet2', :description => 'Should be boring')
@net << PetriNet::Place.new(name: 'A')
@net.generate_reachability_graph # Don't know what to test here, bit this crashed with an Error before...
end
def test_empty_net3
@net = PetriNet::Net.new(:name => 'EmptyNet3', :description => 'Should be boring')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Transition.new(name:'T1')
@net.generate_reachability_graph # Don't know what to test here, bit this crashed with an Error before...
end
def test_looped_net1
@net = PetriNet::Net.new(:name => 'LoopedNet1', :description => 'Should be looped')
@net << PetriNet::Place.new(name: 'A')
@net << PetriNet::Place.new(name: 'B')
@net << PetriNet::Transition.new(name:'T1')
@net << PetriNet::Transition.new(name:'T2')
@net << PetriNet::Arc.new(source:@net.get_place('A'), destination:@net.get_transition('T1'))
@net << PetriNet::Arc.new(source:@net.get_place('B'), destination:@net.get_transition('T2'))
@net << PetriNet::Arc.new(source:@net.get_transition('T1'), destination:@net.get_place('B'))
@net << PetriNet::Arc.new(source:@net.get_transition('T2'), destination:@net.get_place('A'))
@net.get_place('A').add_marking
@net.to_gv
rg = @net.generate_reachability_graph
rg.to_gv
assert_equal "Reachability Graph [LoopedNet1]\n----------------------------\nDescription: \nFilename: \n\nNodes\n----------------------------\n9: Node9 ([1, 0])\n10: Node10 ([0, 1])\n\nEdges\n----------------------------\n11: Edge11 9: Node9 ([1, 0]) -> 10: Node10 ([0, 1]) )\n13: Edge13 10: Node10 ([0, 1]) -> 9: Node9 ([1, 0]) )\n\n", rg.to_s
end
end
| true |
78e9862f5733a24115578e7c2c57ec46d1c552a6 | Ruby | jessicamurphyma/tts_notes | /Week 6 SQL and Active Record /middle.rb | UTF-8 | 54 | 3.125 | 3 | [] | no_license | def middle(array)
puts array[1]
end
middle([1,2,3]) | true |
39a3ef00b878b8c6d14d3a03a23d80e1dfe37a65 | Ruby | LeandrOS1/ruby-samples | /primer-hangout/Perro.rb | UTF-8 | 269 | 3 | 3 | [] | no_license | require "./Mascota"
class Perro < Mascota
attr_accessor :talla
def initialize(nombre, talla, peso)
super(nombre, peso)
@talla = talla
end
def costo_servicio
case talla
when "G"
super + 150.0
when "P"
super + 80.0
else
0
end
end
end | true |
67a08e3db86c4f5e65ca97b4f701d0ad2ff945c4 | Ruby | stripe/stripe-ruby | /lib/stripe/instrumentation.rb | UTF-8 | 3,671 | 2.59375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Stripe
class Instrumentation
# Event emitted on `request_begin` callback.
class RequestBeginEvent
attr_reader :method
attr_reader :path
# Arbitrary user-provided data in the form of a Ruby hash that's passed
# from subscribers on `request_begin` to subscribers on `request_end`.
# `request_begin` subscribers can set keys which will then be available
# in `request_end`.
#
# Note that all subscribers of `request_begin` share the same object, so
# they must be careful to set unique keys so as to not conflict with data
# set by other subscribers.
attr_reader :user_data
def initialize(method:, path:, user_data:)
@method = method
@path = path
@user_data = user_data
freeze
end
end
# Event emitted on `request_end` callback.
class RequestEndEvent
attr_reader :duration
attr_reader :http_status
attr_reader :method
attr_reader :num_retries
attr_reader :path
attr_reader :request_id
attr_reader :response_header
attr_reader :response_body
attr_reader :request_header
attr_reader :request_body
# Arbitrary user-provided data in the form of a Ruby hash that's passed
# from subscribers on `request_begin` to subscribers on `request_end`.
# `request_begin` subscribers can set keys which will then be available
# in `request_end`.
attr_reader :user_data
def initialize(request_context:, response_context:,
num_retries:, user_data: nil)
@duration = request_context.duration
@http_status = response_context.http_status
@method = request_context.method
@num_retries = num_retries
@path = request_context.path
@request_id = request_context.request_id
@user_data = user_data
@response_header = response_context.header
@response_body = response_context.body
@request_header = request_context.header
@request_body = request_context.body
freeze
end
end
class RequestContext
attr_reader :duration
attr_reader :method
attr_reader :path
attr_reader :request_id
attr_reader :body
attr_reader :header
def initialize(duration:, context:, header:)
@duration = duration
@method = context.method
@path = context.path
@request_id = context.request_id
@body = context.body
@header = header
end
end
class ResponseContext
attr_reader :http_status
attr_reader :body
attr_reader :header
def initialize(http_status:, response:)
@http_status = http_status
@header = response ? response.to_hash : nil
@body = response ? response.body : nil
end
end
# This class was renamed for consistency. This alias is here for backwards
# compatibility.
RequestEvent = RequestEndEvent
# Returns true if there are a non-zero number of subscribers on the given
# topic, and false otherwise.
def self.any_subscribers?(topic)
!subscribers[topic].empty?
end
def self.subscribe(topic, name = rand, &block)
subscribers[topic][name] = block
name
end
def self.unsubscribe(topic, name)
subscribers[topic].delete(name)
end
def self.notify(topic, event)
subscribers[topic].each_value { |subscriber| subscriber.call(event) }
end
def self.subscribers
@subscribers ||= Hash.new { |hash, key| hash[key] = {} }
end
private_class_method :subscribers
end
end
| true |
4c89b2290747ebb9be079a045f097514c21ae9a1 | Ruby | DouglasAllen/facebook_group_files | /ruby-coding-exercises/january/12.rb | UTF-8 | 784 | 2.734375 | 3 | [] | no_license |
# https://www.crondose.com/2017/01/build-pseudo-random-number-generator-follows-specific-sequence/
require 'rspec'
def pseudo_random(num)
srand 1
Fiber.new do
num.times do
Fiber.yield rand 100
end
end
end
describe 'Psudeo random number generator' do
it 'creates the same sequence of random numbers' do
random_sequence = pseudo_random 8
expect(random_sequence.resume).to eq(37)
expect(random_sequence.resume).to eq(12)
expect(random_sequence.resume).to eq(72)
expect(random_sequence.resume).to eq(9)
expect(random_sequence.resume).to eq(75)
expect(random_sequence.resume).to eq(5)
expect(random_sequence.resume).to eq(79)
expect(random_sequence.resume).to eq(64)
end
end
system 'rspec 12.rb' if __FILE__ == $PROGRAM_NAME
| true |
0bacdb07c6b7af8a935d19edc6bde23430e7a5c7 | Ruby | thinkerbot/clipr | /test/clipr/rule/actions_test.rb | UTF-8 | 1,181 | 2.609375 | 3 | [
"X11-distribute-modifications-variant",
"MIT"
] | permissive | require "#{File.dirname(__FILE__)}/../../test_helper.rb"
require 'clipr'
class ActionsTest < Test::Unit::TestCase
Actions = Clipr::Rule::Actions
def test_add_adds_string_action
actions = Actions.intern do
add "(> 1 2)"
end
assert_equal "(> 1 2)", actions.to_s
end
def test_register_registers_callable_object_as_action
block = lambda {}
actions = Actions.new
action = actions.register(block, :a, :b)
assert_equal block, action.callback
assert_equal [:a, :b], action.variables
end
def test_callback_registers_block_as_action
block = lambda {}
actions = Actions.new
action = actions.callback(:a, :b, &block)
assert_equal block, action.callback
assert_equal [:a, :b], action.variables
end
#
# dup test
#
def test_duplicates_do_not_add_actions_to_one_another
a = Actions.new
action1 = a.callback {}
b = a.dup
assert_equal "#{action1}", a.to_s
assert_equal "#{action1}", b.to_s
action2 = b.callback {}
action3 = a.callback {}
assert_equal "#{action1} #{action3}", a.to_s
assert_equal "#{action1} #{action2}", b.to_s
end
end | true |
43f8b06c1790f070689f9245da30b23cd6303b41 | Ruby | hyprul/school-domain-houston-web-071618 | /lib/school.rb | UTF-8 | 356 | 3.671875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
class School
attr_reader :roster
def initialize(name)
@name = name
@roster = {}
end
def add_student(name, grade)
@roster[grade] ||= []
@roster[grade] << name
end
def grade(grade)
@roster[grade]
end
def sort
sorted = {}
@roster.each do |grade, students|
sorted[grade] = students.sort
end
sorted
end
end
| true |
98601773a3f0aa8e29f7ca05744e8138daf6437c | Ruby | saintlove/cookbook-app | /runner.rb | UTF-8 | 1,234 | 2.609375 | 3 | [] | no_license | require 'unirest'
#INDEX ACTION
# response =Unirest.get("http://localhost:3000/api/recipes")
# puts JSON.pretty_generate(response.body)
#SHOW ACTION
# response = Unirest.get("http://localhost:3000/api/recipes/1")
# puts JSON.pretty_generate(response.body)
#CREATE ACTION
# response = Unirest.post("http://localhost:3000/api/recipes",
# parameters: {
# title: "baked squirrel",
# chef:"joe",
# ingredients: "road kill",
# directions: "pick up whatever is around and bake it",
# prep_time: 90
# }
# )
# puts JSON.pretty_generate(response.body
#UPDATE ACTION
# recipe_id = 1
# runner_params = {
# title: "Cake"
# }
# response = Unirest.patch(
# "http://localhost:3000/api/recipes/#{recipe_id}",
# parameters: runner_params
# )
# recipe_hash = response.body
# puts JSON.pretty_generate(recipe_hash)
#DESTROY ACTION
recipe_id = 3
response = Unirest.delete("http://localhost:3000/api/recipes#{recipe_id}")
data = response.body
puts JSON.pretty_generate(data) | true |
f94af57b1e7cbf45b0bab7c9ae9fd107493a5040 | Ruby | KqSMea8/HelloProjects | /HelloXcodeproj/02 - Ruby Helper/01_test_dump_object.rb | UTF-8 | 400 | 2.640625 | 3 | [] | no_license | require_relative './rubyscript_helper'
string = 'hello, world'
dict = {"key" => "value"}
array = []
number = 3
nilValue = nil
def test(param)
return param
end
dump_object(string)
dump_object(dict)
dump_object(array)
dump_object(number)
dump_object("string")
dump_object({"key" => "value"})
dump_object([1, 2, 3])
dump_object(3.14)
dump_object(nilValue)
dump_object(test('FrameworkPackager'))
| true |
eaf6a885f6327f441c2c6ae331a3f5f2ff5a0b1a | Ruby | patrickdavey/AoC | /2015/day7/rshift_logic.rb | UTF-8 | 647 | 3.234375 | 3 | [] | no_license | class RShiftLogic
def initialize(first_input, shift_by, wire)
@first_input = first_input
@shift_by = shift_by.to_i
@wire = wire
end
def has_value?
first_input.is_a?(Integer)
end
def value
first_input >> shift_by
end
def try_resolve(all_logics)
# if we're in here, then we know we are looking for a gate
@first_input = if first_input.is_a?(Integer)
first_input
else
source = all_logics.find {|l| l.wire == first_input }
return unless source.has_value?
source.value
end
end
attr_reader :first_input, :shift_by,:wire
end
| true |
1cf423a22585a5d8628a84c9434d7d2aaeeeb388 | Ruby | kohbis/leetcode | /algorithms/0941.valid-mountain-array/solution.rb | UTF-8 | 654 | 3.40625 | 3 | [] | no_license | # @param {Integer[]} a
# @return {Boolean}
def valid_mountain_array(a)
return false if a.size < 3
i = 1
while i < a.size
break if a[i] <= a[i - 1]
i += 1
end
return false if i == a.size || i == 1
while i < a.size
return false if a[i] >= a[i - 1]
i += 1
end
true
end
# # @param {Integer[]} a
# # @return {Boolean}
# def valid_mountain_array(a)
# return false unless a.size >= 3
# return false unless a.count(a.max) == 1
# top = a.find_index(a.max)
# left, right = a[...top], a[top+1..]
# return false if left.empty? || right.empty?
# (left == left.sort.uniq) && (right == right.sort.uniq.reverse)
# end
| true |
3856bc5f9fcc63f47661596b94c7c930c7302020 | Ruby | rickbmitchell/memr-app | /app/models/post.rb | UTF-8 | 2,176 | 2.59375 | 3 | [] | no_license | include Magick
class Post < ActiveRecord::Base
belongs_to :user
has_many :votes
has_one :meme
has_one :archive
has_attached_file :avatar, :styles =>
{ :medium => "400x400>", :thumb => "100x100>" },
:default_url => "missing.png", id: "avatar"
validates_attachment_content_type :avatar,
content_type: /\Aimage\/.*\Z/
validates :top_text, length: { maximum: 34 }
validates :bottom_text, length: { maximum: 17 }
MAX_LINE_CHARACTERS=17
MAX_CHARACTERS=34
def to_param
"#{id}-#{user_id}"
end
# def last_week
# where(:created_at => (1.week.ago.beginning_of_week..1.week.ago.end_of_week)
# end
# def winner
# @post = Post.all.where(:created_at => (Time.zone.now.beginning_of_week..Time.zone.now.end_of_week))
# @winner = @post.votes.count.reverse.first(1)
# end
def top_line_meme(top)
two_line_meme(top)
end
def bottom_line_meme(bottom)
two_line_meme(nil, bottom)
end
def two_line_meme(top, bottom=nil)
if (top.length > MAX_CHARACTERS || bottom.length > MAX_LINE_CHARACTERS)
raise "Too many characters"
end
if (top.length > MAX_LINE_CHARACTERS)
top_parts = top.split(' ')
count = 0
top_top = ""
bottom_top = ""
top_parts.each do |part|
if count + (part.length + 1) < MAX_LINE_CHARACTERS
top_top += " " + part
count += part.length + 1
else
bottom_top += " " + part
end
end
top = top_top + "\n" + bottom_top
end
img = Image.read(File.open(Meme.get_current_meme.avatar.path)).first
caption = Draw.new
caption.font = 'lib/assets/ufonts.com_impact.ttf'
caption.fill = 'white'
caption.pointsize = 50
caption.font_weight = BoldWeight
caption.stroke = 'black'
caption.stroke_width = 3
if (top)
caption.annotate(img, 0,0,0,10, top.upcase) do
self.gravity = NorthGravity
end
end
if (bottom)
caption.annotate(img, 0,0,0,10, bottom.upcase) do
self.gravity = SouthGravity
end
end
img.write(Rails.root + "public/memes/#{to_param}entry.jpg")
end
end
| true |
b8915c76bffb7fdd003310cdb6fc9762ffedca75 | Ruby | njbryan/ls-rb100-book | /exercises/05-attayItemReplacement.rb | UTF-8 | 137 | 3.0625 | 3 | [
"MIT"
] | permissive | array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.push(11)
p array
array.unshift(0)
p array
array.delete(11)
p array
array.push(3)
p array
| true |
813c51bc2cb64662859d2d96b412176e215d587b | Ruby | mpedersen2054/tealeaf | /course1/week4/exceptions.rb | UTF-8 | 227 | 2.8125 | 3 | [] | no_license | i = 0
while i <= 10
begin
if i == 0
1/0
end
raise "random runtime exception"
p "I should never get executed!"
rescue ZeroDivisionError
p 'I am rescuing only ZeroDivisionError'
i += 1
end
end | true |
0665e925718a845bea64b88a47eecc91e952e107 | Ruby | billstoneberg/say-hello-ruby-ruby-intro-000 | /say_hello.rb | UTF-8 | 94 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def say_hello(name)
name "Gabriela"
name("Ruby Programmer")
puts "Hello #{name}!"
end
| true |
ccfccf9b20ddef70ec5e05e41c3bca299bfb0b3e | Ruby | volodymyr-mykhailyk/advent-of-code-2019 | /lib/tasks/day11/runner.rb | UTF-8 | 1,016 | 3.03125 | 3 | [] | no_license | require_relative '../utils/printer'
require_relative '../utils/input_reader'
require_relative '../../universe/ship/hull_painting_robot'
require_relative '../../universe/communication/space_image'
include Utils::Printer
input_reader = Utils::InputReader.new(File.expand_path('input.txt'))
PANEL_DIMENSION = 100
program = input_reader.one_line.split_with(',').to_integer.read
info "Painting side panel with #{program.length} hull robot program"
robot = Universe::Ship::HullPaintingRobot.new(program, PANEL_DIMENSION)
robot.paint_side_panel
info "Painting complete. Number of painted panels: #{robot.painted_panels_count}"
info "Painting side panel with with first panel white"
robot = Universe::Ship::HullPaintingRobot.new(program, PANEL_DIMENSION, 1)
robot.paint_side_panel
info "Painting complete. Number of painted panels: #{robot.painted_panels_count}"
image = Universe::Communication::SpaceImage.new(robot.map.flatten, PANEL_DIMENSION, PANEL_DIMENSION)
info "Rendered license plate:"
puts image.render_image
| true |
c838ddb8dc1ee08cb867dee544f159a486da2ae8 | Ruby | akcrono/blackjack | /blackjack.rb | UTF-8 | 1,594 | 4.21875 | 4 | [] | no_license | require_relative 'card'
require_relative 'deck'
require_relative 'hand'
def play_again? game_result
puts game_result
puts "Do you want to play again?(y/n)"
if gets.chomp == 'y'
return true
end
false
end
def play_game
deck = Deck.new
dealer_hand = Hand.new
player_hand = Hand.new
2.times do |i|
dealer_hand.draw(deck.draw)
player_hand.draw(deck.draw)
end
puts "\nThis is your hand:"
player_hand.print
puts "Total score: #{player_hand.total_score}"
puts "What would you like to do?(hit/stand)"
player_response = gets.chomp
while player_response != 'stand'
if player_response != 'hit' && player_response != 'stand'
puts "Invalid input."
else
player_hand.draw(deck.draw)
puts "\nThis is your hand:"
player_hand.print
puts "Total score: #{player_hand.total_score}"
if player_hand.is_bust?
return play_again?("Player busts. You lose!")
end
puts "What would you like to do?(hit/stand)"
end
player_response = gets.chomp
end
puts "Dealer has:"
dealer_hand.print
while dealer_hand.total_score <= 16
dealer_hand.draw(deck.draw)
puts "Dealer now has:"
dealer_hand.print
end
if dealer_hand.is_bust?
return play_again?("Dealer busts. You win!")
else
puts "Player's score: #{player_hand.total_score}"
puts "Dealer's score: #{dealer_hand.total_score}"
if player_hand > dealer_hand
return play_again?("Congratulations! You win.")
else
return play_again?("Oh no! The dealer wins!")
end
end
end
while play_game
end
| true |
5c2a7a7730bdee246be31d76ab8516d08f56fceb | Ruby | dkentuk/ruby | /Desktop/RubyWork/30192014/personclean.rb | UTF-8 | 717 | 4.1875 | 4 | [] | no_license | require 'pry'
class Person
#creates setter and getters methods
attr_accessor :hair_color, :top_color
#only getter
attr_reader :height
def initialize(height = 0.0)
@hair_color = nil
@height = height
@top_color = nil
end
#methods
def dance
puts 'I am dancing'
end
def sleep
puts 'I am sleeping'
end
end
#inherited class
class Baby < Person
attr_accessor :smells
def cry
if @smells
"Waaaargh"
else
"I don't smell, so I'm not crying"
end
end
def dance
"I'm a baby, do a barrel roll, press a to shoot"
end
end
binding.pry | true |
73939bca98074ebdf57adb02e58d89301922af6b | Ruby | paeeon/tealeaf-intro | /intro_to_programming/variables/name.rb | UTF-8 | 272 | 3.9375 | 4 | [] | no_license | puts "What's your first name?"
first_name = gets.chomp
puts "Okay, what's your last name?"
last_name = gets.chomp
name = first_name + " " + last_name
puts "Hi, " + name + "!"
10.times do
puts "I really, really, really, really, really, really like you, " + name + "!"
end | true |
1cb821aca1df91003fdf6ec03c8b070451c50931 | Ruby | nkeller1/futbol | /lib/calculator.rb | UTF-8 | 96 | 2.78125 | 3 | [] | no_license | module Calculator
def find_pct(a, b)
(a.length.to_f / b.length.to_f).round(2)
end
end
| true |
13ebab49f87396cc2f847dc7ba9739494f5f8ac8 | Ruby | kanndide/william-kann-cli-app | /lib/william_kann_cli_app.rb | UTF-8 | 2,566 | 3.53125 | 4 | [
"MIT"
] | permissive | require "william_kann_cli_app/version"
module WilliamKannCliApp
class CLI
def call
puts "Welcome to the Warren Buffet (Berkshire Hathaway) holdings thingy!"
main_menu
end
def main_menu
puts "What would you like to see?"
puts "Current holdings, or holdings for another year? Type 'current holdings' or 'different year'."
user_input = gets.strip
if user_input == "Current holdings" || user_input == "current holdings" || user_input == "Current Holdings"
find_or_create_and_print("2017", "qtr4")
elsif user_input == "Different year" || user_input == "different year" || user_input == "Different year"
choose_your_own
elsif user_input == "exit"
exit
end
restart
end
def display_years
EdgarScraper.scrape_years.each do |x|
puts "#{x.gsub('/', '')}"
end
end
def display_qtr(year)
EdgarScraper.scrape_for_qtr(year).each do |x|
puts "#{x.gsub('/', '')}"
end
end
def choose_your_own
puts "What year would you like to see"
puts "*Note that some years or quarters may not have the correct format to show data.*"
display_years
puts "Please choose a year."
year = gets.strip
puts "What quarter would you like to check?"
display_qtr(year)
puts "Please choose a quarter."
qtr = gets.strip
find_or_create_and_print(year, qtr)
end
def restart
puts "Would you like to know more?"
user_input = gets.strip
if user_input == "yes"
main_menu
else
exit
end
end
def self.error_restart
puts "Would you like to try again?"
user_input = gets.strip
if user_input == "yes"
self.new.call
else
exit
end
end
def find_or_create_and_print(year, qtr)
if Reports.find_by_year_and_qtr(year, qtr) == nil
object = Reports.new(EdgarScraper.hash_13fhr(year, qtr))
Reports.print_report(object)
else
Reports.print_report(Reports.find_by_year_and_qtr(year, qtr))
end
end
end
end
| true |
ad588399f582f93986220a80e6c12529b7a53f7b | Ruby | yuriskorobogatov/RoR | /Lesson_6/route.rb | UTF-8 | 794 | 3.46875 | 3 | [] | no_license | require_relative 'instance_counter'
class Route
attr_reader :stations, :name
include InstanceCounter
def initialize(name, first_station, last_station)
@name = name
@stations = [first_station, last_station]
register_instance
validate!
end
def add_station(station)
@stations.insert(-2, station)
end
def delete_station(station)
@stations.delete(station) if station != @stations[0] && station != @stations[-1]
end
def validate!
raise "Название маршрута должно быть не менее шести символов" if @name.length < 6
@stations.each do |station|
raise "Введенный объект не является объктом класса Station" unless station.is_a? Station
end
true
end
end | true |
80bf60b011dfe781331fc801e149818c81d3ac90 | Ruby | PunitDh/Dystoland | /methods.rb | UTF-8 | 12,891 | 3.1875 | 3 | [] | no_license | # $wall_buff = 3
#############################################################################
def count_em(string, substring)
string.scan(/(?=#{substring})/).count
end
#############################################################################
def clamp(val, min, max)
return min if val <= min
return max if val >= max
return val
end
# #############################################################################
# def read_char
# STDIN.echo = false
# STDIN.raw!
# input = STDIN.getc.chr
# if input == "\e" then
# input << STDIN.read_nonblock(3) rescue nil
# input << STDIN.read_nonblock(2) rescue nil
# end
# ensure
# STDIN.echo = true
# STDIN.cooked!
# return input
# end
# #############################################################################
# def show_single_key
# c = read_char
# up = 0
# down = 0
# left = 0
# right = 0
# case c
# when " "
# puts "SPACE"
# when "\t"
# puts "TAB"
# when "\r"
# puts "RETURN"
# when "\n"
# puts "LINE FEED"
# when "\e"
# puts "ESCAPE"
# when "\e[A"
# puts "UP ARROW"
# up = 1
# when "\e[B"
# puts "DOWN ARROW"
# down = 1
# when "\e[C"
# puts "RIGHT ARROW"
# right = 1
# when "\e[D"
# puts "LEFT ARROW"
# left = 1
# when "\177"
# puts "BACKSPACE"
# when "\004"
# puts "DELETE"
# when "\e[3~"
# puts "ALTERNATE DELETE"
# when "\u0003"
# puts "CONTROL-C"
# exit 0
# when /^.$/
# puts "SINGLE CHAR HIT: #{c.inspect}"
# else
# puts "SOMETHING ELSE: #{c.inspect}"
# end
# return [right-left, down-up]
# end
def tmpgets
tmp = gets
end
def cutscenedraw(name)
Image.print(name)
# puts "\n"*5
Message.print(name)
tmpgets
end
def winsize
IO.console.winsize
rescue LoadError
Integer(`tput co`)
end
def cutscenes(messages)
messages.cycle(1) { |message| cutscene(message) }
end
def insult
insults = ["You will not get away with this, you gleeking flap-mouthed haggard",
"Don't you need a license to be that ugly?",
"I bet your brain feels as good as new, seeing that you've never used it.",
"I don't know what makes you so stupid, but it really works!",
"If you had another brain, it would be lonely.",
"Did they make the Idiot-bot blueprints out of you?",
"You will go no further than this, maggot-pie!",
"How did you get this far, turd-goblin?",
"Don't you have a terribly empty feeling - in your skull?",
"Learn from your parents' mistakes - use birth control!",
"Turn yourself in, now!",
"I bet your mother has a loud bark!",
"Do you still love nature, despite what it did to you?",
"Keep talking, someday you'll say something intelligent.",
"I heard you went to have your head examined but the doctors found nothing there.",
"I'm going to rupture your evil face with a brick",
"Begone before I break your stinking spine with an anvil",
"I'm going to make you cry like a schoolgirl",
"Did you know you have receding gums?",
"After I'm done with you, you're going to wish you were never born",
].sample
end
def showarmory(player,prompt,convertdisabled=false)
lastselected = 1
hrequest = nil
prices = {"gun": 12000, "healthpack": 800, "cipher": 100}
begin
puts ""
puts (" You have: " + (player.credits.to_s + " credits").yellow).center(100)
options = {
"Buy Gun " + "(#{prices[:gun]} Credits)".yellow => 1,
"Buy healthpacks " + "(#{prices[:healthpack]} Credits)".yellow => 2,
# "Purchase Ciphers " + "(#{prices[:cipher]} Credits)".yellow => 3,
# "View Powers" => 4,
{ name: "Purchase Ciphers".light_black, disabled: "(Not yet available)".light_black } => 3,
{ name: "View Powers".light_black, disabled: "(Not yet available)".light_black } => 4,
{ name: "Convert garbage data".light_black, disabled: "(Not yet available)".light_black } => 5,
"[Exit Armory]" => 6
}
if not convertdisabled
options["Purchase Ciphers " + "(#{prices[:cipher]} Credits)".yellow] = options.delete options.key(3)
options["View Powers"] = options.delete options.key(4)
options["Convert garbage data"] = options.delete options.key(5)
options["[Exit Armory]"] = options.delete options.key(6)
end
request = promptchoices(prompt, "\n Choose your option:", options, lastselected)
lastselected = request
case request
when 1
if player.gundamage < 3.5
case promptchoices(prompt, "\n Are you sure you want to purchase a gun for #{prices[:gun]} credits?", {"Yes"=>1, "No"=>2})
when 1
if player.gundamage < 3.5
if player.credits >= prices[:gun]
player.credits -= prices[:gun]
player.gundamage = 3.5
puts "\n\n You have purchased a gun for #{prices[:gun]} credits.\n\n"
else
puts "\n\n You do not have enough credits to purchase this item.\n\n"
end
end
end
else
puts "\n\n You have already purchased a gun.\n\n"
end
when 2
case promptchoices(prompt, "\n Are you sure you want to purchase 1 healthpack for #{prices[:healthpack]} credits?", {"Yes"=>1, "No"=>2})
when 1
if player.credits >= prices[:healthpack]
player.credits -= prices[:healthpack]
player.healthpacks += 1
else
puts "\n\n You do not have enough credits to purchase this item.\n\n"
end
end
when 3
case promptchoices(prompt, "\n Are you sure you want to purchase 1 cipher for #{prices[:cipher]} credits?", {"Yes"=>1, "No"=>2})
when 1
if player.credits >= prices[:cipher]
player.credits -= prices[:cipher]
player.ciphers += 1
else
puts "\n\n You do not have enough credits to purchase this item.\n\n"
end
end
when 4
p player.powers
# do this
when 5
begin
gdata = promptchoices(prompt, "\n Choose which cipher to convert: ", [player.garbagedata, "[Exit]"].flatten)
if not gdata == "[Exit]"
player.garbagedata.delete(gdata)
decipher = [gdata].pack("B*").to_s
powerval = decipher.count("\\^aeiou")+decipher.length*decipher.count("\\^aeiou")
puts "\n\n You have gained the following power: " + decipher + ", " + powerval.to_s
player.powers << [decipher, powerval]
end
end until gdata == "[Exit]"
tmpgets
when 6
hrequest = promptchoices(prompt, "\n\nAre you sure you want to exit the Armory?", {"Yes" => 1, "No" => 2})
end
end until hrequest == 1
end
def enemyencounter(player, prompt, enemy, health=20, garbagadataunlock=true, initialquote=nil)
e = Enemy.new(enemy,health)
cutscene "\n\n\n\n\n\n Your path is being blocked by: #{e.name.capitalize.light_magenta}"
Image.print(e.name)
tmpgets
cutscene "\n #{e.name.capitalize} says: \"#{(initialquote.nil?) ? insult() : initialquote}\"\n"
cutscene " You have entered "+"Battle Mode".light_magenta + "!"
attackround = 0
eattackmultiplier = 1
criticalstrike = 1
request = nil
fleeattempt = false
lastselected = 1
begin
puts "\n\t\t #{e.name.capitalize}'s health: #{e.health}/#{e.maxhealth} " + ("█".red)*((e.health/5).ceil)
puts "\t\t Your Health: #{player.health}/#{player.maxhealth} " + ("█".green)*((player.health/5).ceil)
request = promptchoices(prompt, "Your move:", {"Attack #{e.name.capitalize}" => 1, "Throw Grenade (Qty: "+player.grenades.to_s.light_red+")" => 2, "Heal (Qty:"+player.healthpacks.to_s.light_blue+")" => 3, "Hide from #{e.name.capitalize}" => 4, "Run away" => 5}, lastselected)
lastselected = request
case request
when 1
criticalstrike = rand(1.5..3.5) if rand() > 0.6
attackdmg = (rand() *5 * criticalstrike * player.gundamage).ceil
puts (attackdmg < 1) ? "\n\n You attack #{e.name.capitalize} and miss." : "\n\n You attack #{e.name.capitalize} and cause #{attackdmg} damage."
puts " \n Critical Strike!!" if (criticalstrike > 1 and attackdmg >= 10)
e.health -= attackdmg
criticalstrike = 1
when 2
if player.grenades > 0
attackdmg = (rand(10..24) * rand(0.9..1.1)).ceil
puts "\n You throw a grenade and deal #{attackdmg} damage to #{e.name.capitalize}."
e.health -= attackdmg
player.grenades -= 1
else
puts "\n You fumble around in your backpack to find a grenade, but find none."
end
when 3
if (player.health == player.maxhealth)
puts "\n You are already at max health."
else
if (player.healthpacks > 0)
puts "\n You use 1 healthpack from your backpack and gain 10 health."
player.healthpacks -= 1
player.health = [player.maxhealth, player.health + 10].min
else
puts "\n You fumble around in your backpack to find a healthpack, but find none."
end
end
when 5
puts "\n You turn on your heels and attempt to escape..."
tmpgets
fleeattempt = true if rand() > 0.75
puts "\n #{e.name.capitalize} yells: " + ((fleeattempt) ? "\"Yes, yes, run away, little mouse...\"" : "\"Stand and fight me, coward\"")
puts "\n Flee attempt failed..." if not fleeattempt
end
tmpgets
break if e.health <= 0
if rand() > 0.6 or attackround == 0
puts " #{e.name.capitalize} is " + ["annoyed","bitter","enraged","exasperated","furious","impassioned","indignant","irritated","irritable","offended","outraged","resentful"].sample + "."
tmpgets
if rand() > 0.8
cutscene " #{e.name.capitalize} #{["gears up", "readies himself"].sample} for #{["a destructive","a ruinous","a disastrous","a catastrophic","a calamitous","a cataclysmic","a pernicious","a noxious","a harmful","a damaging","an injurious","a hurtful"].sample} attack."
eattackmultiplier = rand(1.5..2.5)
end
end
enemydmg = (rand()*e.attack * eattackmultiplier).ceil
puts (enemydmg < 1) ? "\n #{e.name.capitalize} attacks you and misses." : "\n #{e.name.capitalize}'s attack #{["causes", "deals"].sample} #{enemydmg} damage."
puts " Ouch!!" if eattackmultiplier > 1 and enemydmg >= 10
player.health -= enemydmg
eattackmultiplier = 1
tmpgets
break if player.health <= 0
attackround += 1
Image.print(e.name)
cutscene "\n #{e.name.capitalize} says: \"#{insult()}\"\n"
end until (e.health <= 0 or (request == 5 and fleeattempt==true))
if (player.health <= 0)
puts "\n\n"
puts "You have died!".center(100)
puts "\n\n\n"
exit
end
if (not request == 5)
puts ("\t\t\tYou have " + ["destroyed","defeated","crushed","conquered","beaten"].sample + ": #{e.name.capitalize}!")
puts ("\t\t\tYou have gained: " + (e.healthpacks.to_s + " healthpack(s)").light_blue)
player.healthpacks += e.healthpacks
puts ("\t\t\tYou have gained: " + (e.credits.to_s + " credits").yellow)
player.credits += e.credits
if e.grenades > 0
puts "\t\t\tYou have gained: " + (e.grenades.to_s + " grenades").light_red
player.grenades += e.grenades
end
if (garbagadataunlock)
tmpgets
garbagedata = random_word().flatten
garbagedatachoices = garbagedata.dup
garbagedatachoices.push("[Collect All]","[Exit]")
begin
puts "\n The enemy has dropped the following garbage data: \n"
gdata = promptchoices(prompt," Choose which data to collect or press [Collect All]",garbagedatachoices)
garbagedatachoices.delete(gdata)
player.garbagedata << gdata unless (gdata=="[Exit]" or gdata =="[Collect All]")
player.garbagedata << garbagedatachoices[0..(garbagedatachoices.length-2)] if gdata =="[Collect All]"
player.garbagedata.flatten!
end until (gdata=="[Exit]" or gdata =="[Collect All]")
end
else
puts "\n You have fled the battle."
end
tmpgets
puts "\n\n\t\t\tYour stats: "
puts "\t\t\t - Health: "+"#{player.health}".light_green
puts "\t\t\t - Credits: "+"#{player.credits}".yellow
puts "\t\t\t - Healthpacks: "+"#{player.healthpacks}".light_blue
puts "\t\t\t - Grenades: "+"#{player.grenades}".light_blue
tmpgets
end
def random_word()
words = ["precede","panic","delete","borrow","large","sympathetic","filter","swarm","crossing","amputate","slap","hero","spell","electronics","head","bill","charismatic","beat","census","full","amuse","pound","institution","behead","ostracize","tough","progress","satisfied","flag","fascinate"]
r = (rand()*5 + 1).floor
a = []
r.times do
w = words.sample
words.delete(w)
a << w.unpack("B*")
end
return a
end
def promptchoices(prompt, question, choices, lastselected=1)
prompt.select(question, choices, show_help: :never, cycle: true)
# do |menu|
# menu.default (choices.key(lastselected)[:disabled]) ? lastselected : 1
# choices.each do |key,value|
# menu.choice key, value
# end
# end
end
def cutscene(message)
maximum_length = winsize()[1].to_i - 20
str = Array.new
if (message.length > maximum_length)
for i in 0..((message.length/maximum_length))
pmsg = message[..(i*maximum_length)]
lastspace = pmsg.rindex(" ")
message[lastspace] = "\n" if not lastspace.nil?
end
end
str = message.split("\n")
for i in 0..str.length-1
puts str[i].to_s
end
tmpgets
end
def printprompt(message)
puts message
tmpgets
end | true |
2f73fbe71865e8a1d7ce455ae942a54a2d85863c | Ruby | abhinavgunwant/hackerrank-solutions | /Domains/Ruby/06 - Strings/05 - Ruby - Strings - Methods II/solution.rb | UTF-8 | 259 | 3.28125 | 3 | [
"MIT"
] | permissive | def strike(s)
"<strike>#{s}</strike>"
end
def mask_article(s, arr)
arr.each do | word |
# create a RegEx pattern based on the word in array!
pattern = Regexp.new word
s = s.gsub(pattern, strike(word))
end
return s
end | true |
40cc38bece81ec84166f061cd0eaf695ba1929b7 | Ruby | acmassey3698/backend_mod_1_prework | /section1/exercises/ex6.rb | UTF-8 | 1,273 | 4.5 | 4 | [] | no_license | #establishes the number for types of people
types_of_people = 10
#creates a variable 'x' that is a string interpolating variable "types_of_people"
x = "There are #{types_of_people} types of people."
#creates variable 'binary' and sets its value to a string
binary = "binary"
#creates variable 'do_not' and sets it equal to a string that is the contracted form of the two words
do_not = "don't"
#creates variable 'y' that equals a string containing two interpolated variables
y = "Those who know #{binary} and those who #{do_not}."
#prints variable x
puts x
#prints variable y
puts y
#prints a string containing variable x
puts "I said: #{x}."
#prints a string containing variable y
puts "I also said: '#{y}'."
#creates variable "hilarious" and gives it a false boolean value
hilarious = false
#creates "joke_evaluation" variable and equates it to a string with interpolated variable
joke_evaluation = "Isn't that joke so funny?! #{hilarious}"
#prints 'joke_evaluation' variable
puts joke_evaluation
#creates variable 'w' and sets it equal to the left side of the sentemce
w = "This is the left side of..."
#creates variable 'e' and sets it equal to the right side of the sentence
e = "a string with a right side."
#prints the two previous strings combined
puts w + e
| true |
8f72e997f4ceb47a2bed1b4e4f1e7354971700e1 | Ruby | vma13/University | /Archive/5sem/BD/aero_tickets/aero/lib/controllers/helper.rb | UTF-8 | 1,433 | 2.546875 | 3 | [] | no_license | module Helper
def companies_select(name, selected)
"<select name = '#{name}'>" +
Company.find_all(@db).map do |c|
if c[:id].to_i == selected.to_i
"<option value = '#{c[:id]}' selected>#{c[:name]}</option>"
else
"<option value = '#{c[:id]}'>#{c[:name]}</option>"
end
end.join("\n") +
"</select>"
end
def is_departure_select(name, selected = true)
options = {:true => 'отлетающий', :false => 'прилетающий'}
"<select name = '#{name}'>" +
options.map do |k, v|
"<option value = '#{k}'#{k.to_s == selected.to_s ? ' selected' : ''}>#{v}</option>"
end.join("\n") +
"</select>"
end
def place_type_select(name, selected)
options = {:a => 'бизнес класс', :b => 'эконом класс', :c => 'премиум класс'}
"<select name = '#{name}'>" +
options.map do |k, v|
"<option value = '#{v}'#{v.to_s == selected.to_s ? ' selected' : ''}>#{v}</option>"
end.join("\n") +
"</select>"
end
def flights_select(name, selected)
"<select name = '#{name}'>" +
Flight.find_all(@db).map do |c|
if c[:id].to_i == selected.to_i
"<option value = '#{c[:id]}' selected>#{c[:code]}</option>"
else
"<option value = '#{c[:id]}'>#{c[:code]}</option>"
end
end.join("\n") +
"</select>"
end
end
| true |
161dc343dbde550bd06ff3f896ca212086ab1238 | Ruby | aasmith/struggle | /lib/struggle/arbitrators/card_play.rb | UTF-8 | 4,337 | 3 | 3 | [
"MIT"
] | permissive | module Arbitrators
class CardPlay < MoveArbitrator
fancy_accessor :player, :optional
needs :deck, :china_card, :hands, :cards, :guard_resolver
# used for tracking state over two-instruction plays
attr_accessor :previous_card, :previous_action
def initialize(player:, optional: false)
super
self.player = player
# Is this an optional play? The player can pass by playing
# a Noop instruction.
self.optional = optional
end
def before_execute(move)
log move.instruction.to_s
end
def after_execute(move)
if noop?(move) || second_part?
complete
else
card = cards.find_by_ref(move.instruction.card_ref)
if card.side == player.opponent && !space?(move)
self.previous_card = move.instruction.card_ref
self.previous_action = move.instruction.card_action
else
complete
end
end
end
##
# Checks the move is valid against numerous conditions.
#
# If the player is unable to play a card (i.e. empty hand) then accept
# a noop instruction.
#
# Otherwise, check the move contains a CardPlay instruction and that the
# player has the card in hand (or is playable in the case of the china
# card).
#
# Asserts the particular action cannot get the game into an unplayable
# state. Checks the appropriate action Guard.
#
# If the card contains an opponent event, then also verify that two moves
# are played -- one for an event and one for an operation, in either order
# and using the same card.
#
# If the card contains an opponent event, but is being spaced, then ensure
# a one part move.
#
# If this CardPlay is optional, then allow the player to play as normal
# or accept a Noop instruction to pass.
#
def accepts?(move)
return false if incorrect_player?(move)
return false if eventing_china_card?(move)
if able_to_play? && !optional?
playing_valid_card_allowed_by_guard?(move)
elsif able_to_play? && optional?
playing_valid_card_allowed_by_guard?(move) or noop?(move)
else
noop?(move)
end
end
##
# The player is able to play if this is the second part of a card play,
# or their hand is not empty.
#
def able_to_play?
second_part? || !hands.hand(player).empty?
end
def playing_valid_card_allowed_by_guard?(move)
card_play?(move) && valid_card?(move) && guard_allows?(move)
end
def noop?(move)
Instructions::Noop === move.instruction
end
def card_play?(move)
Instructions::PlayCard === move.instruction
end
def valid_card?(move)
if second_part?
same_card_as_previous?(move) && opposing_action?(move)
else
card_in_possession?(move)
end
end
# Delegates to the guard if the move is an operation, otherwise returns
# true.
def guard_allows?(move)
if OPERATIONS.include?(move.instruction.card_action)
guard_resolver.resolve(move).allows?
else
true
end
end
def space?(move)
move.instruction.card_action == :space
end
def opposing_action?(move)
action = move.instruction.card_action
if action == :event
OPERATIONS.include?(previous_action)
else
previous_action == :event
end
end
def same_card_as_previous?(move)
previous_card && previous_card == move.instruction.card_ref
end
def card_in_possession?(move)
card = cards.find_by_ref(move.instruction.card_ref)
if card.china_card?
china_card.playable_by?(player)
else
hands.hand(player).include?(card)
end
end
##
# Is this the second part of a two-part move?
#
# This is only known for sure once the first move has been executed.
#
def second_part?
previous_card || previous_action
end
# Rejects any attempt to play the China Card as an event.
def eventing_china_card?(move)
return false unless Instructions::PlayCard === move.instruction
card = cards.find_by_ref(move.instruction.card_ref)
card.china_card? && move.instruction.card_action == :event
end
alias optional? optional
end
end
| true |
41b674befa06627ef9251c66d54e84c362dbe293 | Ruby | festinalent3/ruby-kickstart | /session2/3-challenge/4_array.rb | UTF-8 | 1,637 | 4.4375 | 4 | [
"MIT"
] | permissive | # Write a method named get_squares that takes an array of numbers
# and returns a sorted array containing only the numbers whose square is also in the array
#
# get_squares [9] # => []
# get_squares [9,3] # => [3]
# get_squares [9,3,81] # => [3, 9]
# get_squares [25, 4, 9, 6, 50, 16, 5] # => [4, 5]
# This time you will have to define the method, it's called: get_squares
def get_squares(array)
return_array = []
power_nr = 0
array = array.sort
array.each_with_index { | nr, index |
#sqrt_nr = Math.sqrt(nr)
power_nr = nr ** 2 #16
current_nr = nr #4
array.each_with_index { | nr, index |
if Math.sqrt(nr) == current_nr
return_array.push(current_nr)
break
end
}
# array = array.shift if array.length != 1
}
return_array
end
# def get_squares(numbers)
# numbers.select { |n| numbers.include? n*n }.sort
# end
# loop_nr = array.length
#
# array.each { | nr |
# sqrt_nr = Math.sqrt(nr)
# while loop_nr !=0
# array.each_with_index { | number, index | return_array.push(number) if sqrt_nr == number}
# end
# array.pop[]
# loop_nr +=1
# }
#https://www.codecademy.com/articles/glossary-ruby
#
# 1 få in arrayen
# 2 få ut alla rötter ur alla nummer i arrayen
# 3. jämföra första arrayen om varje numemr^2 == any of numrena i den andra arrayen
#4. ta bort duplicates
# 4. spara ner dem som är true i en ny array och returnera den
#
#
# Math.sqrt(expression)
# Example
#
# Math.sqrt(100)
# => 10.0
#
# Math.sqrt(5+4)
# => 3.0
#
# Math.sqrt(Math.sqrt(122+22) + Math.sqrt(16))
# => 4.0
| true |
8889954716be285311e09e5fc47295d11945ec0d | Ruby | NoahZinter/weather_getter_api | /spec/services/forecast_service_spec.rb | UTF-8 | 2,622 | 2.609375 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe ForecastService do
before :all do
@lat = 39.738453
@lon = -104.984853
@data = ForecastService.get_forecast(@lat, @lon)
end
describe '.get_forecast' do
it 'retrieves forecast with lat and lng' do
expect(@data[:lat].round(2)).to eq @lat.round(2)
expect(@data[:lon].round(2)).to eq @lon.round(2)
expect(@data[:timezone]).to eq 'America/Denver'
expect(@data[:current]).is_a? Hash
end
it 'contains current weather info' do
expect(@data[:current][:dt]).is_a? Integer
string_time = @data[:current][:dt].to_s
expect(DateTime.strptime(string_time, '%s')).is_a? DateTime
expect(@data[:current][:sunrise]).is_a? Integer
expect(DateTime.strptime(@data[:current][:sunrise].to_s, '%s')).is_a? DateTime
expect(@data[:current][:sunset]).is_a? Integer
expect(DateTime.strptime(@data[:current][:sunset].to_s, '%s')).is_a? DateTime
expect(@data[:current][:temp]).to be_a(Float).or be_a(Integer)
expect(@data[:current][:temp]).to be < 150
expect(@data[:current][:feels_like]).to be_a(Float).or be_a(Integer)
expect(@data[:current][:feels_like]).to be < 150
expect(@data[:current][:humidity]).to be_a(Float).or be_a(Integer)
expect(@data[:current][:uvi]).to be_a(Float).or be_a(Integer)
expect(@data[:current][:visibility]).to be_a(Float).or be_a(Integer)
expect(@data[:current][:weather][0][:description]).is_a? String
expect(@data[:current][:weather][0][:icon]).is_a? String
end
it 'contains daily weather info' do
expect(@data[:daily]).is_a? Array
@data[:daily].each do |day|
expect(day).is_a? Hash
expect(day).to have_key(:dt)
expect(day).to have_key(:sunrise)
expect(day).to have_key(:sunset)
expect(day).to have_key(:temp)
expect(day[:temp]).to have_key(:max)
expect(day[:temp]).to have_key(:min)
expect(day).to have_key(:weather)
expect(day[:weather]).is_a? Array
expect(day[:weather][0][:description]).is_a? String
expect(day[:weather][0][:icon]).is_a? String
end
end
it 'contains hourly weather info' do
expect(@data[:hourly]).is_a? Array
@data[:hourly].each do |hour|
expect(hour).is_a? Hash
expect(hour).to have_key(:dt)
expect(hour).to have_key(:temp)
expect(hour).to have_key(:weather)
expect(hour[:weather]).is_a? Array
expect(hour[:weather][0][:description]).is_a? String
expect(hour[:weather][0][:icon]).is_a? String
end
end
end
end
| true |
da2504e91c9e783b3262aa91a139fee9f6f488cf | Ruby | gitvar/Assessment-149-Revision | /4. Blocks/e1_blocks.rb | UTF-8 | 422 | 3.9375 | 4 | [] | no_license | def echo_with_yield(str)
yield if block_given?
str
end
puts echo_with_yield("Hello!") # No error if using 'if block_given?'
# puts echo_with_yield { puts "world" }
# => ArgumentError: wrong number of arguments (0 for 1) #
puts echo_with_yield("hello!") { puts "world" } # world and return "hello!"
# puts echo_with_yield("hello", "world!") { puts "world" }
# => ArgumentError: wrong number of arguments (2 for 1)
| true |
9c0bd57b151c93d6f61bca7cede6ab279be24c7d | Ruby | learn-co-students/nyc-web-010620 | /07-oo-review-part-2/ride.rb | UTF-8 | 288 | 2.9375 | 3 | [] | no_license | class Ride
attr_accessor :duration, :price, :passenger, :driver
@@all = []
def initialize(duration, price, passenger, driver)
@duration = duration
@price = price
@passenger = passenger
@driver = driver
@@all << self
end
def self.all
@@all
end
end | true |
ec4a255b3147b63560ebd879b4b3ff99966834d1 | Ruby | srashidi/RSpec_Project | /connect_four/spec/cage_spec.rb | UTF-8 | 5,535 | 3.21875 | 3 | [] | no_license | require 'spec_helper'
describe Cage do
before :each do
@cage = Cage.new
end
describe "#new" do
it "creates a new Cage object with no pieces" do
expect(@cage.row1).to eql "| | | | | | | |"
expect(@cage.row2).to eql "| | | | | | | |"
expect(@cage.row3).to eql "| | | | | | | |"
expect(@cage.row4).to eql "| | | | | | | |"
expect(@cage.row5).to eql "| | | | | | | |"
expect(@cage.row6).to eql "| | | | | | | |"
end
end
describe "#display" do
it "displays the current cage" do
expect(STDOUT).to receive(:puts).with("")
expect(STDOUT).to receive(:puts).with(" 1 2 3 4 5 6 7")
expect(STDOUT).to receive(:puts).with(@cage.row1)
expect(STDOUT).to receive(:puts).with(@cage.row2)
expect(STDOUT).to receive(:puts).with(@cage.row3)
expect(STDOUT).to receive(:puts).with(@cage.row4)
expect(STDOUT).to receive(:puts).with(@cage.row5)
expect(STDOUT).to receive(:puts).with(@cage.row6)
expect(STDOUT).to receive(:puts).with("")
@cage.display
end
end
describe "#place_piece" do
context "when column is empty" do
before :each do
@move = @cage.place_piece(:red,3)
end
it "puts piece on the bottom row in the correct column" do
expect(@cage.row1).to eql "| | | | | | | |"
expect(@cage.row2).to eql "| | | | | | | |"
expect(@cage.row3).to eql "| | | | | | | |"
expect(@cage.row4).to eql "| | | | | | | |"
expect(@cage.row5).to eql "| | | | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | | | |"
end
it "returns the coordinate of the newly-placed piece" do
expect(@move).to eql [3,6]
end
it "puts piece on the bottom row in a different column" do
@cage.place_piece(:black,5)
expect(@cage.row1).to eql "| | | | | | | |"
expect(@cage.row2).to eql "| | | | | | | |"
expect(@cage.row3).to eql "| | | | | | | |"
expect(@cage.row4).to eql "| | | | | | | |"
expect(@cage.row5).to eql "| | | | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | #{BLACK} | | |"
end
it "returns the coordinate of the newly-placed piece" do
@move = @cage.place_piece(:black,5)
expect(@move).to eql [5,6]
end
end
context "when column has at least one piece" do
before :each do
@cage.place_piece(:red,3)
@cage.place_piece(:black,5)
@cage.place_piece(:red,3)
end
it "puts piece on the row above the bottom row in the correct column" do
expect(@cage.row1).to eql "| | | | | | | |"
expect(@cage.row2).to eql "| | | | | | | |"
expect(@cage.row3).to eql "| | | | | | | |"
expect(@cage.row4).to eql "| | | | | | | |"
expect(@cage.row5).to eql "| | | #{RED} | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | #{BLACK} | | |"
end
context "when another piece is placed in the same column" do
it "puts piece on the row above that row in the correct column" do
@cage.place_piece(:black,3)
expect(@cage.row1).to eql "| | | | | | | |"
expect(@cage.row2).to eql "| | | | | | | |"
expect(@cage.row3).to eql "| | | | | | | |"
expect(@cage.row4).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row5).to eql "| | | #{RED} | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | #{BLACK} | | |"
end
end
end
context "when column is filled" do
before do
@cage.place_piece(:red,3)
@cage.place_piece(:black,3)
@cage.place_piece(:red,3)
@cage.place_piece(:black,3)
@cage.place_piece(:red,3)
@cage.place_piece(:black,3)
end
context "when a piece is placed in the same column" do
it "gives an error message and returns an error" do
expect(STDOUT).to receive(:puts).with("Error: Column is full. Try again...")
move = @cage.place_piece(:red,3)
expect(@cage.row1).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row2).to eql "| | | #{RED} | | | | |"
expect(@cage.row3).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row4).to eql "| | | #{RED} | | | | |"
expect(@cage.row5).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | | | |"
expect(move).to eql :FullColumnError
end
end
context "when a piece is placed in a different, open column" do
it "places the piece in the correct spot" do
move = @cage.place_piece(:red,5)
expect(@cage.row1).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row2).to eql "| | | #{RED} | | | | |"
expect(@cage.row3).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row4).to eql "| | | #{RED} | | | | |"
expect(@cage.row5).to eql "| | | #{BLACK} | | | | |"
expect(@cage.row6).to eql "| | | #{RED} | | #{RED} | | |"
expect(move).to eql [5,6]
end
end
end
end
end | true |
3fbf6f5f12e8a3909c2d9dc1d8eb8cca9a947176 | Ruby | tosiaki/imaginationspace | /lib/import_association_map.rb | UTF-8 | 545 | 2.984375 | 3 | [
"MIT",
"Beerware",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class ImportAssociationMap
def initialize
@import_association_map = []
end
def add_association(old_record, new_record, type)
@import_association_map << {old_record: old_record, new_record: new_record, type: type}
end
def get_by_old_id(id, type)
result = @import_association_map.select { |entry| entry[:type] == type && entry[:old_record]['id'] == id }
if result[0]
result[0][:new_record]
else
# puts "Notice: entry of id #{id} and type #{type} does not exist. Perhaps it is deleted?"
end
end
end | true |
4f225d5d9f5439c4ffd5c7a7537904ac287a7a9a | Ruby | jeremiahogutu/ttt-10-current-player-cb-gh-000 | /lib/current_player.rb | UTF-8 | 298 | 3.59375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def turn_count(board)
playCount = 0
board.each do |playSpace|
if playSpace == "X" || playSpace == "O"
playCount+=1
end
end
return playCount
end
def current_player(board)
playerTurn = turn_count(board)
if playerTurn % 2 == 0
return "X"
else
return "O"
end
end
| true |
906264aeb89002cb47491191758147b099b3497c | Ruby | dirtyRuby/Practice | /EachMapVowel/map_vowel.rb | UTF-8 | 182 | 3.15625 | 3 | [] | no_license | module MapVowel
def map_vowel(&proc)
vowels = ['a','o','u','i','e'].to_enum
vowels.map{proc.call(vowels.next)}
end
end
#Test
include MapVowel
map_vowel{ |x| puts x+'1'}
| true |
033661abba70a2348eab335cafa5706cfb4e851a | Ruby | innlouvate/bank_tech_test | /spec/account_spec.rb | UTF-8 | 1,238 | 2.953125 | 3 | [] | no_license | require "./lib/account.rb"
describe Account do
subject(:account) {described_class.new(statement)}
let(:statement) { double :statement }
let(:date) { Time.new(2012, 01, 10) }
before do
allow(statement).to receive(:new_transaction)
end
describe "#initialize" do
it "customer has a balance of £0" do
expect(account.balance).to eq 0
end
end
describe "#deposit" do
it "adds the specified amount to the balance" do
expect{ account.deposit(50) }.to change{ account.balance }.by(50)
end
it "calls for a new transaction to be added to the statement" do
expect(statement).to receive(:new_transaction)
account.deposit(50, date)
end
end
describe "#withdraw" do
it "subtracts the specified amount from the balance" do
account.deposit(50)
expect{ account.withdraw(10) }.to change{ account.balance }.by(-10)
end
it "calls for a new transaction to be added to the statement" do
expect(statement).to receive(:new_transaction)
account.withdraw(10, date)
end
end
describe "#print_statement" do
it "calls for the statement to be printed" do
expect(statement).to receive(:print)
account.print_statement
end
end
end
| true |
9a5c28da46b192cf34129066a0dda45bd49a434a | Ruby | hxcan/sbrowser_ruby_prototype | /SWebPageWidget.rb | UTF-8 | 6,609 | 2.515625 | 3 | [] | no_license | require 'Qt4'
require 'StbWebView.rb'
require 'qtwebkit'
class SWebPageWidget < Qt::Widget
signals 'shouldOpenNewTab()','titleChanged(QString)','iconChanged(QIcon)'
slots 'gotoUrlBarUrl()','refreshUrl(QUrl)','indicateLoadStart()','indicateLoadProgress(int)','indicateLoadFinished(bool)','indiateIconChanged()','focusWebView()'
def destroyWebPage()
@wbPg.disconnect() #断开信号连接《。
wbStng=@wbPg.page().settings() #获取设置对象。
wbStng.setAttribute(Qt::WebSettings::PluginsEnabled,false) #禁用插件《。
@wbPg.stop() #停止网页。
if @wbPg #网页视图存在。
@wbPg.setHtml('') #设置空白《的《内容《。
end #if @wbPg #网页视图存在。
@wbPg=nil #标记《为《无用。
end #def destroyWebPage()
def isFirstTimeLoad()
return @firstTimeLoad #是否是第一次载入。
end #def isFirstTimeLoad()
def focusWebView()
@wbPg.setFocus() #设置焦点。
end #def focusWebView()
def getWebView()
return @wbPg #返回网页视图。
end #def getWebView()
def setBrowserWindow(brsWnd2St)
@brsrWnd=brsWnd2St #记录。
end #def setBrowserWindow(brsWnd2St)
def createWindow(wndTp)
result=@brsrWnd.createWindow(wndTp) #要求浏览器窗口本身创建一个新窗口。
return result #返回结果。
end #def createWindow(wndTp)
def indiateIconChanged()
emit iconChanged(@wbPg.icon()) #发射信号。
end #def indiateIconChanged()
def indicateLoadFinished(suc)
if suc #载入成功。
crtTtl=@wbPg.title() #获取页面标题。
else #页面载入出错。
crtTtl='Page load error' #设置页面标题。
end
emit titleChanged(crtTtl) #发射信号。
end #def indicateLoadFinished(suc)
def indicateLoadProgress(crtPrg)
if (crtPrg) #进度值存在。
crtTtl='%d%' % crtPrg #获取进度值字符串。
else #进度值不存在。
crtTtl='0%' #获取进度值字符串。
end #if (crtPrg) #进度值存在。
if @wbPg.title() #标题存在。
crtTtl+=@wbPg.title() #接上标题。
end #if @wbPg.title() #标题存在。
emit titleChanged(crtTtl) #显示进度。
end #def indicateLoadProgress(crtPrg)
def indicateLoadStart()
emit titleChanged('Loading...') #发射信号。
end #def indicateLoadStart()
def refreshUrl(nwUrl)
pp('url changed:'+nwUrl.toString()) #Debug.
@urlBr.setText(nwUrl.toString()) #显示新的URL。
end #def refreshUrl(nwUrl)
def gotoUrlBarUrl()
pp('url bar text class:',@urlBr.text().class) #Debug.
pp('url bar text content:',@urlBr.text()) #Debug.
urlTxt=@urlBr.text() #获取路径条文字内容。
urlTxt=URI.decode(urlTxt) #将百分号编码解码。
@urlBr.setText(urlTxt) #重新显示路径条文字。
raUrl=Qt::Url.new(@urlBr.text()) #构造一个裸的URL对象。
pp('raw url:',raUrl.toString()) #输出原始URL。
pp('raw url is valid?:',raUrl.isValid()) #是否有效。
raUrlSch=raUrl.scheme() #获取协议。
if !( raUrl.isValid()) #对象未能成功转换成URL。
raUrl=Qt::Url.new('http://'+@urlBr.text()) #目前能够想到的情况就是,纯数字的主机名加上端口号。因此在这里补上一个协议头。
@urlBr.setText(raUrl.toString()) #补上HTTP。显示新的URL内容。
else
if (raUrlSch.empty?) #协议为空,则默认补上http协议。
raUrl.setScheme('http') #补上http协议。
@urlBr.setText(raUrl.toString()) #补上HTTP。显示新的URL内容。
end
end #if (raUrl==nil) #对象不存在。
@wbPg.load(raUrl) #转到对应的页面。
@wbPg.setFocus() #焦点转移到网页中。
end #def GotoUrlBarUrl()
def getUrl()
return @urlBr.text() #返回URL输入条的内容。
end #def getUrl()
def initialize(parent=nil)
super()
@firstTimeLoad=true #是第一次载入。
vLyt=Qt::VBoxLayout.new() #竖直布局器。
setLayout(vLyt) #设置布局器。
@urlBr=Qt::LineEdit.new() #URL输入条。
connect(@urlBr,SIGNAL('returnPressed()'),self,SLOT('gotoUrlBarUrl()')) #按了回车键,则转到URL输入条所指定的URL。
urlLyt=Qt::HBoxLayout.new() #水平布局器。
nvTlBr=Qt::ToolBar.new() #创建工具条。
urlLyt.addWidget(nvTlBr) #添加工具条到布局中。
urlLyt.addWidget(@urlBr) #添加URL输入条。
nwTbBtn=Qt::PushButton.new(tr('New Tab')) #新建标签页按钮。
connect(nwTbBtn,SIGNAL('clicked()'),self,SIGNAL('shouldOpenNewTab()')) #按钮被单击,则发射信号,应当新建空白标签页。
urlLyt.addWidget(nwTbBtn) #添加新建标签页按钮。
vLyt.addLayout(urlLyt) #添加URL布局器。
@wbPg=StbWebView.new() #创建网页视图。
@wbPg.setWebPageWidget(self) #设置自身的指针。
connect(@wbPg,SIGNAL('titleChanged(QString)'),self,SIGNAL('titleChanged(QString)')) #标题变化,则发射标题变化信号。
connect(@wbPg,SIGNAL('iconChanged()'),self,SLOT('indiateIconChanged()')) #图标变化,则发射图标变化信号。
connect(@wbPg,SIGNAL('urlChanged(QUrl)'),self,SLOT('refreshUrl(QUrl)')) #URL变化,则显示新的URL。
connect(@wbPg,SIGNAL('loadStarted()'),self,SLOT('indicateLoadStart()')) #开始载入,则显示载入中。
connect(@wbPg,SIGNAL('loadProgress(int)'),self,SLOT('indicateLoadProgress(int)')) #载入进度变化,则显示进度变化。
connect(@wbPg,SIGNAL('loadFinished(bool)'),self,SLOT('indicateLoadFinished(bool)')) #载入完成,则显示进度变化。
vLyt.addWidget(@wbPg) #添加网页视图。
#导航工具条:
bckAct=@wbPg.pageAction(Qt::WebPage::Back) #获取后退按钮。
nvTlBr.addAction(bckAct) #添加后退按钮。
rldAct=@wbPg.pageAction(Qt::WebPage::Reload) #获取刷新按钮。
connect(rldAct,SIGNAL('triggered()'),self,SLOT('focusWebView()')) #重新载入,则给网页赋予焦点。
nvTlBr.addAction(rldAct) #添加刷新按钮。
end
def setFirstTimeLoad(ftl2St)
@firstTimeLoad=ftl2St #记录。
end #def setFirstTimeLoad(ftl2St)
def setUrl(url2St)
@urlBr.setText(url2St) #显示URL。
end
def startLoad()
@firstTimeLoad=false #不再是第一次载入了。
gotoUrlBarUrl() #载入URL输入栏中的路径。
end #def startLoad()
end | true |
f51e2df31a123e04665b2a35dbbbb8ec7d26c1c9 | Ruby | ianderse/gosu_dodger | /init.rb | UTF-8 | 5,857 | 2.859375 | 3 | [] | no_license | #TODO:
#Add shields (3 per game, icons at the bottom) (done)
#Ability to shoot (done)
#remove explosion gfx after a set amount of time (done)
#scrolling for background
#Powerups
#Extra point drops from enemies
require 'gosu'
require './player'
require './enemy'
require './explosion'
require './bullet'
require './shields'
require 'rubygems'
class GameWindow < Gosu::Window
def initialize width=800, height=600, fullscreen=false
super
self.caption = "Gosu Tutorial"
@song = Gosu::Song.new(self, './data/sound/space.mp3')
@song.play
@explode_sound = Gosu::Sample.new(self, './data/sound/explosion.wav')
@player_shot_sound = Gosu::Sample.new(self, './data/sound/player_shot.wav')
@shields_icon = Gosu::Image.new(self, './data/gfx/shield.png')
@font = Gosu::Font.new(self, Gosu::default_font_name, 20)
@background = Gosu::Image.new(self, './data/gfx/space.png', false)
@player = Player.new(self)
@player.warp(350, 520)
@shield = Shields.new(@player, self)
@enemies = Array.new
@bullets = Array.new
@explodes = Array.new
@powerups = Array.new
@game_is_paused = true
@game_over = false
@frame = 0
end
def reset_game
if @player.score > @player.topscore
@player.topscore = @player.score
end
@player.shield_count = 3
@player.score = 0
@shield.status = false
@enemies.reject! do |enemy|
true
end
@bullets.reject! do |bullet|
true
end
@powerups.reject! do |powerup|
true
end
game_pause_toggle
end
def update
if @game_is_paused == false
@frame += 1
if @shield.status == true
@shield.counter += 1
end
#add new enemy to enemy array
if @player.score > 125
if rand(100) < 15 and @enemies.size < 20
@enemies.push(Enemy.new(self))
end
elsif @player.score > 75 && @player.score < 125
if rand(100) < 8 and @enemies.size < 15
@enemies.push(Enemy.new(self))
end
elsif @player.score < 75
if rand(100) < 4 and @enemies.size < 10
@enemies.push(Enemy.new(self))
end
end
#move enemy
@enemies.each { |enemy| enemy.move }
#move bullets
@bullets.each { |bullet| bullet.move }
#move powerups
@powerups.each { |powerup| powerup.move }
#move player
@player.move_left if self.button_down?(Gosu::KbLeft)
@player.move_right if self.button_down?(Gosu::KbRight)
@shield.move_left if self.button_down?(Gosu::KbLeft)
@shield.move_right if self.button_down?(Gosu::KbRight)
#Collision detection
@enemies.each do |enemy|
if Gosu::distance(enemy.x, enemy.y, @player.x, @player.y) < 40
if @shield.status == true
@enemies.delete(enemy)
@explode_sound.play
@player.score += 5
else
@game_over = true
reset_game
end
end
@bullets.reject! do |bullet|
@enemies.reject! do |enemy|
if Gosu::distance(enemy.x, enemy.y, bullet.x, bullet.y) < 40
@explode_sound.play
@explodes.push(Explosion.new(enemy, self))
@player.score += 5
enemy.drop_powerup(@powerups, enemy, self)
true
end
end
end
end
@powerups.each do |powerup|
if Gosu::distance(powerup.x, powerup.y, @player.x, @player.y) < 30
if @player.shield_count < 3
@player.shield_count += 1
end
@powerups.delete(powerup)
end
end
#remove enemy from array (and screen) when it hits the bottom subtract from player score
@enemies.reject! do |enemy|
if enemy.bottom?
@player.score -= 2
true
else
false
end
end
@powerups.reject! do |powerup|
if powerup.bottom?
true
else
false
end
end
#remove explosion based on time
if @explodes != nil
if @frame > 35
@explodes.shift
@frame = 0
end
end
#remove explosion based on number on scren
if @explodes.size > 5
@explodes.shift
end
end
end
def draw
@background.draw(0,0,0)
@player.draw
@enemies.each { |enemy| enemy.draw }
@bullets.each { |bullet| bullet.draw }
@explodes.each { |exp| exp.draw }
@powerups.each { |powerup| powerup.draw }
@font.draw("Score: #{@player.score}", 10, 10, 1, 1.0, 1.0, 0xffffff00)
@font.draw("Top Score: #{@player.topscore}", 10, 30, 1, 1.0, 1.0, 0xffffff00)
if @game_is_paused
if @game_over
@font.draw("GAME OVER", 265, 280, 1, 2.0, 2.0, 0xffffff00)
else
@font.draw("GAME IS PAUSED", 265, 280, 1, 2.0, 2.0, 0xffffff00)
@font.draw("shift to shoot", 265, 380, 1, 2.0, 2.0, 0xffffff00)
@font.draw("space activates shields", 265, 420, 1, 2.0, 2.0, 0xffffff00)
end
@font.draw("press 'p' to resume", 255, 330, 1, 2.0, 2.0, 0xffffff00)
end
if @shield.status == true
if @shield.counter > 125
@shield.status = false
end
@shield.draw
end
@i = @player.shield_count
while @i > 0
@shields_icon.draw_rot(0+(@i*50), 575, 1, 0, center_x = 0.5, center_y = 0.5, factor_x = 0.25, factor_y = 0.25)
@i -= 1
end
end
def game_pause_toggle
@game_is_paused = !@game_is_paused
end
def button_up(key)
self.close if key == Gosu::KbEscape
if key == Gosu::KbP
@game_over = false
game_pause_toggle
end
if @game_is_paused == false
if key == Gosu::KbLeftShift
@player_shot_sound.play
@bullets.push(Bullet.new(@player, self, 0))
end
if key == Gosu::KbSpace
if @shield.status == false
@shield.toggle
end
end
end
end
end
window = GameWindow.new
window.show | true |
b2d34aed4f4ed3f3d4d91487f894fd9e867ff11e | Ruby | gregors/boilerpipe-ruby | /lib/boilerpipe/filters/density_rules_classifier.rb | UTF-8 | 1,135 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | # Classifies TextBlocks as content/not-content through rules that have been determined
# using the C4.8 machine learning algorithm, as described in the paper
# "Boilerplate Detection using Shallow Text Features", particularly using text densities and link
# densities.
module Boilerpipe::Filters
class DensityRulesClassifier
def self.process(doc)
# return doc if doc.text_blocks.size < 2
empty = Boilerpipe::Document::TextBlock.empty_start
text_blocks = [empty] + doc.text_blocks + [empty]
text_blocks.each_cons(3) do |slice|
prev, current, nxt = *slice
current.content = classify(prev, current, nxt)
end
doc
end
def self.classify(prev, current, nxt)
return false if current.link_density > 0.333333
if prev.link_density <= 0.555556
if current.text_density <= 9
return true if nxt.text_density > 10
return prev.text_density <= 4 ? false : true
else
return nxt.text_density == 0 ? false : true
end
else
return false if nxt.text_density <= 11
true
end
end
end
end
| true |
6cfc82850d8c68770f8bed3fbe69a0115818ea63 | Ruby | chameleon-bi/chambi_oa | /spec/support/login_macros.rb | UTF-8 | 635 | 2.640625 | 3 | [
"MIT"
] | permissive | # Login methods for administrator
module LoginMacros
def login(administrator, initial_path)
visit initial_path
fill_in_details(administrator)
check_path(initial_path)
end
def submit_login
click_button 'Log In'
expect(page).to have_text('Logged in!')
end
private
def fill_in_details(administrator)
fill_in 'login_name', with: administrator.username
fill_in 'password', with: administrator.password
submit_login
end
def check_path(initial_path)
if initial_path == login_path
expect(current_path).to eq(root_path)
else
expect(current_path).to eq(initial_path)
end
end
end
| true |
a33812be8b3d227a6adffd825e6f885b29d8f783 | Ruby | erose357/project_manager | /app/services/forecast.rb | UTF-8 | 646 | 2.921875 | 3 | [] | no_license | class Forecast
attr_reader :high, :low, :conditions, :icon_url, :weekday
def initialize(attrs)
@location = attrs[:date][:tz_long]
@weekday = attrs[:date][:weekday]
@day = attrs[:date][:day]
@month = attrs[:date][:month]
@year = attrs[:date][:year]
@high = attrs[:high][:fahrenheit]
@low = attrs[:low][:fahrenheit]
@conditions = attrs[:conditions]
@icon = attrs[:icon]
@icon_url = attrs[:icon_url]
end
def date
"#{month}/#{day}/#{year}"
end
def city
location.split('/')[1]
end
private
attr_reader :month, :day, :year, :location
end
| true |
911a1bc3fd4f821d2b2a6bd6cb29a7f526d04b7e | Ruby | cuzik/report-generator | /preprocessor.rb | UTF-8 | 1,660 | 3.046875 | 3 | [] | no_license | require 'simple_xlsx_reader'
require 'time'
require 'csv'
def open_xlsx(file_name)
workbook = SimpleXlsxReader.open file_name
report = workbook.sheets.find(name: 'report').first
matrix = []
max_length = 0
report.rows.each { |x| x.length > max_length ? max_length = x.length : nil}
rows = report.rows.map{ |x| x.length < max_length ? x + Array.new(max_length - x.length) : x }
rows[3..-1].each do |row|
row = row.map{ |x| x.to_s.gsub("\nEntrada", "") }
row = row.map{ |x| x.to_s.gsub("\nInício de inter.", "") }
row = row.map{ |x| x.to_s.gsub("\nVolta de inter.", "") }
row = row.map{ |x| x.to_s.gsub("\nSaída", "") }
matrix << [row[0]] + row[2...-4].map{ |x| Time.parse(x) rescue x }
end
matrix
end
def sanitizer(matrix)
new_matrix = []
matrix.each do |row|
data_row = [row[0]]
for i in 1...row.length do
if data_row.last.is_a?(String) || row[i].is_a?(String) || data_row.last <= row[i]
# p data_row.last
# p row[i]
if (!row[i].is_a?(String) || row[i] != "") && row[i] != Time.parse('00:00')
data_row << row[i]
end
end
end
new_matrix << data_row
end
new_matrix
end
def formatter_matrix_to_csv(matrix)
matrix.map { |x| x.map{ |a| a.strftime("%H:%M") rescue a } }
end
def generate_csv(matrix, file_name)
File.write(file_name, formatter_matrix_to_csv(matrix).map(&:to_csv).join)
end
Dir.glob('data/*').select{ |e| File.file? e }.each do |file_name|
p file_name.sub('xlsx', 'csv').sub('data', 'data_csv')
generate_csv(
sanitizer(open_xlsx(file_name)),
file_name.sub('xlsx', 'csv').sub('data', 'data_csv')
)
end
| true |
388630759ea2c43d093bd903cbb9c033fc74e0c3 | Ruby | vma13/University | /Archive/9sem/rtos/rt/chma.rb | UTF-8 | 714 | 3.1875 | 3 | [] | no_license | def main()
arr = []
deadline = []
n = gets.to_i
n.times do
arr << gets.split.map{|x| x.to_i}
end
max = arr[n-1][1]
for i in 0...n
task = arr[i][1]
while task < max
deadline << task
task += arr[i][1]
end
end
deadline << max
deadline = deadline.sort.uniq
for i in 0...deadline.size
task = deadline[i].to_f
s = 0
for j in 0...n
s += (task/arr[j][1]).ceil.to_i*arr[j][0].to_i #ceil - окркгление до ближайшего целого
print "#{(task/arr[j][1]).ceil.to_i}*#{arr[j][0].to_i} "
if j != n-1
print "+ "
end
end
if s > task
print " > "
else
print " <= "
end
print " #{task.to_i}\n"
end
end
main()
| true |
39931ab789de8f2e91395c27386e1f3cd4101283 | Ruby | beegibson/fp-for-rubyists | /mutable_total.rb | UTF-8 | 424 | 3.546875 | 4 | [] | no_license | def mutable_total_cart(items)
total = 0
items.each do |item|
total += item.cost
end
total
end
def recursive_total_cart(items)
head, *tail = items
if tail.empty?
head.cost
else
head.cost + recursive_total_cart(tail)
end
end
def immutable_total_cart(items)
items.inject(0) { |total, item| total + item.cost}
end
class Item
attr_reader :cost
def initialize(cost)
@cost = cost
end
end
| true |
0fe89081d17107d50fd57f541873ce7feba3eb28 | Ruby | stAndrei/the_task | /app/models/statistics.rb | UTF-8 | 2,438 | 2.671875 | 3 | [
"MIT"
] | permissive | class Statistics
def revenue
gross_sales - payouts
end
def rejection_rate
count_jobs('rejected') / count_jobs(%w(accepted done)) * 100
end
def predicted_revenue(future_date)
forecast, sigma = get_forecast(future_date)
{
forecast: forecast,
sigma: sigma,
best: forecast + sigma,
worse: forecast - sigma
}
end
def user_stats(from, to)
{
best_clients: top_client('revenue desc', from, to),
worse_clients: top_client('revenue asc', from, to),
best_subcontractor: best_subcontractor(from, to),
worse_overdue_client: worse_overdue_client(from, to)
}
end
private
def payouts
SubcontractorPayout.sum(:amount)
end
def gross_sales
Invoice.sum(:paid_amount)
end
def count_jobs(status)
Job.where(status: status).count.to_f
end
def get_forecast(future_date)
line_fit = LineFit.new
days, revenues = sum_revenue_by_day
line_fit.setData(days, revenues)
forecast = line_fit.forecast(future_date.to_date.mjd) - revenues.last
sigma = line_fit.sigma
[forecast, sigma]
end
def sum_revenue_by_day
@revenue_by_day ||= Job.joins(:invoice, :subcontractor_payout)
.select('end_date, sum(amount) - sum(paid_amount) as revenue')
.group(:end_date)
.order(:end_date)
days = []
revenues = []
sum_revenue = 0
@revenue_by_day.each do |day|
sum_revenue += day.revenue
days << day.end_date.mjd
revenues << sum_revenue
end
[days, revenues]
end
def top_client(order, from, to)
Client.joins(jobs: [:invoice, :subcontractor_payout])
.where(jobs: {end_date: from..to})
.group('jobs.client_id')
.select('clients.*, sum(amount) - sum(paid_amount) as revenue')
.order(order)
.limit(5)
end
def best_subcontractor(from, to)
Subcontractor.joins(jobs: [:invoice, :subcontractor_payout])
.select('subcontractors.*, sum(amount) - sum(paid_amount) as revenue')
.where(jobs: {end_date: from..to})
.group('jobs.subcontractor_id')
.order('revenue desc')
.first
end
def worse_overdue_client(from, to)
Client.joins(jobs: :invoice)
.select('clients.*, sum(julianday(CURRENT_DATE) - julianday(jobs.end_date)) as overdue')
.where(jobs: {end_date: from..to}, invoices: {status: :overdue})
.group('invoices.client_id')
.order('overdue desc')
.first
end
end
| true |
258f0bacdafd2185e7b171dfbb811ab71a1cf2ac | Ruby | jeanbahnik/exercism | /ruby/leap/leap.rb | UTF-8 | 194 | 3.46875 | 3 | [] | no_license | class Year
def self.leap?(year)
answer = false
answer = true if year % 4 == 0
answer = false if (year % 100 == 0 && year % 400 != 0)
return answer
end
end | true |
f193cb62110b3bd07c9cba7725cdc7f1e3cbe023 | Ruby | jef-abraham/arabic2english | /spec/arabic2english_spec.rb | UTF-8 | 2,671 | 3.140625 | 3 | [] | no_license | require 'spec_helper'
require_relative '../arabic2english'
describe "arabic2english" do
it "should reply 'one'" do
expect(get_full_word(1)).to eq('one')
end
it "should reply 'two'" do
expect(get_full_word(2)).to eq('two')
end
it "should reply 'five'" do
expect(get_full_word(5)).to eq('five')
end
it "should reply 'eleven'" do
expect(get_full_word(11)).to eq('eleven')
end
it "should reply 'twenty'" do
expect(get_full_word(20)).to eq('twenty')
end
it "should reply 'twenty one'" do
expect(get_full_word(21)).to eq('twenty one')
end
it "should reply 'thirty one'" do
expect(get_full_word(31)).to eq('thirty one')
end
it "should reply 'fourty one'" do
expect(get_full_word(41)).to eq('fourty one')
end
it "should reply 'ninety one'" do
expect(get_full_word(91)).to eq('ninety one')
end
it "should reply 'ninety five'" do
expect(get_full_word(95)).to eq('ninety five')
end
it "should reply 'one hundred'" do
expect(get_full_word(100)).to eq('one hundred')
end
it "should reply 'one hundred thirty'" do
expect(get_full_word(130)).to eq('one hundred thirty')
end
it "should reply 'one hundred ninety nine'" do
expect(get_full_word(199)).to eq('one hundred ninety nine')
end
it "should reply 'two hundred'" do
expect(get_full_word(200)).to eq('two hundred')
end
it "should reply 'two hundred fifty'" do
expect(get_full_word(250)).to eq('two hundred fifty')
end
it "should reply 'one thousand'" do
expect(get_full_word(1000)).to eq('one thousand')
end
it "should reply 'two thousand'" do
expect(get_full_word(2000)).to eq('two thousand')
end
it "should reply 'nine thousand nine hundred ninety nine'" do
expect(get_full_word(9999)).to eq('nine thousand nine hundred ninety nine')
end
it "should reply 'twenty three thousand'" do
expect(get_full_word(23000)).to eq('twenty three thousand')
end
it "should reply 'one lakhs'" do
expect(get_full_word(100000)).to eq('one lakhs')
end
it "should reply 'one lakhs one'" do
expect(get_full_word(100001)).to eq('one lakhs one')
end
it "should reply 'one lakhs twenty three thousand four hundred fifty six'" do
expect(get_full_word(123456)).to eq('one lakhs twenty three thousand four hundred fifty six')
end
it "should reply 'one crore'" do
expect(get_full_word(10000000)).to eq('one crore')
end
it "should reply 'nine crore ninety nine lakhs ninety nine thousand nine hundred ninety nine'" do
expect(get_full_word(99999999)).to eq('nine crore ninety nine lakhs ninety nine thousand nine hundred ninety nine')
end
end
| true |
c2efd0d4c426f44175df77d61a4a440a90a4b2c3 | Ruby | sarceneaux/study-hall-classwork | /pal.rb | UTF-8 | 243 | 4.09375 | 4 | [] | no_license | #this is my comment for you to find later
puts "Enter a word. We'll see if it's a palindrome"
word = gets.chomp
reverseWord = word.reverse
if reverseWord == word
puts "#{word} is a palindrome"
else
puts "#{word} is NOT a palindrome"
end
| true |
71aa6c3b4c947c5e9d44090fed2ddcd7756dbff9 | Ruby | b-studios/doc.js | /lib/generator/generator.rb | UTF-8 | 8,412 | 3.109375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require_relative '../renderer'
require_relative '../dom/dom'
require_relative '../helper/helper'
module Generator
# If you already familiar with Ruby on Rails: Generators are pretty much like Controllers in Rails.
# That's like in Rails:
#
# - They use the existing data-model (The {Dom} in our case)
# - They start the rendering process in a view, by calling {Renderer#render render}.
# - If you want to make use of data in a view, you can store it in an instance-variable, like `@nodes`
# - Helpers are included in the generator, so you can utilize their messages in views
#
# The major difference between controllers in Rails and generators in DocJs is, that DocJs triggers
# all generators one after another and there is no real interaction between the views and the
# generator.
#
# In other words, after collecting all necessary informations about the JavaScript-Files and
# Markdown-Documents DocJs uses the Generators to create the final output.
#
# @example a simple generator
# module Generator
# class MyTestGenerator < Generator
# # For more information about those methods, see section Generator-Specification methods
# describe 'does awesome things'
# layout 'application'
# start_method :go
# templates '/views/special_ones'
#
# protected
#
# def go
# in_context Dom.root do
# @elements = []
# Dom.root.each_child do |child|
# @elements << child unless child.is_a? Dom::NoDoc
# end
#
# render 'my_view', :to_file => 'output_file.html'
# end
# end
# end
# end
#
# The following image should help you to get a general overview, how the components of DocJs interact:
#
# 
#
# One may notice, that {Renderer} and {Generator::Generator} are not that separable, as shown in this
# image. In fact the concrete Generator (like {Generator::ApiIndexGenerator}) inherits from
# {Generator::Generator}, which in turn inherits from {Renderer}.
# So we've got an inheritence-chain like:
#
# Generator::ApiIndexGenerator < Generator::Generator < Renderer
#
# Helpers
# -------
# You can create your own helper functions, bundled in a custom helper-module. They automatically
# will be mixed in all Generators, as long as they match the following conditions:
#
# - Your module has to be a Submodule of Helper
# - Your code has to be included somewhere (i.e. `require 'my_helper'` in `application.rb`)
#
# For example your helper could look like:
#
# # TEMPLATE_PATH/helpers/my_helper.rb
# module Helper::MyHelper
# def my_greeter
# "Hello Woooorld"
# end
# end
#
# # TEMPLATE_PATH/application.rb
# require_relative 'helpers/my_helper'
#
# Then you could use them in your Generator or in your Views
#
# # TEMPLATE_PATH/views/template.html.erb
# <h1><%= my_greeter %></h1>
class Generator < Renderer
def initialize
# At this point we pass the configurations to our Parent `Renderer`
super(Configs.templates + configs(:templates), configs(:layout))
# include all Helpers
Helper.constants
.map { |c| Helper.const_get c }
.each { |mod| extend mod if mod.is_a? Module }
# Set Global Context to Dom's root node
@_context = Dom.root
end
# @group Generator-Specification methods
# This description is used in the cli-command `docjs generators` to list all generators and their
# descriptions
#
# @param [String] desc A short description of this generators task
def self.describe(desc)
self.set_config(:description, desc.to_s)
end
# Specifies which layout should be used to render in (Default is `nil`)
#
# @param [String] layout_view
def self.layout(layout_view)
unless layout_view.nil?
self.set_config(:layout, 'layout/' + layout_view)
else
self.set_config(:layout, nil)
end
end
# Which method should be invoked, if generator is executed (Default is `:index`)
#
# @param [String, Symbol] method
def self.start_method(method)
self.set_config(:start_method, method.to_sym)
end
# The path to your views (Default is `/views`)
#
# You can use this method, to specify a special template path, for example if you want to use
# a subdirectory of your views, without always having to provide the full path in all `render`-calls
#
# @note the layout-path is always relative to your specified path (i.e. `layout 'application'`
# and `templates 'my_custom'` will result in a required layout file with a path like
# `my_custom/layout/application.html.erb`
#
# @param [String] path_to_views Relative path from your scaffolded template-directory, but with
# a leading `/`, like `/views/classes`
def self.templates(path_to_views)
self.set_config(:templates, path_to_views)
end
# @note not neccesarily needed, because all Helpers are included by default
#
# Can be used to include a helper in a Generator
def self.use(helper_module)
include helper_module
end
# @group Context manipulation- and access-methods
# Modyfies the Dom-resolution-context {#context} to `new_context`, while in `&block`. After
# leaving the block, the context will be switched back.
#
# @param [Dom::Node] new_context The new context
# @yield block The block, in which the context is valid
def in_context(new_context, &block)
old_context = @_context
@_context = new_context
yield
@_context = old_context
end
# Retreives the current Dom-resolution-context, which can be specified by using {#in_context}
#
# @return [Dom::Node] the context, to which all relative nodes should be resolved
def context
@_context
end
# Resolves a nodename in the specified context, by using {Dom::Node#resolve} on it.
#
# @param [String] nodename
# @return [Dom::Node, nil]
# @see Dom::Node#resolve
def resolve(nodename)
@_context.resolve nodename
end
# @group System-Methods
# Calls always the specified `:start_method` on this Generator. (Default for :start_method is
# 'index')
def perform
unless self.respond_to? configs(:start_method)
raise Exception, "#{self.class} needs to implement specified start-method '#{configs(:start_method)}'"
end
self.send configs(:start_method)
end
# Is used by {DocJs#generators} to provide a list of all generators and their descriptions
#
# @return [String] description, which has been previously entered using `.describe`
def self.description
configs(:description)
end
# Returns all Generators, by finding all constants in the Generator-Module and filtering them
# for classes with parent {Generator::Generator}.
#
# @return [Array<Generator>]
def self.all
# Otherwise we don't get the global Generator-Module
gen_module = Object.const_get(:Generator)
gen_module.constants
.map { |c| gen_module.const_get c }
.select { |klass| klass.class == Class and klass.superclass == self }
end
protected
# @group helper methods to make usage of class-variables work in **inheriting** classes
def self.configs(attribute)
key = "@@_configs_#{attribute.to_s}".to_sym
defaults = {:templates => '/views',
:layout => nil,
:description => 'No description given.',
:start_method => :index }
if self.class_variable_defined? key
self.class_variable_get(key)
else
defaults[attribute.to_sym]
end
end
# the instance equivalent to get the class-variable of the **inheriting** class
def configs(*args)
self.class.configs(*args)
end
def self.set_config(attribute, value)
key = "@@_configs_#{attribute.to_s}".to_sym
self.class_variable_set(key, value)
end
end
end | true |
f921fc7c3e3488f6f4639aa4231661015e7169bd | Ruby | jamesxuhaozhe/learn-ruby | /ex12.rb | UTF-8 | 160 | 2.75 | 3 | [] | no_license | first, second, third = ARGV
puts "This is the first argument #{first}"
puts "This is the second argument #{second}"
puts "This is the thrid argument #{third}"
| true |
231bc5a020b592b3c6b87ba89e3eaae79392d49f | Ruby | ivar/magic-search-engine | /lib/indexer.rb | UTF-8 | 12,763 | 2.578125 | 3 | [] | no_license | require "date"
require "ostruct"
require "json"
require "set"
require "pathname"
require "pry"
require_relative "ban_list"
require_relative "format/format"
require_relative "indexer/card_set"
require_relative "indexer/oracle_verifier"
require_relative "indexer/foreign_names_verifier"
# ActiveRecord FTW
class Hash
def slice(*keys)
keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) }
end
def compact
reject{|k,v| v.nil?}
end
def map_values
result = {}
each do |k,v|
result[k] = yield(v)
end
result
end
end
class Pathname
def write_at(content)
parent.mkpath
write(content)
end
end
class Indexer
def initialize
json_path = Pathname(__dir__) + "../data/AllSets-x.json"
@data = JSON.parse(json_path.read)
end
def format_names
[
"battle for zendikar block",
"commander",
"ice age block",
"innistrad block",
"invasion block",
"kamigawa block",
"legacy",
"lorwyn-shadowmoor block",
"masques block",
"mirage block",
"mirrodin block",
"modern",
"odyssey block",
"onslaught block",
"ravnica block",
"return to ravnica block",
"scars of mirrodin block",
"shards of alara block",
"shadows over innistrad block",
"standard",
"tarkir block", # mtgjson inconsistently calls it khans of tarkir block sometimes
"tempest block",
"theros block",
"time spiral block",
"un-sets",
"urza block",
"vintage",
"zendikar block",
]
end
def formats
@formats ||= Hash[
format_names.map{|n| [n, Format[n].new]}
]
end
def algorithm_legalities_for(card_data)
result = {}
sets_printed = card_data["printings"].map{|set_code| @sets_code_translator[set_code]}
card = OpenStruct.new(
name: normalize_name(card_data["name"]),
layout: card_data["layout"],
printings: sets_printed.map{|set_code|
OpenStruct.new(set_code: set_code)
},
)
formats.each do |format_name, format|
status = format.legality(card)
result[format_name] = status if status
end
result
end
def save_all!(path)
path = Pathname(path)
path.parent.mkpath
path.write(prepare_index.to_json)
end
def index_card_data(card_data)
# mtgjson is being silly here
if card_data["name"] == "B.F.M. (Big Furry Monster)"
card_data["text"] = "You must play both B.F.M. cards to put B.F.M. into play. If either B.F.M. card leaves play, sacrifice the other.\nB.F.M. can be blocked only by three or more creatures."
card_data["cmc"] = 15
card_data["power"] = "99"
card_data["toughness"] = "99"
card_data["manaCost"] = "{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}{B}"
card_data["types"] = ["Creature"]
card_data["subtypes"] = ["The-Biggest-Baddest-Nastiest-Scariest-Creature-You'll-Ever-See"]
card_data["colors"] = ["Black"]
end
if card_data["names"]
# https://github.com/mtgjson/mtgjson/issues/227
if card_data["name"] == "B.F.M. (Big Furry Monster)"
# just give up on this one
elsif card_data["layout"] == "split"
# All primary
elsif card_data["layout"] == "double-faced"
if card_data["manaCost"] or card_data["name"] == "Westvale Abbey"
# Primary side
else
card_data["secondary"] = true
end
elsif card_data["layout"] == "flip"
raise unless card_data["number"] =~ /[ab]\z/
card_data["secondary"] = true if card_data["number"] =~ /b\z/
elsif card_data["layout"] == "meld"
if card_data["manaCost"] or card_data["name"] == "Hanweir Battlements"
# Primary side
else
card_data["secondary"] = true
end
else
binding.pry
end
end
printings = card_data["printings"].map{|set_code| @sets_code_translator[set_code]}
# arena/rep are just reprints, and some are uncards
if printings.all?{|set_code| %W[uh ug uqc hho arena rep].include?(set_code) }
funny = true
else
funny = nil
end
card_data.slice(
"name",
"names",
"power",
"toughness",
"loyalty",
"manaCost",
"text",
"types",
"subtypes",
"supertypes",
"cmc",
"layout",
"reserved",
"hand", # vanguard
"life", # vanguard
"rulings",
"secondary",
).merge(
"printings" => [],
"colors" => format_colors(card_data["colors"]),
"funny" => funny
).compact
end
def index_printing_data(card_data)
if card_data["name"] == "B.F.M. (Big Furry Monster)"
card_data["flavor"] = %Q["It was big. Really, really big. No, bigger than that. Even bigger. Keep going. More. No, more. Look, we're talking krakens and dreadnoughts for jewelry. It was big"\n-Arna Kennerd, skyknight]
end
card_data.slice(
"flavor",
"artist",
"border",
"timeshifted",
"number",
"multiverseid",
).merge(
"rarity" => format_rarity(card_data["rarity"]),
"release_date" => Indexer.format_release_date(card_data["releaseDate"]),
"watermark" => format_watermark(card_data["watermark"]),
).compact
end
def report_legalities_fail(name, mtgjson_legalities, algorithm_legalities)
@reported_fail ||= {}
return if @reported_fail[name]
@reported_fail[name] = true
mtgjson_legalities = mtgjson_legalities.sort
algorithm_legalities = algorithm_legalities.sort
puts "FAIL #{name}"
unless (mtgjson_legalities - algorithm_legalities).empty?
puts "Extra formats (mtgjson):"
puts (mtgjson_legalities - algorithm_legalities).map(&:inspect)
end
unless (algorithm_legalities - mtgjson_legalities).empty?
puts "Extra formats (algo):"
puts (algorithm_legalities - mtgjson_legalities).map(&:inspect)
end
puts ""
end
def prepare_index
sets = {}
cards = {}
card_printings = {}
@sets_code_translator = {}
foreign_names_verifier = ForeignNamesVerifier.new
oracle_verifier = OracleVerifier.new
@data.each do |set_code, set_data|
@sets_code_translator[set_code] = set_data["magicCardsInfoCode"] || set_data["code"].downcase
end
@data.each do |set_code, set_data|
set_code = @sets_code_translator[set_code]
set = Indexer::CardSet.new(set_code, set_data)
sets[set_code] = set.to_json
# This is fixed in new mtgjson, but we must rollback:
set_data["cards"].each do |card_data|
card_data["name"].gsub!("Æ", "Ae")
end
set.ensure_set_has_card_numbers!
set_data["cards"].each do |card_data|
name = card_data["name"]
sets_printed = card_data["printings"].map{|set_code2| @sets_code_translator[set_code2]}
mtgjson_legalities = format_legalities(card_data)
# It seems incorrect
if sets_printed == ["cns"] or sets_printed == ["cn2"]
mtgjson_legalities["commander"] = mtgjson_legalities["vintage"]
end
if mtgjson_legalities["khans of tarkir block"]
mtgjson_legalities["tarkir block"] = mtgjson_legalities.delete("khans of tarkir block")
end
algorithm_legalities = algorithm_legalities_for(card_data)
if mtgjson_legalities != algorithm_legalities
report_legalities_fail(name, mtgjson_legalities, algorithm_legalities)
end
card = index_card_data(card_data)
oracle_verifier.add(set_code, card)
card_printings[name] ||= []
card_printings[name] << [set_code, index_printing_data(card_data)]
foreign_names_verifier.add name, set_code, card_data["foreignNames"]
end
end
oracle_verifier.verify!
card_printings.each do |card_name, printings|
cards[card_name] = oracle_verifier.canonical(card_name).merge("printings" => printings)
end
foreign_names_verifier.verify!
# Link foreign names
cards.each do |card_name, card|
foreign_names = foreign_names_verifier.foreign_names(card_name)
card["foreign_names"] = foreign_names if foreign_names
end
# This is apparently real, but mtgjson has no other side
# http://i.tcgplayer.com/100595_200w.jpg
[
"Chandra, Fire of Kaladesh",
"Jace, Vryn's Prodigy",
"Kytheon, Hero of Akros",
"Liliana, Heretical Healer",
"Nissa, Vastwood Seer",
].each do |card_name|
cards[card_name]["printings"].delete_if{|c,| c == "ptc"}
end
# Fixing printing dates of promo cards
cards.each do |name, card|
# Prerelease
ptc_printing = card["printings"].find{|c,| c == "ptc" }
# Release
mlp_printing = card["printings"].find{|c,| c == "mlp" }
# Gameday
mgdc_printing = card["printings"].find{|c,| c == "mgdc" }
# Media inserts
mbp_printing = card["printings"].find{|c,| c == "mbp" }
real_printings = card["printings"].select{|c,| !["ptc", "mlp", "mgdc", "mbp"].include?(c) }
guess_date = real_printings.map{|c,d| d["release_date"] || sets[c]["release_date"] }.min
if ptc_printing and not ptc_printing[1]["release_date"]
raise "No guessable date for #{name}" unless guess_date
guess_ptc_date = (Date.parse(guess_date) - 6).to_s
ptc_printing[1]["release_date"] = guess_ptc_date
end
if mlp_printing and not mlp_printing[1]["release_date"]
raise "No guessable date for #{name}" unless guess_date
mlp_printing[1]["release_date"] = guess_date
end
if mgdc_printing and not mgdc_printing[1]["release_date"]
raise "No guessable date for #{name}" unless guess_date
mgdc_printing[1]["release_date"] = guess_date
end
if mbp_printing and not mbp_printing[1]["release_date"]
raise "No guessable date for #{name}" unless guess_date
mbp_printing[1]["release_date"] = guess_date
end
end
# Output in canonical form, to minimize diffs between mtgjson updates
cards = Hash[cards.sort]
cards.each do |name, card|
card["printings"] = card["printings"].sort_by{|sc,d| [sets.keys.index(sc),d["number"],d["multiverseid"]] }
end
# Fix DFC cmc
cards.each do |name, card|
next unless card["layout"] == "double-faced" and not card["cmc"]
other_names = card["names"] - [name]
raise "DFCs should have 2 names" unless other_names.size == 1
other_cmc = cards[other_names[0]]["cmc"]
if other_cmc
card["cmc"] = other_cmc
else
# Westvale Abbey / Ormendahl, Profane Prince has no cmc on either side
end
end
# Unfortunately mtgjson changed its mind,
# and there's no way to distinguish front and back side of melded cards
[
"Brisela, Voice of Nightmares",
"Hanweir, the Writhing Township",
"Chittering Host",
].each do |melded|
parts = cards[melded]["names"] - [melded]
parts.each do |n|
cards[n]["names"] -= (parts - [n])
end
end
# CMC of melded card is sum of front faces
cards.each do |name, card|
next unless card["layout"] == "meld"
other_names = card["names"] - [name]
next unless other_names.size == 2 # melded side
other_cmcs = other_names.map{|other_name| cards[other_name]["cmc"]}
card["cmc"] = other_cmcs.compact.inject(0, &:+)
end
{"sets"=>sets, "cards"=>cards}
end
def format_watermark(watermark)
watermark && watermark.downcase
end
def format_rarity(rarity)
r = rarity.downcase
if r == "mythic rare"
"mythic"
elsif r == "basic land"
"basic"
else
r
end
end
def format_legalities(card_data)
legalities = card_data["legalities"]
return {} if card_data["layout"] == "token"
Hash[
(legalities||[])
.map{|leg|
[leg["format"].downcase, leg["legality"].downcase]
}
.reject{|fmt, leg|
["classic", "prismatic", "singleton 100", "freeform", "tribal wars legacy", "tribal wars standard"].include?(fmt)
}
]
end
def format_colors(colors)
color_codes = {"White"=>"w", "Blue"=>"u", "Black"=>"b", "Red"=>"r", "Green"=>"g"}
(colors||[]).map{|c| color_codes.fetch(c)}.sort.join
end
def normalize_name(name)
name.gsub("Æ", "Ae").tr("Äàáâäèéêíõöúûü", "Aaaaaeeeioouuu")
end
# FIXME: This really shouldn't be here
def self.format_release_date(date)
return nil unless date
case date
when /\A\d{4}-\d{2}-\d{2}\z/
date
when /\A\d{4}-\d{2}\z/
"#{date}-01"
when /\A\d{4}\z/
"#{date}-01-01"
else
raise "Release date format error: #{date}"
end
end
end
| true |
fc067b6a9e05b8229ec0ef08757be2f59fea3a41 | Ruby | Wertster/fsm | /helpers/fsm_event_source.rb | UTF-8 | 1,224 | 2.9375 | 3 | [
"CC0-1.0"
] | permissive | require 'yaml'
require 'socket'
require_relative 'fsm_const'
require_relative 'fsm_event'
#Utility mixin, with event handling methods
module FsmEventSource
#Include constants into this module namespace
include FsmConst
#Establshes binding to a datagram socket on localhost
def fsm_listen
@socket ||= UDPSocket.new
@socket.bind(IP_ADDR, UDP_PORT)
end
#Take an event identifier and data/message, instantiate and serialise event object to send
def fsm_raise(event, data=nil)
#Instantiate socket object if not already an instance variable
@socket ||= UDPSocket.new
#Instntiate event object with the event and data
evt = FsmEvent.new(event, data)
#Serialise event object to YAML for transport
yml = YAML.dump(evt)
#Send it...
@socket.send(yml, 0, IP_ADDR, UDP_PORT)
end
#Read and parse an event off the socket and parse YAML into object
def fsm_read
#Blocking listen on the socket it not already listening
fsm_listen if @socket.nil?
#Pull the next message from the inbound socket
raw = @socket.recvfrom(1024)
#Extract the first segment from the message object
raw_msg = raw.first
#De-serialise back into Event object
evt=YAML.load(raw_msg)
#Return it
return evt
end
end | true |
97efd03b606342835fd074ae3c1d7e5cbcf90c7b | Ruby | ravihebbar6/problem-solving | /ruby/problems/stack_test.rb | UTF-8 | 173 | 2.890625 | 3 | [] | no_license | require '../data_structures/stack.rb'
x = Stack.new([])
p x.list
x.push(1)
p x.list
x.push(2)
p x.list
x.push(3)
p x.list
x.pop
p x.list
x.pop
p x.list
x.pop
p x.list | true |
4c0136cc95b94ea23600c053f50e6d8ee71c46e4 | Ruby | corntrace/sleeve | /lib/Sleeve.rb | UTF-8 | 913 | 3.265625 | 3 | [] | no_license | module Sleeve
def push_into_sleeve_pocket(obj, label='')
@sleeve_pocket = @sp ||= SleevePocket.new
@sp.push(obj, label)
end
def fetch_from_sleeve_pocket(label, obj=nil)
@sleeve_pocket.fetch(label)
end
end
class SleevePocket
# attributes that we would try one by one on a model
@@tries = [:title, :name, :username, :user_name, :email]
def initialize
@pocket = {}
end
def push(obj, label='')
if label.blank?
# need to guess the label
@pocket[guess_the_label(obj)] = obj
else
@pocket[label] = obj
end
end
def guess_the_label(obj)
@@tries.each do |item|
return obj.send(item) if obj.respond_to?(item)
end
raise "You have to pass a label to #{obj}"
end
# def build_and_push(type, label)
# @pocket[label] = type.classify.constantize.new
# end
#
def fetch(label)
@pocket[label]
end
end | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.