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 |
---|---|---|---|---|---|---|---|---|---|---|---|
bcf8a94f1cc9cf612b32c4e3e15e51e07729c093
|
Ruby
|
cmarshall10450/week-2-day-2-snakes-and-ladders
|
/specs/Dice.spec.rb
|
UTF-8
| 366 | 3.0625 | 3 |
[] |
no_license
|
require('minitest/autorun')
require_relative('../Dice')
class TestDice < MiniTest::Test
def setup
@dice = Dice.new()
end
def test_has_6_sides
assert_equal(6, @dice.sides.count)
end
def test_dice_rolls_random_number_between_1_and_6
result = @dice.roll
possible_nums = [1, 2, 3, 4, 5, 6]
assert_equal(true, possible_nums.include?(result))
end
end
| true |
a62bd0c3d71ce813cbb4f201c2e201d449e8408a
|
Ruby
|
datamapper/dm-adjust
|
/lib/dm-adjust/collection.rb
|
UTF-8
| 1,411 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
module DataMapper
class Collection
def adjust(attributes = {}, reload = false)
raise NotImplementedError, 'adjust *with* validations has not be written yet, try adjust!'
end
##
# increment or decrement attributes on a collection
#
# @example [Usage]
# * People.all.adjust(:salary => +1000)
# * Children.all(:age.gte => 18).adjust(:allowance => -100)
#
# @param attributes <Hash> A hash of attributes to adjust, and their adjustment
# @param reload <FalseClass,TrueClass> If true, affected objects will be reloaded
#
# @api public
def adjust!(attributes = {}, reload = false)
return true if attributes.empty?
reload_conditions = if reload
model_key = model.key(repository.name)
Query.target_conditions(self, model_key, model_key)
end
adjust_attributes = adjust_attributes(attributes)
repository.adjust(adjust_attributes, self)
if reload_conditions
@query.clear
@query.update(:conditions => reload_conditions)
self.reload
end
true
end
private
def adjust_attributes(attributes)
adjust_attributes = {}
model.properties(repository.name).values_at(*attributes.keys).each do |property|
adjust_attributes[property] = attributes[property.name]
end
adjust_attributes
end
end # Collection
end # DataMapper
| true |
5c33b122da59f1f9cc015298acdcf1847c25a470
|
Ruby
|
murdens/Ruby
|
/prog5.rb
|
UTF-8
| 209 | 3.25 | 3 |
[] |
no_license
|
str =''
while str != 'BYE'
#puts 'Hi, Sonny'
str = gets.chomp
if str == str.upcase
puts 'NO, NOT SINCE ' + rand(1930..1951).to_s+'!'
else puts 'HUH?! SPEAK UP, SONNY!'
end
end
| true |
cd84625924da25709ca86d4273a010534544e2be
|
Ruby
|
geckods/CodeForces
|
/ED59/b.rb
|
UTF-8
| 209 | 2.9375 | 3 |
[] |
no_license
|
if File.exists?("input")
$stdin = File.open("input")
$stdout = File.open("output","w")
end
n = gets.to_i
n.times do
kx = gets.chomp.split(" ").map(&:to_i)
k = kx[0]
x = kx[1]
puts 9*(k-1) + x
end
| true |
7c6c893ead7e1b096e16769e6fcf3972b7966521
|
Ruby
|
alexg622/project_euler_app_academy
|
/problem_fifteen.rb
|
UTF-8
| 224 | 3.234375 | 3 |
[] |
no_license
|
# Lattice Paths
# Problem 15
def lattice_paths(num_one, num_two)
total_moves = num_one + num_two
(1..total_moves).inject(:*) / (1..num_two).inject(:*) / ((1..num_one).inject(:*))
end
lattice_paths(20, 20)
# 137846528820
| true |
3a801e39550e986622612614921f763f16c479b9
|
Ruby
|
Neetha11/Test
|
/stud_string.rb
|
UTF-8
| 1,248 | 3.796875 | 4 |
[] |
no_license
|
final = ""
for i in 0..2
puts "Enter the student first name"
first_name = gets.chomp
puts "Enter the student second name"
second_name =gets.chomp
puts "Enter their marks"
marks=gets.chomp
final = final.concat(first_name.concat(second_name).concat('$').concat(marks).concat('$'))
end
puts final
final_split = final.split('$')
puts "Enter the name to get the mark"
get_mark = gets.chomp
result = final_split.index(get_mark)
dis_mark = result +1
puts final_split[dis_mark]
puts "Enter the name to delte the mark"
get_name = gets.chomp
search_name = final_split.index(get_name) + 1
del_mark = final_split[search_name]
final_split.delete(get_name)
final_split.delete(del_mark)
final_join = final_split.join('$')
puts final_join
puts "students with mark > 70 ::\n"
for i in (0..final_split.length)
if i % 2 != 0
if final_split[i].to_i > 70
puts final_split[i-1]
end
end
end
puts "descending order of their marks"
name_sort = final_split.sort
puts name_sort
| true |
d1895c8b785cb704eecd722f7e7f31e776366bbb
|
Ruby
|
charliepatronr/rails-challenge-practice-chi01-seng-ft-080320
|
/app/models/company.rb
|
UTF-8
| 1,551 | 2.59375 | 3 |
[] |
no_license
|
class Company < ApplicationRecord
has_many :offices
has_many :buildings, through: :offices
has_many :employees
accepts_nested_attributes_for :offices
#why did office_ids work? Does this validation take care of both office_id and company_id???
validates :name, :office_ids, presence: true
def offices_attributes=(office_attributes)
office_attributes.each do |key, value|
building = value["id"].to_i
floor_arr = value["offices"]
floor_arr = floor_arr.reject(&:blank?)
floor_arr.each do |floor|
office = Office.create(building_id: building, floor: floor )
self.offices << office
end
end
end
def buildings_and_offices
building_and_office = {}
buildings = self.buildings.uniq
offices = self.offices
buildings.each do |building|
offices_arr = []
offices.each do |office|
if( building.id == office.building_id)
offices_arr << office.floor
end
building_and_office[building.name] = offices_arr
end
end
building_and_office
end
def total_rent
building_office = self.buildings_and_offices
total = 0
building_office.each do |key, value|
building = Building.find_by(name: key)
value.each do |floor|
total += building.rent_per_floor
end
end
total
end
end
| true |
27e8625158aa6704a6f4135b4e8c0b7d532376b4
|
Ruby
|
emomax/AdventOfCode2015
|
/dec8/task1/main.rb
|
UTF-8
| 1,995 | 3.703125 | 4 |
[] |
no_license
|
#################
# Pieslicer #
# 2015 #
#################
## --- Day 8, task 1: Matchsticks ---
# Space on the sleigh is limited this year, and
# so Santa will be bringing his list as a digital
# copy. He needs to know how much space it will
# take up when stored.
# It is common in many programming languages to
# provide a way to escape special characters in
# strings. For example, C, JavaScript, Perl, Python,
# and even PHP handle special characters in very similar ways.
# However, it is important to realize the difference
# between the number of characters in the code
# representation of the string literal and the number
# of characters in the in-memory string itself.
# Santa's list is a file that contains many double-quoted
# string literals, one on each line. The only escape
# sequences used are \\ (which represents a single backslash),
# \" (which represents a lone double-quote character),
# and \x plus two hexadecimal characters (which represents
# a single character with that ASCII code).
# Disregarding the whitespace in the file, what is the
# number of characters of code for string literals
# minus the number of characters in memory for the
# values of the strings in total for the entire file?
# ****** FUNCTIONS ****** #
def parseRow(row)
literalLength = row.length
inMemoryLength = 0
stripped = row
stripped[row.length - 1] = ""
stripped[0] = ""
if stripped.match /\\x[a-f0-9]{2}/
stripped.gsub! /\\x[a-f0-9]{2}/, "\."
end
if stripped.match /\\\\/
stripped.gsub! /\\\\/, "\\"
end
if stripped.match /\\"/
stripped.gsub! /\\"/, "\""
end
return literalLength, stripped.length
end
# ******** BODY ********* #
stringLiterals = 0
inMemory = 0
file = File.new("input.txt", "rb")
while row = file.gets# and $line < 30
row.strip!
literal, inMem = parseRow(row)
stringLiterals = stringLiterals + literal
inMemory = inMemory + inMem
end
file.close
size = stringLiterals - inMemory
puts "Size of Santa's list: " + size.to_s
| true |
0caa5d1dbf79e52878bac4f456a637bd6b3e659d
|
Ruby
|
strivedi183/wdi3-rails
|
/r2013-03-08-tradr/app/models/stock.rb
|
UTF-8
| 778 | 2.78125 | 3 |
[] |
no_license
|
# == Schema Information
#
# Table name: stocks
#
# id :integer not null, primary key
# symbol :string(255)
# price :decimal(, )
# shares :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Stock < ActiveRecord::Base
attr_accessible :symbol, :price, :shares, :user_id
belongs_to :user, :inverse_of => :stocks
def get_quote
YahooFinance::get_quotes(YahooFinance::StandardQuote, self.symbol)[self.symbol].lastTrade
end
def current_position
self.shares * get_quote
end
def initial_position
self.shares * self.price
end
before_save :purchase
def purchase
price = get_quote
if price.present?
self.price = price
end
end
end
| true |
43d6a087aad52aa3971e13244d9fb22d9001d2d3
|
Ruby
|
chrisg67/solar-panels-rails
|
/spec/models/five_minute_reading_spec.rb
|
UTF-8
| 1,626 | 2.546875 | 3 |
[] |
no_license
|
require 'spec_helper'
describe FiveMinuteReading do
before { @reading = FiveMinuteReading.new(time: "2013-08-07 10:05:00", power: 0.2, total_power: 5888.0 ) }
subject { @reading }
it { should respond_to(:time) }
it { should respond_to(:power) }
it { should respond_to(:total_power) }
describe "when time is missing" do
it "should not be valid" do
@reading.time = nil
expect(@reading).not_to be_valid
end
end
describe "when power is missing" do
it "should not be valid" do
@reading.power = nil
expect(@reading).not_to be_valid
end
end
describe "when total_power is missing" do
it "should not be valid" do
@reading.total_power = nil
expect(@reading).not_to be_valid
end
end
describe "when time is already used" do
before do
reading_with_duplicate_time = @reading.dup
reading_with_duplicate_time.save
end
it { should_not be_valid }
end
describe "when an entry with the same power is supplied" do
before do
reading_with_duplicate_power = @reading.dup
reading_with_duplicate_power.time = "2013-12-31 00:00:00"
reading_with_duplicate_power.total_power = 0
reading_with_duplicate_power.save
end
it { should be_valid }
end
describe "when an entry with the same total_power is supplied" do
before do
reading_with_duplicate_total_power = @reading.dup
reading_with_duplicate_total_power.time = "2013-12-31 00:00:00"
reading_with_duplicate_total_power.power = 0
reading_with_duplicate_total_power.save
end
it { should be_valid }
end
end
| true |
6c6499ebc131b02fad8f81b8eb5409733623ec69
|
Ruby
|
jamillosantos/tfprog2012.1
|
/classes/base/Player.rb
|
UTF-8
| 1,762 | 2.515625 | 3 |
[] |
no_license
|
module MadBirds
module Base
class Player < Chingu::BasicGameObject
attr_reader :startTime, :char
attr_accessor :name, :deaths, :kills
trait :timer
def initialize(options)
super
self.name = options[:name]
self.kills = 0
self.deaths = 0
@startTime = Gosu::milliseconds
end
public
def name
@name
end
def name=(value)
@name = value
@char.name.text = value unless @char.nil?
end
def deaths
@deaths
end
def deaths=(value)
@deaths = value
end
def kills
@kills
end
def kills=(value)
@kills = value
end
def char
@char
end
def startTime
@startTime
end
def createChar
@char = MadBirds::Bird.create(:player=>self, :class=>'redbird')# create(:x=>200, :y=>0, :center_x=>0.5, :center_y=>0.5, :image)
end
def charDied!
after (@parent.rules[:rebirthDelay]) do
self.createChar
end
end
end
class Player1 < Player
def createChar
super
@char.input = {
:s => :shoot,
:a => :startJump,
:released_a => :jump,
:c => :turnLeft,
:b => :turnRight,
:holding_c => :move,
:holding_b => :move,
:f => :startChangeAngle,
:v => :startChangeAngle,
:holding_f => :incAngle,
:holding_v => :decAngle
}
end
end
class Player2 < Player
def createChar
super
@char.input = {
:i => :shoot,
:o => :startJump,
:released_o => :jump,
:left => :turnLeft,
:right => :turnRight,
:holding_left => :move,
:holding_right => :move,
:up => :startChangeAngle,
:down => :startChangeAngle,
:holding_up => :incAngle,
:holding_down => :decAngle
}
end
end
end
end
| true |
89c9e6eedebab718c61a8b52eefbf7e17cb81d17
|
Ruby
|
gmanirud/interngr
|
/spec/models/student_spec.rb
|
UTF-8
| 3,448 | 2.609375 | 3 |
[] |
no_license
|
require 'spec_helper'
#Spec for the student model
describe Student do
before {@test_student = Student.new(fname: "Bob", lname: "Loblaw", password: "interngrpass", password_confirmation: "interngrpass", email: "[email protected]", year: 1, school: "University of Toronto", discipline: "ECE")}
subject {@test_student}
it {should respond_to (:fname)}
it {should respond_to (:lname)}
it {should respond_to (:email)}
it {should respond_to (:year)}
it {should respond_to (:school)}
it {should respond_to (:discipline)}
it {should respond_to (:password_digest)}
it {should respond_to (:password_confirmation)}
it {should respond_to (:remember_token)}
it {should respond_to (:authenticate)}
it {should respond_to (:admin)}
it {should be_valid}
it {should_not be_admin}
describe "with admin attribute set to true" do
before do
@test_student.save!
@test_student.toggle!(:admin)
end
it {should be_admin}
end
#presence tests
describe "first name is not present" do
before {@test_student.fname = " "}
it {should_not be_valid}
end
describe "last name is not present" do
before {@test_student.lname = " "}
it {should_not be_valid}
end
describe "email is not present" do
before {@test_student.email = " "}
it {should_not be_valid}
end
describe "school is not present" do
before {@test_student.school = " "}
it {should_not be_valid}
end
describe "discipline is not present" do
before {@test_student.discipline = " "}
it {should_not be_valid}
end
#length validation tests
describe "first name is too long" do
before {@test_student.fname = "a"*31}
it {should_not be_valid}
end
describe "last name is too long" do
before {@test_student.lname = "a"*31}
it {should_not be_valid}
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo.
foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@test_student.email = invalid_address
expect(@test_student).not_to be_valid
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[[email protected]]
addresses.each do |valid_address|
@test_student.email = valid_address
expect(@test_student).to be_valid
end
end
end
describe "email address is already taken" do
before do
student_with_dup_email = @test_student.dup
student_with_dup_email.email = @test_student.email.upcase
student_with_dup_email.save
end
it {should_not be_valid}
end
#Authentication tests
describe "with a password that's too short" do
before { @test_student.password = @test_student.password_confirmation = "a" * 5 }
it { should be_invalid }
end
describe "return value of authenticate method" do
before { @test_student.save }
let(:found_student) { Student.find_by(email: @test_student.email) }
describe "with valid password" do
it { should eq found_student.authenticate(@test_student.password) }
end
describe "with invalid password" do
let(:user_for_invalid_password) { found_student.authenticate("wrongpassword") }
it { should_not eq user_for_invalid_password }
specify { expect(user_for_invalid_password).to be_false }
end
end
describe "remember token" do
before {@test_student.save}
its(:remember_token) {should_not be_blank}
end
end
| true |
c7f6cce53cc39e39e5f13f0ebdcb10716014d744
|
Ruby
|
antoshalee/kaminari-logarithmic
|
/lib/kaminari/logarithmic/strategies/base_strategy.rb
|
UTF-8
| 553 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
module Kaminari
module Logarithmic
module Strategies
class BaseStrategy
def build
fail NotImplementedError
end
private
def asc?
@asc ||= (@global_start <= @global_finish)
end
def desc?
!asc?
end
def enough?(value)
if asc?
value >= @global_finish
else
value <= @global_finish
end
end
def not_enough?(value)
!enough?(value)
end
end
end
end
end
| true |
7ef39a685fc1798db72d7b20b5bcd6d9b4385802
|
Ruby
|
tjlytle/halidator
|
/lib/halidator.rb
|
UTF-8
| 767 | 2.65625 | 3 |
[] |
no_license
|
require 'json'
require_relative './halidate/pure_ruby'
require_relative './halidate/json_schema'
class Halidator
attr_accessor :errors
def initialize(hal, engine = :pure_ruby)
case hal
when String
@json_string = hal
parse_json
else
@json = hal
end
@errors = []
if engine == :json_schema
extend Halidate::JsonSchema
else
extend Halidate::PureRuby
end
end
def parse_json
@json = JSON.parse(@json_string)
end
def valid?
result = validate_json_as_hal
show_errors
result
end
def debug(*str)
if $DEBUG
$stderr.puts str
end
end
def show_errors
debug ["\nERRORS-VVVVVVVVVVVVVVVVVV",
*errors,
"ERRORS-^^^^^^^^^^^^^^^^^^"]
end
end
| true |
2185da378751a2595fa0c2b2edf1bb4c4411c610
|
Ruby
|
fredrondina/mod1_final_paired_assessment
|
/lib/student.rb
|
UTF-8
| 322 | 3.59375 | 4 |
[] |
no_license
|
require 'pry'
class Student
attr_reader :name, :age, :scores
def initialize(attribute_hash = Hash.new)
@name = attribute_hash[:name]
@age = attribute_hash[:age]
@scores = []
end
def log_score(score)
@scores << score
end
def grade
(@scores.sum.to_f / @scores.length).round(1)
end
end
| true |
a449ef4d4b20cad9b3e0f013c4a03636e2b185df
|
Ruby
|
itiut/sutra-copying
|
/perfect-ruby/c08/li08.05.rb
|
UTF-8
| 77 | 2.578125 | 3 |
[] |
no_license
|
def yield_proc
yield
end
proc_obj = Proc.new { 1 }
p yield_proc &proc_obj
| true |
c1565d4ce9c1dee40d61677e4250500130d79f0c
|
Ruby
|
lwoodson/ddata
|
/spec/ddata/hash_spec.rb
|
UTF-8
| 1,200 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
require 'ddata/hash'
describe Ddata::Hash do
let(:redis) {Redis.new}
let(:dhash) {Ddata::Hash.new(connection: redis, key: 'ddata-hash')}
before {redis.flushdb}
describe "#__setobj__ & #__getobj__" do
it "should store hash in redis" do
dhash.__setobj__(a: 1, b: 2)
redis.keys.should == ['ddata-hash']
result = dhash.__getobj__
result['a'].should == 1
result['b'].should == 2
end
end
context "with 2 elements" do
before do
dhash['a'] = 1
dhash['b'] = 2
dhash = Ddata::Hash.new(connection: redis, key: 'ddata-hash')
end
describe "#[] and #[]=" do
it "should retrieve data from redis" do
dhash['a'].should == 1
dhash['b'].should == 2
end
end
describe "#keys" do
it "should return all keys from redis" do
dhash.keys.should == ['a','b']
end
end
describe "#values" do
it "should return all values from redis" do
dhash.values.should == [1,2]
end
end
describe "#clear" do
it "should clear the data from redis" do
dhash.clear
redis.keys.include?('ddata-hash').should_not == true
end
end
end
end
| true |
53a67073d634e36e833a145b53aefb8363036f2b
|
Ruby
|
DeuterGraves/codeclan_kareoke_classes_homework
|
/specs/venue_spec.rb
|
UTF-8
| 2,607 | 3.421875 | 3 |
[] |
no_license
|
require("minitest/autorun")
require("minitest/rg")
require("pry")
require_relative("../song.rb")
require_relative("../guest.rb")
require_relative("../room.rb")
require_relative("../venue.rb")
class VenueTest < MiniTest::Test
def setup()
@song1 = Song.new("Golden Chain of Hate", "Blue Balls Deluxe", "Whisky, whores and overtime, have taken her place, now she's gone...")
@song2 = Song.new("Two Minutes to Midnight", "Iron Maiden", "As the reasons for the carnage cut their meat and lick the gravy, we oil the jaws of the war machine and feed it with our babies")
@song3 = Song.new("Alive", "Pearl Jam", "Son, she said, have I got a little story for you...")
@song4 = Song.new("Copacabana", "Barry Manilow", "Her name was Lola, she was a showgirl with yellow feathers in her hair and a dress cut down to there...")
@song5 = Song.new("Right Hand Man", "Hamilton Original Cast", "Dying is easy, young man, living is harder")
@song6 = Song.new("Float On", "Modest Mouse", "I backed my car into a cop car the other day well, he just drove off - sometimes life's okay")
@song7 = Song.new("Jack and Diane", "John Cougar Melloncamp", "A little ditty 'bout Jack & Diane Two American kids growing up in the heart land")
@guest1 = Guest.new("Puck", 75, @song1)
@guest2 = Guest.new("Jamie", 75, @song2)
@guest3 = Guest.new("Karen", 75, @song3)
@guest4 = Guest.new("Rob", 75, @song4)
@guest5 = Guest.new("Celeste", 75, @song5)
@guest6 = Guest.new("Taylor", 75, @song6)
@guest7 = Guest.new("Amanda", 75, @song7)
@room1 = Room.new([@guest1, @guest2], 3, 25, [])
@room2 = Room.new([@guest1, @guest2, @guest3, @guest4, @guest5, @guest6], 8, 45, [])
@venue = Venue.new("The Sing Song Room", [@room1], 0)
end
def test_venue_has_name()
assert_equal("The Sing Song Room", @venue.name)
end
def test_venue_has_rented_rooms()
assert_equal(1, @venue.rented_rooms.length())
end
def test_venue_has_till()
assert_equal(0, @venue.till)
end
# increase till
def test_increase_till()
@venue.increase_till(15)
assert_equal(15, @venue.till)
end
# release a room (remove room from the room array) remove guests from room.
def test_release_room()
@venue.release_room(@room1)
assert_equal([], @room1.guests)
assert_equal([], @venue.rented_rooms)
end
# rent a room (put a room in the rooms array, collect the money)
def test_rent_a_room()
@venue.rent_room(@room2,@guest2)
assert_equal(2, @venue.rented_rooms.length())
assert_equal(45, @venue.till)
assert_equal(30, @guest2.wallet)
end
# end class
end
| true |
6cdbcdcf3cd621b3f0c3a47aa1495777c17d726b
|
Ruby
|
jkshareef/collections_practice-seattle-web-career-042219
|
/collections_practice.rb
|
UTF-8
| 883 | 3.859375 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
def sort_array_asc(array)
return array.sort
end
def sort_array_desc(array)
return array.sort { |x,y| y <=> x }
end
def sort_array_char_count(array)
array.sort_by { |word| word.length }
end
def swap_elements(array)
array.insert(1, array[2])
array.delete_at(3)
array
end
def swap_elements_from_to(array, index, destination_index)
end
def reverse_array(array)
array.reverse
end
def kesha_maker(array)
array.map do |word|
word.insert(2, '$')
word.slice!(3)
end
array
end
def find_a(array)
arr = []
array.each do |word|
if word.start_with?("a")
arr.push(word)
end
end
arr
end
def sum_array(array)
array.inject { |sum, n| sum + n }
end
def add_s(array)
arr = []
array.each_with_index.collect { |word, index|
if index != 1
arr.push(word + "s")
elsif index == 1
arr.push(word)
end }
arr
end
| true |
53626afe75f9f7b79a0fe83342bf1fd6a19bc20e
|
Ruby
|
dibyn/CodeWars-Challenges
|
/RubyCodeWarz/no_of_people_inBus.rb
|
UTF-8
| 1,948 | 4.28125 | 4 |
[] |
no_license
|
=begin
Number of people in the bus
There is a bus moving in the city, and it takes and drop some people in each bus stop.
You are provided a list (or array in JS) of integer array.
Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item).
The first integer array has 0 number in the second item, since the bus is empty in the first bus stop.
Your task is to return number of people in the bus after the last bus station. Take a look on the test cases :)
Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.
<Other Solutions>
<-1->
def number(bus_stops)
passengers = 0
bus_stops.each do |a,b|
passengers += a - b
end
passengers
end
<--2-->
def number(bus_stops)
bus_stops.reduce(0) { |k, (on, off)| k + on - off }
end
<---3--->
def number(bus_stops)
i = 0
answer = []
bus_stops.each do |array|
i = ((array[0] + i) - array[1])
answer << i
end
return answer.last
end
<----4---->
def number(bus_stops)
onboard = 0
bus_stops.flatten.each_with_index do |item, i|
if i.even?
onboard += item
elsif i.odd?
onboard -= item
end
end
onboard
end
<-----5---->
def number(bus_stops)
on = 0
off = 0
bus_stops.flatten.each_with_index do |el, idx|
if idx%2===0
on+=el
else
off+=el
end
end
answer = on-off
return answer
end
<------6------>
def number(bus_stops)
a = 0
bus_stops.to_s.delete("[],").split.map.with_index do |v,i|
if i % 2 == 0
a = a - v.to_i
end
if i % 2 != 0
a = a + v.to_i
end
end
return a * -1
end
=end
def number(bus_stops)
vitra=0
bahira=0
i=0
while i<bus_stops.size
vitra = vitra + bus_stops[i][0]
bahira = bahira + bus_stops[i][1]
i = i + 1
end
vitra - bahira
end
puts number(77)
| true |
0bb53bab862efa63b29b76d5c68e24c18c342605
|
Ruby
|
motri/oystercard
|
/lib/journey.rb
|
UTF-8
| 546 | 3.203125 | 3 |
[] |
no_license
|
class Journey
attr_reader :history, :in_journey, :entry_station, :exit_station, :journey
def initialize
@in_journey = false
@entry_station = nil
@exit_station = nil
end
def start(station)
print 'Forgot to tap out!' if @in_journey
@in_journey = true
@entry_station = station
@journey = {@entry_station => nil}
end
def end(station)
@in_journey = false
@exit_station = station
@journey = {@entry_station => station}
end
def in_journey?
@in_journey
end
def fare
1
end
end
| true |
dc34ef4599c003babf620bb380b4964dade85c9a
|
Ruby
|
presha/Employee
|
/company1.rb
|
UTF-8
| 990 | 3.65625 | 4 |
[] |
no_license
|
#Testing file..
require "Trainee"
require "Developer"
class Company1
attr_accessor :company_name
def initialize(name=nil)
self.company_name = name
@employees=[]
end
def display_name
self.company_name
end
def << (employee)
@employees<<employee
end
def display_employees
@employees.each do |emp|
puts "-----------------"
puts emp.employee
puts "=================="
end
end
end
comp1 = Company1.new
developer1 = Developer.new("Presha")
developer2 = Developer.new("Pratyush")
Developer.add_employee("bashanta")
Developer.add_employee("Lujaw")
Developer.add_employee("Rohit")
company1 = Company.new
comp1 << developer1
comp1 << developer2
trainee1 = Trainee.new("Aashis")
Trainee.add_employee("Jitendra")
puts("total number of developers\n")
puts developer1.display_developer
puts("\ntotal number of trainees\n")
puts trainee1.display_trainee
puts "\nTotal number of employees\n"
comp1.display_employees
| true |
0a6c9bc2ada46e989ebea27e56b0d0d819fb807d
|
Ruby
|
ubpb/katalog
|
/app/services/concerns/record_related_service.rb
|
UTF-8
| 1,423 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
module RecordRelatedService
extend ActiveSupport::Concern
# A helper method which tries to update the record property of each element
# of a collection of objects responding to 'record'. Therefor, it issues a
# search using the given search_engine_adapter and updates the record property
# for each element where a corresponding search result hit is present.
#
# @example
# get_record_items_result = ils_adapter.get_record_items(record_id)
# update_records!(get_record_items_result)
#
def update_records!(collection, search_engine_adapter)
if collection.any? && search_engine_adapter
record_ids = collection.map(&:record).map(&:id).compact
if record_ids.any?
search_result = SearchRecordsService.call(
adapter: search_engine_adapter,
search_request: {
queries: [
{
type: "unscored_terms",
field: "id",
terms: record_ids
}
],
# count is used instead of length, because collection is an Enumerable, not an array
size: record_ids.count
}
)
collection.each do |_element|
if corresponding_hit = search_result.find { |_hit| _hit.record.id == _element.record.id }
_element.record = corresponding_hit.record
end
end
end
end
return collection
end
end
| true |
efc797e02792669857215888c794b3e87a1a86fd
|
Ruby
|
95-Samb/advent-of-code
|
/intcode_helpers/intcode_instructions.rb
|
UTF-8
| 873 | 2.921875 | 3 |
[] |
no_license
|
class IntcodeInstructions
def execute(instruction,i,intcode,parameters)
@cycle = [1,2,7,8].include?(instruction) ? 4 : 2
case instruction
when 1
intcode[intcode[i + 3]] = parameters[0] + parameters[1]
when 2
intcode[intcode[i + 3]] = parameters[0] * parameters[1]
when 5
if parameters[0] != 0
i = parameters[1]
@cycle = 0
else @cycle = 3
end
when 6
if parameters[0] == 0
i = parameters[1]
@cycle = 0
else @cycle = 3
end
when 7
parameters[0] < parameters[1] ?
intcode[intcode[i + 3]] = 1 : intcode[intcode[i + 3]] = 0
when 8
parameters[0] == parameters[1] ?
intcode[intcode[i + 3]] = 1 : intcode[intcode[i + 3]] = 0
end
i += @cycle
{:intcode => intcode,:pointer => i}
end
end
| true |
d0abf916b28b2a7e8952352eac944978bde72144
|
Ruby
|
kauec/Glasses-1
|
/spec/tests/range_search_test.rb
|
UTF-8
| 1,838 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
describe 'search entries which have a value within a specific range' do
context 'search with params sanitized by ActiveRecord' do
it 'returns all the results with a field bigger than or equal to some arbitrary value' do
(Glasses.search_range(Player, {age_min: '110'}).size).should == 3
end
it 'returns all the results with a field lesser than or equal to some arbitrary value' do
(Glasses.search_range(Player, {age_max: '110'}).size).should == 8
end
it 'returns all the results with a field bigger than or equal to some arbitrary value and with another field lesser than or equal to some other arbitrary value' do
(Glasses.search_range(Player, {age_min: '20', age_max: '110'}).size).should == 4
end
it 'returns all the results which satisfies both "field in the range" and "field with same prefix" conditions' do
(Glasses.search_range(Player, {first_name: 'Jane', age_min: '110'}).size).should == 1
end
end
context 'search without params sanitized by ActiveRecord' do
it 'returns all the results with a field bigger than or equal to some arbitrary value' do
(Glasses.raw_search_range(Player, {age_min: '110'}).size).should == 3
end
it 'returns all the results with a field lesser than or equal to some arbitrary value' do
(Glasses.raw_search_range(Player, {age_max: '110'}).size).should == 8
end
it 'returns all the results with a field bigger than or equal to some arbitrary value and with another field lesser than or equal to some other arbitrary value' do
(Glasses.raw_search_range(Player, {age_min: '20', age_max: '110'}).size).should == 4
end
it 'returns all the results which satisfies both "field in the range" and "field with same prefix" conditions' do
(Glasses.raw_search_range(Player, {first_name: 'Jane', age_min: '110'}).size).should == 1
end
end
end
| true |
26cbda4453632c069446e679cccf36a2d3c67274
|
Ruby
|
jamisonordway/denver_puplic_library
|
/lib/book.rb
|
UTF-8
| 340 | 2.65625 | 3 |
[] |
no_license
|
class Book
attr_reader :author_first_name,
:author_last_name,
:title,
:publication_date
attr_accessor :book_info
def initialize(hash)
@author_first_name = hash.values[0]
@author_last_name = hash.values[1]
@title = hash.values[2]
@publication_date = hash.values[3]
end
end
| true |
c99e7f20da1603189afcb2f755428eb4e21c2d6d
|
Ruby
|
projectcypress/health-data-standards
|
/test/unit/ext/string_test.rb
|
UTF-8
| 388 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'test_helper'
class StringTest < ActiveSupport::TestCase
test "can be true values" do
assert "TRUE".to_boolean
assert "true".to_boolean
assert "t".to_boolean
assert "1".to_boolean
end
test "can be false values" do
assert ! "false".to_boolean
end
test "will return false for non-boolean like values" do
assert ! "bacon".to_boolean
end
end
| true |
09a5800ccfc88529bcddbde9a8f569991ec7f490
|
Ruby
|
darchi07/codeiq
|
/exruby3.rb
|
UTF-8
| 282 | 3.359375 | 3 |
[] |
no_license
|
# coding: utf-8
#filenameの文字列の長さの結果が8で出力されるのはどれ?
filename = "text.txt"
puts "length :#{filename.length}"
puts "size: #{filename.size}"
puts "count : #{filename.count}"
#答え:lengthとsize,countは配列の要素数を返す関数
| true |
1005144b3a0802206e56e87c327bcbc8294b3770
|
Ruby
|
ayjlee/betsy
|
/test/models/order_item_test.rb
|
UTF-8
| 1,518 | 2.59375 | 3 |
[] |
no_license
|
require "test_helper"
describe OrderItem do
let(:item1) {order_items(:orderitem1)}
let(:order1) {orders(:pending_order)}
let(:product) { products(:soap)}
describe 'relationships' do
it "has a product" do
item1.must_respond_to :product
item1.must_be_kind_of OrderItem
item1.product.must_be_kind_of Product
end
it "has an order" do
item1.must_respond_to :order
item1.order.must_equal order1
end
end
describe 'validations' do
it "requires a quantity" do
item_no_quantity = OrderItem.new
item_no_quantity.valid?.must_equal false
item_no_quantity.errors.messages.must_include :quantity
end
it "requires that quantity is a positive integer " do
item1.quantity.must_be_kind_of Integer
item1.quantity.must_be :>, 0
item1.quantity.must_equal 1
end
it "accepts valid quantity" do
valid_quantity = [1, 20, 30, 4, 5]
valid_quantity.each do |quantity|
valid_orderitem = OrderItem.new(product_id: product.id, order_id: order1.id, quantity: quantity)
valid_orderitem.valid?.must_equal true
end
end
it "rejects invalid quantity" do
invalid_quantity = [-1, 0, 'one', nil]
invalid_quantity.each do |quantity|
invalid_orderitem = OrderItem.new(product_id: product.id, order_id: order1.id, quantity: quantity)
invalid_orderitem.valid?.must_equal false
invalid_orderitem.errors.messages.must_include :quantity
end
end
end
end
| true |
6d078696043f27d3a254559cdbb197faaa2a9ea4
|
Ruby
|
e86400/phase-0-tracks
|
/ruby/santa.rb
|
UTF-8
| 1,406 | 3.328125 | 3 |
[] |
no_license
|
class Santa
def initialize(gender, ethnicity)
#puts "Initializing Santa instance..."
@gender = gender
@ethnicity = ethnicity
@age = 0
end
def speak
puts "Ho, ho, ho! Haaaappy holidays!"
end
def eat_milk_and_cookies(snickerdoodle)
puts "That was a good #{snickerdoodle}!"
end
#reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
santas = []
example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"]
example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"]
example_genders.length.times do |i|
santas << Santa.new(example_genders[i], example_ethnicities[i])
end
# we make an empty container for our puppy collection
santa_collection = []
santas.each do |description|
puts "Creating #{@gender} #{@ethnicity}santa..."
santa_collection << Santa.new(@gender,@ethnicity)
puts "There are now #{santa_collection.length} santas"
end
puts "Testing each santa instance in the array to make sure it can speak and eat cookies ..."
santa_collection.each do |action|
action.speak
action.eat_milk_and_cookies("oatmeal cookie")
end
end
# santa = Santa.new("female", "Mexican")
# santa.speak
# santa.eat_milk_and_cookies("gingerbread")
| true |
6138f72023a2cd0e59f1d2b1168b22484be35965
|
Ruby
|
FSolM/bowling-score-giver
|
/lib/FileHandling.rb
|
UTF-8
| 2,231 | 3.828125 | 4 |
[] |
no_license
|
require "./lib/helpers/ErrorMessages.rb"
##
# This module contains all the methods that are necessary for handling and parsing the data from the text file
module FileHandling
VALUES = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "F"]
##
# The #extension works as a quick inspector of the inputted file name; it checks if the user added the .txt file extension, if not, it adds
# it to the string
def self.extension(file_name)
if file_name.include? ".txt"
return file_name
else
return file_name + ".txt"
end
end
##
# The #retrieve receives a string as a param and searches the files folder for it. It then opens the selected file and parses the contents.
# It also contains the first conditional for checking that the contents of the file are valid
def self.retrieve(file = "base.txt")
path = Dir.pwd + "/files/" + file
if File.exists? path
file = File.open(Dir.pwd + "/files/" + file, "r")
else
ErrorMessages.noFile
return nil
end
parser(file)
end
##
# The #parser works as the entry point of the conditions analysis of the module. It will check that the current file is not empty and if its
# not, will send said file to the #analyzer
def self.parser (file)
# The file is empty, it doens't need to be analyzed
if File.zero? file
ErrorMessages.emptyFile
return nil
end
analyzer(file)
end
##
# The #analyzer works as the looper that adds all the file data into a workable array; it's also where some of the conditions of a valid file are
# made
def self.analyzer(file)
lines = []
data = file.readlines.each do |line|
line = line.chomp
# If line has a blank space, it jumps it
next if line == ""
# If the line doesn't contain a space between the score and name, it exits with nil
if !line.include? " "
ErrorMessages.noSpaces
return nil
end
# If the last value of the string is not a number between 0 and 10 or the letter F, it exits with nil
if !self::VALUES.include? line.split(" ")[1]
ErrorMessages.wrongScore
return nil
end
lines << line
end
lines
end
end
| true |
78a0563db2c38b30b23682c93b1b1e31ec4fe148
|
Ruby
|
plato721/head-first-design-ruby
|
/compound_patterns/ducks/duck_simulator.rb
|
UTF-8
| 910 | 2.859375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
Dir['./lib/**/*.rb'].each { |f| require f}
class DuckSimulator
def initialize(duck_factory=nil)
@duck_factory = duck_factory
@duck_factory ||= QuackCounterFactory.new
end
def perform
all_ducks = Flock.new
# some assorted ducks
ducks = ["mallard_duck", "decoy_duck", "darkwing_duck", "rubber_duck"]
ducks.each do |type|
duck = @duck_factory.send("create_#{type}".to_sym)
all_ducks.add(duck)
end
# our goose
all_ducks.add(GooseAdapter.new(Goose.new))
# mallards only, nested flock
mallard_ducks = Flock.new
5.times { mallard_ducks.add(@duck_factory.create_mallard_duck) }
all_ducks.add(mallard_ducks)
# our observer
zoologist = Zoologist.new
all_ducks.register_observer(zoologist)
all_ducks.quack
puts "Total quacks: #{QuackCounter.quack_count}"
end
end
sim = DuckSimulator.new
sim.perform
| true |
24a340ec7736061e3652dd9bfa36018ebfd79f76
|
Ruby
|
bcurren/unison
|
/spec/unit/tuples/primitive_tuple_spec.rb
|
UTF-8
| 40,999 | 2.96875 | 3 |
[] |
no_license
|
require File.expand_path("#{File.dirname(__FILE__)}/../../unison_spec_helper")
module Unison
module Tuples
describe PrimitiveTuple do
attr_reader :tuple
describe "Class Methods" do
describe ".new" do
context "when .polymorphic_allocate is overridden" do
it "returns the object that is returned by .polymorphic_allocate" do
other_class = Class.new(PrimitiveTuple) do
member_of(User.set)
end
(class << User; self; end).class_eval do
define_method :polymorphic_allocate do |attrs|
other_class.allocate
end
end
instance = User.new
instance.class.should == other_class
end
end
end
describe ".member_of" do
it "associates the Tuple class with a Set and vice-versa" do
users_set = User.set
users_set.name.should == :users
users_set.tuple_class.should == User
end
end
describe ".attribute" do
it "delegates to .set" do
mock.proxy(User.set).add_primitive_attribute(:nick_name, :string, {})
User.attribute(:nick_name, :string)
end
context "when passed :default option" do
it "defaults the PrimitiveAttribute value to the passed-in :default option value" do
User.attribute_reader(:nick_name, :string, :default => "Bobo")
User.new.nick_name.should == "Bobo"
end
context "when subclassed" do
it "defaults the PrimitiveAttribute value to the :default option value passed-in to the superclass" do
User.attribute_reader(:nick_name, :string, :default => "Bobo")
Developer.new.nick_name.should == "Bobo"
end
end
end
context "when passed a block" do
it "causes #[] to return the result of applying the block to the PrimitiveAttribute's value" do
User.attribute_reader(:nick_name, :string) do |value|
"homeboy #{value}"
end
user = User.new(:nick_name => "Bobo")
user[:nick_name].should == "homeboy Bobo"
user.nick_name.should == "homeboy Bobo"
end
end
end
describe ".attribute_reader" do
it "creates an attribute on the .set" do
mock.proxy(User.set).add_primitive_attribute(:nick_name, :string, {})
User.attribute_reader(:nick_name, :string)
end
it "adds a reader method to the Tuple" do
User.attribute_reader(:nick_name, :string)
user = User.new(:nick_name => "Bob")
user.nick_name.should == "Bob"
end
it "does not add a writer method to the Tuple" do
User.attribute_reader(:nick_name, :string)
user = User.new
user.should_not respond_to(:nick_name=)
end
context "when the type is :boolean" do
it 'defines a #{name}? reader alias' do
User.attribute_reader(:has_crabs, :boolean)
user = User.new(:has_crabs => true)
user.has_crabs.should be_true
user.has_crabs?.should be_true
end
end
describe ":default option" do
context "when a :default is supplied" do
it "defaults the value to the supplied default value" do
User.attribute_reader(:nick_name, :string, :default => "jumbo")
User.new.nick_name.should == "jumbo"
User.new(:nick_name => "shorty").nick_name.should == "shorty"
end
context "when default value is false" do
it "defaults the attribute value to false" do
User.attribute_reader(:is_awesome, :boolean, :default => false)
User.new.is_awesome.should be_false
User.new(:is_awesome => true).is_awesome.should be_true
end
end
context "when passed a Proc" do
it "defaults the attribute value to the result of #instance_eval(&the_passed_in_Proc)" do
User.attribute_reader(:nick_name, :string, :default => lambda {name + "y"})
User.new(:name => "Joe").nick_name.should == "Joey"
User.new(:name => "Joe", :nick_name => "Joe Bob").nick_name.should == "Joe Bob"
User.new(:name => "Joe", :nick_name => nil).nick_name.should == nil
end
end
end
context "when a :default is not supplied" do
it "does not default the value" do
User.attribute_reader(:nick_name, :string)
User.new.nick_name.should be_nil
User.new(:nick_name => "shorty").nick_name.should == "shorty"
end
end
end
end
describe ".attribute_writer" do
it "creates an attribute on the .set" do
mock.proxy(User.set).add_primitive_attribute(:nick_name, :string, {})
User.attribute_writer(:nick_name, :string)
end
it "adds a writer method to the Tuple" do
User.attribute_writer(:nick_name, :string)
user = User.new(:nick_name => "Bob")
user.nick_name = "Jane"
user[:nick_name].should == "Jane"
end
it "does not add a reader method to the Tuple" do
User.attribute_writer(:nick_name, :string)
user = User.new
user.should_not respond_to(:nick_name)
end
describe ":default option" do
context "when a :default is supplied" do
it "defaults the value to the supplied default value" do
User.attribute_writer(:nick_name, :string, :default => "jumbo")
User.new[:nick_name].should == "jumbo"
User.new(:nick_name => "shorty")[:nick_name].should == "shorty"
end
context "when default value is false" do
it "defaults the attribute value to false" do
User.attribute_reader(:is_awesome, :boolean, :default => false)
User.new[:is_awesome].should be_false
User.new(:is_awesome => true)[:is_awesome].should be_true
end
end
end
context "when a :default is not supplied" do
it "does not default the value" do
User.attribute_reader(:nick_name, :string)
User.new[:nick_name].should be_nil
User.new(:nick_name => "shorty")[:nick_name].should == "shorty"
end
end
end
end
describe ".attribute_accessor" do
it "creates an attribute on the .set" do
mock.proxy(User.set).add_primitive_attribute(:nick_name, :string, {}).at_least(1)
User.attribute_accessor(:nick_name, :string)
end
it "adds a reader and a writer method to the Tuple" do
User.attribute_accessor(:nick_name, :string)
user = User.new(:nick_name => "Bob")
user.nick_name = "Jane"
user.nick_name.should == "Jane"
user[:nick_name].should == "Jane"
end
describe ":default option" do
context "when a :default is supplied" do
it "defaults the value to the supplied default value" do
User.attribute_reader(:nick_name, :string, :default => "jumbo")
User.new.nick_name.should == "jumbo"
User.new(:nick_name => "shorty").nick_name.should == "shorty"
end
context "when default value is false" do
it "defaults the attribute value to false" do
User.attribute_reader(:is_awesome, :boolean, :default => false)
User.new.is_awesome.should be_false
User.new(:is_awesome => true).is_awesome.should be_true
end
end
end
context "when a :default is not supplied" do
it "does not default the value" do
User.attribute_reader(:nick_name, :string)
User.new.nick_name.should be_nil
User.new(:nick_name => "shorty").nick_name.should == "shorty"
end
end
end
end
describe ".synthetic_attribute" do
attr_reader :user, :attribute
before do
@attribute = User.synthetic_attribute :team_name do
team.signal(:name)
end
@user = User.create(:team_id => "mangos")
end
it "adds a method to the Tuple that returns the value of the #signal returned by instance eval'ing the given block" do
user.team_name.should == user.team.name
new_name = "The Bananas"
user.team.name = new_name
user.team_name.should == new_name
end
it "adds a SyntheticAttribute to the #set.attributes" do
User.set[:team_name].should == attribute
end
end
describe ".relates_to_many" do
it "creates an instance method representing the given Relation" do
User.relates_to_many(:custom_photos) do
Photo.set.where(Photo[:user_id].eq(id))
end
user = User.create(:id => "bob", :name => "Bob")
user.custom_photos.should == Photo.set.where(photos_set[:user_id].eq("bob"))
end
it 'creates a "#{name}_relation" method to return the relation' do
user = User.find("nathan")
user.photos_relation.should == user.photos
end
context "when the Relation definition is invalid" do
it "includes the definition backtrace in the error message" do
User.relates_to_many(:invalid) {raise "An Error"}; definition_line = __LINE__
lambda do
User.new
end.should raise_error(RuntimeError, Regexp.new("#{__FILE__}:#{definition_line}"))
end
end
context "when subclassed" do
it "creates an instance method representing the given Relation subclass" do
user = Developer.create(:id => "jeff", :name => "Jeff")
photo = Photo.create(:id => "jeff_photo", :user_id => "jeff", :name => "Jeff's Photo")
user.photos.should == [photo]
end
end
end
describe ".relates_to_one" do
attr_reader :photo
before do
@photo = Photo.find("nathan_photo_1")
end
it "defines a method named after the name which returns the Relation that is produced by instance-evaling the block" do
photo.user.should_not be_nil
photo.user.should == User.where(User[:id].eq(photo[:user_id]))
end
describe "the defined reader method" do
context "when the produced Relation is #nil?" do
it "returns nil" do
users_set.delete(photo.user.tuple)
photo.user_relation.should be_nil
photo.user.class.should == NilClass
end
end
context "when the produced Relation is not #nil?" do
it "returns a SingletonRelation whose #operand is the block's return value" do
Photo.class_eval do
relates_to_one :relates_to_one_user do
User.where(User[:id].eq(user_id))
end
end
photo = Photo.create(:user_id => "nathan")
photo.relates_to_one_user.should_not be_nil
photo.relates_to_one_user.class.should == Relations::SingletonRelation
photo.relates_to_one_user.operand.should == User.where(User[:id].eq(photo[:user_id]))
end
end
end
it 'creates a "#{name}_relation" method to return the relation' do
photo.user_relation.should == photo.user
end
context "when the Relation definition is invalid" do
it "includes the definition backtrace in the error message" do
User.relates_to_one(:invalid) {raise "An Error"}; definition_line = __LINE__
lambda do
User.new
end.should raise_error(RuntimeError, Regexp.new("#{__FILE__}:#{definition_line}"))
end
end
context "when subclassed" do
it "creates an instance method representing the given Relation subclass" do
user = Developer.create(:id => "jeff", :name => "Jeff")
profile = Profile.create(:id => "jeff_profile", :owner_id => "jeff")
user.profile.should == profile
end
end
end
describe ".has_many" do
attr_reader :user
before do
@user = User.find("nathan")
end
it "assigns a HasMany instance on the PrimitiveTuple during initialization" do
user.photos.class.should == Relations::HasMany
end
describe ":through option" do
it "assigns a HasManyThrough instance on the PrimitiveTuple during initialization" do
user.fans.class.should == Relations::HasManyThrough
end
end
context "when passed a customization block" do
it "calls the block on the default generated relation, using its return value as the instance relation" do
user = User.find("nathan")
user.active_accounts.should_not be_empty
user.accounts.any? do |account|
!account.active?
end.should be_true
user.active_accounts.each do |account|
account.should be_active
end
end
end
end
describe ".has_one" do
attr_reader :user
before do
@user = User.find("nathan")
end
it "assigns a HasOne instance on the PrimitiveTuple during initialization" do
user.profile.class.should == Relations::HasOne
end
describe "customization block" do
context "when not passed a block" do
it "returns a Selection on the target Relation where the foreign key Attribute is EqualTo the instance's #id" do
user.photos.should == Photo.where(Photo[:user_id].eq(user[:id]))
end
end
context "when passed a block" do
describe "the reader method" do
it "calls the block on the default generated Relation, and uses a SingletonRelation whose #operand is the return value of the block as its instance Relation" do
user.active_account.class.should == Relations::SingletonRelation
user.active_account.operand.should == Account.where(Account[:user_id].eq(user[:id])).where(Account.active?)
user_without_active_account = User.find("ross")
user_without_active_account.active_account.should be_nil
end
end
end
end
end
describe ".belongs_to" do
attr_reader :profile, :user
before do
@profile = Profile.find("nathan_profile")
@user = User.find("nathan")
end
it "assigns a BelongsTo instance on the PrimitiveTuple during initialization" do
profile.owner.class.should == Relations::BelongsTo
end
describe "customization block" do
context "when not passed a block" do
it "returns a Selection on the target Relation where the foreign key Attribute is EqualTo the instance's #id" do
profile.owner.should == user
end
end
context "when passed a block" do
describe "the reader method" do
it "returns the result of the default Selection yielded to the block" do
profile.yoga_owner.should == User.where(User[:id].eq(profile[:owner_id])).where(User[:hobby].eq("Yoga"))
Profile.find("corey_profile").yoga_owner.should be_nil
end
end
end
end
end
describe ".where" do
it "delegates to .set" do
predicate = User[:name].eq("Nathan")
mock.proxy(User.set).where(User[:name].eq("Nathan"))
User.where(User[:name].eq("Nathan"))
end
end
describe ".order_by" do
it "delegates to .set" do
mock.proxy(User.set).order_by(User[:name])
User.order_by(User[:name])
end
end
describe ".project" do
it "delegates to .set" do
mock.proxy(User.set).project(User[:name])
User.project(User[:name])
end
end
describe ".singleton" do
it "delegates to .set" do
mock.proxy(User.set).singleton
User.singleton
end
end
describe ".push" do
it "delegates to .set" do
mock.proxy(User.set).push
User.push
end
end
describe ".pull" do
it "delegates to .set" do
mock.proxy(User.set).pull
User.pull
end
end
describe ".fetch" do
it "delegates to .set" do
mock.proxy(User.set).fetch
User.fetch
end
end
describe ".find" do
it "delegates to .set" do
User.find("nathan").should == User.set.find("nathan")
end
end
describe ".find_or_pull" do
it "delegates to #find_or_pull on the #relation" do
User.find_or_pull("buffington").should == User.set.find_or_pull("buffington")
end
end
describe ".create" do
it "instantiates an instance of the Tuple with the given attributes and inserts it into its .set, then returns it" do
User.find("ernie").should be_nil
user = User.create(:id => "ernie", :name => "Ernie")
User.find("ernie").should == user
end
end
describe ".basename" do
it "returns the last segment of name" do
tuple_class = Class.new(PrimitiveTuple)
stub(tuple_class).name {"Foo::Bar::Baz"}
tuple_class.basename.should == "Baz"
end
end
describe ".set" do
context "when .member_of was not called" do
attr_reader :tuple_class, :set
before do
@tuple_class = Class.new(PrimitiveTuple)
stub(tuple_class).name {"MyShoe"}
@set = tuple_class.set
end
it "returns a new Set whose name is underscored and pluralized class name as a Symbol" do
set.name.should == :my_shoes
end
it "retains the new Set" do
set.should be_retained_by(tuple_class)
end
it "sets the #tuple_class of the new Set to self" do
set.tuple_class.should == tuple_class
end
end
context "when .member_of was called" do
it "returns the passed-in Set" do
set = Relations::Set.new(:sets)
tuple_class = Class.new(PrimitiveTuple) do
member_of(set)
end
tuple_class.set.should == set
end
end
context "when subclassed" do
context "when .member_of was not called on the subclass" do
it "returns the superclass.set" do
sub_class = Class.new(User)
sub_class.set.should == User.set
end
end
context "when .member_of was called on the subclass" do
it "returns the passed-in Set" do
sub_set = Relations::Set.new(:sub_users)
sub_class = Class.new(User) do
member_of(sub_set)
end
sub_class.set.should == sub_set
end
end
end
end
describe "all instance methods of Set and Array, excluding to_ary, methods of PrimitiveTuple, and methods that start with __" do
it "are delegated from PrimitiveTuple subclasses to their .set" do
(Relations::Set.instance_methods + Array.instance_methods - PrimitiveTuple.methods).each do |method_name|
next if method_name =~ /^__|^to_ary$/
User.send(method_name)
end
end
end
describe ".memory_fixtures" do
it "delegates to #set" do
fixtures_hash = {
"joe" => {:name => "Joe"}
}
mock.proxy(User.set).memory_fixtures(fixtures_hash)
User.memory_fixtures(fixtures_hash)
end
end
describe ".load_memory_fixtures" do
it "delegates to #set" do
mock.proxy(User.set).load_memory_fixtures
User.load_memory_fixtures
end
end
describe ".database_fixtures" do
it "delegates to #set" do
fixtures_hash = {
"joe" => {:name => "Joe"}
}
mock.proxy(User.set).database_fixtures(fixtures_hash)
User.database_fixtures(fixtures_hash)
end
end
describe ".load_database_fixtures" do
it "delegates to #set" do
mock.proxy(User.set).load_database_fixtures
User.load_database_fixtures
end
end
end
describe "Instance Methods" do
before do
User.superclass.should == PrimitiveTuple
@tuple = User.new(:id => "nathan", :name => "Nathan")
end
describe "#initialize" do
attr_reader :tuple
before do
@tuple = User.new(:id => "nathan", :name => "Nathan")
end
it "assigns a hash of attribute-value pairs corresponding to its Relation" do
tuple[:id].should == "nathan"
tuple[:name].should == "Nathan"
end
it "sets new? to true" do
tuple.should be_new
end
it "sets dirty? to true" do
tuple.should be_dirty
end
context "when Unison.test_mode? is true" do
before do
Unison.test_mode?.should be_true
end
it "if an #id is provided, honors it" do
user = User.create(:id => "obama", :name => "Obama")
user.id.should == "obama"
end
it "if no #id is provided, sets :id to a generated guid" do
user = User.create(:name => "Obama")
user.id.should_not be_nil
end
end
context "when Unison.test_mode? is false" do
before do
Unison.test_mode = false
end
it "if an #id is provided, raises an error" do
lambda do
User.create(:id => "obama", :name => "Obama")
end.should raise_error
end
end
end
describe "#composite?" do
it "should be false" do
tuple.should_not be_composite
end
end
describe "#primitive?" do
it "should be true" do
tuple.should be_primitive
end
end
describe "#[]" do
context "when passed an Attribute defined on #relation" do
it "returns the value" do
profile do
tuple[User.set[:id]].should == "nathan"
tuple[User.set[:name]].should == "Nathan"
end
end
end
context "when passed an Attribute defined on a different #set" do
it "raises an exception" do
lambda do
tuple[photos_set[:id]]
end.should raise_error
end
end
context "when passed #set" do
it "returns self" do
tuple[tuple.set].should == tuple
end
end
context "when passed a Symbol corresponding to a name of an Attribute defined on #set" do
it "returns the value" do
tuple[:id].should == "nathan"
tuple[:name].should == "Nathan"
end
end
context "when passed a Symbol that does not correspond to a name of an Attribute defined on #set" do
it "raises an exception" do
lambda do
tuple[:fantasmic]
end.should raise_error
end
end
context "when passed a Relation != to #set" do
it "raises an exception" do
lambda do
tuple[photos_set]
end.should raise_error
end
end
end
describe "#[]=" do
attr_reader :retainer
before do
@retainer = Object.new
tuple.retain_with(retainer)
end
after do
tuple.release_from(retainer)
end
context "when passed an Attribute as the index argument" do
it "delegates to #set_value on the PrimitiveField matching the given Attribute" do
mock.proxy(tuple.field_for(tuple.set[:name])).set_value("New Name")
tuple[tuple.set[:name]] = "New Name"
end
end
context "when passed a Symbol as the index argument" do
it "delegates to #set_value on the PrimitiveField matching the Attribute named by the Symbol" do
mock.proxy(tuple.field_for(tuple.set[:name])).set_value("New Name")
tuple[:name] = "New Name"
end
end
context "when the passed in value is different than the original value" do
attr_reader :new_value
before do
@new_value = "Corey"
tuple[:name].should_not == new_value
end
it "triggers the on_update event" do
update_args = []
tuple.on_update(retainer) do |attribute, old_value, new_value|
update_args.push [attribute, old_value, new_value]
end
old_value = tuple[:id]
new_value = "#{tuple[:id]}_id"
tuple[:id] = new_value
update_args.should == [[tuple.set[:id], old_value, new_value]]
end
end
context "when the passed in value is the same than the original value" do
it "does not trigger the on_update event" do
tuple.on_update(retainer) do |attribute, old_value, new_value|
raise "Don't taze me bro"
end
tuple[:name] = tuple[:name]
end
end
end
describe "#dirty?" do
context "when any PrimitiveField is #dirty?" do
it "returns true" do
tuple.primitive_fields.any? do |field|
field.dirty?
end.should be_true
tuple.should be_dirty
end
end
context "when no #primitive_fields are #dirty?" do
it "returns false" do
tuple.pushed
tuple.primitive_fields.any? do |field|
field.dirty?
end.should be_false
tuple.should_not be_dirty
end
end
end
describe "#push" do
it "calls Unison.origin.push(self)" do
mock.proxy(origin).push(tuple)
tuple.push
end
it "sets new? to false" do
tuple.should be_new
tuple.push
tuple.should_not be_new
end
it "sets dirty? to false" do
tuple.push
tuple[:name] = "#{tuple[:name]} with addition"
tuple.should be_dirty
tuple.push
tuple.should_not be_dirty
end
it "returns self" do
tuple.push.should == tuple
end
end
describe "#delete" do
it "removes itself from its #set" do
tuple = User.find("nathan")
tuple.set.should include(tuple)
tuple.delete
tuple.set.should_not include(tuple)
end
end
describe "#pushed" do
it "sets new? to false" do
tuple.should be_new
tuple.pushed
tuple.should_not be_new
end
it "sets dirty? to false" do
tuple.pushed
tuple[:name] = "#{tuple[:name]} with addition"
tuple.should be_dirty
tuple.pushed
tuple.should_not be_dirty
end
it "returns self" do
tuple.pushed.should == tuple
end
end
describe "#has_attribute?" do
it "delegates to #set" do
tuple.has_attribute?(:id).should == tuple.set.has_attribute?(:id)
end
end
describe "#has_synthetic_attribute?" do
it "delegates to #set" do
tuple.has_synthetic_attribute?(:conqueror_name).should == tuple.set.has_synthetic_attribute?(:conqueror_name)
end
end
describe "#persistent_hash_representation" do
it "returns a Hash of attribute => value pairs for only #primitive_fields" do
tuple.persistent_hash_representation.should == {
:id => "nathan",
:hobby => "Bomb construction",
:name => "Nathan",
:team_id => nil,
:developer => nil,
:show_fans => true
}
end
end
describe "#hash_representation" do
it "returns a Hash of attribute => value pairs for all #fields" do
hash_representation = tuple.hash_representation
hash_representation.keys.length.should == tuple.fields.length
tuple.fields.each do |field|
hash_representation[field.attribute.name].should == field.value
end
end
end
describe "#fields" do
it "returns an Array of all Fields" do
publicize tuple, :fields_hash
tuple.fields.should == tuple.fields_hash.values
end
end
describe "#primitive_fields" do
it "returns an Array of all PrimitiveFields from the #fields hash" do
tuple.fields.any? {|field| field.instance_of?(SyntheticField)}.should be_true
primitive_fields = tuple.primitive_fields
primitive_fields.should_not be_empty
primitive_fields.each do |field|
field.class.should == PrimitiveField
end
end
end
describe "#synthetic_fields" do
it "returns an Array of all SyntheticFields from the #fields hash" do
tuple.fields.any? {|field| field.instance_of?(PrimitiveField)}.should be_true
synthetic_fields = tuple.synthetic_fields
synthetic_fields.should_not be_empty
synthetic_fields.each do |field|
field.class.should == SyntheticField
end
end
end
describe "#field_for" do
context "when passed an Attribute in the PrimitiveTuple" do
it "returns the Field corresponding to the Attribute" do
attribute = User[:id]
field = tuple.field_for(attribute)
field.tuple.should == tuple
field.attribute.should == attribute
end
end
context "when passed a Symbol that names an Attribute in the PrimitiveTuple" do
it "returns the Field corresponding to the Attribute" do
attribute = User[:id]
field = tuple.field_for(:id)
field.tuple.should == tuple
field.attribute.should == attribute
end
end
context "when passed an Attribute that is not in the PrimitiveTuple" do
it "raises an ArgumentError" do
lambda do
field = tuple.field_for(Photo[:id])
end.should raise_error(ArgumentError)
end
end
context "when passed a Symbol that does not name an Attribute in the PrimitiveTuple" do
it "raises an ArgumentError" do
lambda do
field = tuple.field_for(:hello_there)
end.should raise_error(ArgumentError)
end
end
end
describe "#<=>" do
it "sorts on the :id attribute" do
tuple_1 = Photo.find("nathan_photo_1")
tuple_2 = Photo.find("nathan_photo_2")
(tuple_1 <=> tuple_2).should == -1
(tuple_2 <=> tuple_1).should == 1
(tuple_1 <=> tuple_1).should == 0
end
end
describe "#signal" do
attr_reader :user, :signal
before do
@user = User.find("nathan")
end
context "when passed a Symbol" do
before do
@signal = user.signal(:name)
end
context "when the Symbol is the #name of a PrimitiveAttribute in the PrimitiveTuple's #set" do
it "returns an AttributeSignal for the corresponding PrimitiveAttribute" do
signal.attribute.should == users_set[:name]
end
context "when passed a block" do
it "returns a DerivedSignal with the AttributeSignal as its #source" do
derived_signal = user.signal(:name) do |value|
"#{value} the Terrible"
end
derived_signal.class.should == Signals::DerivedSignal
derived_signal.value.should == "#{user.name} the Terrible"
end
end
end
context "when the Symbol is the #name of a SyntheticAttribute in the PrimitiveTuple's #set" do
before do
User.synthetic_attribute :team_name do
team.signal(:name)
end
@user = User.create(:team_id => "mangos")
end
it "returns the Signal defined by the SyntheticAttribute for this PrimitiveTuple" do
signal = user.signal(:team_name)
signal.retain_with(retainer = Object.new)
signal.value.should == user.team.name
on_change_args = []
signal.on_change(retainer) do |*args|
on_change_args.push(args)
end
expected_old_name = user.team.name
new_name = "The Tacos"
user.team.name = new_name
on_change_args.should == [[new_name]]
signal.release_from(retainer)
end
context "when passed a block" do
it "returns a DerivedSignal with the signal associated with the synthetic attribute as its #source" do
derived_signal = user.signal(:team_name) do |value|
"#{value} Suck!"
end
derived_signal.class.should == Signals::DerivedSignal
derived_signal.value.should == "#{user.team_name} Suck!"
end
end
end
context "when the Symbol names a SingletonRelation" do
it "returns a SingletonRelationSignal with the Relation as its #value" do
signal = user.signal(:team)
signal.class.should == Signals::SingletonRelationSignal
signal.value.should == user.team
end
end
context "when the Symbol is not the #name of any kind of attribute or relation" do
it "raises an ArgumentError" do
lambda do
@signal = user.signal(:bullshit)
end.should raise_error(ArgumentError)
end
end
end
context "when passed an PrimitiveAttribute" do
context "when the PrimitiveAttribute belongs to the PrimitiveTuple's #set" do
before do
@signal = user.signal(users_set[:name])
end
it "returns an AttributeSignal with #attribute set to the passed in PrimitiveAttribute" do
signal.attribute.should == users_set[:name]
end
context "when passed a block" do
it "returns a DerivedSignal with the AttributeSignal as its #source" do
derived_signal = user.signal(users_set[:name]) do |value|
"#{value} the Terrible"
end
derived_signal.class.should == Signals::DerivedSignal
derived_signal.value.should == "#{user.name} the Terrible"
end
end
end
context "when the PrimitiveAttribute does not belong to the PrimitiveTuple's #set" do
it "raises an ArgumentError" do
lambda do
@signal = user.signal(photos_set[:name])
end.should raise_error(ArgumentError)
end
end
end
context "when passed a SyntheticAttribute" do
before do
User.synthetic_attribute :team_name do
team.signal(:name)
end
@user = User.create(:team_id => "mangos")
end
it "returns the Signal defined by the SyntheticAttribute for this PrimitiveTuple" do
signal = user.signal(User[:team_name])
signal.retain_with(retainer = Object.new)
signal.value.should == user.team.name
on_change_args = []
signal.on_change(retainer) do |*args|
on_change_args.push(args)
end
expected_old_name = user.team.name
new_name = "The Tacos"
user.team.name = new_name
on_change_args.should == [[new_name]]
signal.release_from(retainer)
end
context "when passed a block" do
it "returns a DerivedSignal with the signal associated with the synthetic attribute as its #source" do
derived_signal = user.signal(:team_name) do |value|
"#{value} Suck!"
end
derived_signal.class.should == Signals::DerivedSignal
derived_signal.value.should == "#{user.team_name} Suck!"
end
end
end
end
describe "#bind" do
context "when passed in expression is an Attribute" do
it "retrieves the value for an Attribute defined on the set of the Tuple class" do
tuple.bind(User.set[:id]).should == "nathan"
tuple.bind(User.set[:name]).should == "Nathan"
end
end
context "when passed in expression is not an Attribute" do
it "is the identity function" do
tuple.bind(:id).should == :id
tuple.bind("nathan").should == "nathan"
tuple.bind("Hi").should == "Hi"
end
end
end
describe "#==" do
attr_reader :other_tuple
context "when other is not a Tuple" do
it "returns false" do
other_object = Object.new
tuple.should_not == other_object
end
end
context "when other Tuple#fields == #fields" do
before do
@other_tuple = User.new(:id => "nathan", :name => "Nathan")
publicize other_tuple, :fields
other_tuple.fields.should == tuple.fields
end
it "returns true" do
tuple.should == other_tuple
end
end
context "when other Tuple#fields != #fields" do
before do
@other_tuple = User.new(:id => "nathan_clone", :name => "Nathan's Clone")
publicize other_tuple, :fields
other_tuple.fields.should_not == tuple.fields
end
it "returns false" do
tuple.should_not == other_tuple
end
end
end
end
end
end
end
| true |
f56eb97b4db4bdc1f1c1aebd2eb6dc5583fcaefa
|
Ruby
|
robesris/fb_nd
|
/app/models/piece/nav.rb
|
UTF-8
| 644 | 2.59375 | 3 |
[] |
no_license
|
class Piece::Nav < Piece
def val
60
end
def side1
Constants::KING
end
def move_to(space, pass)
self.player.update_attribute(:in_check_this_turn, self.in_check?)
super(space, pass)
end
def in_check?
self.player.in_check?
end
def flip
return false if self.in_check? || self.player.in_check_this_turn?
if super
self.player.win_game
else
return false
end
end
def goal_over
if self.player.empty_keep? && self.player.nav.in_last_row?
self.player.win_game
end
end
def die
super
self.player.lose_game
end
def is_creature?
false
end
end
| true |
0be011aaf6a2553c2a120710c58e0c2c806ef0ff
|
Ruby
|
haydenwalls/Solar-System
|
/planet.rb
|
UTF-8
| 733 | 3.25 | 3 |
[] |
no_license
|
class Planet
attr_reader :name, :color, :mass_kg, :distance_from_sun_km, :fun_fact
def initialize(name, color, mass_kg, distance_from_sun_km, fun_fact)
raise ArgumentError.new("Mass value must be greater than zero") if mass_kg.to_i <= 0
raise ArgumentError.new("Distance from Sun must be greater than zero") if distance_from_sun_km.to_i <= 0
@name = name
@color = color
@mass_kg = mass_kg
@distance_from_sun_km = distance_from_sun_km
@fun_fact = fun_fact
end
def summary
return "#{@name} datafile:
Color: #{@color}
Mass (kg): #{@mass_kg}
Distance from the Sun (km): #{@distance_from_sun_km}
Fun Fact: #{@fun_fact}"
end
end
| true |
d77fd9d7c7199497eea9db8df7bb630211b0d5fd
|
Ruby
|
bchatelard/CronIt
|
/lib/cron_it.rb
|
UTF-8
| 386 | 2.546875 | 3 |
[] |
no_license
|
require 'active_support/time'
class CronIt
def self._every
@every || []
end
def self.every(time, opts = {})
@every ||= []
@every << [time, opts]
end
def self._run
@run ||= []
b = eval("#{self.to_s}.new")
if !b.nil?
@run.each do |r|
eval("b.#{r}")
end
end
end
def self.run(func)
@run ||= []
@run << func
end
end
| true |
33d5c33851a55d1b0e265b525f9bc9fec3e4c367
|
Ruby
|
timsully/RB_101_Programming_Foundations
|
/lesson_04/practice_problems_01/practice_problem_02.rb
|
UTF-8
| 354 | 4.09375 | 4 |
[] |
no_license
|
# Practice Problem 2
# How does count treat the block's return value? How can we find out?
['ant', 'bat', 'caterpillar'].count do |str|
str.length < 4
end
# A block is given so it counts the number of elements for which the block returns a true value. Thus, returning the numbers of elements that is less than 4 characters within the array which is 2.
| true |
a6ed824f8eb5ec9fdd7e226ce4925e0183365176
|
Ruby
|
ko1/ruby-ptrace
|
/sample/fakeeintr.rb
|
UTF-8
| 1,664 | 3.0625 | 3 |
[] |
no_license
|
#
# fakeeintr.rb
#
require 'optparse'
require 'ptrace'
opt = OptionParser.new{|o|
o.on('-p', '--pid PID'){|pid|
$pid = pid.to_i
}
o.on('--unistd UNISTD_FILE_PATH'){|us|
# for exmaple: '/usr/include/asm-i486/unistd.h'
$uni_std_file_path = us
}
o.on('-v', '--verbose'){
$verbose = true
}
}
opt.parse!(ARGV)
if defined?($uni_std_file_path)
# read syscall number information
class PTrace
SYSCALL = Hash.new
File.read($uni_std_file_path).each_line{|line|
/\#define __NR_(\S+)\s+(\d+)/ =~ line
SYSCALL[$2.to_i] = $1
}
end
end
if defined? PTrace::SYSCALL
def syscall_name eax
PTrace::SYSCALL[eax]
end
else
def syscall_name eax
eax.to_s
end
end
$n = 0
$intr_signal = :SIGALRM
def fake_eintr? name
if $n < 100
$n += 1
true
else
$n = 0
false
end
end
def exec_trap ptrace
regs = ptrace.getregs
name = syscall_name regs.orig_eax
puts "#{$is_call ? 'call:' : 'rtrn:'} #{name}" if $verbose
$is_call = !$is_call
if fake_eintr? name
if $is_call # returning timing
ptrace.syscall
else
ptrace.syscall $intr_signal
end
else
ptrace.syscall # continue
end
end
def trace_syscall ptrace
$is_call = true
ptrace.wait
ptrace.syscall
while e = ptrace.wait
case e
when :SIGTRAP
exec_trap ptrace
else
if e == $intr_signal
ptrace.syscall
else
ptrace.syscall e
end
end
end
end
if defined?($pid)
ptrace = PTrace.attach($pid)
elsif ARGV.empty?
puts opt.help
exit
else
ptrace = PTrace.exec(ARGV.join(' '))
end
puts "PID: #{ptrace.pid}" if $verbose
trace_syscall(ptrace)
| true |
1daf4fe268d4713a81716617f896840721721f63
|
Ruby
|
pdxwolfy/Challenges
|
/Pascal/pascals_triangle.rb
|
UTF-8
| 764 | 3.546875 | 4 |
[] |
no_license
|
#!/usr/bin/env ruby
# Copyright (c) 2016 Pete Hanson
# frozen_string_literal: true
# :reek:FeatureEnvy
class Triangle
attr_reader :rows
def initialize height
@rows = (1..height).map { next_row }
end
private
def next_row
bottom_row = @previous_row ? [0, *@previous_row, 0] : [0, 1]
@previous_row = bottom_row.each_cons(2).map { |left, right| left + right }
end
end
# class Triangle
# attr_reader :rows
#
# def initialize height
# factorial = [1]
# 1.upto(height).each { |n| factorial << n * factorial.last }
#
# @rows = 0.upto(height - 1).map do |row|
# 0.upto(row).map do |seq|
# factorial[row] / (factorial[seq] * factorial[row - seq])
# end
# end
# end
# end
#
# puts Triangle.new(500).rows.last
| true |
9ceb13084b922e3042345b2c644da0a584ecbf5d
|
Ruby
|
mhdz9/codewars
|
/Ruby/ipv4-to-int32.rb
|
UTF-8
| 764 | 3.875 | 4 |
[] |
no_license
|
=begin
Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).
- 1st octet 128 has the binary representation: 10000000
- 2nd octet 32 has the binary representation: 00100000
- 3rd octet 10 has the binary representation: 00001010
- 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.
Write a function ip_to_int32(ip) ( JS: ipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number.
ipToInt32("128.32.10.1") => 2149583361
=end
def ip_to_int32(ip)
return ip.split(".").map {|x| x.to_i.to_s(2).rjust(8,"0")}.join("").to_i(2)
end
| true |
97c7b2b01595402b68b6baa6e7c8f4bfdec6d194
|
Ruby
|
PersonofNote/cypher-sinatra
|
/cypher.rb
|
UTF-8
| 1,050 | 3.46875 | 3 |
[] |
no_license
|
require 'sinatra'
#puts "Secrets! Put in a message and I'll encode it for you."
#message = gets.chomp
#puts "Input a (whole) number for me to use."
#shift = gets.chomp.to_i
def ceasar_cypher(message,shift)
new_message = []
letters = message.split('')
letters.each do |lett|
num = lett.ord
if num.between?(97,122)
num = (num + shift)
if num > 122
num = (num - 122) + 96
elsif num < 97
num = (num + 122) - 96
end
end
if num.between?(65,91)
num = (num + shift)
if num > 91
num = (num - 91) + 65
elsif num < 65
num = (num + 91) - 65
end
end
new_message << num.chr
end
return new_message.join
end
get '/' do
message = params["message"]
shift = params["shift"].to_i
new_message = ceasar_cypher(message,shift) unless message.nil?
#render erb template called index. Create local variable for x that is equal to x from this file.
erb :index, :locals => {:shift => shift, :message => message, :new_message => new_message}
end
| true |
cf215eff873f351020c7ae7926bf281708d74878
|
Ruby
|
clyeager/oop
|
/lesson_4/practice_problems_medium1/medium1_1.rb
|
UTF-8
| 405 | 3.578125 | 4 |
[] |
no_license
|
class BankAccount
attr_reader :balance
def initialize(starting_balance)
@balance = starting_balance
end
def positive_balance?
balance >= 0
end
end
#Alyssa thinks Ben is missing the @ on the balance instance variable in the body
# of the positive_balance? method. Who is right?
#Ben is correct because he is referencing the balance getter method, given to him by attr_reader :balance
| true |
fc560259ffa5cc1c0507fc9961bb0662ad567862
|
Ruby
|
night1ightning/ruby_course
|
/listen1/calculate_ideal_weith.rb
|
UTF-8
| 576 | 3.5625 | 4 |
[] |
no_license
|
require 'io/console'
def ideal_weight(growth)
growth - 110
end
puts "Программа подсчета"\
" идеального веса попросит вас ввести имя и рост.\n"\
"Введите Enter, чтобы начать.\n"
STDIN.getch
print ' Ваше имя : '
name = gets.chomp
print ' Ваш рост : '
growth = gets.to_i
puts ''
weight = ideal_weight(growth)
if (weight > 0)
puts "Здраствуйте \"#{name}\", ваш идеальный вес #{weight}."
else
puts 'Ваш вес уже оптимальный'
end
| true |
3f2b175019fd9bd39cdc5e927e22eec376a711a7
|
Ruby
|
mrcc87/arduino_ruby
|
/blink_led_menu.rb
|
UTF-8
| 945 | 2.640625 | 3 |
[] |
no_license
|
require 'artoo'
# Circuit and schematic here: http://arduino.cc/en/Tutorial/Blink
#
connection :arduino, :adaptor => :firmata, :port => '/dev/cu.usbmodemfa131' #linux
#connection :firmata, :adaptor => :firmata, :port => '127.0.0.1:8023'
device :board, :driver => :device_info
device :led, :driver => :led, :pin => 13
work do
puts "Firmware name: #{board.firmware_name}"
puts "Firmata version: #{board.version}"
if (led.on?)
led.off
end
loop do
puts "=" * 40
puts "Press 1 to turn on and 2 to turn off the led. q to quit..."
input = gets.chomp
case input
when '1'
if (led.off?)
puts "Turning the led on..."
led.on
else
puts "The led is already on."
end
when '2'
if (led.on?)
puts "Turning the led off..."
led.off
else
puts "The led is already off."
end
when 'q'
puts "Quitting..."
break
end
end
end
| true |
2fabc60f0b72257f60d8326dded264376deaaf8e
|
Ruby
|
NativeScript/webkit
|
/Tools/iExploder/iexploder-1.7.2/tools/osx_last_crash.rb
|
UTF-8
| 1,664 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env ruby
# Copyright 2010 Thomas Stromberg - All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# Gives you information about the most recent crash for each application
# that has crashed within the last 2 days
$LogDir=ENV['HOME'] + '/Library/Logs/CrashReporter'
$Days=1
$StackCount=5
files=`find #$LogDir -mtime -#$Days -type f | grep -v synergy`
files.each { |filename|
filename.chop!
record = 0
date=''
stackTrace = []
File.open(filename).readlines.each { |line|
#puts line
if line =~ /^Date.*(200.*)/
date = $1
end
if line =~ /^Thread \d+ Crashed/
record = 1
# reset the stack trace
stackTrace = []
end
if record
stackTrace << line
record = record + 1
# stop recording after $StackCount lines
if record > ($StackCount + 2)
record = nil
end
end
}
puts File.basename(filename) + " - " + date
puts "==================================================="
stackTrace.each { |line|
puts line
}
puts ""
}
| true |
5c446483b9ed472c1265ac985de7c38b2c2dfa8b
|
Ruby
|
zbb272/OO-mini-project-dc-web-career-021819
|
/app/models/Allergen.rb
|
UTF-8
| 204 | 2.875 | 3 |
[] |
no_license
|
class Allergen
attr_accessor :ingredient, :user
@@all = []
def initialize (ingredient, user)
@ingredient, @user = ingredient, user
@@all << self
end
def self.all
@@all
end
end
| true |
7b5b137f4e9096d0d39538c061b3df21afdbb91e
|
Ruby
|
eashman/verisign_vip
|
/lib/verisign_vip.rb
|
UTF-8
| 13,818 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'savon'
require 'uuidtools'
require 'hpricot'
require 'yaml'
class VerisignVIP
class << self
# Use the ActivateToken API to activate new or
# inactive credentials. If the activation is
# successful, the credential is Enabled and
# ready for use.
def activate_token(token_id, otp1 = nil, otp2 = nil)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:OTP1>#{otp1}</wsdl:OTP1>" if otp1
attributes += "<wsdl:OTP2>#{otp2}</wsdl:OTP2>" if otp2
soap_request(:mgmt, "ActivateToken", attributes)
end
# Use the DeactivateToken API to deactivate
# credentials. If you no longer want to allow
# a credential to be used on your Web site,
# you can deactivate the credential by
# setting it to the Inactive state.
#
# When you deactivate a token, you can also
# specify the reason you deactivated. This
# information will be used as part to provide
# network wide intelligence information for
# the token.
def deactivate_token(token_id, reason = nil)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:Reason>#{reason}</wsdl:Reason>" if reason
soap_request(:mgmt, "DeactivateToken", attributes)
end
# Use the Validate API to authenticate credentials.
# To authenticate an Enabled credential, send a
# Validate call including the credential ID and a
# security code. Credentials are validated according
# to the security profile for that credential type.
# The Validate API can also be used to validate
# temporary security codes.
#
# When you send a Validate call, the VIP Web
# Services check the validity of the security code
# and return a response.
def validate(token_id, otp)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:OTP>#{otp}</wsdl:OTP>"
soap_request(:val, "Validate", attributes)
end
# Use the ValidateMultiple API to validate one of
# several credentials. To authenticate a user
# that has more than one credential, send a
# ValidateMultiple API call to check all of the
# user’s credentials against a single
# security code.
def validate_multiple(token_ids, otp, send_successful_token_id = false)
raise "An array of token IDs is required" unless token_ids.is_a?(Array)
attributes = ""
token_ids.each do |token|
attributes += "<wsdl:TokenId>#{token}</wsdl:TokenId>"
end
attributes += "<wsdl:OTP>#{otp}</wsdl:OTP>"
attributes += "<wsdl:SendSuccessfulTokenId>#{send_successful_token_id}</wsdl:SendSuccessfulTokenId>"
soap_request(:val, "ValidateMultiple", attributes)
end
# When a user does not use their credential
# for an extended period of time, the credential
# becomes out of synchronization. Synchronization
# with VIP restores the credential’s synchronization.
#
# The Synchronize API restores a credential to
# synchronization. To synchronize an end user
# credential that is out of synchronization, send
# a synchronize call that includes the credential
# ID and two consecutive security codes. When you
# send a synchronize call, the VIP Web Services
# check the validity of the security codes, and
# return a response.
#
# Note: SMS credentials do not need to be
# synchronized.
def synchronize(token_id, otp1, otp2)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:OTP1>#{otp1}</wsdl:OTP1>"
attributes += "<wsdl:OTP2>#{otp2}</wsdl:OTP2>"
soap_request(:val, "Synchronize", attributes)
end
# Credentials become locked when they exceed
# the configured number of allowed
# continuous validation failures.
#
# Use the UnlockToken API to unlock credentials
# that have become locked. Unlocking a
# credential changes the state of the
# credential from Locked to Enabled and makes
# it ready for use.
#
# Note: Verify that a user is in possession of
# their credential before you unlock it. First,
# verify the user’s identity through some other
# means, and then request a security code from
# the user. To check the security code, use the
# CheckOTP API. If the CheckOTP call succeeds,
# then make an UnlockToken call.
def unlock_token(token_id)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
soap_request(:mgmt, "UnlockToken", attributes)
end
# Use the DisableToken API to disable a credential.
# Disabling a credential changes its state from
# Enabled or Locked to Disabled, and makes it
# unavailable for use. For example, an issuer
# should disable a credential if an end-user reports
# that the credential has been forgotten,
# lost, or stolen.
#
# When you disable a token, you can also specify
# the reason you disabled it. This information will
# be used as part to provide network wide
# intelligence information for the token.
def disable_token(token_id, reason = nil)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:Reason>#{reason}</wsdl:Reason>" if reason
soap_request(:mgmt, "DisableToken", attributes)
end
# Credentials can not be used, tested, or synchronized
# unless they are Enabled.
#
# Use the EnableToken API to enable credentials that
# an issuer has disabled.
#
# Use this operation to change the state of a disabled
# credential to Enabled. When you Enable a credential,
# VIP Web Services check the validity of the credential
# ID and return a response. If the enable operation is
# successful, the credential changes from Disabled to
# Enabled and is ready for use.
def enable_token(token_id)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
soap_request(:mgmt, "EnableToken", attributes)
end
# Use the SetTemporaryPassword API to set a temporary
# security code for a credential. You can optionally
# set an expiration date for the security code, or
# set it for one-time use only. The request requires
# the credential ID and the temporary security code
# string.
#
# You can also use the SetTemporaryPassword API to
# clear a temporary security code. To clear the
# temporary security code, send the
# SetTemporaryPassword API and leave the
# TemporaryPassword request parameter empty.
#
# Note: The SetTemporaryPassword API works on both
# Disabled and Enabled credentials. VeriSign
# recommends that you check the credential state
# before issuing a temporary security code. This
# prevents users from trying to authenticate using
# disabled credentials.
def set_temporary_password(token_id, temporary_password, expiration_date = nil, one_time_use_only = nil)
raise "expiration_date must be a Ruby Time object" if expiration_date and !expiration_date.is_a?(Time)
raise "one_time_use_only must be either true or false" if one_time_use_only && ![true, false].include?(one_time_use_only)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:TemporaryPassword>#{temporary_password}</wsdl:TemporaryPassword>"
attributes += "<wsdl:ExpirationDate>#{expiration_date.iso8601}</wsdl:ExpirationDate>" if expiration_date
attributes += "<wsdl:OneTimeUseOnly>#{one_time_use_only}</wsdl:OneTimeUseOnly>" if one_time_use_only
soap_request(:mgmt, "SetTemporaryPassword", attributes)
end
# Use the GenerateTemporaryPassword API to generate a
# temporary security code for a credential. You
# can optionally set an expiration date for the
# security code, or set it for one-time use only.
# The request requires the credential ID.
#
# Note: The GenerateTemporaryPassword API works on
# both Disabled and Enabled credentials. VeriSign
# recommends that you check the credential state
# before issuing a temporary security code. This
# prevents users from trying to authenticate
# using disabled credentials.
def generate_temporary_password(token_id, expiration_date = nil, one_time_use_only = nil)
raise "expiration_date must be a Ruby Time object" if expiration_date and !expiration_date.is_a?(Time)
raise "one_time_use_only must be either true or false" if one_time_use_only && ![true, false].include?(one_time_use_only)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:ExpirationDate>#{expiration_date.iso8601}</wsdl:ExpirationDate>" if expiration_date
attributes += "<wsdl:OneTimeUseOnly>#{one_time_use_only}</wsdl:OneTimeUseOnly>" if one_time_use_only
soap_request(:mgmt, "GenerateTemporaryPassword", attributes)
end
# Use the SetTemporaryPwdExpiration API to change
# the expiration date for a temporary security
# code you previously set using the
# SetTemporaryPwdExpiration API.
def set_temporary_pwd_expiration(token_id, expiration_date = nil)
raise "expiration_date must be a Ruby Time object" if expiration_date and !expiration_date.is_a?(Time)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:ExpirationDate>#{expiration_date.iso8601}</wsdl:ExpirationDate>" if expiration_date
soap_request(:mgmt, "SetTemporaryPwdExpiration", attributes)
end
# Use the GetTemporaryPwdExpiration API to find
# out the expiration date for a credential for
# which a temporary security code is already set.
def get_temporary_pwd_expiration(token_id)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
soap_request(:mgmt, "GetTemporaryPwdExpiration", attributes)
end
# Use the CheckOTP API to validate or synchronize a
# credential even if the credential is locked.
#
# The CheckOTP API validates or synchronizes a
# credential based on the number of security codes
# you provide. If you provide one security code,
# CheckOTP validates the credential. If you provide
# two security codes, CheckOTP synchronizes the credential.
#
# If a CheckOTP call fails to validate a credential,
# the CheckOTP call does not increment the credential's
# failed validation count. If a CheckOTP call synchronizes
# a credential, it does not change the credential state.
# You cannot use the CheckOTP API for credentials in a
# new or inactive state.
#
# Note: TheCheckOTP API call is for administrative
# purposes only, and is not a substitute for the
# Validate and Synchronize APIs.
#
# Do not use the CheckOTP API for normal authentication
# and synchronization because it overrides the
# requirement (in the Validate and Synchronize APIs)
# that a credential is Enabled.
#
# Because CheckOTP authenticates and synchronizes
# locked credentials, VeriSign recommends that you
# use it only when you can verify the identity of
# an end user. For normal authentication and
# synchronization, use the Validate and
# Synchronize APIs.
def check_otp(token_id, otp1, otp2 = nil)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
attributes += "<wsdl:OTP1>#{otp1}</wsdl:OTP1>"
attributes += "<wsdl:OTP2>#{otp2}</wsdl:OTP2>" if otp2
soap_request(:mgmt, "CheckOTP", attributes)
end
# Use the GetTokenInformation API to get detailed
# information about a credential, such as the
# credential state, whether it is a hardware or
# software credential, the credential expiration date,
# and the last time an API call was made to the VIP
# Web Services about the credential. The request
# requires only the credential ID.
def get_token_information(token_id)
attributes = "<wsdl:TokenId>#{token_id}</wsdl:TokenId>"
soap_request(:mgmt, "GetTokenInformation", attributes)
end
def get_server_time
soap_request(:prov, "GetServerTime")
end
private
def configuration
begin
@configuration ||= YAML::load(File.open(Rails.root.join("config", "verisign.yml")))
rescue Errno::ENOENT
raise Errno::ENOENT, "You must create a file called 'verisign.yml' containing configuration options in your config/ directory. See the README for details."
end
end
def soap_request(endpoint, action, attributes = nil)
host = configuration[Rails.env]["hostname"]
client = Savon::Client.new("https://#{host}/#{endpoint}/soap")
client.request.http.ssl_client_auth(
:cert => OpenSSL::X509::Certificate.new(File.open(configuration[Rails.env]["certificate_file"])),
:key => OpenSSL::PKey::RSA.new(File.open(configuration[Rails.env]["private_key_file"]), configuration[Rails.env]["private_key_password"]),
:ca_file => "cacert.pem",
:verify_mode => OpenSSL::SSL::VERIFY_PEER
)
response = client.send("#{action}!") do |soap|
soap.action = action
soap.input = action, { :Version => "2.0", :Id => UUIDTools::UUID.timestamp_create.to_s }
soap.namespace = "http://www.verisign.com/2006/08/vipservice"
soap.body = attributes if attributes
end
parse_response(response.to_xml)
end
def parse_response(xml)
Hpricot::XML(xml)
end
end
end
| true |
ab2259f14b76c0cb28200a0e4bccc6db2ecf70f0
|
Ruby
|
wjb108/intro-programming-with-ruby
|
/ruby_exercises_prep_folder/loops1/loopception.rb
|
UTF-8
| 1,528 | 4.375 | 4 |
[] |
no_license
|
=begin
The code below is an example of a nested loop. Both loops currently loop infinitely.
Modify the code so each loop stops after the first iteration.
=end
=begin
My Answer:
added break in lines 17 and 19, 17 more obvious and 19 less obvious had i put a break
in line 15 it wouldn't have executed the rest of the commands
LS Answer:
Looping within a loop is not uncommon.
Therefore, it's important to understand how to avoid infinite loops and where to place break statements.
When it comes to nested loops, it can be difficult to clearly understand what's going on.
As you digest the code, focus on one loop at a time.
We begin by modifying the innermost block.
This loop can be stopped by placing break on the line following #puts.
This forces the loop to iterate only once.
After we've fixed the innermost loop, our attention is now focused on the parent loop.
We modify this loop the same way we modified the child loop:
by placing break on the line following the end of the innermost loop.
The code in this exercise is considered bad practice.
We use it to illustrate how to break out of a nested loop, not to encourage the use of loops that only perform one iteration.
We can easily rewrite this code without using any loops, but then the problem makes no sense:
puts 'This is the outer loop.'
puts 'This is the inner loop.'
puts 'This is outside all loops.'
=end
loop do
puts 'This is the outer loop.'
loop do
puts 'This is the inner loop.'
break
end
break
end
puts 'This is outside all loops.'
| true |
af4d597aded40bc598ccf113cf367c3ecf0672db
|
Ruby
|
elikohen/EKServicesGenerator
|
/model/service.rb
|
UTF-8
| 662 | 2.640625 | 3 |
[] |
no_license
|
class Service
attr_accessor :messages
@messages
def hasPost
messages.each do |message|
if message.isPost || message.isPostJSON
return true
end
end
return false
end
def hasGet
messages.each do |message|
if message.isGet
return true
end
end
return false
end
def hasPut
messages.each do |message|
if message.isPut || message.isPutJSON
return true
end
end
return false
end
def hasDelete
messages.each do |message|
if message.isDelete || message.isDeleteJSON
return true
end
end
return false
end
end
| true |
1d6cbe7e096b6c18687c8588edc8aca53e400296
|
Ruby
|
apiology/punchlist
|
/lib/punchlist/renderer.rb
|
UTF-8
| 362 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Punchlist
# Render a text format of offenses
class CliRenderer
def render(output)
lines = output.map do |offense|
"#{offense.filename}:#{offense.line_num}: #{offense.line}"
end
out = lines.join("\n")
if out.empty?
out
else
out + "\n"
end
end
end
end
| true |
7c6e0314820e96530520cbadc0518bc778d5d880
|
Ruby
|
apfeltee/shellstuff
|
/programs/curse.rb
|
UTF-8
| 849 | 2.890625 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
#!/usr/bin/env ruby
require "pp"
require "optparse"
require "shellwords"
INITIAL_CURSEWORDS = %w(fuck shit crap damn bastard idiot)
class CurseWords
def initialize
@cursewords = INITIAL_CURSEWORDS
@opts = %w(-A3 -inP --color=always)
@realargs = []
@prs = OptionParser.new{|prs|
prs.on("-w <s>", "--word=<s>", "Additional curse word"){|v|
@cursewords.push(v)
}
}
@prs.parse!
end
def msg(str)
$stderr.puts("curse:msg: #{str}")
end
def run
if ARGV.length > 0 then
cursepat = "(#{@cursewords.map{|s| s.shellescape }.join("|")})"
cmd = ["grep", "-r", *@opts, cursepat, *@realargs]
msg "using pattern #{cursepat.inspect}"
msg "running #{cmd}, please be patient ..."
exec(*cmd)
else
puts(@prs.help)
end
end
end
begin
CurseWords.new.run
end
| true |
03462769916f4a8fb1ea8e4b1d4516f671448b4f
|
Ruby
|
hidetsubo/.emacs.d
|
/src/rurima/db-1_9_3/method/-rake-file-utils/i.verbose.rake
|
UTF-8
| 532 | 3.171875 | 3 |
[] |
no_license
|
kind=defined
visibility=public
names=verbose
--- verbose(value = nil){ ... }
詳細を出力するかどうかを制御します。
@param value 真を指定すると詳細を出力します。
例
verbose # 現在の状態を返します。
verbose(v) # 与えられた状態に変更します。
verbose(v) { code } # ブロックを評価する間だけ与えられた状態に変更します。
# ブロックの評価が終わると元の値に戻します。
| true |
3304cb5f7b09f8f49f82360d9d0462f660feae41
|
Ruby
|
srividhyashanker/cs61aPrepCourse
|
/Chapter14/programLogger.rb
|
UTF-8
| 327 | 3.046875 | 3 |
[] |
no_license
|
def log descriptionOfBlock, &block
puts 'Beginning "' + descriptionOfBlock + '"...'
doBlock = block.call
puts '..."' + descriptionOfBlock + '" finished, returning: ' + doBlock.to_s
end
log 'outer block' do
log 'some little block' do
2 + 2 +1
end
log 'yet another block' do
puts 'I like Thai food!'
end
5 == 3
end
| true |
4f9b374daa85f208b164290f7bfc4f7aefa30feb
|
Ruby
|
dariota/swagger-demo
|
/client/echo_client.rb
|
UTF-8
| 487 | 2.515625 | 3 |
[] |
no_license
|
require 'swagger_client'
require 'echo_api_remote'
api_client = SwaggerClient::EchoServerApi.new
remote_client = EchoApiRemote::EchoServerApi.new
data, status_code, headers = api_client.what_did_i_say_with_http_info(ARGV[0])
puts "Local:"
puts "\tI said: \"#{data.client_said}\""
puts "\tStatus: #{status_code}"
data, status_code, headers = remote_client.what_did_i_say_with_http_info(ARGV[0])
puts "Remote:"
puts "\tI said: \"#{data.client_said}\""
puts "\tStatus: #{status_code}"
| true |
095115567e721b8dcaab1fc46e1da552e5eadf96
|
Ruby
|
kareemgrant/warmup-exercises
|
/15-say-1/say.rb
|
UTF-8
| 1,035 | 4.09375 | 4 |
[] |
no_license
|
class Say
def initialize(number)
left = number
tens = left/10
num_string = ''
case tens
when 9
num_string += "ninety"
when 8
num_string += "eighty"
when 7
num_string += "seventy"
when 6
num_string += "sixty"
when 5
num_string += "fifty"
when 4
num_string += "forty"
when 3
num_string += "thirty"
when 2
num_string += "twenty"
else
num_string += "ninety"
end
left = left - (tens * 10)
ones = left
puts ones
#puts num_string
case ones
when 1
num_string += "one"
when 2
num_string += "two"
when 3
puts "in here"
num_string += "three"
when 4
num_string += "four"
when 5
num_string += "five"
when 6
num_string += "six"
when 7
num_string += "seven"
when 8
num_string += "eight"
when 9
num_string += "nine"
else
num_string += " "
end
puts num_string
end
end
Say.new(93)
Say.new(23)
| true |
f34446e58267a842e004899b41169fc0c39671a1
|
Ruby
|
yunglleung1/OO-Art-Gallery-nyc-web-071618
|
/app/models/painting.rb
|
UTF-8
| 423 | 3.375 | 3 |
[] |
no_license
|
class Painting
attr_reader :title, :style
@@all = []
def initialize(title, style)
@title = title
@style = style
@@all << self
end
def self.all# Get a list of all paintings
@@all
end
def self.get_painting_styles# Get a list of all painting styles
style = all.map do |painting|
painting.style
end
style.uniq #a style should not appear more than once in the list
end
end
| true |
15a902cddff6a8c141473f05f41f44cc660b58bf
|
Ruby
|
Brendamcr2/Game
|
/Game.rb
|
UTF-8
| 1,141 | 3.546875 | 4 |
[] |
no_license
|
Nice Job Girl!! xoxo Rhece!
control_var = ""
until control_var == "exit"
puts "Welcome to Trivia!"
puts "Today you will be tested on how well you know movies!"
puts "Good luck! Write begin when ready to start Trivia!"
welcome = gets.chomp
case welcome
when "begin"
puts "______________________________________________"
puts "What role does Leonardo Dicaprio play in the movie Titanic?"
ans = gets.chomp
if ans == 'Jack'
puts 'Great job! Next question...'
puts "_____________________________________________"
else
puts "incorrect!"
end
puts "Did Julia Roberts play in the film Pretty Woman?"
ans = gets.chomp
if ans == "yes"
puts "Great job!"
puts "_________________________________________________"
else
puts "Wrong answer! Sorry, start game over"
end
puts "Which of the following songs features in The Lion King:
a. Let It Go, b. Circle of Life, c. Circle of Love?"
ans = gets.chomp
if ans == "b"
puts "Great job!"
puts "Thank you for playing Trivia!"
else
puts "Not quite! Start over!"
end
when "exit"
control_var = "exit"
end #case
end #loop
Good job!
| true |
53d1b50a8ba6ccb35037647581e4cd2f37bc0233
|
Ruby
|
orimolad/aa_classwork
|
/w4d1/skeleton/lib/00_tree_node.rb
|
UTF-8
| 1,368 | 3.5 | 4 |
[] |
no_license
|
require "byebug"
class PolyTreeNode
attr_reader :value, :parent,
:children
def initialize(value)
@value = value
@parent = nil
@children = []
end
def parent=(node) # node = nil or any node instance
if node == nil
@parent.children.delete(self)
@parent = nil
elsif self.parent == nil # if our current node doesn't have a parent yet
@parent = node # parent = node we passed into this method
@parent.children << self
elsif self.parent != nil # elsif our current node already has a parent
@parent.children.delete(self)
@parent = node
@parent.children << self
end
end
def add_child(child_node) #node1.add_child(node2) node1 = parent, node2 = child
if [email protected]?(child_node)
child_node.parent = self # node2.parent = node1
end
end
def remove_child(child_node)
child_node.parent = nil
end
def dfs(target)
return self if self.value == target
return nil if self.children.empty?
i = 0
while i < self.children.length
store = self.children[i].dfs(target)
return store unless store.nil?
i+=1
end
nil
end
def bfs(target)
queue = [self]
until queue.empty?
el = queue.shift
return el if el.value == target
queue += el.children
end
nil
end
end
| true |
795342a91df740e7c6886ad9b0a96f4c8bcf23e0
|
Ruby
|
epogue/wowwer
|
/lib/wowwer/race.rb
|
UTF-8
| 429 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
module Wowwer
class Race < Wowwer::Base
class << self
def all(options={})
@races ||= get("data/character/races", options)['races'].map do |race|
new race
end
end
def find(id, options={})
all(options).detect{|r| r.id == id }
end
def find_by_name(name, options={})
all(options).detect{|r| r.name.downcase == name.downcase }
end
end
end
end
| true |
35754bcce9af969ef06169d766d4a931dba20335
|
Ruby
|
huminya/homework
|
/lrthw/ex19.rb
|
UTF-8
| 890 | 4.3125 | 4 |
[] |
no_license
|
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket."
puts # a blank line
end
# directly use numbers
puts "We can just give the function numbers directly:(20,30)"
cheese_and_crackers(20,30)
# use variables
puts "OR, we can use variables from our script:(amount_of_cheese=10, amount_of_crackers=50)"
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
# do math inside
puts "we can even do math inside too:(10+20,5+6)"
cheese_and_crackers(10+20, 5+6)
# use variables and math
puts "And we can combine the two, variables and math:(amount_of_cheese+100, amount_of_crackers+200)"
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 200)
| true |
e8b006b01cb28d0767faa64374554585df172b56
|
Ruby
|
Gutylla/ctci-ruby
|
/kpalindrome.rb
|
UTF-8
| 498 | 3.28125 | 3 |
[] |
no_license
|
def kpalindrome(s, k)
isKPalDP(s, s.reverse) <= 2*k
end
def isKPalDP(str1, str2)
n = str1.length
dp = Array.new(n+1) { Array.new(n+1) }
(n+1).times do |i|
(n+1).times do |j|
if i == 0
dp[i][j] = j
elsif j == 0
dp[i][j] = i
elsif str1[i - 1] == str2[j - 1]
dp[i][j] = dp[i - 1][j - 1]
else
dp[i][j] = 1 + [dp[i - 1][j], dp[i][j - 1]].min
end
end
end
dp[n][n]
end
s= "abrarbra"
k= 1
p kpalindrome(s, k)
| true |
c609e67d52df0748f5c9af2f162b1ba31236def5
|
Ruby
|
Jonesyd/launchschool_exercises
|
/small_problems/42_e5_after_midnight_p1.rb
|
UTF-8
| 573 | 3.6875 | 4 |
[] |
no_license
|
def plus_24(num)
if num < 0
num += 24
plus_24(num)
else
num
end
end
def time_of_day(integer)
hours, mins = integer.divmod(60)
days, hours = hours.divmod(24) if hours >= 24
hours = plus_24(hours) if integer < 0
array = [mins, hours]
hour = array.fetch(1) { 0 }
array = [mins, hour]
format("%02d:%02d", array[1], array[0])
end
p time_of_day(0) == "00:00"
p time_of_day(-3) == "23:57"
p time_of_day(35) == "00:35"
p time_of_day(-1437) == "00:03"
p time_of_day(3000) == "02:00"
p time_of_day(800) == "13:20"
p time_of_day(-4231) == "01:29"
| true |
f970fee87bded457ddcc437a84498621a8d5e713
|
Ruby
|
eleetyson/practice
|
/majority-element-rb/majority_element.rb
|
UTF-8
| 452 | 3.625 | 4 |
[] |
no_license
|
# given an array of numbers, return the majority element
# the majority element is a value that makes up more than half of the array's elements
# assume that the given array will always have a majority element
# also assume that the array length is always at least one element
def find_majority_element(nums)
counts = {}
nums.each do |num|
counts[num] ? counts[num] += 1 : counts[num] = 1
end
return counts.key(counts.values.max)
end
| true |
8043c1835a61734991f048462f5d454574088c1d
|
Ruby
|
paratiger/Whisky-list
|
/test/shoulda/custom_matchers/be_valid_with_factory_matcher.rb
|
UTF-8
| 785 | 2.671875 | 3 |
[] |
no_license
|
module Shoulda
module CustomMatchers
def be_valid_with_factory
BeValidWithFactoryMatcher.new( self.name.gsub(/Test$/, '').underscore.to_sym )
end
class BeValidWithFactoryMatcher
def initialize(class_name)
@class_name = class_name
end
def matches?(subject)
@instance = Factory.build( @class_name )
@instance.valid?
end
def failure_message
"Factory for #{@class_name} should have been valid, but was not"
end
def negative_failure_message
"Factory for #{@class_name} should have been invalid, but was valid"
end
def description
"should have a factory which generates a valid instance of #{@class_name}"
end
end
end
end
| true |
59726d33713c82191742262cecf00c837575f6d6
|
Ruby
|
tienan/textlab
|
/plot_2.rb
|
UTF-8
| 3,209 | 2.65625 | 3 |
[] |
no_license
|
require 'tk'
class TkEvent::Event
attr_accessor :x_nonzoom, :y_nonzoom
end
class TkScrolledCanvas < TkCanvas
include TkComposite
attr_reader :zoom
def initialize_composite(keys={})
@zoom = 1.0
@h_scr = TkScrollbar.new(@frame)
@v_scr = TkScrollbar.new(@frame)
@canvas = TkCanvas.new(@frame)
@path = @canvas.path
@canvas.xscrollbar(@h_scr)
@canvas.yscrollbar(@v_scr)
TkGrid.rowconfigure(@frame, 0, :weight=>1, :minsize=>0)
TkGrid.columnconfigure(@frame, 0, :weight=>1, :minsize=>0)
@canvas.grid(:row=>0, :column=>0, :sticky=>'news')
@h_scr.grid(:row=>1, :column=>0, :sticky=>'ew')
@v_scr.grid(:row=>0, :column=>1, :sticky=>'ns')
delegate('DEFAULT', @canvas)
delegate('background', @frame, @h_scr, @v_scr)
delegate('activeforeground', @h_scr, @v_scr)
delegate('troughcolor', @h_scr, @v_scr)
delegate('repeatdelay', @h_scr, @v_scr)
delegate('repeatinterval', @h_scr, @v_scr)
delegate('borderwidth', @frame)
delegate('relief', @frame)
delegate_alias('canvasborderwidth', 'borderwidth', @canvas)
delegate_alias('canvasrelief', 'relief', @canvas)
delegate_alias('scrollbarborderwidth', 'borderwidth', @h_scr,
@v_scr)
delegate_alias('scrollbarrelief', 'relief', @h_scr, @v_scr)
configure(keys) unless keys.empty?
end
def zoom_by zf
zf = Float(zf)
@zoom *= zf
vf = (1 - 1/zf) / 2
x0, x1 = xview ; xf = x0 + vf * (x1-x0)
y0, y1 = yview ; yf = y0 + vf * (y1-y0)
scale 'all', 0, 0, zf, zf
configure :scrollregion => bbox("all")
xview "moveto", xf
yview "moveto", yf
end
def zoom_to z
zoom_by(z/@zoom)
end
def bind(ev, cb)
if cb.class == String
super
else
super(ev, proc{ |e| process_event(e, cb) })
end
end
def itembind(tag, ev, cb)
if cb.class == String
super
else
super(tag, ev, proc{ |e| process_event(e, cb) })
end
end
def coords(tag, *args)
newargs = adjust_coords(@zoom, args)
ret = super(tag, *newargs)
return ret unless ret.class == Array
ret.collect { |v| v / @zoom }
end
def move(tag, x, y)
super(tag, x*@zoom, y*@zoom)
end
def create(type, *args)
newargs = adjust_coords(@zoom, args)
super(type, *newargs)
end
private
def process_event(e, cb)
if e.x then e.x_nonzoom=e.x/@zoom ; end
if e.y then e.y_nonzoom=e.y/@zoom ; end
cb.call e
end
def adjust_coords(mul, args)
args.collect do |arg|
arg.class == Array ? arg.collect { |v| v * mul } : arg
end
end
end
class TkcItem
alias orig_initialize initialize
def initialize(parent, *args)
if parent.class == TkScrolledCanvas
zoom = parent.zoom
newargs = args.collect do |arg|
arg.class == Array ? arg.collect { |v| v * zoom } : arg
end
else
newargs = args
end
orig_initialize parent, *newargs
end
def bind(ev, cb)
super(ev, proc{ |e|
if @parent.class == TkScrolledCanvas
zoom = @parent.zoom
if e.x then e.x_nonzoom=e.x/zoom ; end
if e.y then e.y_nonzoom=e.y/zoom ; end
cb.call e
end
})
end
end
| true |
8c3c9a75b62da0c4f24114526156e12c55250876
|
Ruby
|
raza23/pfwtfp-practice-with-array-integers-lab-atl-web-042219-gap
|
/lib/array_practice.rb
|
UTF-8
| 1,302 | 3.953125 | 4 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
array_of_integers = *0...50
def all_odds(array)
array.find_all{|x| x%2 == 1}
# return all odd numbers from the input array
end
def all_evens(array)
array.find_all{|x| x%2 == 0}
# return all even numbers from the input array
end
def all_squares(array)
array.map{|x| x ** 2}
# return the square of all numbers from the input array
end
def first_square_greater_than_350(array)
array.find{|x| x**2 > 350}
# return the first number from the input array whose square is greater than 350
end
def all_squares_greater_than_350(array)
array.find_all{|x| x**2 > 350}
# return all the numbers from the input array whose square is greater than 350
end
def all_cubes(array)
array.map{|x| x ** 3}
# return the cube of all numbers from the input array
end
def first_cube_greater_than_500(array)
array.find{|x| x**3 > 500}
# return the first number from the input array whose cube is greater than 500
end
def all_cubes_greater_than_500(array)
array.find_all{|x| x**3 > 500}
# return all the numbers from the input array whose cube is greater than 500
end
def sum(array)
array.reduce(:+)
# return the sum of all integers from the input array
end
def average_value(array)
array.reduce(:+)/array.count.to_f
# return the average of all integers from the input array
end
| true |
af630361a88394b5bf6df174bc55c81696906cfc
|
Ruby
|
pbcoronel/project_euler
|
/ruby/problem_007.rb
|
UTF-8
| 101 | 2.875 | 3 |
[] |
no_license
|
require "prime"
def getprime(n)
array = Prime.first n
array.last
end
p getprime(10001)
| true |
9f26729cf222831122f3a5e1c8c5a67e300d6344
|
Ruby
|
lukesiem/joggle-rails
|
/spec/product_spec.rb
|
UTF-8
| 1,139 | 2.609375 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe Product, type: :model do
describe 'Validations' do
before(:each) do
@category = Category.new(name: 'Fruit')
end
it "is valid if it has all attributes" do
@product = Product.new(name: 'Watermelon', price: 200, quantity: 30, category: @category)
expect(@product.valid?).to be true
end
it "is not valid without a valid name" do
@product = Product.new( price: 50, quantity: 2, category:@category)
expect(@product.valid?).to be false
end
it "is not valid without a price" do
@product = Product.new( name: 'Watermelon', quantity: 2, category: @category)
expect(@product.valid?).to be false
end
it "is not valid without a quantity" do
@product = Product.new( name: 'Watermelon', price: 200, quantity: nil, category: @category)
expect(@product.valid?).to be false
end
it "is not valid without a category" do
@product = Product.new( name: 'Watermelon', price: 200, quantity: 40, category: nil)
expect(@product.valid?).to be false
end
end
end
| true |
b4570acdfde36df8108c8aabaad9e445fdbad678
|
Ruby
|
bonitour/API-3.0-Ruby
|
/lib/cielo/api30/external_authentication.rb
|
UTF-8
| 1,740 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
module Cielo
module API30
# Credit card data
#
# @attr [String] card_number Credit card number
# @attr [String] holder Holder name
# @attr [String] expiration_date Credit card expiration date
# @attr [String] security_code Credit card security code
# @attr [Boolean] save_card Whether or not to save the card
# @attr [String] brand Credit card brand
# @attr [String] card_token Card token
class ExternalAuthentication
attr_accessor :cavv,
:xid,
:eci,
:version,
:reference_id
def initialize(args = {})
@cavv = args[:cavv]
@xid = args[:xid]
@eci = args[:eci]
@version = args[:version]
@reference_id = args[:reference_id]
end
def to_json(*options)
hash = as_json(*options)
hash.to_json(*options)
end
def self.from_json(data)
return if data.nil?
data = JSON.parse(data)
external_authentication = new
external_authentication.cavv = data['Cavv']
external_authentication.xid = data['Xid']
external_authentication.eci = data['Eci']
external_authentication.version = data['Version']
external_authentication.reference_id = data['ReferenceID']
external_authentication
end
def as_json(_options = {})
remove_nulls(
Cavv: @cavv,
Xid: @xid,
Eci: @eci,
Version: @version,
ReferenceID: @reference_id
)
end
def safe_json
as_json
end
def remove_nulls(hash)
hash.reject { |_k, v| v.nil? || v.eql?('null') || v.eql?({}) }
end
end
end
end
| true |
98dfecc9c01bea9bf2b6a496dd5d82c78b1fdba3
|
Ruby
|
valeriecs10/chess
|
/pieces/stepable.rb
|
UTF-8
| 501 | 2.828125 | 3 |
[] |
no_license
|
module Stepable
def moves
move_diffs.each_with_object([]) do |diff, arr|
current_pos = [@pos[0] + diff[0], @pos[1] + diff[1]]
next unless @board.valid_pos?(current_pos)
if @board[current_pos].is_a?(NullPiece) || @board[current_pos].color != self.color
arr << current_pos
end
end
end
private
def move_diffs
# Overwritten by subclass
raise "Move_diffs not instantiated"
end
end
| true |
57395f628ef9e04f596819d8431bee56bb74608e
|
Ruby
|
tkosuga/tiikitter.jp
|
/app/lib/google_map/geo_coder.rb
|
UTF-8
| 1,605 | 3.34375 | 3 |
[] |
no_license
|
#
# これの 移植。
# http://wiki.forum.nokia.com/index.php/Google_Maps_API_in_Java_ME%EF%BC%88%E6%97%A5%E6%9C%AC%E8%AA%9E%EF%BC%89
#
class GoogleMap::GeoCoder
include Math
OFFSET = 2 ** 28
RADIUS = OFFSET / Math::PI
#
# 経度を指定したピクセルで移動します
#
def move_lng_by_pixel(x, delta, zoom)
(((lng_to_x(x)+(delta << (21 - zoom))) - OFFSET) / RADIUS) * 180 / Math::PI
end
#
# 経度と経度の距離をピクセルで返します
#
def lng_to_pixel(from, to, zoom)
((lng_to_x(from) - lng_to_x(to)) >> (21 - zoom))
end
def lng_to_x(lng)
(OFFSET + RADIUS * lng * Math::PI / 180).round
end
#
# 緯度を指定したピクセルで移動します
#
def move_lat_by_pixel(y, delta, zoom)
(Math::PI / 2 - 2 * atan(exp(((lat_to_y(y)+(delta << (21-zoom))) - OFFSET) / RADIUS))) * 180 / Math::PI
end
#
# 緯度と緯度の距離をピクセルで返します
#
# def lat_to_pixel(lat = 0, zoom = 5)
#
# exp = sin(lat*Math::PI/180)
#
# exp = -0.9999 if (exp < -0.9999)
# exp = 0.9999 if (exp > 0.9999)
#
# (256*(2^(zoom-1)))+(0.5*log((1+exp)/(1-exp)))*((-256*(2 ** zoom))/(2*Math::PI))
# end
#
# 緯度と緯度の距離をピクセルで返します
#
def lat_to_pixel(from, to, zoom)
((lat_to_y(from) - lat_to_y(to)) >> (21 - zoom)) * -1
end
def lat_to_y(lng)
((OFFSET - RADIUS * log((1 + sin(lng * Math::PI / 180)) / (1 - sin(lng * Math::PI / 180))) / 2)).round
end
end
| true |
e354fd70406460169232547ce1e8db58e48496b3
|
Ruby
|
kzkn/sakuramarket
|
/app/models/purchase.rb
|
UTF-8
| 2,239 | 2.78125 | 3 |
[] |
no_license
|
class Purchase < ApplicationRecord
TAX_RATE = 0.08
SHIP_TIME_CANDIDATES = %w(8-12 12-14 14-16 16-18 18-20 20-21)
belongs_to :order, touch: true
validates :order, presence: true, uniqueness: true
validates :tax_rate, numericality: true
validates :cod_cost, numericality: true
validates :ship_cost, numericality: true
validates :total, numericality: true
validates :ship_name, presence: true
validates :ship_address, presence: true
validates :ship_due_date, presence: true, inclusion: { in: proc { Purchase.ship_date_candidates } }
validates :ship_due_time, presence: true, inclusion: { in: proc { Purchase::SHIP_TIME_CANDIDATES } }
validate :order_has_item, :order_is_assigned_to_user, if: :has_order?
before_validation :set_tax_rate, on: :create
before_validation :set_attrs_from_order, on: :create, if: :has_order?
def self.ship_date_candidates
# 3 営業日から 14 営業日
today = Date.current
(1..Float::INFINITY).lazy
.map{ |i| today + i }
.select{ |d| !d.saturday? && !d.sunday? }
.take(14)
.drop(2)
.to_a
end
def self.new_for_user(user)
Purchase.new(ship_name: user.ship_name, ship_address: user.ship_address)
end
def ship_params
{ ship_name: ship_name, ship_address: ship_address }
end
def self.cod_cost(order)
Cost.of_cod(order.subtotal)
end
def self.ship_cost(order)
Cost.of_ship(order.total_quantity)
end
def self.total(order, tax_rate = TAX_RATE)
total = order.subtotal + Purchase.cod_cost(order) + Purchase.ship_cost(order)
Purchase.taxation(total, tax_rate)
end
private
def has_order?
order.present?
end
def order_has_item
errors.add(:order, 'カートが空です。') unless order.items.exists?
end
def order_is_assigned_to_user
errors.add(:order, 'どのユーザーにも割り当てられていないカートです。') unless order.user.present?
end
def set_tax_rate
self.tax_rate = TAX_RATE
end
def set_attrs_from_order
self.cod_cost = Purchase.cod_cost(order)
self.ship_cost = Purchase.ship_cost(order)
self.total = Purchase.total(order, tax_rate)
end
def self.taxation(n, tax_rate)
(n + n * tax_rate.to_r).to_i
end
end
| true |
e8a8b76a8c5cdef72c4711269ab522e9cc7a4ffe
|
Ruby
|
JC-LL/gtk3_ruminations
|
/methodo_1/5_force_directed_graph_drawing/window.rb
|
UTF-8
| 3,691 | 2.703125 | 3 |
[] |
no_license
|
require 'gtk3'
class Canvas < Gtk::DrawingArea
def initialize
super()
set_size_request(800,100)
signal_connect('draw') do
on_expose
end
end
def on_expose
cr = window.create_cairo_context
cr.set_line_width(0.5)
w = allocation.width
h = allocation.height
cr.translate(w/2, h/2)
cr.arc(0, 0, 120, 0, 2*Math::PI)
cr.stroke
for i in (1..36)
cr.save
cr.rotate(i*Math::PI/36)
cr.scale(0.3, 1)
cr.arc(0, 0, 120, 0, 2*Math::PI)
cr.restore
cr.stroke
end
end
end
class Window < Gtk::Window
def initialize args={} # I want to show it's possible to pass some args
super() # mandatory parenthesis ! otherwise : wrong arguments: Gtk::Window#initialize({})
set_title 'jcll_3'
set_default_size 900,600
set_border_width 10
set_window_position :center
set_destroy_callback
hbox = Gtk::Box.new(:horizontal, spacing=6)
add hbox
canvas = Canvas.new
hbox.pack_start(canvas,:expand=>true,:fill=> true)
#...instead of :
# hbox.add canvas
vbox = Gtk::Box.new(:vertical,spacing=6)
hbox.add vbox
button = Gtk::Button.new(label:"open")
button.signal_connect("clicked"){on_open_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
button = Gtk::Button.new(:label => "run")
button.signal_connect("clicked"){on_run_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
button = Gtk::Button.new(:label => "stop")
button.signal_connect("clicked"){on_stop_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
button = Gtk::Button.new(:label => "step")
button.signal_connect("clicked"){on_step_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
button = Gtk::Button.new(:label => "save")
button.signal_connect("clicked"){on_save_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
button = Gtk::Button.new(:label => "quit")
button.signal_connect("clicked"){on_quit_clicked(button)}
vbox.pack_start(button,:expand => false, :fill => false, :padding => 0)
show_all
end
def on_open_clicked button
puts '"open" button was clicked'
dialog=Gtk::FileChooserDialog.new(
:title => "choose",
:parent => self,
:action => Gtk::FileChooserAction::OPEN,
:buttons => [[Gtk::Stock::OPEN, Gtk::ResponseType::ACCEPT],
[Gtk::Stock::CANCEL, Gtk::ResponseType::CANCEL]])
filter_sexp = Gtk::FileFilter.new
filter_sexp.name = "s-expr filter"
filter_sexp.add_pattern("*.sexp")
filter_sexp.add_pattern("*.sxp")
dialog.add_filter(filter_sexp)
filter_rb = Gtk::FileFilter.new
filter_rb.name = "ruby filter"
filter_rb.add_pattern("*.rb")
dialog.add_filter(filter_rb)
dialog.show_all
case dialog.run
when Gtk::ResponseType::ACCEPT
puts "filename = #{dialog.filename}"
#puts "uri = #{dialog.uri}"
dialog.destroy
else
dialog.destroy
end
end
def on_run_clicked button
puts '"run" button was clicked'
end
def on_stop_clicked button
puts '"stop" button was clicked'
end
def on_step_clicked button
puts '"step" button was clicked'
end
def on_save_clicked button
puts '"save" button was clicked'
end
def on_quit_clicked button
puts "Closing application"
Gtk.main_quit
end
def set_destroy_callback
signal_connect("destroy"){Gtk.main_quit}
end
end
window=Window.new
Gtk.main
| true |
f9e33ab7fe76f11e9ca99617ffb09d188fcc3577
|
Ruby
|
VanQuishi/hangman-game
|
/lib/hangman.rb
|
UTF-8
| 6,427 | 3.484375 | 3 |
[] |
no_license
|
require "csv"
class Hangman
attr_accessor :player_name
attr_reader :misses, :corrects, :stage, :id
attr_reader :key_word #for the sake of debugging. Take this out when finished
public
def initialize(player_name,misses=[],corrects=[],stage=0,key_word = find_key_word("5desk.txt"),id = -1)
@id = id
@player_name = player_name
@key_word = key_word
@misses = misses
@corrects = corrects
@stage = stage
end
def game()
puts "Hi #{@player_name} <3"
puts "Your word is #{@key_word.length}-letter long."
puts "You have #{6-@stage} lives left."
display_hangman()
display_corrects()
display_misses()
print "Do you want to save the game?(Y/n)"
choice = gets.chomp
if choice.downcase == 'y'
save_game()
else
while @stage < 6 do
if @corrects.length == @key_word.length
puts File.read("assets/winner.txt")
break
end
print "Guess a letter: "
guess = gets.chomp.downcase
is_correct_guess = hit_or_miss(guess)
if is_correct_guess == true
puts "Nice guess!!!"
else
puts "Wrong :("
@stage += 1
end
display_hangman()
display_corrects()
display_misses()
if @stage == 6
puts "The secret word is #{@key_word}"
break
end
print "Do you want to save the game?(Y/n)"
choice = gets.chomp
if choice.downcase == 'y'
save_game()
break
else
next
end
end
end
end
def self.load_game()
puts "List of load game: "
contents = CSV.open 'assets/saved_games.csv', headers: true, header_converters: :symbol
contents.each do |row|
puts "ID: #{row[:id]} Username: #{row[:player_name]}"
end
file = CSV.open 'assets/saved_games.csv', headers: true, header_converters: :symbol
print "Enter the game ID that you want to continue: "
match = gets.chomp
file.each do |row|
if row[:id] == match
puts "match!!!"
load_id = row[:id].to_i()
load_player_name = row[:player_name]
load_misses = row[:misses].split("")
load_corrects = row[:corrects].split("")
load_stage = row[:stage].to_i()
load_key_word = row[:key_word]
player = Hangman.new(load_player_name, load_misses, load_corrects, load_stage, load_key_word, load_id)
player.game()
end
end
end
private
def find_key_word(filename)
lines = File.readlines(filename)
word = lines[rand(lines.length)].chomp
while word.length < 5 || word.length > 12 do
word = lines[rand(lines.length)].chomp
end
return word
end
def display_corrects()
for i in 0..(@key_word.length-1)
if @corrects.include?(@key_word[i].downcase)
print "#{@key_word[i]} "
else
print '_ '
end
end
puts "\n"
end
def display_misses()
misses_string = @misses.join(', ')
puts "Misses: #{misses_string}"
end
def display_hangman()
if @stage == 0
puts File.read("assets/hm0.txt")
elsif @stage == 1
puts File.read("assets/hm1.txt")
elsif @stage == 2
puts File.read("assets/hm2.txt")
elsif @stage == 3
puts File.read("assets/hm3.txt")
elsif @stage == 4
puts File.read("assets/hm4.txt")
elsif @stage == 5
puts File.read("assets/hm5.txt")
elsif @stage == 6
puts File.read("assets/hm6.txt")
end
end
def hit_or_miss(guess)
if @key_word.downcase.include?(guess)
@key_word.split("").each do |letter|
if letter.downcase == guess.downcase
@corrects.push(guess)
end
end
return true
else
@misses.push(guess)
return false
end
end
def save_game()
if @id == -1
current_size = CSV.read("assets/saved_games.csv").size
p "current size: #{current_size}"
id = current_size + 1
p "this user id: #{id}"
CSV.open("assets/saved_games.csv", "a+") do |csv|
csv << ["#{id}", "#{@player_name}", "#{@misses.join()}", "#{@corrects.join()}", "#{@stage}", "#{@key_word}"]
end
else
file = CSV.read("assets/saved_games.csv")
edited_ows = file.each_with_index.map do |row, index|
if index == @id
row[2] = "#{@misses.join()}"
row[3] = "#{@corrects.join()}"
row[4] = "#{@stage.to_s()}"
end
end
CSV.open("assets/saved_games.csv", "wb") do |csv|
file.each do |row|
csv << row
end
end
end
end
end
print "New game or Load game?(N/l): "
option = gets.chomp
if option.downcase == 'l'
Hangman.load_game()
else
print "What is your name? "
name = gets.chomp
player = Hangman.new(name)
player.game()
end
| true |
98c57d43016c1e2bae5b2283e7ed9d18ecd7fbe0
|
Ruby
|
KOCage/Vinehalla
|
/db/seeds.rb
|
UTF-8
| 5,757 | 2.96875 | 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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# File structure necessary for seed script to work:
# File structure expected to be VINEHALLA_PATH (declared in config/initializers/constants.rb):
# folders: Output, Tools, Vines --- files: none
# File structure expected inside Vines:
# folders: one folder for each vine author, one folder called "Unknown" for vines without known authors --- files: none
# File structure expected inside each author and "Unknown" folder:
# files: video files that will be considered vines.
#
# Database build logic:
# Get all children of the VINEHALLA_PATH\\Vines\\ folder
#
# for each folder, set the author name equal to the folder name
# Get all children of that folder
# for each video file (currently expecting mp4, though may expand this in the future)
# see if there is a matching jpg screenshot file (will be the same name but jpg instead of mp4)
# IF THERE IS NOT: use ffmpeg to create a screenshot from 3 seconds in to the video
# create a vine entry in the database with title: (filename - extension)
# author: the author set by the folder name
# path: the path to the video file
# image_path: the path of the image file, if it was found
require 'csv'
require "base64"
vinesPath = VINEHALLA_PATH + "Vines\\"
# Get all children of the VINEHALLA_PATH\\Vines\\ folder
vinesChildren = Dir.children(vinesPath)
# for each folder, set the author name equal to the folder name
vinesChildren.each do |authorFolder|
# seems a little unneccessary, I think this variable will make the later code more readable
author = authorFolder
author_path = vinesPath + authorFolder + "\\"
vineDetails_path = author_path + "vineDetails.csv"
# read in the vineDetails csv as a CSV Table.
vineDetails = nil
if (File.exist?(vineDetails_path))
vineDetails = CSV.parse(File.read(vineDetails_path), headers: true)
end
# Get all children of that folder
authorChildren = Dir.children(author_path)
# for each video file (currently expecting mp4, though may expand this in the future)
authorChildren.each do |file|
if !file.include? ".mp4"
# don't work any non video file
next
end
# store the path of the file and pull the title out
file_path = author_path + file
title = file.clone
# Default the title to be the file name excluding extension
title[".mp4"] = ""
# Default tags and dialogue to empty strings
tags = ""
dialogue = ""
# If the vineDetails file was found, search the vineDetails CSV Table for a row with the same title
if (!vineDetails.nil?)
vineDetailsRow = vineDetails.find { |r|
r["File"] == file
}
# if the returned row exists, update the title, tags, and dialogue variables
# If the value in the row is not nil, update the variables.
if (!vineDetailsRow.nil?)
if (!vineDetailsRow["Title"].nil?)
title = vineDetailsRow["Title"]
end
if (!vineDetailsRow["Tags"].nil?)
tags = vineDetailsRow["Tags"]
end
if (!vineDetailsRow["Dialogue"].nil?)
dialogue = vineDetailsRow["Dialogue"]
end
end
end
# There should be a screenshot with the same filename but as a jpg.
image_file = (title + ".jpg")
image_path = author_path + image_file
# If there isn't a screenshot, create one using ffmpeg.
# ffmpeg -ss 00:00:03 -i "INPUTPATH" -vframes 1 -q:v 2 "OUTPUTPATH"
if !authorChildren.include? image_file
ffmpegCommand = VINEHALLA_PATH + "Tools\\ffmpeg.exe -ss 00:00:03 -i \"[INPUTFILE]\" -vframes 1 -q:v 2 \"[OUTPUTFILE]\""
ffmpegCommand["[INPUTFILE]"] = file_path
ffmpegCommand["[OUTPUTFILE]"] = image_path
result = %x{#{ffmpegCommand}}
end
# Read in the image screenshot and create a base64 encoded string of it. Store that in image_source to be put in the database.
image_source = File.open(image_path, "rb") do |file|
Base64.strict_encode64(file.read)
end
# create a vine entry in the database with title: (filename - extension)
# author: the author set by the folder name
# path: the path to the video file
# image_path: the path of the image file
# tags: found in the vineDetails csv file, or is empty string
# dialogue: found in the vineDetails csv file, or is empty string
# image_source: base64 encoded string of the screenshot
# puts "title: #{title}, author: #{author}, path: #{file_path}, image_path: #{image_path}, tags: #{tags}, dialogue: #{dialogue}, image_source: #{image_source}"
Vine.create(title: title,
author: author,
path: file_path,
image_path: image_path,
tags: tags,
dialogue: dialogue,
image_source: image_source)
end
end
| true |
0b3aeaf595741b31b4be761d8bca4dcfcd13ecbc
|
Ruby
|
rmagick/rmagick
|
/spec/rmagick/image/displace_spec.rb
|
UTF-8
| 2,200 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
RSpec.describe Magick::Image, '#displace' do
it 'works' do
image = described_class.new(20, 20)
image2 = described_class.new(20, 20) { |options| options.background_color = 'black' }
expect { image.displace(image2, 25) }.not_to raise_error
result = image.displace(image2, 25)
expect(result).to be_instance_of(described_class)
expect(result).not_to be(image)
expect { image.displace(image2, 25, 25) }.not_to raise_error
expect { image.displace(image2, 25, 25, 10) }.not_to raise_error
expect { image.displace(image2, 25, 25, 10, 10) }.not_to raise_error
expect { image.displace(image2, 25, 25, Magick::CenterGravity) }.not_to raise_error
expect { image.displace(image2, 25, 25, Magick::CenterGravity, 10) }.not_to raise_error
expect { image.displace(image2, 25, 25, Magick::CenterGravity, 10, 10) }.not_to raise_error
expect { image.displace }.to raise_error(ArgumentError)
expect { image.displace(image2, 'x') }.to raise_error(TypeError)
expect { image.displace(image2, 25, []) }.to raise_error(TypeError)
expect { image.displace(image2, 25, 25, 'x') }.to raise_error(TypeError)
expect { image.displace(image2, 25, 25, Magick::CenterGravity, 'x') }.to raise_error(TypeError)
expect { image.displace(image2, 25, 25, Magick::CenterGravity, 10, []) }.to raise_error(TypeError)
image2.destroy!
expect { image.displace(image2, 25, 25) }.to raise_error(Magick::DestroyedImageError)
end
it 'accepts an ImageList argument' do
image = described_class.new(20, 20)
image_list = Magick::ImageList.new
image_list.new_image(10, 10)
expect { image.displace(image_list, 25) }.not_to raise_error
expect { image.displace(image_list, 25, 25) }.not_to raise_error
expect { image.displace(image_list, 25, 25, 10) }.not_to raise_error
expect { image.displace(image_list, 25, 25, 10, 10) }.not_to raise_error
expect { image.displace(image_list, 25, 25, Magick::CenterGravity) }.not_to raise_error
expect { image.displace(image_list, 25, 25, Magick::CenterGravity, 10) }.not_to raise_error
expect { image.displace(image_list, 25, 25, Magick::CenterGravity, 10, 10) }.not_to raise_error
end
end
| true |
ed9c5612f307b5f5871fe205335ed15534e7fcc3
|
Ruby
|
xdanielsb/Ruby_Workshop
|
/palindrome.rb
|
UTF-8
| 342 | 4 | 4 |
[] |
no_license
|
=begin
Daniel Santos
Super easy program to say if a set of words are palindromes
=end
def is_palindrome(*args)
args.each do |word|
if word != word.reverse
puts word
return FALSE
end
end
return true
end
result = is_palindrome("lol", "mariiram", "jjjeeejjj")
unless result
puts "NO"
else
puts "YES"
end
| true |
9688a33848b2064e5fbc7ca5cc70037379d78862
|
Ruby
|
LyleF27/Lauch-school-intro-to-programming-ruby
|
/chapter_8_hashes/exercise_2.rb
|
UTF-8
| 421 | 3.96875 | 4 |
[] |
no_license
|
# Look at Ruby's merge method. Notice that it has two versions. What is the difference between merge and merge!? Write a program that uses both and illustrate the differences.
# the difference is that the merge without the ! doesnt mutate the caller and the merge! with the ! does
hash1 = {
cats: ["Simba", "Nala"]
}
hash2 = {
dogs: ["Spot", "buster"]
}
p hash1.merge(hash2)
p hash1
p hash1.merge!(hash2)
p hash1
| true |
bed2ffc7756e133ad6e4ab7c79ad8b45b01e72cd
|
Ruby
|
elailai94/Watts
|
/source-code/screens/geometry-screens/triangle_area_screen.rb
|
UTF-8
| 2,738 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
#==============================================================================
# Watts
#
# @description: Module for providing functions to work with TriangleAreaScreen
# objects
# @author: Elisha Lai
# @version: 0.0.1 15/06/2015
#==============================================================================
# Triangle area screen module (triangle_area_screen.rb)
require_relative '../../elements/screen_header.rb'
require_relative '../../elements/screen_label.rb'
require_relative '../../elements/screen_edit_line.rb'
# Object definition
class TriangleAreaScreen < Shoes
url('/title_screen/geometry_screen/triangle_area_screen',
:triangle_area_screen)
# Draws the triangle area screen on the Shoes app window.
def triangle_area_screen
@heading = 'Triangle area = 0.5 × base × height'
background('images/geometry_large.png')
# Triangle area screen header
ScreenHeader.new(self, '/title_screen/geometry_screen', @@font, @heading)
# Triangle area screen content
flow(:height => 640, :width => 1080, :scroll => true) do
# Left margin offset
stack(:height => 640, :width => 80) do
end
# Content column
stack(:height => 640, :width => 1000) do
ScreenLabel.new(self, @@font, @heading, 'Base')
flow do
@base = ScreenEditLine.new(self, @@font, @heading)
@base_units = ['cm', 'm', 'km', 'in', 'ft', 'yd', 'mi']
@base_unit = list_box(:width => 100,
:font => @@font,
:items => @base_units)
@base_unit.change do
@height_unit.choose(@base_unit.text)
end
end
ScreenLabel.new(self, @@font, @heading, 'Height')
flow do
@height = ScreenEditLine.new(self, @@font, @heading)
@height_units = ['cm', 'm', 'km', 'in', 'ft', 'yd', 'mi']
@height_unit = list_box(:width => 100,
:font => @@font,
:items => @height_units)
@height_unit.change do
@base_unit.choose(@height_unit.text)
end
end
@calculate = button('Calculate')
@result_display = flow
@error_display = flow
@calculate.click do
@result_display.clear do
@result = Joules.triangle_area(@base.text.to_f,
@height.text.to_f)
@triangle_area = para(@result.to_s)
@triangle_area_unit = para(" #{@base_unit.text}", sup('2'))
@triangle_area.style(@@screen_result_text_styles)
@triangle_area_unit.style(@@screen_result_text_styles)
end
end
end
end
end
end
| true |
d70b7bfc1101d667ca3c3cad16fba22172c68847
|
Ruby
|
stringham/contests
|
/2012-mebipenny/finals/server/territory/move.rb
|
UTF-8
| 170 | 2.625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Territory
class Move
PASS = 'PASS'
attr_reader :tile, :favor
def initialize(tile, favor)
@tile = tile
@favor = favor
end
end
end
| true |
b6d4df301da1b9c03441018f2fd843fcdd139cbb
|
Ruby
|
CelesteComet/Launch-School
|
/challenges/Clock/clock.rb
|
UTF-8
| 730 | 3.578125 | 4 |
[] |
no_license
|
class Clock
def initialize(minutes)
@total_minutes = minutes % 1440
@hours = @total_minutes / 60
@minutes = @total_minutes % 60
end
def self.at(hours, minutes = 0)
Clock.new(hours * 60 + minutes)
end
def +(minutes)
Clock.new(@total_minutes += minutes)
end
def -(minutes)
Clock.new(@total_minutes -= minutes)
end
def to_s
stringify(@hours) + ":" + stringify(@minutes)
end
def ==(anotherClockObj)
if anotherClockObj.class == "Clock"
self.to_s == anotherClockObj.to_s ? true : false
else
false
end
end
def class
"Clock"
end
private
def stringify(numericTime)
numericTime < 10 ? "0" + numericTime.to_s : numericTime.to_s
end
end
| true |
f73c1e897962e7b6c03ec306bc160339191e7355
|
Ruby
|
kazuhiroinaba/clear_sky
|
/sky.rb
|
UTF-8
| 3,090 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'rmagick'
=begin
blue = light rain /snow
green = light thunderstorms/moderate rain shower
yellow = moderate thunderstorms, rainshower
magenta to read = severe thunderstorm / flooding rain
=end
=begin
HSL color value:
360 : red
300 : purple
240 : blue
120 : green
60 : yellow
0 : red
=end
def hue(image_name)
path = "/home/tan/clear_sky/#{image_name}"
img = Magick::Image.read(path).first
hueArr = Array.new(img.rows) {Array.new(img.columns) }
img.rows.times do |row|
img.columns.times do |column|
#a 10x10 grid centered on coordinate x , y
x = row - (1/2)
y = column - (1/2)
#create an Arr of all the pixel within the 10x10 square
#constitute to build a new sub-image
pixels_at_location = img.dispatch(row, column, 1, 1, "RGB")
new_img = Magick::Image.constitute(1, 1, "RGB", pixels_at_location)
#scale image to one pixel ,grab the average color and
# get the first hue value
pix = new_img.scale(1,1)
averageColor = pix.pixel_color(0,0)
areaHue = averageColor.to_hsla.first
hueArr[row][column] = areaHue
end
end
return hueArr
end
=begin
#testing for rain intensity at specific coordinate
x = gets.chomp.to_i
y = gets.chomp.to_i
value = hueArr[x][y]
puts value
if value < 60 || value > 240
puts "heavy rain"
elsif value >=60 && value <150
puts "moderate rain"
else
puts "light"
end
#Testing and comparing hue value
#First link is the formula, Second link is the calculator
#http://stackoverflow.com/questions/23090019/fastest-formula-to-get-hue-from-rgb
#http://www.rapidtables.com/convert/color/rgb-to-hsl.htm
puts "X coordinate : #{row}, Y coordinate : #{column}"
#This extract 16 bit RGB color, convert it to 8 bit
rgb = img.pixel_color(row, column)
red = rgb.red / 257
green = rgb.green / 257
blue = rgb.blue / 257
#Use the RGB value and first link to manually get the hue value at each coordinate
puts "red=#{red} green=#{green} blue=#{blue}"
#Manual calculation from RGB to HSL
#get a range of 0-1 by dividing by 255. color range from 0-255
r = red / 255.0
g = green / 255.0
b = blue / 255.0
max = [r, g, b].max
min = [r, g, b].min
#max == 0 mean r g b = 0, there no heat/hue on that coordinate
if max == 0
puts "no hue value"
else
if max == r
hue = (g - b) / ( max - min)
elsif max == g
hue = 2.0 + (b - r) / (max - min)
else
hue = 4.0 + (r - g) / (max - min)
end
hue*= 60.0
hue+= 360.0 if hue < 0
puts "area hue: #{areaHue}"
puts "manual hue: #{hue }"
end
sleep(0.5)
end
=end
| true |
5a4d1929784edad206da45bb564748e1486f563e
|
Ruby
|
sjwats/payroll
|
/app/models/commission.rb
|
UTF-8
| 1,641 | 3.6875 | 4 |
[] |
no_license
|
#require_relative 'sales'
class Commission < Employee
#the initialize method is inherited from Employee which along with attr_reader
#allows us to instantiate each new Commission employee with the same
#instance variables used in Employee (@last_name etc) here to call the Commission
#employees attributes (@last_name,@base_pay, etc)the same way as with Employee.
#In the company class, everytime a row is passed where the
#salary structure matches 'commission' the employee is automatically
#created with a new instance of Commission so the methods below
#get run once per employee that matches and when we use
#the instance variables they only correspond to the single employee
#being instantiated as a new Commission object from the commission class.
#the other missing methods (net_pay, etc) are also missing because
#they are being inherited and thus don't have to be repeated here
def gross_pay
super + commission
end
def commission
commission = Sales.employee_sales #gives us list of employee sales
if @last_name == "Lob" #checks to see if the last name of the employee being created/categorized belongs
commission['Lob'] * 0.005 #if the name belongs, multiplies the employees' sales by their commission percentage
else
commission['Bobby'] * 0.015
end
end
def display
puts "***#{@first_name} #{@last_name}***" #again, as with above can use @first_name etc because we are inheriting the initialize mthod from employees for each class
puts "Gross Salary: #{gross_pay}"
puts "Commission: #{commission}"
puts "Net Pay: #{net_pay.round(2)}\n"
end
end
| true |
8520385b4e839e79012051e3e7fbd662ceec0942
|
Ruby
|
uk-gov-mirror/ONSdigital.ons_data_models
|
/test/models/observation_test.rb
|
UTF-8
| 2,506 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require "test_helper"
require "models/observation"
class ObservationTest < ActiveSupport::TestCase
context "with an observation" do
should "have required fields" do
observation = FactoryGirl.build(:empty_observation)
assert observation.valid? == false
assert observation.errors[:slug].empty? == false
assert observation.errors[:dataset].empty? == false
end
should "have fields for dataset dimensions" do
observation = FactoryGirl.create(:observation)
# place comes from the dataset dimensions
observation.place = "MM1"
observation.save
# reload from mongo
observation = Observation.find(observation.id)
assert_equal "MM1", observation.place
end
should "not accept fields that aren't in dataset dimensions" do
observation = FactoryGirl.create(:observation)
assert_raise NoMethodError do
observation.made_up_field = "WAT"
end
end
should "validate that an assigned dimension value is from our concept scheme" do
observation = FactoryGirl.create(:observation)
observation.place = "MM1"
assert observation.valid?
end
should "raise a validation error for an assigned dimension not in concept scheme" do
observation = FactoryGirl.create(:observation)
observation.place = "NOPE"
assert observation.valid? == false
end
should "validate that an assigned data attribute value is from valid concept scheme" do
observation = FactoryGirl.create(:observation)
observation.provisional = true
assert observation.valid? == true
end
should "allow an assigned data attribute value to not have a concept scheme" do
observation = FactoryGirl.create(:observation)
data_attribute = FactoryGirl.create(:data_attribute, {name: "notes", title: "Notes"})
dataset = observation.dataset
dataset.data_attributes[data_attribute.id] = nil
dataset.save
observation.notes = "This observation is incredibly rare and pondered by many data scientists"
observation.save
assert observation.valid? == true
assert observation.notes == "This observation is incredibly rare and pondered by many data scientists"
end
should "have measures assigned to it" do
observation = FactoryGirl.create(:observation)
observation.price_index = 111.5
observation.save
assert observation.valid? == true
assert observation.price_index == 111.5
end
end
end
| true |
1fb382eb3dfb215640e56923ce388d62c7d2a630
|
Ruby
|
jonathanhester/projecteuler
|
/prob_9.rb
|
UTF-8
| 124 | 3.078125 | 3 |
[] |
no_license
|
(1..1000).each do |i|
(1..1000).each do |j|
x = 1000 - i - j
puts x * i * j if x * x == (i * i + j * j)
end
end
| true |
04bd455df479e69382ce1bbfcc2c24ec2395b68d
|
Ruby
|
YDOCHOUSE/learn_ruby
|
/07_book_titles/book.rb
|
UTF-8
| 472 | 3.703125 | 4 |
[] |
no_license
|
class Book
attr_writer :title
def initialize(title='')
@title = title
end
def title
titleize(@title)
end
def titleize(string)
book_title = string.split(' ')
no_cap = ['the','a', 'an', 'at', 'by', 'for', 'in', 'of', 'on', 'to', 'up', 'and', 'as', 'but', 'it', 'or']
book_title.each do |word|
word.capitalize! unless no_cap.include?(word)
end
book_title[0] = book_title.first.capitalize
book_title.join(' ')
end
end
| true |
756ff2d7ff606a37982f12078cc5366286d881dc
|
Ruby
|
aarti/data-structures-ruby
|
/code/bplustree/bplustree_test.rb
|
UTF-8
| 505 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
require 'minitest/autorun'
require_relative 'bplustree'
class BplustreeTest < MiniTest::Unit::TestCase
def test_initialize_btree
branching_factor = 3
first = {"1"=> "one"}
second ={"2"=> "My Second Data"}
b = Bplustree.new(branching_factor, first, second )
assert_equal false, b.root.is_leaf
p b.root
assert_equal first.first[1], b.get(first.first[0])
#assert_equal "root{[1,2][#{first},#{second}]}", b.to_s
end
# TODO
def test_insert_some_data
end
end
| true |
92b06e0042c538d2ab17ee4258f8c1e1f01c1d5e
|
Ruby
|
mayra-cabrera/sudoku-validator
|
/lib/subgrid.rb
|
UTF-8
| 423 | 3.21875 | 3 |
[] |
no_license
|
class Subgrid
GRIDS = [0, 1, 2]
X1 = [0, 1, 2]
X2 = [3, 4, 5]
X3 = [6, 7, 8]
POSITIONS = [X1, X2, X3]
attr_reader :values
def initialize data
self.values = data
end
def values=(data)
@values = []
GRIDS.each do |grid|
POSITIONS.each do |position|
subgrid = []
position.each{ |p| subgrid << data[p][grid] }
@values << subgrid.flatten
end
end
end
end
| true |
07ee907520c0b1d7338192df5d4007f0ae7ec30b
|
Ruby
|
stuartc/marsbot
|
/spec/lib/marsbot/tracker_spec.rb
|
UTF-8
| 1,591 | 2.71875 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'spec_helper'
describe Marsbot::Tracker do
let(:plane) { Marsbot::Plane.new(x: 5, y: 3) }
let(:tracker) { described_class.new(plane: plane) }
describe '#out_of_bounds' do
before do
tracker << robot
end
subject { tracker.out_of_bounds }
context 'when true' do
let(:robot) do
Marsbot::Robot.new(x: 6, y: 5, orientation: 'N', instructions: %w[F])
end
it { is_expected.to eql [robot] }
end
end
describe "#next_coordinate" do
let(:robot) do
Marsbot::Robot.new(x: 3, y: 5, orientation: 'N', instructions: %w[F])
end
subject { tracker.next_coordinate(robot, instruction) }
context 'going forward' do
let(:instruction) { "F" }
it { is_expected.to eql [3,6] }
end
context 'changing direction' do
let(:instruction) { "L" }
it { is_expected.to eql [3,5] }
end
end
describe 'moving' do
let(:robots) do
[
Marsbot::Robot.new(
x: 1, y: 1, orientation: "E",
instructions: "RFRFRFRF".chars
),
Marsbot::Robot.new(
x: 3, y: 2, orientation: "N",
instructions: "FRRFLLFFRRFLL".chars
),
Marsbot::Robot.new(
x: 0, y: 3, orientation: "W",
instructions: "LLFFFLFLFL".chars
)
]
end
it do
robots.map do |robot|
tracker.process(robot)
# puts "#{robot.coordinates.join(' ')} #{robot.orientation}"
end
expect(tracker.out_of_bounds).to contain_exactly(robots[1])
end
end
end
| true |
4b91400b79beca9a83c5b90bfee01f86f370b6d9
|
Ruby
|
benmerkel/homework_assignments
|
/methods_and_flow_control/fizz_buzz.rb
|
UTF-8
| 430 | 3.53125 | 4 |
[] |
no_license
|
#!/usr/bin/env ruby
# While doing some research on loops, I saw the 'for'
# loop and decided to go with this. It seems pretty clean
# in that I don't have to declare 'counter' separately
# from the 'for' loop.
for counter in (1..100)
if (counter % 3).zero? && (counter % 5).zero?
puts 'FizzBuzz'
elsif (counter % 3).zero?
puts 'Fizz'
elsif (counter % 5).zero?
puts 'Buzz'
else
puts counter
end
end
| true |
89bd58dfa32807c043813dcc3e31f88ac92b1a16
|
Ruby
|
amandeep1420/RB101
|
/RB101/Small Problems/E9/8_sequence.rb
|
UTF-8
| 538 | 3.890625 | 4 |
[] |
no_license
|
# def sequence(count, num)
# result_arr = []
# for i in (1..count)
# result_arr << num * i
# end
# result_arr
# end
# note: ranges have access to #Enumerable methods; don't need to convert to array beforehand
# see below:
(1..5).map { |num| num }
=> [1, 2, 3, 4, 5]
# so....
def sequence(count, num)
(1..count).map { |i| num * i }
end
sequence(5, 1) == [1, 2, 3, 4, 5]
sequence(4, -7) == [-7, -14, -21, -28]
sequence(3, 0) == [0, 0, 0]
sequence(0, 1000000) == []
# check out their solution
# is a concise solution
| true |
5b3784f7db491575dc074ceea08ad9473b55a676
|
Ruby
|
rodrigomanhaes/rasper_client
|
/lib/rasper_client/client.rb
|
UTF-8
| 3,064 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require 'net/http'
require 'base64'
require 'json'
module RasperClient
class Client
def initialize(host:, port: nil, timeout: nil, path_prefix: nil,
secure: true, empty_nil_values: false,
username: nil, password: nil)
@host = host
@port = port
@timeout = timeout
@empty_nil_values = empty_nil_values
@path_prefix = path_prefix
@secure = secure
@username = username
@password = password
end
def add(options)
symbolize_keys(options)
encode_options(options)
response = execute_request(:add, options)
JSON.parse(response.body) == { 'success' => true }
end
def generate(options)
symbolize_keys(options)
empty_nil_values(options) if @empty_nil_values
options = encode_data(options)
response = execute_request(:generate, options)
result = JSON.parse(response.body)
Base64.decode64(result['content'])
end
private
def execute_request(action, options)
response = Net::HTTP.start(*build_request_params) do |http|
request = Net::HTTP::Post.new(uri_for(action))
request.body = options.to_json
request.basic_auth(@username, @password) if @username && @password
http.request(request)
end
check_for_errors(response)
response
end
def build_request_params
options = {}
options[:read_timeout] = @timeout if @timeout
options[:use_ssl] = true if @secure
[@host, @port, options].compact
end
def symbolize_keys(options)
%w(name content images report data parameters).each do |s|
symbolize_key(options, s)
end
if options[:images]
options[:images].each do |image|
symbolize_key(image, :name)
symbolize_key(image, :content)
end
end
end
def symbolize_key(hash, key)
hash[key.to_sym] = hash.delete(key.to_s) if hash.key?(key.to_s)
end
def encode_options(options)
options[:content] = Base64.encode64(options[:content]) if options[:content]
if options[:images]
options[:images].each do |image|
image[:content] = Base64.encode64(image[:content])
end
end
end
def encode_data(options)
{ data: Base64.encode64(options.to_json) }
end
def empty_nil_values(hash)
hash.each_key do |key|
if hash[key].is_a?(Hash)
empty_nil_values(hash[key])
elsif hash[key].is_a?(Array)
hash[key].each {|item| empty_nil_values(item) if item.is_a?(Hash) }
else
hash[key] = '' if hash[key].nil?
end
end
end
def uri_for(action)
uri_build_class
.build(
host: @host,
port: @port,
path: "#{@path_prefix}/#{action}"
)
.to_s
end
def uri_build_class
@secure ? URI::HTTPS : URI::HTTP
end
def check_for_errors(response)
raise RasperClient::Error.invalid_credentials if response.code.to_i == 401
end
end
end
| true |
8a7fae0722fe563762e7ea3c83b6201611077a1b
|
Ruby
|
zooniverse-glacier/lita-zooniverse
|
/lib/lita/api/ouroboros_project.rb
|
UTF-8
| 1,532 | 2.59375 | 3 |
[] |
no_license
|
require_relative 'project'
module Lita
module Api
class OuroborosProject
include Api::Project
def self.api_headers
{
"Content-Type" => "application/json",
"Accept" => "application/json"
}
end
def self.projects_search(project_names)
project_names.map do |name|
api_host = "https://api.zooniverse.org/projects/#{name}"
HTTParty.get(api_host, { headers: api_headers })
end
end
def self.find_project_names(search_query)
all_projects = HTTParty.get(api_host_projects, { headers: api_headers })
projects = all_projects.select do |project|
[ project["display_name"], project["name"] ].any? do |name|
name.match(/(#{search_query.join(",")})/i)
end
end
projects.map{ |p| p["name"] }
end
def self.projects(search_query)
project_names = find_project_names(search_query)
return project_names if project_names.empty?
projects_search(project_names).map { |project| self.new(project) }
end
def self.api_host_projects
@api_host_projects ||= "https://api.zooniverse.org/projects/list"
end
def to_s
"(O): #{project["bucket_path"]} -- #{project["zooniverse_id"]} -- #{project["display_name"]} "\
"(classifications: #{project["classification_count"]}, "\
"classifiers: #{project["user_count"]}, completed_subjects: #{project["complete_count"]})"
end
end
end
end
| true |
fd9d452578c8cb21218e8864e4c4d6657e282b0a
|
Ruby
|
edhowland/viper
|
/lib/bufnode/peek.rb
|
UTF-8
| 329 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
# peek - class Peek - command peek - returns char of LineNode/right
class Peek < BaseNodeCommand
def call(*args, env:, frames:)
a = args_parse! args
if @options[:r]
perform(a[0], env: env, frames: frames) { |node| node[-1] }
else
perform(a[0], env: env, frames: frames, &:first)
end
end
end
| true |
23b0def09c4cbec30cc0c69d5abc00ec13540287
|
Ruby
|
y-kazuya/Rest_App
|
/app/models/owner.rb
|
UTF-8
| 1,870 | 2.71875 | 3 |
[] |
no_license
|
class Owner < ApplicationRecord
attr_accessor :remember_token
before_save { email.downcase! }
###################validates############################################################
validates :name, presence: true, length: { maximum: 50 }, uniqueness: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 100 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :profile,length: { maximum: 500 }
validates :born,length: { maximum: 100 }
validates :age, numericality: {less_than_or_equal_to: 100}, unless: :have_age?
validates :phone_number , uniqueness: true,numericality:{less_than_or_equal_to: 9999999999999} ,unless: :have_phone_number?
validates :password, presence: true, length: { minimum: 6 }
has_secure_password
def have_age?
age.nil?
end
def have_phone_number?
phone_number.nil?
end
def Owner.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# ランダムトークン
def Owner.new_token
SecureRandom.urlsafe_base64
end
# 永続セッションのためにユーザーをデータベースに記憶する
def remember
self.remember_token = Owner.new_token
update_attribute(:remember_digest, Owner.digest(remember_token))
end
# 渡されたトークンがダイジェストと一致したらtrueを返す
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# ユーザーのログイン情報を破棄する
def forget
update_attribute(:remember_digest, nil)
end
end
| true |
8e73146c374ef0d3106b88f62a07c13b10374b23
|
Ruby
|
ajesler/advent-of-code
|
/2020/ruby/day01/solution.rb
|
UTF-8
| 2,037 | 2.8125 | 3 |
[] |
no_license
|
# frozen_string_literal: true
# Run the solver with the input after __END__
# $ ruby solver.rb
#
# Run the solver using a file as input
# $ ruby solver.rb test_input.txt
#
# Run solver specs with
# $ ruby solver.rb --specs
class Solver
def initialize(numbers, components: 2)
@numbers = numbers
@components = components
end
def solve
components = @numbers.combination(@components).find { |n| n.sum == 2020 }
puts "#{components.join(' * ')} = #{components.inject(:*)}"
end
end
require 'test/unit'
Test::Unit::AutoRunner.need_auto_run = false
class SolverSpec < Test::Unit::TestCase
end
if $PROGRAM_NAME == __FILE__
first_argument = ARGV.shift
if first_argument == '--specs'
# Run the specs
Test::Unit::AutoRunner.need_auto_run = true
else
data_source = first_argument.nil? ? DATA.read : File.read(first_argument)
# Run the solver
numbers = data_source.split(/\r?\n/).map(&:to_i)
Solver.new(numbers, components: 2).solve
Solver.new(numbers, components: 3).solve
end
end
__END__
1981
1415
1767
1725
1656
1860
1272
1582
1668
1202
1360
1399
1517
1063
1773
1194
1104
1652
1316
1883
1117
522
1212
1081
1579
1571
1393
243
1334
1934
1912
1784
1648
1881
1362
1974
1592
1639
1578
1650
1771
1384
1374
1569
1785
1964
1910
1787
1865
1373
1678
1708
1147
1426
1323
855
1257
1497
1326
1764
1793
1993
1926
1387
1441
1332
1018
1949
1807
1431
1933
2009
1840
1628
475
1601
1903
1294
1942
1080
1817
1848
1097
1600
1833
1665
1919
1408
1963
1140
1558
1847
1491
1367
1826
1454
1714
2003
1378
1301
1520
1269
1820
1252
1760
1135
1893
1904
1956
1344
1743
1358
1489
1174
1675
1765
1093
1543
1940
1634
1778
1732
1423
1308
1855
962
1873
1692
1485
1766
1287
1388
1671
1002
1524
1891
1627
1155
1185
1122
1603
1989
1343
1745
1868
1166
1253
1136
1803
1733
1310
1762
1319
1930
1637
1726
1446
266
1121
1851
1819
1284
1959
1449
1965
1687
1079
1808
1839
1626
1359
1935
1247
1932
1951
1318
1597
1268
643
1938
1741
1721
1640
1238
1976
1237
1960
1805
1757
1990
1276
1157
1469
1794
1914
1982
1115
1907
1846
1674
| true |
f3eb347029bd260d85a4cc757d8b60758bd5e2b3
|
Ruby
|
alexanderwjrussell/CodeWars
|
/ConvertToUnicode.rb
|
UTF-8
| 155 | 3.375 | 3 |
[] |
no_license
|
def uni_total(string)
array = string.chars.to_a
total = 0
array.each do |n|
total = total + n.ord
end
puts total
end
uni_total("Alexander")
| true |
6e61fecf3abcb12bf9f8cb751132daa9b2c71885
|
Ruby
|
YuukiMAEDA/AtCoder
|
/Ruby/ABC/C/GeT_AC.rb
|
UTF-8
| 243 | 2.625 | 3 |
[] |
no_license
|
n,q=gets.split.map(&:to_i)
s=gets.chomp
lrs=q.times.map{gets.split.map(&:to_i)}
sum=[0]*(n+1)
(n-1).times do |i|
sum[i+1]+=1 if s[i]=="A" && s[i+1]=="C"
end
n.times{|i| sum[i+1]+=sum[i]}
lrs.each do |lr|
puts sum[lr[1]-1]-sum[lr[0]-1]
end
| true |
9d4a8859fc4821fae185f2473d6223df55e6c2bc
|
Ruby
|
ralake/Battleships
|
/lib/player.rb
|
UTF-8
| 140 | 2.8125 | 3 |
[] |
no_license
|
class Player
attr_accessor :board
def board
@board
end
def receive_shot(coordinates)
@board.shoot(coordinates)
end
end
| true |
ab6aa8385c92b3dede9f5e42c4792e8b7b1a5f7d
|
Ruby
|
jwStriker/aAclasswork
|
/Chess Final/piece.rb
|
UTF-8
| 1,907 | 3.546875 | 4 |
[] |
no_license
|
require_relative 'slideable.rb'
require_relative 'stepable.rb'
class Piece
attr_reader :value, :color, :board
attr_accessor :position
def initialize(color, board, position)
#@value = :*
@color = color
@board = board
@position = position
end
end
class Pawn < Piece
def initialize(color, board, position)
@value = "p"
super(color, board, position)
end
def moves(piece = @value)
mod = {"Red" => 1, "Blue" => -1}[@color]
x, y = @position
possible_moves = []
if (x == 1 && @color == "Red") || (x == 6 && @color == "Blue")
possible_moves << [x+(mod*2), y] if @board[x+(mod*2)][y].color.nil? && ((x+(mod*2)).between?(0,7) && (y).between?(0,7))
end
x += mod
# y always modded
possible_moves << [x, y-1] if ((x).between?(0,7) && (y-1).between?(0,7)) && @board[x][y-1].value != "-" && @board[x][y-1].color != @color
possible_moves << [x, y+1] if ((x).between?(0,7) && (y+1).between?(0,7)) && @board[x][y+1].value != "-" && @board[x][y+1].color != @color
possible_moves << [x, y] if @board[x][y].color.nil? && ((x).between?(0,7) && (y).between?(0,7))
possible_moves
end
end
class Bishop < Piece
include Slideable
def initialize(color, board, position)
@value = "B"
super(color, board, position)
end
end
class Rook < Piece
include Slideable
def initialize(color, board, position)
@value = "R"
super(color, board, position)
end
end
class Queen < Piece
include Slideable
def initialize(color, board, position)
@value = "Q"
super(color, board, position)
end
end
class King < Piece
include Stepable
def initialize(color, board, position)
@value = "K"
super(color, board, position)
end
end
class Knight < Piece
include Stepable
def initialize(color, board, position)
@value = "k"
super(color, board, position)
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.