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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ad563580aeb89e951c29660e88b9fb8837b1cf17
|
Ruby
|
rstacruz/embassy
|
/test/factories.rb
|
UTF-8
| 1,124
| 2.796875
| 3
|
[] |
no_license
|
require 'ffaker-ext'
# Returns a word that matches the given block's condition
def word(options={}, &blk)
while true
word = Faker::Lorem.word
break if yield(word)
end
word
end
def User.spawn(hash={})
hash[:email] ||= Faker::Internet.email
hash[:password] ||= 'password'
hash[:profile_name] ||= word { |w| (3..20).include?(w.length) && Profile[w].nil? }
hash[:display_name] ||= Faker::Name.name
User.new(hash)
end
def Project.spawn(hash={})
hash[:name] ||= Faker::Lorem.title
hash[:category_names] ||= [(Category.random || Category.spawn!).name]
Project.new(hash)
end
def Category.spawn(hash={})
hash[:name] ||= word { |w| Category[w].nil? }
Category.new(hash)
end
def Image.spawn(hash={})
hash[:image_file] ||= Main.root('test/fixtures/images/nyancat.png')
Image.new(hash)
end
def User.spawn!(hash={}) spawn(hash).save end
def Image.spawn!(hash={}) spawn(hash).save end
def Project.spawn!(hash={}) spawn(hash).save end
def Category.spawn!(hash={}) spawn(hash).save end
class Sequel::Model
def self.random
all.shuffle.first
end
end
| true
|
1d6a4d52a95f0fb61e80a4c2025713ba997c764d
|
Ruby
|
kmamykin/funfair
|
/lib/funfair/pub_sub/publish_request.rb
|
UTF-8
| 2,101
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
module Funfair
module PubSub
# Represents an asynchronous request to publish event to an exchange.
# Usage:
# request = publisher.publish(exchange_name, message_data)
# request.callback { puts "Succeeded" }
# request.errback { |error_message| puts error_message }
# See: http://eventmachine.rubyforge.org/docs/DEFERRABLES.html
class PublishRequest
include EventMachine::Deferrable
attr_accessor :tag
attr_reader :logger
def initialize(publisher, exchange_name, message_data)
@publisher, @exchange_name = publisher, exchange_name.to_s
@serialized_data = MultiJson.dump(message_data)
@timeout = 30 # in sec
@logger = Funfair.logger
end
def publish
@publisher.on_channel_ready do |channel|
EM.next_tick do
logger.debug "Declaring publisher's exchange: #{@exchange_name}"
channel.fanout(@exchange_name, :durable => true) do |exchange|
# publisher_index should have been incremented by exchange.publish in channel after_publish callback
self.tag = channel.publisher_index + 1
logger.debug "Publishing message: #{@serialized_data} to #{exchange.name}"
exchange.publish(@serialized_data, {:persistent => true}) do
logger.debug "Message sent: #{@serialized_data}"
# this is executed on EM.next_tick
# and just means that AMQP passed the message to OS, no other guarantees made at this point
timeout @timeout, 'PublishRequest timed out without confirmation (either ACK or NACK).'
end
end
end
end
end
def ack!(tag, multiple)
succeed if matches_tag?(tag, multiple)
end
def nack!(tag, multiple, reason)
fail(reason) if matches_tag?(tag, multiple)
end
def fail!(reason)
fail reason
end
def matches_tag?(tag, multiple)
return false unless tag
multiple ? self.tag <= tag : self.tag == tag
end
end
end
end
| true
|
b0fb1c6d2d9914922d3cbc9f1c2dbe8a9037d1ea
|
Ruby
|
RichardLW6/Tealeaf_Week2
|
/oop_paper_rock_scissors/oop_prs2.rb
|
UTF-8
| 2,123
| 4.25
| 4
|
[] |
no_license
|
#OOP Paper, Rock, Scissors - Second Version (May/June 2015)
class Player
attr_accessor :player_choice
def initialize
@player_choice = ""
end
def player_chooses
begin
puts "Please choose Paper (P), Rock (R), or Scissors (S)..."
self.player_choice = gets.chomp.upcase
end until ['P', 'R', 'S'].include?(self.player_choice) == true
case self.player_choice
when 'P'
self.player_choice = 'Paper'
when 'R'
self.player_choice = 'Rock'
when 'S'
self.player_choice = 'Scissors'
end
end
end
class Computer
attr_accessor :computer_choice
def initialize
@computer_choice = ['Paper', 'Rock', 'Scissors'].sample
end
end
class PaperRockScissors
attr_accessor :user, :opponent, :outcome, :winner, :continue_option
def initialize
puts "Welcome to Paper, Rocks, and Scissors!\n"
@user = ""
@opponent = ""
@outcome = ""
@winner = true
@continue_option
end
def choose_hands
self.user = Player.new.player_chooses
self.opponent = Computer.new.computer_choice
end
def player_wins?
if (self.user == 'Rock' && self.opponent == 'Scissors') ||
(self.user == 'Paper' && self.opponent == 'Rock') ||
(self.user == 'Scissors' && self.opponent == 'Paper')
self.winner = true
elsif user == opponent
self.winner = 'Tie'
else
self.winner = false
end
end
def make_outcome
self.outcome = "You chose #{self.user} and the computer chose #{self.opponent}\n"
end
def show_winner
if winner == true
puts outcome
puts "Player wins!"
elsif winner == false
puts outcome
puts "Computer wins!"
else
puts outcome
puts "It's a Tie!"
end
end
def play_again?
begin
puts "Would you like to play again? (Y/N)"
self.continue_option = gets.chomp.upcase
end until ['Y', 'N'].include?(continue_option)
end
def run
begin
choose_hands
player_wins?
make_outcome
puts winner
show_winner
play_again?
end until continue_option == 'N'
end
end
PaperRockScissors.new.run
| true
|
b881257b4c4e4b70b654aaeb7d5abaa5dbe17f9f
|
Ruby
|
kanon2580/tot
|
/app/models/tag.rb
|
UTF-8
| 408
| 2.671875
| 3
|
[] |
no_license
|
class Tag < ApplicationRecord
validates :name, presence: true
has_many :taggings
has_many :issues, through: :taggings
def self.search(team, q)
return team.tags if q == ""
splited_q = q.split(/[[:blank:]]+/)
tags = []
splited_q.each do |q|
next if q == ""
tags += team.tags.where('LOWER(name) LIKE ?', "%#{q}%".downcase)
end
tags.uniq!
return tags
end
end
| true
|
ddbf99e2796731b476b34d18f6bdcf4a701c5de8
|
Ruby
|
bhatarchanas/add_ons_for_mcsmrt
|
/get_singletons_and_utax.rb
|
UTF-8
| 1,094
| 2.734375
| 3
|
[] |
no_license
|
require 'trollop'
require 'bio'
#ruby ../mcsmrt_mod/parse_all_info_file.rb -a all_bc_reads_info_first_few_lines.txt -o parsed_all_bc_reads_info.txt
opts = Trollop::options do
opt :allreadsfile, "File with all the reads", :type => :string, :short => "-r"
opt :allinfofile, "File with all the reads and information regarding each of it", :type => :string, :short => "-a"
opt :outfile, "Output file with stats from all info file", :type => :string, :short => "-o"
end
all_reads_file = Bio::FlatFile.auto(opts[:allreadsfile], "r")
all_info_file = File.open(opts[:allinfofile], "r")
out_file = File.open(opts[:outfile], "w")
read_name_array = []
all_info_file.each do |line|
line_split = line.split("\t")
read_name = line_split[0]
note = line_split[-2]
#puts note
if note == "forward_singleton" or note == "reverse_singleton"
read_name_array.push(read_name)
end
end
all_reads_file.each do |entry|
#puts entry.definition
read_def = entry.definition.split(";")[0]
if read_name_array.include?(read_def)
out_file.puts(">#{read_def}")
out_file.puts(entry.naseq.upcase)
end
end
| true
|
f99cb9ee5f841fa2624ddb41e3d1793687d80c2c
|
Ruby
|
camillesk/test_cr_api
|
/app/models/cart.rb
|
UTF-8
| 259
| 2.578125
| 3
|
[] |
no_license
|
class Cart < ApplicationRecord
belongs_to :customer
has_many :cart_items
def total_cart_price
total = 0
CartItem.all.map do |item|
med = Medicine.find(item.medicine_id)
total = item.quantity * med.value
end
total
end
end
| true
|
6047295311a3b5b623c79af073a23aeba33195d4
|
Ruby
|
josekim/phase-0-tracks
|
/databases/build_82/college_students.rb
|
UTF-8
| 1,062
| 2.78125
| 3
|
[] |
no_license
|
# require gems
require_relative 'build_database'
require_relative 'prompts'
done = false
puts WELCOME
input = gets.chomp
database = College_Students.new(input)
until database.database_done
end
until done
puts CMD_PROMPTS
input = gets.chomp
if input.to_i == 1
puts SEARCH_STUDENT_PROMPT
option = gets.chomp
puts SEARCH_TERM
term = gets.chomp
database.search(option.to_i,term)
elsif input.to_i == 2
puts GET_FIRST_NAME
first_name = gets.chomp
puts GET_LAST_NAME
last_name = gets.chomp
puts GET_AGE
age = gets.chomp
puts GET_UNIVERSITY
university = gets.chomp
puts GET_MAJOR
major = gets.chomp
database.create_new_student(first_name, last_name, age, university, major)
elsif input.downcase == "done"
done = true
end
end
######### Features ########
# Clear my Database
# Find Student
# => what Major
# => what school
# => update school
# Find a University
# => what is the population
# => who are the students
# => alphabitize
# Create a New Data Base
# Delete My Data Base
| true
|
79a8b868bf08587fd60f0292319fcd69bfd31ca3
|
Ruby
|
osak/Contest
|
/Euler/46.rb
|
UTF-8
| 556
| 3.453125
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
def infinite_odd
n = 3;
while true do
yield n;
n += 2;
end
end
primes = Array.new;
isprime = Hash.new;
primes.push(2);
isprime[2] = true;
infinite_odd { |n|
root = Math.sqrt(n);
ok = true;
primes.each { |p|
break if p > root;
if n % p == 0 then
ok = false;
break;
end
}
if ok then
primes.push(n);
isprime[n] = true;
else
goldbach = false;
for i in 1..root do
if isprime[n-2*i*i] then
goldbach = true;
break;
end
end
if !goldbach then
p n
exit;
end
end
p n if n%10000 == 1;
}
| true
|
140ec2ff3e1269bfd5b46f4f46cdd60fceefeff6
|
Ruby
|
KrakatoaComCafe/codefights
|
/Arcade/Intro/01 - The Journey Begins/2 - centuryFromYear/centuryFromYear.rb
|
UTF-8
| 180
| 3.203125
| 3
|
[] |
no_license
|
def centuryFromYear(year)
rest = year % 100
oldCentury = rest == 0
if oldCentury
return (year / 100)
else
return (year / 100 + 1)
end
end
| true
|
da741aa8b0d96fc956f74da83b926045f5cfba01
|
Ruby
|
BrentOnRails/App_Academy
|
/Feb11 - SQL/tag.rb
|
UTF-8
| 1,524
| 2.96875
| 3
|
[] |
no_license
|
require './QuestionsDatabase'
require './SQL.rb'
class Tag < Sql
attr_reader :id
attr_accessor :name
def self.all
users = QuestionsDatabase.instance.execute("SELECT * FROM tags")
users.map { |user| Tag.new(user) }
end
def self.find_by_id(id)
question = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT *
FROM tags
WHERE tags.id = ?
SQL
Tag.new(question[0])
end
def self.most_popular(n)
QuestionsDatabase.instance.execute(<<-SQL,n)
SELECT *
FROM tags
JOIN question_tags as qt ON qt.tag_id = tags.id
JOIN question_likes ON question_likes.question_id = qt.question_id
GROUP BY tags.id
ORDER BY COUNT(question_likes.user_id) DESC
LIMIT ?
SQL
end
def initialize(option = {})
@id = option["id"]
@name = option["name"]
end
def most_popular_questions(n)
result = QuestionsDatabase.instance.execute(<<-SQL, self.id, n)
SELECT
questions.id, questions.title, questions.body, questions.author_id
FROM
questions JOIN question_likes ON questions.id = question_likes.question_id
WHERE
questions.id IN (SELECT question_tags.question_id
FROM
tags JOIN question_tags ON tags.id = question_tags.tag_id
WHERE
tag_id = ?)
GROUP BY questions.id
ORDER BY COUNT(question_likes.user_id) DESC
LIMIT ?
SQL
result.map{ |result| Question.new(result)}
end
def save
@id = super({"object" => self, "name" => self.name})
end
end
| true
|
ed26ff1571dbf4c84569f1753885d513813199ec
|
Ruby
|
CodeGrade/hourglass
|
/app/models/term.rb
|
UTF-8
| 1,422
| 2.765625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
# A university Term, which consists of many courses.
class Term < ApplicationRecord
has_many :courses, dependent: :destroy
# these underscores make .humanize create a space ( ).
# rubocop:disable Naming/VariableNumber
enum semester: { fall: 10, spring: 30, summer_1: 40, summer: 50, summer_2: 60 }
# rubocop:enable Naming/VariableNumber
has_many :registrations, through: :courses
has_many :staff_registrations, through: :courses
has_many :proctor_registrations, through: :courses
has_many :professor_course_registrations, through: :courses
scope :active, -> { where(archived: false) }
scope :sorted, -> { sort_by(&:canonical_name).reverse }
validates :semester,
inclusion: { in: Term.semesters.keys },
uniqueness: {
scope: :year,
message: lambda do |object, _data|
"Terms must be unique, but the semester/year pair <code>#{object.name}</code> already exists"
end,
}
def canonical_name
season = "#{Term.semesters[semester]}_#{semester}"
arch = archived? ? 'a' : 'z'
"#{arch} #{effective_year} #{season} #{name}"
end
def name
"#{semester.humanize} #{year}"
end
private
def effective_year
# Fall is part of numerically-next *academic* year
add = Term.semesters[semester] < Term.semesters[:spring] ? 1 : 0
year + add
end
end
| true
|
822835488c679d92cc236e923b193e0bdf4d3358
|
Ruby
|
victortyau/CodeEval
|
/Capitalize Words/cap.rb
|
UTF-8
| 394
| 3.65625
| 4
|
[] |
no_license
|
class CapWords
def initialize
@lines = ""
archivo()
end
def archivo
file_name = ARGV[0]
if File.exist?(file_name)
@lines = IO.readlines(file_name);
end
end
def mayusc
@lines.each do |line|
if !line.nil?
array_line = line.delete("\n").split(" ")
data = array_line.map(&:capitalize)
end
puts data.join(" ")
end
end
end
cw = CapWords.new
cw.mayusc
| true
|
5127b1888eca4bb44cec8a0ac9baf26af6941d98
|
Ruby
|
JNEdrozo/hotel
|
/lib/hotel_admin.rb
|
UTF-8
| 3,799
| 3.09375
| 3
|
[] |
no_license
|
require 'date'
require 'date_range'
require_relative 'room'
require_relative 'reservation'
require_relative 'BookingSystem_Errors'
module BookingSystem
class HotelAdmin
attr_reader :room_list, :reservation_list, :block_list
def initialize
#hotel admin knows all reservations (non-block and block)
@reservation_list = []
@block_list = []
#hotel admin knows all rooms in hotel
@room_list = BookingSystem::Room.all
end
def reserve_room(first_name, last_name, room_id, room_rate, start_date, end_date, block_id = nil)
requested_range = DateRange.new(start_date, end_date)
if block_id.nil? #if a room doesn't have a block_id, blacklist all rooms that are blocked
raise UnavailableRoomError.new("Room is unavailable") if @block_list.any? do |block|
block.date_range.overlaps?(requested_range) && block.rooms_array.any? { |room| room.id == room_id }
end
end
raise UnavailableRoomError.new("Room is unavailable") if @reservation_list.any? {|reservation|
reservation.room_id == room_id && reservation.date_range.overlaps?(requested_range) && start_date < reservation.end_date
#overlaps? same as:
# reservation.room_id == room_id &&
# !(reservation.start_date >= end_date || reservation.end_date <= start_date)
}
reservation = BookingSystem::Reservation.new(first_name, last_name, room_id, room_rate, start_date, end_date, block_id)
@reservation_list << reservation
end
# Hotel Revisted Changes
def reserve_block(block_id, date_range, rooms_array, discount_room_rate, reservation_list)
if @block_list.any? { |block| block.date_range.overlaps?(date_range) }
@block_list.each do |block|
rooms_array.each do |room|
if block.list_room_ids.include?(room.id)
raise UnavailableRoomError.new("Room is unavailable")
end
end
end
end
block = BookingSystem::Block.new(block_id, date_range, rooms_array, discount_room_rate, reservation_list)
@block_list << block
end
def find_reservations_by_date(specific_date)
reservations_on_date = []
@reservation_list.each do |reservation|
if reservation.date_range.include?(specific_date)
reservations_on_date << reservation
end
end
return reservations_on_date
end
def rooms_available_for_date_range(date_range)
raise InvalidDateRangeError.new("Range must be a DateRange object") if !date_range.is_a? DateRange
unavailable_room_ids = []
@reservation_list.each do |reservation|
if reservation.date_range.overlaps?(date_range)
unavailable_room_ids << reservation.room_id
end
end
available_rooms = @room_list.reject { |room| unavailable_room_ids.include?(room.id) }
return available_rooms
end
end#of_HotelAdmin_class
end#of_module_BookingSystem
# REFACTORED METHODS:
# def rooms_available_for_date_range(date_range)
# raise InvalidDateRangeError.new("Range must be a DateRange object") if !date_range.is_a? DateRange
#
# unavailable_room_ids = []
#
# @reservation_list.each do |reservation|
# if reservation.date_range.include?(date_range)
# unavailable_room_ids << reservation.room_id
# end
# end
#
# available_rooms = []
#
# @room_list.each do |room|
# if unavailable_room_ids.include?(room.id) == false
# available_rooms << room
# end
# end
#
# return available_rooms
# end
=begin
Date notes:
<
source: https://stackoverflow.com/questions/3296539/comparision-of-date-in-ruby
.between?(start_date, end_date)
source: https://stackoverflow.com/questions/4521921/how-to-know-if-todays-date-is-in-a-date-range
=end
| true
|
a7d35e2ba26e555b36346550fe92a3087e39ff3a
|
Ruby
|
Vwampage/dev-installday
|
/helloworld.rb
|
UTF-8
| 229
| 3.53125
| 4
|
[] |
no_license
|
# Hello World in Ruby -- Install day 12/17/12
puts "David Michaels"
puts "a potato in the oven"
puts "a potato on the counter"
puts "...but only once it's ready. that is when you puts a potato out of the oven."
puts "LINE LINE LINE"
| true
|
5a6958449176d85524f4ce95a1704bdcd81aa35f
|
Ruby
|
fela/rlid
|
/lib/rlid/misc/web_page.rb
|
UTF-8
| 2,156
| 3.375
| 3
|
[
"MIT-0"
] |
permissive
|
class NetworkError < StandardError
end
class WebPage
attr_reader :url
def initialize(url)
@url = url
end
# not really random, finds the most central link
def random_link
dump = `lynx -dump #{@url}`
# the second part contains the visible links
links = get_links_from_lynx_output(dump).split("\n")
# take the most central link
link = links[links.size/2]
# get only the actual url
data = link.match(LYNX_LINK_TO_URL)
if data == nil
raise NetworkError, "'#{link}' is not a link"
end
url = data[1] # fist match
WebPage.new(url)
end
def text
`w3m -dump '#{@url}'`
end
def longest_paragraph
paragraphs = text.split(/\n\s*\n/)
paragraphs.each do |par|
par.gsub!(/^\s+/, '')
par.gsub!(/\s+$/, '')
end
#paragraphs.delete_if {|p| p.size < 100 || not_useful(p) }
paragraphs.sort! {|a, b| a.size <=> b.size}
paragraphs.last
end
private
LYNX_DIV1 = "References\n\n Visible links\n" # separation with hidden links
LYNX_DIV2 = "References\n\n" # division without hidden links
LYNX_DIV_HIDDEN = "\n\n Hidden links:\n"
LYNX_LINK_TO_URL = /\s+\d+\. ?(http:\/\/.+)/
# sorry for the unintentional pun :)
def get_links_from_lynx_output(lynx_output)
# suppose there are hidden links
site_parts = lynx_output.split(LYNX_DIV1)
if site_parts.size == 1
# there wheren't hidden links
site_parts = lynx_output.split(LYNX_DIV2)
# make sure the split was successful
if site_parts.size != 2
raise NetworkError, "no links found or invalid lynx output"
end
else
# there where hidden links remove them
site_parts[1, 1] = site_parts[1].split(LYNX_DIV_HIDDEN)
# make sure the split was successful
if site_parts.size != 3
raise NetworkError, "no links found or invalid lynx output"
end
end
return site_parts[1]
end
def not_useful(p)
# substitute unuseful text with ~
changed = p.gsub(' ', '~~')
changed.gsub!(/\D\D\D\D/, '~~~~')
p = changed
p.size < changed.count('~') * 50
false
end
end # class
| true
|
828199a97a6d252215bee618007982c408a9d526
|
Ruby
|
kim2214/Datastructure
|
/atcoder/20_04_04/A - ABC Swap.rb
|
UTF-8
| 264
| 3.28125
| 3
|
[] |
no_license
|
X = gets.chomp.split(' ').map(&:to_i)
def swap_first(arr)
tmp = 0
tmp = arr[0]
arr[0] = arr[1]
arr[1] = tmp
end
def swap_second(arr)
tmp = 0
tmp = arr[0]
arr[0] = arr[2]
arr[2] = tmp
end
swap_first(X)
swap_second(X)
print X[0]," ",X[1]," ",X[2]
| true
|
28b89a389389279efcda28ab55932417e7673391
|
Ruby
|
phlipper/ach
|
/lib/ach/records/nines.rb
|
UTF-8
| 476
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
module ACH::Records
# The number of records must be a multiple of ten (that is, complete 940
# character blocks). If needed, rows that consist of the digit "9" may be
# used to pad the the file.
#
# "Nines" records thus consist of a single constant field containing the digit
# "9" 94 times.
#
# See 2008 ACH Rules, Appx 1, Sec 1.5; Appx 2, Sec 2.3
class Nines < Record
@fields = []
const_field :record_type, ('9' * 94)
end
end
| true
|
001947c5e0f86de2f30ecdc5d8d6944f0a610bbe
|
Ruby
|
jeff-sherling/posh-o-matic
|
/test/unit/user_factory_address_test.rb
|
UTF-8
| 1,246
| 2.703125
| 3
|
[] |
no_license
|
$LOAD_PATH.push 'lib/data'
$LOAD_PATH.push 'lib/log'
require 'user_factory'
require 'minitest/autorun'
require 'minitest/reporters'
require 'console'
# UserFactory address-related unit tests
class UserFactoryAddressTest < Minitest::Test
Minitest::Reporters.use! [Minitest::Reporters::SpecReporter.new,
Minitest::Reporters::JUnitReporter.new]
def test_phone
phone = UserFactory.phone
Console.log.info "Phone: #{phone}"
assert(phone.size == 10, 'Phone should be 10 characters long.')
end
def test_address1
address = UserFactory.address1
Console.log.info "Address 1: #{address}"
assert(address.size >= 10,
'Address1 size should be 10 characters or longer.')
end
def test_address2
room = UserFactory.address2
Console.log.info "Address 2: #{room}"
assert(room.size >= 5, 'Address2 should be 5 characters or longer.')
end
def test_state
state = UserFactory.state_province
Console.log.info "State: #{state}"
assert(state.size == 2, 'State should be two-letter abbreviation.')
end
def test_zip_code
zip = UserFactory.zip_code
Console.log.info "Zip: #{zip}"
assert(zip.size == 5, 'Zip code should be 5 characters long.')
end
end
| true
|
8db21982ef15dcde4d1a75318cd82cf1a2664b4f
|
Ruby
|
johngrayau/jg_piawe
|
/spec/piawe_spec.rb
|
UTF-8
| 13,258
| 3.078125
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Piawe::Person do
let (:valid) do
Piawe::Person.played_by ( {
"name" => "Ebony Boycott",
"hourlyRate" => 75.0030,
"overtimeRate" => 150.0000,
"normalHours" => 35.0,
"overtimeHours" => 7.3,
"injuryDate" => "2016/05/01"
} )
end
let (:invalid_format) do
Piawe::Person.played_by ( {
"name" => nil,
"hourlyRate" => "foo",
"overtimeRate" => "bar",
"normalHours" => "baz",
"overtimeHours" => "twelve",
"injuryDate" => "yesterday"
} )
end
let (:invalid_values) do
Piawe::Person.played_by ( {
"name" => nil,
"hourlyRate" => nil,
"overtimeRate" => nil,
"normalHours" => nil,
"overtimeHours" => nil,
"injuryDate" => "2016/01/50"
} )
end
let (:empty) do
Piawe::Person.played_by ( Hash.new )
end
context "given a valid person_hash" do
it "has the correct name" do expect(valid.name ).to eql("Ebony Boycott" ); end
it "has the correct hourly rate" do expect(valid.hourly_rate ).to eql( 75.003 ); end
it "has the correct overtime rate" do expect(valid.overtime_rate ).to eql( 150.0 ); end
it "has the correct normal hours" do expect(valid.normal_hours ).to eql( 35.0 ); end
it "has the correct overtime hours" do expect(valid.overtime_hours ).to eql( 7.3 ); end
it "has the correct injury date" do expect(valid.injury_date ).to eql( Date.new(2016, 05, 01) ); end
it "calculates the correct injury weeks" do expect( valid.weeks_since_injury( Date.new(2016, 05, 29) ).to_f ).to eql(4.0) ; end
end # given a valid person_hash
context "given a person_hash with invalid format" do
it "rejects the name value" do expect {invalid_format.name }.to raise_error( ArgumentError, /person_hash has a nil value for name key: #{ invalid_format.inspect}/ ); end
it "rejects the hourly rate value" do expect {invalid_format.hourly_rate }.to raise_error( ArgumentError, /person_hash has a non-numeric value for hourlyRate key: #{ invalid_format.inspect}/ ); end
it "rejects the overtime rate value" do expect {invalid_format.overtime_rate }.to raise_error( ArgumentError, /person_hash has a non-numeric value for overtimeRate key: #{ invalid_format.inspect}/ ); end
it "rejects the normal hours value" do expect {invalid_format.normal_hours }.to raise_error( ArgumentError, /person_hash has a non-numeric value for normalHours key: #{ invalid_format.inspect}/ ); end
it "rejects the overtime hours value" do expect {invalid_format.overtime_hours }.to raise_error( ArgumentError, /person_hash has a non-numeric value for overtimeHours key: #{ invalid_format.inspect}/ ); end
it "rejects the injury date value" do expect {invalid_format.injury_date }.to raise_error( ArgumentError, /injury date of yesterday is not in yyyy\/mm\/dd format: #{ invalid_format.inspect}/ ); end
end
context "given a person_hash with invalid_values" do
it "rejects the name value" do expect {invalid_values.name }.to raise_error( ArgumentError, /person_hash has a nil value for name key: #{ invalid_values.inspect}/ ); end
it "rejects the hourly rate value" do expect {invalid_values.hourly_rate }.to raise_error( ArgumentError, /person_hash has a non-numeric value for hourlyRate key: #{ invalid_values.inspect}/ ); end
it "rejects the overtime rate value" do expect {invalid_values.overtime_rate }.to raise_error( ArgumentError, /person_hash has a non-numeric value for overtimeRate key: #{ invalid_values.inspect}/ ); end
it "rejects the normal hours value" do expect {invalid_values.normal_hours }.to raise_error( ArgumentError, /person_hash has a non-numeric value for normalHours key: #{ invalid_values.inspect}/ ); end
it "rejects the overtime hours value" do expect {invalid_values.overtime_hours }.to raise_error( ArgumentError, /person_hash has a non-numeric value for overtimeHours key: #{ invalid_values.inspect}/ ); end
it "rejects the injury date value" do expect {invalid_values.injury_date }.to raise_error( ArgumentError, /person_hash has an invalidly formatted injuryDate key: #{ invalid_values.inspect}/ ); end
end
context "given an empty person_hash" do
it "rejects the name value" do expect {empty.name }.to raise_error( ArgumentError, /person_hash does not have a key of name: #{ empty.inspect}/ ); end
it "rejects the hourly rate value" do expect {empty.hourly_rate }.to raise_error( ArgumentError, /person_hash does not have a key of hourlyRate: #{ empty.inspect}/ ); end
it "rejects the overtime rate value" do expect {empty.overtime_rate }.to raise_error( ArgumentError, /person_hash does not have a key of overtimeRate: #{ empty.inspect}/ ); end
it "rejects the normal hours value" do expect {empty.normal_hours }.to raise_error( ArgumentError, /person_hash does not have a key of normalHours: #{ empty.inspect}/ ); end
it "rejects the overtime hours value" do expect {empty.overtime_hours }.to raise_error( ArgumentError, /person_hash does not have a key of overtimeHours: #{ empty.inspect}/ ); end
it "rejects the injury date value" do expect {empty.injury_date }.to raise_error( ArgumentError, /person_hash does not have a key of injuryDate: #{ empty.inspect}/ ); end
end
end # describe Piawe::Person
describe Piawe do
let (:report_date) do
Date.new(2017, 3, 1)
end
let (:people_array) do
[
{"name" => "Ebony Boycott", "hourlyRate" => 75.0030, "overtimeRate" => 150.0000, "normalHours" => 35.0, "overtimeHours" => 7.3, "injuryDate" => "2016/05/01" }, # 43.42857142857143
{"name" => "Geoff Rainford-Brent", "hourlyRate" => 30.1234, "overtimeRate" => 60.3456, "normalHours" => 25.0, "overtimeHours" => 10.7, "injuryDate" => "2016/08/04" }, # 29.857142857142858
{"name" => "Meg Gillespie", "hourlyRate" => 50.0000, "overtimeRate" => 100.0000, "normalHours" => 37.5, "overtimeHours" => 0.0, "injuryDate" => "2015/12/31" }, # 60.857142857142854
{"name" => "Jason Lanning", "hourlyRate" => 40.0055, "overtimeRate" => 90.9876, "normalHours" => 40.0, "overtimeHours" => 12.4, "injuryDate" => "2013/01/01" } # 217.14285714285714
]
end
let (:rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "27-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "105+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:piawe) do
Piawe.new(people_array, rules_array)
end
let (:report) do
piawe.report(report_date)
end
it 'has a version number' do
expect(Piawe::VERSION).not_to be nil
end
context "given valid arguments, the report" do
it "should have the correct date" do expect( report[:report_date] ).to eql( report_date.strftime("%Y/%m/%d")); end
it "should have the correct number of lines" do expect( report[:report_lines].size ).to eql( 4 ); end
#
it "should have the correct name for person 1" do expect( report[:report_lines][0][:name ] ).to eql(people_array[0]["name"]); end
it "should have the correct pay for person 1" do expect( report[:report_lines][0][:pay_for_this_week ] ).to eql( "2976.08" ); end
it "should have the correct weeks_since_injury for person 1" do expect( report[:report_lines][0][:weeks_since_injury ] ).to eql( "43.43" ); end
it "should have the correct hourly rate for person 1" do expect( report[:report_lines][0][:hourly_rate ] ).to eql( "75.003000" ); end
it "should have the correct overtime rate for person 1" do expect( report[:report_lines][0][:overtime_rate ] ).to eql( "150.000000"); end
it "should have the correct normal hours for person 1" do expect( report[:report_lines][0][:normal_hours ] ).to eql( "35.00" ); end
it "should have the correct overtime hours for person 1" do expect( report[:report_lines][0][:overtime_hours ] ).to eql( "7.30" ); end
it "should have the correct percentage_payable for person 1" do expect( report[:report_lines][0][:percentage_payable ] ).to eql( "80.00" ); end
it "should have the correct overtime_included for person 1" do expect( report[:report_lines][0][:overtime_included ] ).to eql( "true" ); end
#
it "should have the correct name for person 2" do expect( report[:report_lines][1][:name ] ).to eql(people_array[1]["name"]); end
it "should have the correct pay for person 2" do expect( report[:report_lines][1][:pay_for_this_week ] ).to eql( "1119.03" ); end
it "should have the correct weeks_since_injury for person 2" do expect( report[:report_lines][1][:weeks_since_injury ] ).to eql( "29.86" ); end
it "should have the correct hourly rate for person 2" do expect( report[:report_lines][1][:hourly_rate ] ).to eql( "30.123400" ); end
it "should have the correct overtime rate for person 2" do expect( report[:report_lines][1][:overtime_rate ] ).to eql( "60.345600" ); end
it "should have the correct normal hours for person 2" do expect( report[:report_lines][1][:normal_hours ] ).to eql( "25.00" ); end
it "should have the correct overtime hours for person 2" do expect( report[:report_lines][1][:overtime_hours ] ).to eql( "10.70" ); end
it "should have the correct percentage_payable for person 2" do expect( report[:report_lines][1][:percentage_payable ] ).to eql( "80.00" ); end
it "should have the correct overtime_included for person 2" do expect( report[:report_lines][1][:overtime_included ] ).to eql( "true" ); end
#
it "should have the correct name for person 3" do expect( report[:report_lines][2][:name ] ).to eql(people_array[2]["name"]); end
it "should have the correct pay for person 3" do expect( report[:report_lines][2][:pay_for_this_week ] ).to eql( "1312.50" ); end
it "should have the correct weeks_since_injury for person 3" do expect( report[:report_lines][2][:weeks_since_injury ] ).to eql( "60.86" ); end
it "should have the correct hourly rate for person 3" do expect( report[:report_lines][2][:hourly_rate ] ).to eql( "50.000000" ); end
it "should have the correct overtime rate for person 3" do expect( report[:report_lines][2][:overtime_rate ] ).to eql( "100.000000"); end
it "should have the correct normal hours for person 3" do expect( report[:report_lines][2][:normal_hours ] ).to eql( "37.50" ); end
it "should have the correct overtime hours for person 3" do expect( report[:report_lines][2][:overtime_hours ] ).to eql( "0.00" ); end
it "should have the correct percentage_payable for person 3" do expect( report[:report_lines][2][:percentage_payable ] ).to eql( "70.00" ); end
it "should have the correct overtime_included for person 3" do expect( report[:report_lines][2][:overtime_included ] ).to eql( "true" ); end
#
it "should have the correct name for person 4" do expect( report[:report_lines][3][:name ] ).to eql(people_array[3]["name"]); end
it "should have the correct pay for person 4" do expect( report[:report_lines][3][:pay_for_this_week ] ).to eql( "160.02" ); end
it "should have the correct weeks_since_injury for person 4" do expect( report[:report_lines][3][:weeks_since_injury ] ).to eql( "217.14" ); end
it "should have the correct hourly rate for person 4" do expect( report[:report_lines][3][:hourly_rate ] ).to eql( "40.005500" ); end
it "should have the correct overtime rate for person 4" do expect( report[:report_lines][3][:overtime_rate ] ).to eql( "90.987600" ); end
it "should have the correct normal hours for person 4" do expect( report[:report_lines][3][:normal_hours ] ).to eql( "40.00" ); end
it "should have the correct overtime hours for person 4" do expect( report[:report_lines][3][:overtime_hours ] ).to eql( "12.40" ); end
it "should have the correct percentage_payable for person 4" do expect( report[:report_lines][3][:percentage_payable ] ).to eql( "10.00" ); end
it "should have the correct overtime_included for person 4" do expect( report[:report_lines][3][:overtime_included ] ).to eql( "false" ); end
end
end # describe Piawe
| true
|
454976ec4b3ffa081f124f5118d3344a51e742a6
|
Ruby
|
JuniorJoanis/CDD
|
/periodicity.rb
|
UTF-8
| 300
| 3.4375
| 3
|
[] |
no_license
|
class Periodicity
attr_accessor :number, :type
def initialize (number, type = "weekly")
@number = number
@type = type
end
def to_i
if @type == "day"
return @number * 3600 * 24
else
#the type is weekly
return @number * 3600 * 24 * 7
end
end
end
| true
|
962bfc944c6daa2c3e2853707aee41f41143d700
|
Ruby
|
iamnotnader/tinder_bot
|
/run_tinder.rb
|
UTF-8
| 2,072
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require_relative 'lib/pyro.rb'
require 'json'
# Get this using Charles Proxy
# http://nickfishman.com/post/50557873036/reverse-engineering-native-apps-by-intercepting-network
FACEBOOK_TOKEN = 'XXX'
FACEBOOK_ID = 'XXX'
# We need to sleep when we get rate-limited by Tinder.
SLEEP_SECONDS = 1800
# Where you want to be.
LATITUDE = 40.7231
LONGITUDE = -74.0008
pyro = TinderPyro::Client.new
my_info = pyro.sign_in(FACEBOOK_ID, FACEBOOK_TOKEN)
# print my_info
my_user_id = my_info["user"]["_id"]
puts my_user_id
# Update your location
# Note: this request often takes around 30 seconds
pyro.update_location(LATITUDE, LONGITUDE)
while 1 == 1 do
# Fetch updates (messages, likes, etc)
pyro.fetch_updates
# Try
nearby_users_response = pyro.get_nearby_users
STDERR.puts "nearby_users_response: %s" % nearby_users_response
nearby_users = nearby_users_response.fetch("results", [])
STDERR.puts "nearby_users: %s" % nearby_users.join(", ")
# If we don't have any nearby users, we're probably being throttled by Tinder.
# Try again in a bit.
if nearby_users.length == 0
STDERR.puts "Going to sleep for %s seconds" % SLEEP_SECONDS
sleep SLEEP_SECONDS
# Update our location when we wake up.
pyro.update_location(LATITUDE, LONGITUDE)
end
#print JSON.pretty_generate(nearby_users)
# print parsed['results'][0].keys()
# [u'distance_mi', u'common_like_count', u'common_friend_count', u'common_likes',
# u'bio', u'gender', u'birth_date_info', u'photos', u'common_friends', u'ping_time',
# u'birth_date', u'_id', u'name']
for user in nearby_users
this_user_id = user["_id"]
puts "user_id: %s, distance: %s, birth_date: %s, name: %s" % [this_user_id, user["distance_mi"], user["birth_date"], user["name"]]
pyro.like(this_user_id)
STDOUT.flush
# Can't send a message if you're not matched..
#resp = pyro.send_message(this_user_id, "Hey, let's grab dinner this week :)")
#print resp
end
end
| true
|
d8942e73fd2360a8cf71fe71cd232c016c07c143
|
Ruby
|
tmate/mdocker
|
/lib/mdocker/config/volumes_expansion.rb
|
UTF-8
| 1,479
| 2.703125
| 3
|
[] |
no_license
|
module MDocker
class VolumesExpansion
def self.expand(volumes=[], root:'')
Util::assert_type(Array, value: volumes)
volumes.inject([]) do |result, image|
result << expand_volume(image, root)
end
end
private
def self.expand_volume(volume, root)
Util::assert_type(Hash, String, value: volume)
case volume
when String
pair = volume.match(/(?<host>.+):(?<container>.+)/)
if pair
expand_volume({host: pair[:host], container: pair[:container]}, root)
else
expand_volume({host: volume, container: volume}, root)
end
when Hash
if volume.size == 1
h, c = volume.first
h = h.to_s
c ||= h
expand_volume({host: h, container: c}, root)
elsif volume.size == 2 && volume[:host] && volume[:container]
host = volume[:host].to_s
container = volume[:container].to_s
if named_container?(host)
{host: host,
container: container}
else
{host: File.expand_path(host, root),
container: container}
end
else
raise StandardError.new "unrecognized volume mapping definition:\n#{volume.to_yaml}"
end
else
# ignored
end
end
def self.named_container?(path)
path.match(/^[0-9a-z][0-9a-z\.\-_]*$/i)
end
end
end
| true
|
ed330b58a4f968208feabe10bc9035fa54a7142f
|
Ruby
|
dwnzhao/Sups
|
/app/models/user.rb
|
UTF-8
| 2,187
| 2.828125
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
has_many :items
acts_as_tagger
attr_accessor :password
EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
validates_presence_of :first_name
validates_length_of :first_name, :maximum => 25
validates_presence_of :last_name
validates_length_of :last_name, :maximum => 50
validates_presence_of :username
validates_length_of :username, :within => 8..25
validates_uniqueness_of :username
validates_presence_of :email
validates_length_of :email, :maximum => 100
validates_format_of :email, :with => EMAIL_REGEX
validates_confirmation_of :email
validates_length_of :password, :within => 8..25, :on => :create
before_save :create_hashed_password
after_save :clear_password
scope :named, lambda {|first, last| where(:first_name => first, :last_name => last)}
scope :sorted, order("users.last_name ASC, admin_users.first_name ASC")
attr_protected :hashed_password, :salt
def name
"#{first_name} #{last_name}"
end
def self.authenticate(username="", password="")
user = User.find_by_username(username)
if user && user.password_match?(password)
return user
else
return false
end
end
def password_match?(password="")
hashed_password == User.hash_with_salt(password, salt)
end
def self.make_salt(username="")
Digest::SHA1.hexdigest("Use #{username} with #{Time.now} to make salt")
end
def self.hash_with_salt(password="", salt="")
Digest::SHA1.hexdigest("Put #{salt} on the #{password}")
end
def send_new_password
new_pass = User.random_string(15)
self.password = self.password_confirmation = new_pass
self.save
Notifications.deliver_forgot_password(self.email, self.login, new_pass)
end
private
def create_hashed_password
unless password.blank?
self.salt = User.make_salt(username) if salt.blank?
self.hashed_password = User.hash_with_salt(password, salt)
end
end
def clear_password
self.password = nil
end
def self.random_string(len)
#generat a random password consisting of strings and digits
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
return newpass
end
end
| true
|
10279978d23e2345b6920675300e05feeb22b427
|
Ruby
|
devdevi/scrapingRuby
|
/scraping.rb
|
UTF-8
| 275
| 2.765625
| 3
|
[] |
no_license
|
require 'nokogiri'
require 'open-uri'
# lista de todos los articulos de hackernews
html = open('https://news.ycombinator.com/')
doc = Nokogiri::HTML(html)
# buscamos todos lo elementos de clase title
doc.search('.title a').map do |element|
puts element.inner_text
end
| true
|
fddfcac6e5ef78cb5b2b6c55e5a7b422da7471ba
|
Ruby
|
translation-gang/ru.hanami.github.io
|
/bundle/ruby/2.3.0/gems/middleman-deploy-1.0.0/lib/middleman-deploy/methods/sftp.rb
|
UTF-8
| 1,587
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'net/sftp'
require 'ptools'
module Middleman
module Deploy
module Methods
class Sftp < Ftp
def process
puts "## Deploying via sftp to #{self.user}@#{self.host}:#{path}"
# `nil` is a valid value for user and/or pass.
Net::SFTP.start(self.host, self.user, password: self.pass, port: self.port) do |sftp|
sftp.mkdir(self.path)
Dir.chdir(self.server_instance.build_dir) do
filtered_files.each do |filename|
if File.directory?(filename)
upload_directory(sftp, filename)
else
upload_file(sftp, filename)
end
end
end
end
end
protected
def handle_exception(exception,filename, file_path)
reply = exception.message
err_code = reply[0, 3].to_i
if err_code == 550
sftp.upload(filename, file_path)
end
end
def upload_directory(sftp, filename)
file_path = "#{self.path}/#{filename}"
begin
sftp.mkdir(file_path)
puts "Created directory #{filename}"
rescue
end
end
def upload_file(sftp, filename)
file_path = "#{self.path}/#{filename}"
begin
sftp.upload(filename, file_path)
rescue Exception => exception
handle_exception(exception, filename, file_path)
end
puts "Copied #{filename}"
end
end
end
end
end
| true
|
c50fa9d243ef3521970a56e603f47bc6c81c5380
|
Ruby
|
softscienceprojects/OO-Get-Swole-london-web-080519
|
/tools/console.rb
|
UTF-8
| 835
| 3.03125
| 3
|
[] |
no_license
|
# You don't need to require any of the files in lib or pry.
# We've done it for you here.
require_relative '../config/environment.rb'
# test code goes here
goldsgym = Gym.new(name: "Gold's Gym")
puregym = Gym.new(name: "Puregym")
virgin = Gym.new(name: "Virgin")
hulk = Lifter.new(name: "Inredible Hulk", lift_total: 500)
superhans = Lifter.new(name: "Super Hans", lift_total: 2)
ben = Lifter.new(name: "Super Ben", lift_total: 50)
erin = Lifter.new(name: "Erin", lift_total: 10)
gold_plan_to_golds_gym = Membership.new(cost: 500, gym: goldsgym, lifter: erin)
superhans_puregym_membership = Membership.new(cost: 30, gym: puregym, lifter: superhans)
erins_virgin_membership = Membership.new(cost: 50, gym: virgin, lifter: erin)
bens_puregym_membership = Membership.new(cost: 45, gym: puregym, lifter: ben)
binding.pry
puts "Gains!"
| true
|
91b8e4e12831cab4f62c8866fb99a715f081b21a
|
Ruby
|
10dollars/tendollars.github.io.raw
|
/_plugins/date_page_generator.rb
|
UTF-8
| 1,512
| 2.6875
| 3
|
[] |
no_license
|
module Jekyll
class DatePage < Page
def initialize(site, base, dir, title, posts)
@site = site
@base = base
@dir = dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'interview_date.html')
self.data['title'] = title
self.data['posts_by_date'] = posts
end
end
class DateIndexPage < Page
def initialize(site, base, dir, archives)
@site = site
@base = base
@dir = dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'interview_index.html')
self.data['archives'] = archives
end
end
class DatePageGenerator < Generator
safe true
def generate(site)
archives = {}
site.posts.reverse.each do |post|
year = post.date.year
month = post.date.strftime('%m')
archives[year] ||= {}
(archives[year][month] ||= []) << post
end
archives.each_pair do |year, archive|
year_posts = []
archive.each_pair do |month, posts|
year_posts.concat(posts)
site.pages << DatePage.new(site, site.source, File.join('interviews', year.to_s, month.to_s), "#{posts[0].date.strftime('%B')}, #{year}", posts)
end
site.pages << DatePage.new(site, site.source, File.join('interviews', year.to_s), year, year_posts)
end
site.pages << DateIndexPage.new(site, site.source, 'interviews', archives)
end
end
end
| true
|
a4203a4c3667a2e1c6266720c737a5803d7f16ea
|
Ruby
|
ambreenhasan/bookshelf
|
/app/models/book_ownership.rb
|
UTF-8
| 745
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
class BookOwnership < ActiveRecord::Base
belongs_to :user
belongs_to :book
def time_difference
seconds_since = (Time.now.to_i - self.updated_at.to_i)
if seconds_since >= 86400 #seconds per day
return days(seconds_since)
elsif seconds_since >= 3600 #seconds per hour
return hours(seconds_since)
elsif seconds_since >= 60
return minutes(seconds_since)
else
return "#{seconds_since} seconds ago"
end
end
def days(seconds_since)
days = seconds_since / 3600 / 24
"#{days} days ago"
end
def hours(seconds_since)
hours = seconds_since / 3600
"#{hours} hours ago"
end
def minutes(seconds_since)
minutes = seconds_since / 60
"#{minutes} minutes ago"
end
end
| true
|
4ccf46e05eb41ea2426fe64df778d65fa4b203d4
|
Ruby
|
rdallasgray/digestive
|
/lib/digestive/auth/service.rb
|
UTF-8
| 2,007
| 2.671875
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
# encoding: UTF-8
module Digestive
module Auth
# Handles authentication of a credentialed object, using a given provider.
# The credentialed object will normally be a user, and the provider
# `ActionController::HttpAuthentication::Digest::ControllerMethods`.
# @!attribute [r] user
# @return [Object]
# The currently-authenticated user, or nil
class Service
attr_reader :user
# Create a new Digest::Auth::Service.
# @param [Object] credentialed
# An object responding to constant DIGEST_REALM and
# method find_by_username. See {Digestive::User}.
# @param [Object] provider
# An object responding to methods
# `authenticate_with_http_digest` and
# `request_http_digest_authentication`.
# Defaults to nil; if not given, {Digestive::Auth::Service}
# will expect the methods to be mixed-in, which
# in the context of Rails, they should be.
def initialize(credentialed, provider=nil)
@credentialed = credentialed
@provider = provider || self
end
# Authenticate, optionally with an authorization strategy.
# If authentication can't be verified, prompt for credentials.
# @param [Block] strategy
# Block accepting one argument (an object returned by
# @credentialed.find_by_username) and returning a boolean.
def authenticate(&strategy)
unless authenticated?(strategy)
realm = @credentialed::DIGEST_REALM
@provider.request_http_digest_authentication(realm)
end
end
private
def authenticated?(strategy=nil)
realm = @credentialed::DIGEST_REALM
strategy ||= ->(user) { true }
user = nil
@provider.authenticate_with_http_digest(realm) do |username|
user = @credentialed.find_by_username(username)
user.nil? ? nil : user.password
end
@user = user if strategy.call(user)
end
end
end
end
| true
|
6879fd03d3ed5b7242cd75858045350937dc9e4a
|
Ruby
|
Coding-Knights/chess
|
/app/models/game.rb
|
UTF-8
| 8,253
| 3
| 3
|
[] |
no_license
|
class Game < ApplicationRecord
has_many :pieces, dependent: :destroy
has_many :users
has_many :moves, dependent: :destroy
validates :name, presence: true
scope :available, -> { where(black_player_id: nil)}
# after_create :populate_game!
def opponent(current_user)
current_user.id == white_player_id ? player_two : player_one
end
def player_one
return nil if white_player_id.nil?
return User.find(white_player_id)
end
def player_two
return nil if black_player_id.nil?
return User.find(black_player_id)
end
def player_one=(user)
write_attribute(:white_player_id, user.id)
end
def player_two=(user)
write_attribute(:black_player_id, user.id)
end
def get_player_one
if white_player_id.nil?
return "No Player Two"
else
grab_email_white
end
end
def grab_email_white
return User.find(white_player_id).email
end
def grab_email_black
return User.find(black_player_id).email
end
def get_player_two
if black_player_id.nil?
return "No Player Two"
else
grab_email_black
end
# return (not black_player_id.nil?) ? black_player_id : "No Player Two"
end
def whos_turn?
return white_player_id if turn_number.even?
return black_player_id if turn_number.odd?
end
def end_game(piece)
if piece.is_white?
update(winner_id: white_player_id, loser_id: black_player_id, state: 'Over')
else
update(winner_id: black_player_id, loser_id: white_player_id, state: 'Over')
end
end
def populate_game!
# White Pieces
(0..7).each do |i|
Pawn.create(game_id: id, x_position: i, y_position: 1, color: 1, type: 'Pawn', player_id: white_player_id, piece_number: 5)
end
Rook.create(game_id: id, x_position: 0, y_position: 0, color: 1, type: 'Rook', player_id: white_player_id, piece_number: 0)
Rook.create(game_id: id, x_position: 7, y_position: 0, color: 1, type: 'Rook', player_id: white_player_id, piece_number: 0)
Knight.create(game_id: id, x_position: 1, y_position: 0, color: 1, type: 'Knight', player_id: white_player_id, piece_number: 1)
Knight.create(game_id: id, x_position: 6, y_position: 0, color: 1, type: 'Knight', player_id: white_player_id, piece_number: 1)
Bishop.create(game_id: id, x_position: 2, y_position: 0, color: 1, type: 'Bishop', player_id: white_player_id, piece_number: 2)
Bishop.create(game_id: id, x_position: 5, y_position: 0, color: 1, type: 'Bishop', player_id: white_player_id, piece_number: 2)
Queen.create(game_id: id, x_position: 3, y_position: 0, color: 1, type: 'Queen', player_id: white_player_id, piece_number: 3)
King.create(game_id: id, x_position: 4, y_position: 0, color: 1, type: 'King', player_id: white_player_id, piece_number: 4)
# Black Pieces
(0..7).each do |i|
Pawn.create(game_id: id, x_position: i, y_position: 6, color: 2, type: 'Pawn', player_id: black_player_id, piece_number: 11)
end
Rook.create(game_id: id, x_position: 0, y_position: 7, color: 2, type: 'Rook', player_id: black_player_id, piece_number: 6)
Rook.create(game_id: id, x_position: 7, y_position: 7, color: 2, type: 'Rook', player_id: black_player_id, piece_number: 6)
Knight.create(game_id: id, x_position: 1, y_position: 7, color: 2, type: 'Knight', player_id: black_player_id, piece_number: 7)
Knight.create(game_id: id, x_position: 6, y_position: 7, color: 2, type: 'Knight', player_id: black_player_id, piece_number: 7)
Bishop.create(game_id: id, x_position: 2, y_position: 7, color: 2, type: 'Bishop', player_id: black_player_id, piece_number: 8)
Bishop.create(game_id: id, x_position: 5, y_position: 7, color: 2, type: 'Bishop', player_id: black_player_id, piece_number: 8)
Queen.create(game_id: id, x_position: 3, y_position: 7, color: 2, type: 'Queen', player_id: black_player_id, piece_number: 9)
King.create(game_id: id, x_position: 4, y_position: 7, color: 2, type: 'King', player_id: black_player_id, piece_number: 10)
end
CAPTURED = 1 # constant instance
NOT_CAPTURED = 0 #constant instance
def capture_piece(to_square, captor) # to_square = [x,y] dest, captor = piece moving
# get piece at to_square
captured = getPieceAt(to_square[0],to_square[1])
# change status of the captured piece
captured.captured_status = CAPTURED
# clear board state - set x and y to -1, -1
captured.x_position = -1
captured.y_position = -1
# add to captured_pieces
current_player.captured_pieces << captured
# move captor to to_square
setPieceAt(to_square[0],to_square[1],captor)
end
def getPieceAt(x, y)
found_piece = game.pieces.find do |piece|
piece.x_position == x && piece.y_position == y
end
found_piece
# need to handle if not found (eg exception or expected message)
end
def getPieceById(id)
found_piece = game.pieces.find do |piece|
piece.id == id
end
found_piece
# need to handle if not found (eg exception or expected message)
end
def setPieceAt(x, y, piece)
# check if x and y are on board
# check if x and y are on clear spot
piece.x_position = x
piece.y_position = y
end
def check?(white)
king = pieces_for_color(white).select { |piece| piece.type == 'King' }.first
return false unless king
enemies = get_enemies(king)
enemies.any? { |enemy| enemy.can_take?(king) }
end
def pieces_for_color(white)
pieces.select { |piece| piece.is_white? == white }
end
def checkmate?(white)
return false unless check?(white)
return false if legal_moves(white)
true
end
def can_claim_draw?(current_user)
return true if stalemate?(current_user)
return true if fifty_move_rule?
return false
end
def stalemate?(current_user)
return false if state == 'Black King in Check.'
return false if state == 'White King in Check.'
return false if enough_pieces_remaining(current_user.id == white_player_id)
return false if legal_moves(current_user.id == white_player_id)
return true
end
def legal_moves(white)
legal_moves = []
playable_pieces(white).each do |piece|
(0..7).each do |y|
(0..7).each do |x|
next if !piece.valid_move?(x,y)
next if piece.puts_self_in_check?(x,y)
legal_moves << piece
end
end
end
return legal_moves.present?
end
def enough_pieces_remaining(white)
return playable_pieces(white).count > 3
end
def playable_pieces(white)
playable_pieces = []
pieces_for_color(white).each do |piece|
next if piece.x_position == -2 || piece.x_position == -1
playable_pieces << piece
end
return playable_pieces
end
def fifty_move_rule?
return false if moves.count <= 100
# The limit is 100 since a move in our app is only one player but in chess is for each player
last_fifty_moves = moves.order(updated_at: :desc).limit(100)
return false if pawn_was_moved?(last_fifty_moves)
return false if piece_was_captured?(last_fifty_moves)
return true
end
def pawn_was_moved?(last_fifty_moves)
pawn_moves = last_fifty_moves.find do |move|
move.start_piece == 5 || move.start_piece == 11
end
return pawn_moves.present?
end
def piece_was_captured?(last_fifty_moves)
last_white_player_capture = pieces.where(x_position: -2, y_position: -2).order('updated_at').last
last_black_player_capture = pieces.where(x_position: -1, y_position: -1).order('updated_at').last
# The if statements are to catch if the game has zero captures. A highly unlikely scenario but easy to fix.
if last_white_player_capture && last_black_player_capture
return true if last_fifty_moves.last.updated_at < last_white_player_capture.updated_at
return true if last_fifty_moves.last.updated_at < last_black_player_capture.updated_at
return false
end
if last_white_player_capture
return true if last_fifty_moves.last.updated_at < last_white_player_capture.updated_at
return false
end
if last_black_player_capture
return true if last_fifty_moves.last.updated_at < last_black_player_capture.updated_at
return false
end
return false
end
end
| true
|
75c799f8f9f885792cd56858b18657e8c05bf03f
|
Ruby
|
chanhpark/in-theaters
|
/in-theaters1.rb
|
UTF-8
| 904
| 3.765625
| 4
|
[] |
no_license
|
require 'pry'
require 'json'
movie_data = JSON.parse(File.read("in_theaters.json"))
movies = movie_data["movies"] ###array of hashes
puts "In Theaters Now:\n "
def get_title(movie)
###returns movie title
return movie["title"]
end
def get_mpaa(movie)
###returns mpaa rating
return movie["mpaa_rating"]
end
def avg_score(movie)
###return the average score
average = (movie["ratings"]["critics_score"] + movie["ratings"]["audience_score"]) / 2
return average
end
def top_cast(movie)
###returns the top 3 cast members
array = []
cast = movie["abridged_cast"].take(3)
cast.each do |member|
array << member["name"]
end
array.join(", ")
end
output = []
movies.each do |movie|
output << [avg_score(movie), " - " + get_title(movie) + " (" + get_mpaa(movie) + ") " + "starring " + top_cast(movie)]
end
output.sort!.reverse!
output.each do |movie|
puts movie.join
end
| true
|
9ba1c63e662487a8ff06ee2e771cee4099874dad
|
Ruby
|
dinnosaur/sinatra-mvc-lab-london-web-021720
|
/models/piglatinizer.rb
|
UTF-8
| 1,103
| 3.625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class PigLatinizer
attr_accessor :word
# def initialize(word)
# @word = word
# end
def a_word(word)
letters = word.split("")
new_word = nil
new_letters = letters.dup
if letters[0] =~ /[aeiouAEIOU]/
letters.push("way")
new_word= letters.join()
else
letters.each do |letter|
if letter =~ /[^aeiouAEIOU]/
new_letters.push(letter)
new_letters.shift
else
break
end
end
new_letters.push("ay")
new_word = new_letters.join("")
end
new_word
end
def piglatinize(sentence_or_word)
pigged = []
if sentence_or_word =~ /\s/
words = sentence_or_word.split(" ")
words.each{|word| pigged << a_word(word)}
piggy = pigged.join(" ")
else
piggy = a_word(sentence_or_word)
end
piggy
end
end
| true
|
612cca11afdc5e9bbf31e3a323f075be5d78115b
|
Ruby
|
sadjehwty/pythonchallenge-solver
|
/ruby/level_8.rb
|
UTF-8
| 443
| 2.546875
| 3
|
[] |
no_license
|
# http://www.pythonchallenge.com/pc/def/integrity.html
require 'tempfile'
require 'rbzip2'
a={'user'=>"BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084",
'pwd'=>"BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08"}
a.each_key do |k|
t=Tempfile.new 'tmp'
t.write a[k]
t.rewind
bz2 = RBzip2::Decompressor.new t
a[k]=bz2.read
t.close
end
p a
| true
|
504a7cee962954d0b8333257095e08fb35254198
|
Ruby
|
sabman83/leetcode
|
/komodo_health.rb
|
UTF-8
| 1,262
| 3.8125
| 4
|
[] |
no_license
|
#
# Your previous Plain Text content is preserved below:
#
# 99 fair coins, 1 biased coin (double sided heads)
# select 1 at random - flip it 10 times - record 10 heads in a row
#
# Probability that you selected the biaed coin?
#
# a => the coin is biased
# b => event of getting 10 heads
#
# P(a|b)
#
# P(b|a) = 1
#
# p(a) = 1 / 100
#
# p(b) = 99/100 * (0.5 ^ 10) + 1/100 * 1
#
# P(a|b) = P(b|a)*P(a)/P(b)
#
# 91%
def biased_coin
return 'H'
end
def unbiased_coin
num = rand(2)
return 'H' if num == 0
return 'T' if num == 1
end
def select_coin
num = rand(100)
return 'unbiased' if num > 0
return 'biased'
end
def simulator
coin = select_coin
flips = []
if coin == 'unbiased'
10.times do
flips.push unbiased_coin
end
else
10.times do
flips.push biased_coin
end
end
{type: coin, flips: flips}
end
coin_with_ten_heads = {'biased' => 0, 'unbiased' => 0}
1000000.times do
result = simulator
tail_flips = result[:flips].select {|item| item == 'T'}
if tail_flips.size == 0
coin_with_ten_heads[result[:type]] += 1
end
end
puts (100 *
(coin_with_ten_heads['biased'].to_f /
(coin_with_ten_heads['biased'].to_f + coin_with_ten_heads['unbiased'].to_f)
)
).to_s
| true
|
10cb1db53fc197cf98c855f358e41a65796fad8b
|
Ruby
|
patrickdavey/AoC
|
/2015/day12/json_walker_test.rb
|
UTF-8
| 1,334
| 3.65625
| 4
|
[] |
no_license
|
=begin
--- Day 12: JSAbacusFramework.io ---
Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.
They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.
For example:
[1,2,3] and {"a":2,"b":4} both have a sum of 6.
[[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
{"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
[] and {} both have a sum of 0.
You will not encounter any strings containing numbers.
What is the sum of all numbers in the document?
=end
require "minitest/autorun"
require "./json_walker.rb"
class JsonWalkerTest < Minitest::Test
def test_known_good_examples
sample_data = [
["[1,2,3]", 6],
['{"a":2,"b":4}', 6],
['[[[3]]]',3],
['{"a":{"b":4},"c":-1}',3],
['{"a":[-1,1]}',0],
['{"a":[-1,{"a": 1}]}',0],
['[-1,{"a":1}]',0],
['{"a":[-1,{"a": [[1,2,3]]}]}',5],
['[1,{"c":"red","b":2},3]', 4]
]
sample_data.each do |(json, sum)|
assert_equal sum, JsonWalker.new(json).sum, "#{sum} not the sum of #{json}"
end
end
end
| true
|
9e2050a9b9af9e397c9d162239d40fe9eb216e51
|
Ruby
|
mholyoak/CardGame
|
/Game.rb
|
UTF-8
| 449
| 3.484375
| 3
|
[] |
no_license
|
require_relative 'deck'
require_relative 'Player'
class Game
def initialize (num_players)
@deck = Deck.new
@players = Array.new (num_players) {Player.new}
end
def deal (count)
count.times do
@players.each do |player|
player.receive (@deck.deal)
end
end
end
def play
puts 'playing'
deal(5)
@players.count.times do |count|
puts "Player #{count} #{@players[count]}"
end
end
end
| true
|
df442928bbfe5899d06e8b2e75daf48de9289cb9
|
Ruby
|
ZnWen/Script.NET
|
/Src/Interps/Ruby/ruby-1.8.6/lib/ruby/1.8/wx/classes/image.rb
|
UTF-8
| 946
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
class Wx::Image
# Load a new image from an IO-like object that supports "read"
def self.read(an_io, type_or_mime, index = -1)
img = new
img.load_stream(an_io, type_or_mime, index)
img
end
# Create a new image from Wx::Bitmap, preserving mask information
def self.from_bitmap(bmp)
bmp.convert_to_image
end
# Redefine the initialize method so it raises an exception if a
# non-existent file is given to the constructor; otherwise, wx Widgets
# just carries on with an invalid image, which may cause faults later
wx_init = self.instance_method(:initialize)
define_method(:initialize) do | *args |
if args[0].kind_of? String
if not File.exist?( File.expand_path(args[0]) )
Kernel.raise(ArgumentError, "Image file does not exist: #{args[0]}")
end
end
wx_init.bind(self).call(*args)
end
# Convert to bitmap
def convert_to_bitmap
Wx::Bitmap.from_image(self)
end
end
| true
|
1f56e8c5a2760c93a42522726af3f2dc012c67e6
|
Ruby
|
kweic/grails_blog
|
/src/test/acceptanceTest/features/step_definitions/editing_a_post.rb
|
UTF-8
| 877
| 2.5625
| 3
|
[] |
no_license
|
require_relative "../../features/workflows/create_blog_post"
require_relative "../../features/workflows/edit_blog_post"
require_relative "../../features/workflows/page_interactions"
require_relative "../../features/workflows/main_page_elements"
include CreatePost
include EditPost
include PageInteractions
include MainPage
And(/^I have created a blog post$/) do
@my_post_title = create_and_save_post
click_my_blog
end
When(/^I edit my blog post$/) do
click_first_blog
click_edit_button
@new_title = generate_random_words(2).strip
fill_post_fields(@new_title)
click_update_button
end
Then(/^I am notified that the blog post was successfully edited$/) do
expect(index_page_notification).to eq('Post updated.')
end
And(/^the edits I have made are saved$/) do
click_my_blog
expect(first_post_on_page).to eq(@new_title)
end
| true
|
c1f1826790c5ea5b37b77557efaceab6cdc77c73
|
Ruby
|
JoeQuattrone/intro-to-simple-array-manipulations-online-web-prework
|
/lib/intro_to_simple_array_manipulations.rb
|
UTF-8
| 486
| 3.3125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def using_push(x, y)
x = []
x.push(y)
end
def using_unshift(x, y)
x.unshift(y)
end
def using_pop(x)
x.pop()
end
def pop_with_args(x)
x.pop(2)
end
def using_shift(x)
x.shift()
end
def shift_with_args(a)
a.shift(2)
end
def using_concat(x, y)
x.concat(y)
end
def using_insert(x, y)
x.insert(4, y)
end
def using_uniq(x)
x.uniq
end
def using_flatten(x)
x.flatten()
end
def using_delete(x, y)
x.delete(y)
end
def using_delete_at(x, y)
x.delete_at(y)
end
| true
|
d27306701cce6e4f9e93325f854515fb267ac025
|
Ruby
|
AaronD87/wagefinder
|
/app/services/inflation_service.rb
|
UTF-8
| 168
| 3.078125
| 3
|
[] |
no_license
|
class InflationService
def initialize(wage, years)
@years = years
@wage = wage
end
def inflation
((@wage * 1.024**@years) - @wage).to_i
end
end
| true
|
ae2bcde1f6b2cc457add636c7ec0035da48fe027
|
Ruby
|
brendanboyle87/seal-cori
|
/app/models/petition_generator.rb
|
UTF-8
| 2,146
| 2.59375
| 3
|
[] |
no_license
|
class PetitionGenerator
attr_reader :personal_information, :pdftk, :user
attr_accessor :info_hash
def initialize(personal_information)
@pdftk ||= PdfForms.new(ENV['PDFTK_PATH'] || '/usr/local/bin/pdftk')
@personal_information = personal_information
@user = personal_information.user
@info_hash = {}
end
def parse_data
info_hash["form1[0].#subform[0].TextField1[0]"] = user.first_name + " " + personal_information.middle_name + " " + user.last_name
info_hash["form1[0].#subform[0].TextField2[0]"] = "#{ personal_information.date_of_birth }"
info_hash["form1[0].#subform[0].TextField3[0]"] = "#{ personal_information.previous_name }"
info_hash["form1[0].#subform[0].TextField4[0]"] = "#{ personal_information.address }"
info_hash["form1[0].#subform[0].TextField5[0]"] = "#{ personal_information.city }"
info_hash["form1[0].#subform[0].TextField6[0]"] = "#{ personal_information.state }"
info_hash["form1[0].#subform[0].TextField7[0]"] = "#{ personal_information.zip }"
info_hash["form1[0].#subform[0].TextField8[0]"] = "#{ personal_information.occupation }"
info_hash["form1[0].#subform[0].TextField10[0]"] = "#{ personal_information.hometown }"
info_hash["form1[0].#subform[0].TextField11[0]"] = "#{ personal_information.father_name }"
info_hash["form1[0].#subform[0].TextField12[0]"] = "#{ personal_information.mother_maiden }"
info_hash["form1[0].#subform[0].TextField13[0]"] = "#{ personal_information.spouse_name }"
user.records.each do |record|
if record.felony && record.eligible?
info_hash["form1[0].#subform[0].CheckBox1[1]"] = "1"
info_hash["form1[0].#subform[0].CheckBox1[2]"] = "1"
info_hash["form1[0].#subform[0].CheckBox1[5]"] = "1"
info_hash["form1[0].#subform[0].CheckBox1[6]"] = "1"
else
info_hash["form1[0].#subform[0].CheckBox1[1]"] = "1"
info_hash["form1[0].#subform[0].CheckBox1[5]"] = "1"
end
end
info_hash
end
def fill_form(info)
file = "./lib/assets/sealingpetition#{user.id}.pdf"
pdftk.fill_form './lib/assets/sealingpetition.pdf',file,info
end
end
| true
|
b3190065d37a2e011a4af09e4c3753e7806b26d7
|
Ruby
|
Jonesyd/ls_101_programming_foundations
|
/03_lessons/05_02_duplication.rb
|
UTF-8
| 283
| 3.484375
| 3
|
[] |
no_license
|
# def color_valid(color)
# ["blue", "green"].include?(color.downcase) ? true : false
# end
# solution
def color_valid(color)
color == "blue" || color == "green"
end
p color_valid("blue")
p color_valid("green")
p color_valid("Blue")
p color_valid("Green")
p color_valid("red")
| true
|
3f2d43273ad8d1573af39c42d39095413dcb9445
|
Ruby
|
AssetoTrones/asset-o-tron
|
/db/seeds.rb
|
UTF-8
| 5,760
| 2.6875
| 3
|
[] |
no_license
|
# project_list = [
# ["Redradix Posters", "Technology posters created by redradix.", "", []],
# ["Asset-O-Tron", "Final project of Talentum Empleo developed by Ronald Romero, Nerea Díaz, Diego Sánchez, Lucas Gómez y Marco Antonio López de la Nieta.", "", [1,2,3,4,5,6]]
# ]
#
# project_list.each do |name,description,url,resource_ids|
# Project.create(name: name, description: description, url: url, resource_ids: resource_ids)
# end
#
# resource_list =[
# ["Ruby", "Ruby poster created by redradix", "https://github.com/redradix/posters/raw/master/png/ruby.png", [1, 2]],
# ["AngularJS", "AngularJS poster created by redradix", "https://github.com/redradix/posters/raw/master/png/angular.png", [1, 2]],
# ["CSS3", "CSS3 poster created by redradix", "https://github.com/redradix/posters/raw/master/png/css3.png", [1, 2]],
# ["HTML5", "HTML5 poster created by redradix", "https://raw.githubusercontent.com/redradix/posters/master/png/html5.png", [1, 2]],
# ["Javascript", "Javascript poster created by redradix", "https://raw.githubusercontent.com/redradix/posters/master/png/javascript.png", [1, 2]],
# ["Node.js", "Node.js poster created by redradix", "https://github.com/redradix/posters/raw/master/png/node.png", [1, 2]],
# ["Less.js", "Less.js poster created by redradix", "https://github.com/redradix/posters/raw/master/png/less.png", [1]],
# ["Sass", "Sass poster created by redradix", "https://github.com/redradix/posters/raw/master/png/sass.png", [1]],
# ]
#
# resource_list.each do |name,description,url,project_ids|
# Resource.create(name: name, description: description, url: url, project_ids: project_ids)
# end
#
# #1,2,3,4,5,6,7
Project.create(name: "Posters Redradix", description: "programming posters by Redradix", url: "https://github.com/redradix/posters", resource_ids: [])
Project.create(name: "Asset-O-Tron presentation", description: "the assets for the app presentation", url: "http://uryud.com/assetotron", resource_ids: [])
Project.create(name: "Asset-O-Tron gifs", description: "our gifs for the app presentation", url: "http://uryud.com/assetotron", resource_ids: [])
Project.create(name: "People pretending they are working", description: "our way to look nice and employable", url: "http://uryud.com/assetotron", resource_ids: [])
# posters
Resource.create(name: "Ruby", description: "Ruby poster created by redradix", url: "http://uryud.com/assetotron/ruby.png", project_ids: [1,2])
Resource.create(name: "HTML5", description: "Html5 poster created by redradix", url: "http://uryud.com/assetotron/html5.png", project_ids: [1,2])
Resource.create(name: "CSS3", description: "CSS3 poster created by redradix", url: "http://uryud.com/assetotron/css3.png", project_ids: [1])
Resource.create(name: "JavaScript", description: "JavaScript poster created by redradix", url: "http://uryud.com/assetotron/javascript.png", project_ids: [1])
Resource.create(name: "Sass", description: "Sass poster created by redradix", url: "http://uryud.com/assetotron/sass.png", project_ids: [1])
Resource.create(name: "NodeJs", description: "NodeJs poster created by redradix", url: "http://uryud.com/assetotron/node.png", project_ids: [1])
Resource.create(name: "Angular", description: "Angular poster created by redradix", url: "http://uryud.com/assetotron/angular.png", project_ids: [1])
## Asset-O-Tron assets
Resource.create(name: "Manifest", description: "Our Agile manifest for the finest fair teamworking", url: "http://uryud.com/assetotron/manifest.png", project_ids: [2])
Resource.create(name: "Little roboto", description: "We have a cute mascot!", url: "http://uryud.com/assetotron/more/asseto.jpg", project_ids: [2])
Resource.create(name: "Avatar", description: "Our dummy user needs a cool avatar", url: "http://uryud.com/assetotron/more/asseto-avatar.png", project_ids: [2])
Resource.create(name: "Team", description: "Team introduction", url: "http://uryud.com/assetotron/more/Team.jpg", project_ids: [2])
Resource.create(name: "Poker scrum", description: "Custom poker scrum cards for our meetings", url: "http://uryud.com/assetotron/more/poker.png", project_ids: [2])
# gifs
Resource.create(name: "Diego gif", description: "Diego shows his frustration with css float: 'right'", url: "http://uryud.com/assetotron/more/diego.gif", project_ids: [3])
Resource.create(name: "Nerea gif", description: "Nerea fights bad design and color combination", url: "http://uryud.com/assetotron/more/nerea.gif", project_ids: [3])
Resource.create(name: "Lucas gif", description: "Certain controller errors can bring Lucas down", url: "http://uryud.com/assetotron/more/lucas.gif", project_ids: [3])
Resource.create(name: "Ronnie gif", description: "Ronnie vs unresponsive design", url: "http://uryud.com/assetotron/more/ronnie.gif", project_ids: [3])
Resource.create(name: "Marco gif", description: "Marco has_and_belongs_to_many tables", url: "http://uryud.com/assetotron/more/marco.gif", project_ids: [3])
# serious
Resource.create(name: "Nerea professional look", description: "Nerea knows his stuff", url: "http://uryud.com/assetotron/more/nerea-work.jpg", project_ids: [4])
Resource.create(name: "Diego professional look", description: "Diego knows his stuff", url: "http://uryud.com/assetotron/more/diego-work.jpg", project_ids: [4])
Resource.create(name: "Marco professional look", description: "Marco knows his stuff", url: "http://uryud.com/assetotron/more/marco-work.jpg", project_ids: [4])
Resource.create(name: "Lucas professional look", description: "Lucas knows his stuff", url: "http://uryud.com/assetotron/more/lucas-work.jpg", project_ids: [4])
Resource.create(name: "Ronnie professional look", description: "Ronnie knows his stuff", url: "http://uryud.com/assetotron/more/ronnie-work.jpg", project_ids: [4])
## comments
| true
|
8b13383005c306d21cb3c59fce9809dc1a8ac54f
|
Ruby
|
benjpac/volunteer_tracker
|
/spec/volunteer_spec.rb
|
UTF-8
| 1,132
| 2.890625
| 3
|
[] |
no_license
|
require('spec_helper')
describe(Volunteer) do
describe('.all') do
it('returns all instances of Volunteer class, starts off with no projects') do
expect(Volunteer.all()).to eq([])
end
end
describe('#name') do
it('tells you the the volunteers name') do
test_volunteer = Volunteer.new({:name => "Jeff"})
expect(test_volunteer.name()).to eq("Jeff")
end
end
describe('#id') do
it('tells you its id') do
test_volunteer = Volunteer.new({:name => "Jeff"})
test_volunteer.save()
expect(test_volunteer.id()).to be_an_instance_of(Fixnum)
end
end
describe('#save') do
it('saves volunteer object to database') do
test_volunteer = Volunteer.new({:name => "Jeff", :project_id => 1})
test_volunteer.save()
expect(Volunteer.all()).to eq([test_volunteer])
end
end
describe('#==') do
it("is the same volunteer if it has the same name") do
volunteer = Volunteer.new({:name => "Test Fundraiser", :project_id => 1})
volunteer1 = Volunteer.new({:name => "Test Fundraiser", :project_id => 1})
expect(volunteer).to eq(volunteer1)
end
end
end
| true
|
dffe315d9f8097047a43a454591cbcc40affcf02
|
Ruby
|
sota1235/AOJ-Answers
|
/answers/Introduction/ALDS/alds1_2_a.rb
|
UTF-8
| 261
| 3.453125
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
# AOJ
# ALDS1_2_A
# Buble Sort
gets
n = gets.split(' ').map{|i| i.to_i}
nl = n.length
ct = 0
nl.times do
(nl-1).downto(1) do |j|
if n[j-1] > n[j]
n[j-1], n[j] = n[j], n[j-1]
ct += 1
end
end
end
puts n.join ' '
puts ct
| true
|
7e3bb9eaceaed84a63207a84bf172495e5959bc4
|
Ruby
|
rezanrezano/reverse-each-word-re-coded-000
|
/reverse_each_word.rb
|
UTF-8
| 221
| 3.671875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# sentence1="Hello there, and how are you?"
def reverse_each_word(sentence1)
index=0
result=[]
s=sentence1.split(" ")
while index<=s.length-1
result<<s[index].reverse
index+=1
end
result.join(" ")
end
| true
|
773faa46b40efcd6ce4202c3ad8136ef4d6de3b6
|
Ruby
|
taka9/Practice
|
/ruby/logger.rb
|
UTF-8
| 787
| 3.84375
| 4
|
[] |
no_license
|
# -*- encoding: utf-8 -*-
class Logger
def print message, level, &block
puts "\t" * level + '開始' + message
res = block.call
puts "\t" * level + '終了' + message + ', 戻り値' + res.to_s
return res
end
end
def checkNumber array, &block
count = 0
array.each do |item|
if block.call item
count += 1
end
end
return count
end
logger = Logger.new
# ブロックの前にカンマは付けない
logger.print '外ブロック:配列の中に条件に合致する数値がいくつ入っているか', 0 do
checkNumber [5, 1, 2, 8, 4, 5, 6, 2, 2, 9] do |item|
logger.print '内ブロック:条件に合致するか', 1 do
# ブロックの中ではreturnでなく、nextを使う
puts item
item >= 5
end
end
end
| true
|
233f0e137a64b6ffc25119aff45a67fb6abd8b0f
|
Ruby
|
snarf24/backend_module_0_capstone
|
/day_1/ex4.rb
|
UTF-8
| 1,945
| 3.96875
| 4
|
[] |
no_license
|
# Assigns the cars variable value to the integer 100
cars = 100
# Assigns the space_in_a_car variable value to the float 4.0
space_in_a_car = 4.0
# Assigns the drivers variable value to the integer 30
drivers = 30
# Assigns the passengers variable value to the integer 90
passengers = 90
# Assigns the cars_not_driven variable value to the result of cars - drivers
cars_not_driven = cars - drivers
# Assigns the cars_driven variable value to the same value as the variable drivers
cars_driven = drivers
# Assigns the result of cars_driven * space_in_a_car to value of the carpool_capacity variable
carpool_capacity = cars_driven * space_in_a_car
# Assigns the result of passengers / cars_driven to value of the average_passengers_per_car variable
average_passengers_per_car = passengers / cars_driven
# Prints the string to the terminal replacing the interpolation #{cars} with the assigned value for the variable cars
puts "There are #{cars} cars available."
# Prints the string to the terminal replacing the interpolation #{drivers} with the assigned value for the variable drivers
puts "There are only #{drivers} drivers available."
# Prints the string to the terminal replacing the interpolation #{cars_not_driven} with the assigned value for the variable cars_not_driven
puts "There will be #{cars_not_driven} empty cars today."
# Prints the string to the terminal replacing the interpolation #{carpool_capacity} with the assigned value for the variable carpool_capacity
puts "We can transport #{carpool_capacity} people today."
# Prints the string to the terminal replacing the interpolation #{passengers} with the assigned value for the variable passengers
puts "We have #{passengers} to carpool today."
# Prints the string to the terminal replacing the interpolation #{average_passengers_per_car} with the assigned value for the variable average_passengers_per_car
puts "We need to put about #{average_passengers_per_car} in each car."
| true
|
612bea5bc028e241df8b351c903d026f9ba4f1ab
|
Ruby
|
igorsimdyanov/ruby
|
/arrays/clear.rb
|
UTF-8
| 43
| 2.6875
| 3
|
[] |
no_license
|
arr = [1, 2, 3, 4, 5]
arr.clear
p arr # []
| true
|
808e7c4359c0af39f590084d016c5bd7b1b57247
|
Ruby
|
MasatoraAtarashi/Programming-Competition
|
/atCoder/ABC/172/d.rb
|
UTF-8
| 242
| 3.328125
| 3
|
[] |
no_license
|
require 'prime'
N = gets.to_i
answer = 0
1.upto(N) do |n|
prime_factors = n.prime_division
dividors_num = 1
prime_factors.map{|prime_factor| dividors_num *= (prime_factor[1] + 1) }
answer += dividors_num * n
end
print answers
| true
|
1e9372cdbfc67aab67f39615c3832407e309d294
|
Ruby
|
danwyryunq/eis
|
/kata2/model/jugada.rb
|
UTF-8
| 400
| 2.90625
| 3
|
[] |
no_license
|
require_relative 'elemento'
class Jugada
def initialize(jugador, tipo_elemento)
@jugador = jugador
@elemento = tipo_elemento.new()
end
def empata_con? jugada
return @elemento.empata_con? jugada.elemento
end
def le_gana_a? jugada
return @elemento.le_gana_a? jugada.elemento
end
def jugador
return @jugador
end
def elemento
return @elemento
end
end
| true
|
b38b8d2b4cb7872058fad08228e802bf66cfffb1
|
Ruby
|
fashion-data-exchange/s3_client
|
/lib/fde/s3_client.rb
|
UTF-8
| 2,278
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'aws-sdk-s3'
require "fde/s3_client/version"
module FDE
module S3Client
class AWSAccessKeyIDNotDefinedError < StandardError; end
class AWSSecretAccessKeyNotDefinedError < StandardError; end
class AWSRegionNotDefinedError < StandardError; end
class AWSS3BucketNameNotDefinedError < StandardError; end
class BucketNameNotDefinedError < StandardError; end
class Config
attr_accessor :aws_access_key_id,
:aws_secret_access_key,
:aws_region,
:bucket_name
end
def self.config
@@config ||= Config.new
end
def self.configure
yield self.config
end
def self.s3
if self.config.aws_region.to_s.empty?
raise AWSRegionNotDefinedError
end
Aws::S3::Resource.new(
region: self.config.aws_region,
credentials: self.credentials
)
end
def self.credentials
if self.config.aws_access_key_id.to_s.empty?
raise AWSAccessKeyIDNotDefinedError
end
if self.config.aws_secret_access_key.to_s.empty?
raise AWSSecretAccessKeyNotDefinedError
end
Aws::Credentials.new(
config.aws_access_key_id,
config.aws_secret_access_key
)
end
def self.bucket
if self.config.bucket_name.to_s.empty?
raise BucketNameNotDefinedError
end
self.s3.bucket(self.config.bucket_name)
end
def self.upload_file(file_path, options = {})
if options[:key]
key = options[:folder].to_s + options[:key]
else
key = options[:folder].to_s + File.basename(file_path)
end
self.s3.bucket(self.config.bucket_name).object(key).upload_file(file_path)
end
def self.upload_content(key, content)
self.s3.bucket(self.config.bucket_name).object(key).put(body: content)
end
def self.delete(key)
object = self.bucket.object(key)
object.delete
end
def self.list
self.bucket.objects.collect(&:key)
end
def self.move(key, new_key)
object = self.bucket.object(key)
target = "#{object.bucket.name}/#{new_key}"
object.move_to(target)
end
def self.download(key, target)
object = self.bucket.object(key)
object.download_file(target)
end
end
end
| true
|
5d2751e0f6028717139e955bd0f8c5f969df9fef
|
Ruby
|
drdrongo/rails-reddit
|
/db/seeds.rb
|
UTF-8
| 922
| 2.953125
| 3
|
[] |
no_license
|
def populate_comments(user, post)
rand(0..2).times do
comment = Comment.new(
content: Faker::TvShows::MichaelScott.quote
)
comment.user = user
comment.post = post
comment.save
end
end
def populate_posts(user)
rand(0..10).times do
post = Post.new(
title: Faker::Hacker.noun,
content: Faker::Hacker.say_something_smart
)
post.user = user
post.save
populate_comments(user, post)
end
end
puts 'Destroying existing users, posts, and comments...'
Comment.destroy_all
Post.destroy_all
User.destroy_all
puts 'All users, posts, and comments destroyed.'
puts 'Creating 20 new users...'
20.times do
user = User.new(
username: Faker::Internet.unique.username,
password: Faker::Internet.password(min_length: 6, max_length: 20),
email: Faker::Internet.unique.free_email
)
user.save
populate_posts(user)
end
puts '20 new users created'
puts 'Seeding completed.'
| true
|
aeda5408ace8c75e2fdaddf0246b8b4cfacd7ad7
|
Ruby
|
adamsb6/time-series-data
|
/test/test_time_series_bucket.rb
|
UTF-8
| 3,292
| 3.234375
| 3
|
[
"MIT"
] |
permissive
|
require "test/unit"
require "lib/time_series"
require 'set'
class TestTimeSeriesBucket < Test::Unit::TestCase
# Create a series of test objects,
# one for each allowed grouping period.
def setup
@test_start_point = "2010-01-01T00:45:30+00:00"
@start_time = Time.parse( @test_start_point )
@period = TimeSeries::Period.new( @test_start_point, :month)
@data = TimeSeries::Bucket.new( @period )
# Setup a bunch of datapoints in the correct period
@good_datapoints = (1..10).collect do |i|
TimeSeries::DataPoint.new( @start_time + i, i)
end
@bad_datapoints = (1..10).collect do |i|
TimeSeries::DataPoint.new( @start_time + i, i)
end
end
def test_initialize
assert_instance_of( TimeSeries::Bucket, @data, "Object it a TimeSeries::Bucket object" )
end
def test_raise_from_initialize
assert_raise ArgumentError, "Didn't raise ArgumentError when a TimeSeries::Period was not passed" do
@x = TimeSeries::Bucket.new( "Not a period" )
end
end
def test_append
assert_nothing_raised "Raised exception when valid DataPoint appended to the bucket" do
@data_point = TimeSeries::DataPoint.new( DateTime.parse("2010-01-02T00:45:30+00:00"), 1000 )
@data << @data_point
end
assert_raise ArgumentError do
@data << "Not a DataPoint"
end
end
def test_enumerable
# Add the data to the bucket.
@good_datapoints.each do |dp|
@data << dp
end
# Use Sets rather than Arrays as there is
# no guarentee that the items in the Bucket will be returned in order
# Set up a set to compare against.
@test_values = Set.new( (1..10).collect { |i| i } )
# Now extract the values of each
@values = Set.new( @data.collect { |i| i.value } )
assert_equal( @test_values, @values, "Collect failed to return the correct items")
end
# Test that the sort method works, relies on
# DataPoint.<=> working correctly
def test_sortability
# Push the same set of data in twice.
# so contains [1, .., 10, 1, .., 10]
# which is not sorted.
@good_datapoints.each do |dp|
@data << dp
end
@good_datapoints.each do |dp|
@data << dp
end
# Now extract the values of each
@test_values = (1..10).collect { |i| [i, i] }.flatten
@values = @data.sort.collect { |i| i.value }
assert_equal( @test_values, @values, "Sort failed to sort the items correctly")
end
def test_is_empty
assert( @data.empty? )
@good_datapoints.each do |dp|
@data << dp
end
assert( @data.empty? == false)
end
def test_length
@good_datapoints.each do |dp|
@data << dp
end
assert_equal( 10, @data.length )
end
def test_eql
@a = TimeSeries::Bucket.new( @period )
@b = TimeSeries::Bucket.new( @period )
@good_datapoints.each do |dp|
@a << dp
@b << dp
end
assert( @a.eql?( @b ), "Two identical buckets not eql?")
end
def test_sum
@a = TimeSeries::Bucket.new( @period )
total = 0
@good_datapoints.each do |dp|
@a << dp
total += dp.value
end
assert_equal( total, @a.sum, "Failed to sum up items in a bucket corrrectly")
end
end
| true
|
f439bdb7ddad0cd9e376a064f909394565c524a0
|
Ruby
|
rajatagrawal/Data-Structures
|
/node.rb
|
UTF-8
| 99
| 2.9375
| 3
|
[] |
no_license
|
class Node
attr_accessor :value, :next
def initialize(value=nil)
@value = value
end
end
| true
|
9c0600acb74a7ef745b38a375469cfc5ed6652a1
|
Ruby
|
bcorner13/chef-couchbase
|
/libraries/clustercheck.rb
|
UTF-8
| 3,028
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
require 'net/http'
require 'json'
# I know this is a bit of a mess to begin with
# This whole thing needs to be rewritten as a class
# rubocop:disable Metrics/MethodLength
def get_node_json(ipaddress, username, password)
uri = URI("http://#{ipaddress}:8091/pools/default")
check = Net::HTTP::Get.new(uri)
check.basic_auth username, password
begin
res = Net::HTTP.start(uri.hostname, uri.port, :open_timeout => 10) { |http| http.request(check) }
return unless res.code == '200'
body = JSON.parse(res.body)
return body
rescue # => e
return
end
end
# rubocop:enable Metrics/MethodLength
def found_cluster(jvalue)
if jvalue['nodes'].length > 1
return true
else
return false
end
end
def not_in_cluster(jvalue, selfipaddress)
hostcheck = selfipaddress + ':8091'
jvalue['nodes'].each do |ncheck|
return false if ncheck['hostname'] == hostcheck
end
true
end
def get_known_nodes_from_json(jvalue)
prefix = 'ns_1@'
separator = ','
known_nodes = ''
jvalue['nodes'].each do |known|
known_nodes = known_nodes + separator + prefix + known['hostname'].sub(/:8091/, '')
end
known_nodes
end
def get_timestamp(jvalue)
timestamp = ''
jvalue['nodes'].each do |cnode|
ts = Time.now.to_i
timestamp = ts - cnode['uptime'].to_i
end
timestamp
end
def join_to_cluster(jvalue, selfipaddress, clusterip)
return unless not_in_cluster(jvalue, selfipaddress)
joinarray = {}
clusternodes = get_known_nodes_from_json(jvalue)
joinarray['knownnodes'] = "ns_1@#{selfipaddress}" + clusternodes
joinarray['nodetojoin'] = clusterip
joinarray
end
# rubocop:disable MethodLength, Next
def probe_nodes(searchhash, selfipaddress, username, password, probe = {})
probe['joinhash'] = {}
searchhash.each do |node|
info = get_node_json(node['ipaddress'], username, password)
if info
if found_cluster(info)
probe['joinarray'] = join_to_cluster(info, selfipaddress, node['ipaddress'])
elsif node['ipaddress'] != selfipaddress
ip = node['ipaddress']
probe['joinhash'][ip] = get_timestamp(info)
end
end
end
probe
end
# rubocop:enable MethodLength, Next
def loopit(searchhash, selfipaddress, username, password)
i = 0
while i < 3
probearray = probe_nodes(searchhash, selfipaddress, username, password)
if probearray
return probearray['joinarray'] if probearray['joinarray']
return pickit(probearray['joinhash'], selfipaddress) unless probearray['joinhash'].empty?
end
i += 1
sleep 10
end
end
def pickit(joinhash, selfipaddress)
joinarray = {}
pick = joinhash.sort.reverse.pop
joinarray['nodetojoin'] = pick[0]
joinarray['knownnodes'] = 'ns_1@' + selfipaddress + ',ns_1@' + joinarray['nodetojoin']
joinarray
end
def node_to_join(searchhash, selfipaddress, username, password)
joinarray = loopit(searchhash, selfipaddress, username, password)
joinarray
end
# target=node_to_join(cluster,selfipaddress,username,password)
# print "goning to join #{target}"
| true
|
a14439c567e889394522e5ddab81ac8185a207fd
|
Ruby
|
phoffmann/BP01
|
/app/models/training.rb
|
UTF-8
| 3,349
| 3.21875
| 3
|
[] |
no_license
|
class Training
attr_accessor :items
@items
def initialize
@items = []
end
def add_activity(activity)
@items << activity
end
def find_activity(id)
@result = nil
if @items.size > 0
i = 0
for item in @items do
if item.id == id
@result = i
end
i += 1
end
end
return @result
end
def get_activity(id)
@result = nil
if @items.size > 0
i = 0
for item in @items do
if item.id == id
@result = @items[i]
end
i += 1
end
end
return @result
end
end
class TaskActivity
attr_accessor :id, :type, :status
def initialize(id, type, status)
@id = id
@type = type
@status = status
end
end
class TaskActivityM3 < TaskActivity
attr_accessor :un, :data
def initialize(id, type, status, un, data)
super(id, type, status)
@un = un
@data = data
end
end
class TaskActivityInv1 < TaskActivity
attr_accessor :un, :data
def initialize(id, type, status, un, data)
super(id, type, status)
@un = un
@data = data
puts "--- TaskActivityInv1 ---"
end
end
class TaskActivityM2 < TaskActivity
attr_accessor :un, :data
def initialize(id, type, status, un, data)
super(id, type, status)
@un = un
@data = data
end
end
class TaskActivityM1 < TaskActivity
attr_accessor :data
def initialize(id, type, status, data)
super(id, type, status)
@data = data
end
end
class MaticeComparator
attr_accessor :ms, :mx, :ok
def initialize(ms,mx)
@ms = ms
@mx = mx
@ok = true
end
def print_compared(class_style_table = "",class_style_td_err = "")
if class_style_table != "" then
t = "<table class=\"" + class_style_table + "\">\r\n"
else
t = "<table>\r\n"
end
title = ""
mat_s = Matice.new(@ms).mt
mat_x = Matice.new(@mx).mt
if mat_s && mat_x then
if mat_s.row_size > mat_x.row_size then
r = mat_s.row_size
else
r = mat_x.row_size
end
if mat_s.column_size > mat_x.column_size then
c = mat_s.column_size
else
c = mat_x.column_size
end
ms_a = mat_s.to_a
mx_a = mat_x.to_a
0.upto(r - 1) do |i|
row = "\t<tr>\r\n"
0.upto(c - 1) do |j|
begin
x = mx_a[i][j]
rescue
x = "?"
end
begin
s = ms_a[i][j]
rescue
s = "?"
end
if x.to_s == ""
x = "?"
end
if s.to_s == ""
s = "?"
end
#puts "x: " + x.to_s
#puts "s: " + s.to_s
if x.to_s != "?" then
title = " title=\"" + x.to_s + "\""
else
title = " title=\"_\""
end
if(x == s) then
row += "\t\t<td>" + s.to_s + "</td>\r\n"
else
@ok = false
if class_style_td_err != ""
row += "\t\t<td class=\""+class_style_td_err+"\""+ title +">" + s.to_s + "</td>\r\n"
else
row += "\t\t<td>?</td>\r\n"
end
end
title = ""
end
row += "\t</tr>\r\n"
t += row
#puts row
end
end
t += "</table>\r\n"
return t
end
end
| true
|
3bbd23d331f8fb18a608fda3e4f8c15255cba2e9
|
Ruby
|
kgrz/string_dup
|
/without_freeze.rb
|
UTF-8
| 973
| 2.625
| 3
|
[] |
no_license
|
require 'allocation_tracer'
class WithoutFreeze
IM_A_CONSTANT = "a string"
ANOTHER_CONSTANT = "This is a string"
def run
1000.times do
ANOTHER_CONSTANT.gsub(IM_A_CONSTANT, ''.freeze)
end
end
end
ObjectSpace::AllocationTracer.setup(%i{path line type})
object_without_freeze = WithoutFreeze.new
r = ObjectSpace::AllocationTracer.trace do
1000.times { object_without_freeze.run }
end
r.sort_by { |k,v| v.first }.each do |k,v|
p k => v
end
p string_alloc: ObjectSpace::AllocationTracer.allocated_count_table[:T_STRING]
p :TOTAL => ObjectSpace::AllocationTracer.allocated_count_table.values.inject(:+)
__END__
{["without_freeze.rb", 11, :T_REGEXP]=>[1, 1, 235, 235, 235, 0]}
{["without_freeze.rb", 11, :T_NODE]=>[1000, 0, 1233, 0, 2, 0]}
{["without_freeze.rb", 11, :T_MATCH]=>[1001000, 0, 999921, 0, 3, 239237520]}
{["without_freeze.rb", 11, :T_STRING]=>[3999913, 554, 4058562, 0, 235, 128417952]}
{:string_alloc=>4000004}
{:TOTAL=>5002005}
| true
|
63f0f011c152fc0d00b07b0d67daa0ff69a46c93
|
Ruby
|
eli-zbth/DL_Fundamentos_Ruby
|
/02_Ciclos_y_metodos/pptijera2.rb
|
UTF-8
| 976
| 4.125
| 4
|
[] |
no_license
|
def jugada_to_string(jugada)
if jugada ==1
return "Piedra"
elsif jugada ==2
return "Papel"
else
return "Tijera"
end
end
def jugada(numero_jugador)
inicio = "Turno jugador #{numero_jugador}:
1. Piedra
2. Papel
3. Tijeras
4. Salir
Ingrese opción a jugar:"
puts inicio
jugador =gets.chomp.to_i
until(jugador >= 1 && jugador <=4 )
puts "Opción no válida"
puts inicio
jugador =gets.chomp.to_i
end
if jugador ==4
exit!
end
return jugada_to_string(jugador)
end
def juego (jugador1,jugador2)
if jugador1==jugador2
puts("Empate")
elsif (jugador1=="Tijera" && jugador2=="Piedra") || (jugador1=="Papel" && jugador2=="Tijera") || (jugador1=="Piedra" && jugador2=="Papel")
puts("Gana Jugador 2")
else
puts("Gana Jugador 1")
end
end
jugador1= jugada("uno")
jugador2= jugada("dos")
juego(jugador1,jugador2)
| true
|
d4665d2d19ab5c42633da74a2d04b413d021af05
|
Ruby
|
foondar/freebooterbot
|
/lib/generator.rb
|
UTF-8
| 1,178
| 2.890625
| 3
|
[] |
no_license
|
class Generator
def self.table_generate contents, top = true, modifier = -1
options = []
contents.split("\n")[0..modifier].each{|o| option, weight = o.split("*"); weight = 1 unless weight; weight.to_i.times {options << option}}
description = roll_dice(reroll(inject_sub_generators(options[rand(options.size)])))
#Description.create!(generator: self, description: description) if top
description.gsub(/\r/,'')
end
def self.card_generate contents, top = true
contents.split("\n").map do |line|
roll_dice(inject_sub_generators(line).gsub(/\r/,''))
end
end
def self.inject_sub_generators result
result.gsub(/{([^{]+)}/) { |g| gen, mod = g.gsub(/{|}/,'').split(',');generator = TableGenerator.find_by_name(gen); mod = -1 unless mod; generator ? generator.generate(false, mod.to_i) : g }
end
def self.reroll result
if result.include? '<reroll>'
result.gsub(/<reroll>/, " & #{generate(false)}")
else
result
end
end
def self.roll_dice result
result.gsub(/\d+d\d+/) {|r| n,dice = r.split('d'); roll(n.to_i,dice.to_i)}
end
def self.roll n,d
(1..n).map{rand(1..d)}.reduce(:+).to_s
end
end
| true
|
5c0f8dca991e35539f45fdb1d1528f749392aa4d
|
Ruby
|
Bis87/goodprogrammers_2
|
/lesson_6_7/Shop/product.rb
|
UTF-8
| 641
| 3.484375
| 3
|
[] |
no_license
|
class Product
def initialize(price, quantity)
@quantity = quantity
@price = price
end
def self.show_products(products)
puts "Что вы хотите купить?"
puts ""
products.each_with_index do |product, index|
puts "#{index}: #{product.show}"
end
end
def buy
if @quantity > 0
@quantity -= 1
@price
else
puts 'больше нет'
0
end
end
def show
"#{info} price #{@price}; quantity: #{@quantity}"
end
def check_price
@price
end
def update
end
def info
end
end
| true
|
a586cc15ee5121e7f3b777ec17970884965c6245
|
Ruby
|
misturfixit/tictac
|
/tests/marktest.rb
|
UTF-8
| 7,773
| 2.8125
| 3
|
[] |
no_license
|
require "minitest/autorun"
require_relative "pc_seq.rb"
require_relative "pc_ran.rb"
require_relative "pc_unbeets.rb"
require_relative "console.rb"
require_relative "board.rb"
class Test_marker < Minitest::Test
###((((((1)))((((((()))))((((((MarkTest))))))(((((()))(((((())))))))))###
def test_marker
player = Playerseq.new("x")
assert_equal("x", player.marker)
end
###vvvvvvvvvvvvvvvvvvvvvvvvvvv*Seq Test*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv###
###((((((2)))((((()))(((((((((("Seq"))))))(((((())))))(((((()))))))###
def test_move
player = Playerseq.new("x")
assert_equal(1, player.move(["1","2","3","4","5","6","7","8","9"]))
end
###((((((3)))((((((()))))(((((("Seq"))))))(((((()))(((((())))))))))###
def test_move1
player = Playerseq.new("x")
assert_equal(4, player.move(["x","o","x","4","o","x","7","8","9"]))
end
###((((((4)))((((((()))))(((((("Seq"))))))(((((()))(((((())))))))))###
def test_move2
player = Playerseq.new("x")
assert_equal(1, player.move(["1","2","3","4","5","6","7","8","9"]))
end
###((((((5)))((((((()))))(((((("Seq"))))))(((((()))(((((())))))))))###
def test_move3
player = Playerseq.new("o")
assert_equal(3, player.move(["x","o","3","4","5","6","7","8","9"]))
end
###((((((6)))((((((()))))(((((("Seq"))))))(((((()))(((((())))))))))###
def test_move4
player = Playerseq.new("o")
assert_equal(9, player.move(["x","o","x","o","x","o","x","o","9"]))
end
###^^^^^^^^^^^^^^^^^^^^^^^^^*EndSeqTest*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^###
###vvvvvvvvvvvvvvvvvvvvvvvvv*RanmoveTest*vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv###
###((((((7)))((((((()))))((((((Ran))))))(((((()))(((((())))))))))###
def test_moveran1
board = ["1","2","3","4","5","6","7","8","9"]
player = Playerrand.new("x").move(board)
assert_equal(true, [1,2,3,4,5,6,7,8,9].include?(player))
end
###((((((8)))((((((()))))((((((Ran))))))(((((()))(((((())))))))))###
def test_moveran2
board = ["1","2","x",
"o","x","o",
"o","x","9"]
player = Playerrand.new("o").move(board)
assert_equal(true, [1,2,9].include?(player))
end
###^^^^^^^^^^^^^^^^^^^^^^^^*End Ranmove Test*^^^^^^^^^^^^^^^^^^^^^^^^^^^^^###
###vvvvvvvvvvvvvvvvvvvvvvvvvvUnbeat Testvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv###
###((((((9)))((((((()))))(((((((FmTest))))))(((((()))(((((())))))))))###
def test_f_move_ub1
board = ["1","2","3","4","5","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("5", player.f_move(board))
end
###((((((10)))((((((()))))((((((FmTest)))))(((((())))(((((())))))))))###
def test_f_move_ub2
board = ["1","x","3","4","5","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("1", player.f_move(board))
end
###((((((11)))((((((()))))((((((FmTest))))))(((((()))(((((())))))))))###
def test_f_move_ub3
board = ["x","2","3","4","5","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("5", player.f_move(board))
end
###((((((12)))((((((()))))((((((FmTest))))))(((((()))(((((())))))))))###
def test_f_move_ub4
board = ["1","2","3","4","x","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("7", player.f_move(board))
end
###((((((13)))((((((()))))((((((FmTest))))))(((((()))(((((())))))))))###
def test_f_move_ub5
board = ["1","2","3","x","5","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("1", player.f_move(board))
end
###((((((14)))((((((()))))((((((FmTest))))))(((((()))(((((())))))))))###
def test_f_move_ub6
board = ["1","2","3","4","o","6","7","8","9"]
player = Playerunbeets.new("o")
assert_equal("7", player.f_move(board))
end
###^^^^^^^^^^^^^^^^^^^^^^^^^End^Fmove^Test^^^^^^^^^^^^^^^^^^^^^^^^^^###
# ###vvvvvvvvvvvvvvvvvvvvvvvvvvvv_Win$Block$Test_vvvvvvvvvvvvvvvvvvvvvvvvvvvvv###
# ###((((((15)))((((((()))))((((((Winmove_Hrzl))))))(((((()))(((((())))))))))###
# def test_winmove1
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,1)
# board.place_marker(player.marker,3)
# assert_equal(2, player.win_move(board.board))
# end
# ###((((((16)))((((((()))))((((((Winmove_Hrzl))))))(((((()))(((((())))))))))###
# def test_winmove2
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,4)
# board.place_marker(player.marker,6)
# assert_equal(5, player.win_move(board.board))
# end
# ###((((((17)))((((((()))))((((((Winmove_Hrzl))))))(((((()))(((((())))))))))###
# def test_winmove3
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,7)
# board.place_marker(player.marker,9)
# assert_equal(8, player.win_move(board.board))
# end
# ###((((((18)))((((((()))))((((((Winmove_Hrzl))))))(((((()))(((((())))))))))###
# def test_winmove4
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,7)
# board.place_marker(player.marker,9)
# assert_equal(8, player.win_move(board.board))
# end
# ###((((((19)))((((((()))))((((((Winmove_Vert))))))(((((()))(((((())))))))))###
# def test_winmove5
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,1)
# board.place_marker(player.marker,7)
# assert_equal(4, player.win_move(board.board))
# end
# ###((((((20)))((((((()))))((((((Winmove_Vert))))))(((((()))(((((())))))))))###
# def test_winmove6
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,2)
# board.place_marker(player.marker,5)
# assert_equal(8, player.win_move(board.board))
# end
# ###((((((21)))((((((()))))((((((Winmove_Vert))))))(((((()))(((((())))))))))###
# def test_winmove7
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,3)
# board.place_marker(player.marker,6)
# assert_equal(9, player.win_move(board.board))
# end
# ###((((((22)))((((((()))))((((((Winmove_Diag))))))(((((()))(((((())))))))))###
# def test_winmove8
# board = Board.new
# player = Playerunbeets.new("o")
# board.place_marker(player.marker,1)
# board.place_marker(player.marker,5)
# assert_equal(9, player.win_move(board.board))
# end
# ####((((((23)))((((((()))))((((((Winmove_Diag))))))(((((()))(((((())))))))))###
def test_winmove9
board = ["x","2","x","4","5","6","7","8","9"]
player = Playerunbeets.new("o")
# board.place_marker(player.marker,1)
# board.place_marker(player.marker,2)
assert_equal(2, player.win_move(board))
end
###^^^^^^^^^^^^^^^^^^^^^^^^^End^Winmove^Test^^^^^^^^^^^^^^^^^^^^^^^^^^###
###vvvvvvvvvvvvvvvvvvvvvvvvvvvv$SecMoveTest$vvvvvvvvvvvvvvvvvvvvvvvvvvv###
###(((((()))((((((()))))((((((SecMove))))))(((((()))(((((())))))))))###
def test_secmove1
board = ["x","2","3","4","5","x","7","8","9"]
player = Playerunbeets.new("o")
# board.place_marker(player.marker,1)
# board.place_marker(player.marker,2)
# board.place_marker(player.marker,5)
assert_equal(3, player.sec_move(board))
end
###(((((()))((((((()))))(((((())))))(((((()))(((((())))))))))###
def test_secmove2
board = ["1","2","3","4","5","x","x","8","9"]
player = Playerunbeets.new("o")
assert_equal(3, player.sec_move(board))
end
###(((((()))((((((()))))(((((())))))(((((()))(((((())))))))))###
def test_secmove3
board = ["x","2","3","4","5","6","7","x","9"]
player = Playerunbeets.new("o")
assert_equal(6, player.sec_move(board))
end
###(((((()))((((((()))))(((((())))))(((((()))(((((())))))))))###
###(((((()))((((((()))))(((((())))))(((((()))(((((())))))))))###
###(((((()))((((((()))))(((((())))))(((((()))(((((())))))))))###
end
| true
|
62f376ae537f3d20e9661b2fe36195dca3f2d710
|
Ruby
|
rumman07/rubyonrails
|
/ruby_code_sample/array_any_all.rb
|
UTF-8
| 144
| 3.15625
| 3
|
[] |
no_license
|
numbers = [3, 5, 7, 9, 11, 12]
p result = numbers.any? { |num| num.even? }
result2 = numbers.all? do |num|
num.even?
end
p result2
| true
|
3f08eac86b217a90c7585d008ff71e4e46e72a6e
|
Ruby
|
Flora-manda/Two_player_game
|
/players.rb
|
UTF-8
| 232
| 3.296875
| 3
|
[] |
no_license
|
class Players
attr_reader :name
attr_accessor :highest_life
def initialize(name)
@name = name
@highest_life = 3
end
def looses_life
@highest_life -= 1
end
def dead?
@highest_life <= 0
end
end
| true
|
d6fcd87009500b1e372713c7096dd05b0ba0e91e
|
Ruby
|
sassafracas/programming_languages-nyc-web-042318
|
/programming_languages.rb
|
UTF-8
| 386
| 2.90625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require "pry"
def reformat_languages(languages)
new_hash = {}
languages.each do |style, style_data|
style_data.each do |prog_lang, type_hash|
if new_hash[prog_lang] == nil
new_hash[prog_lang] = type_hash
new_hash[prog_lang][:style] = [style]
else
new_hash[prog_lang][:style] << style
end
end
end
new_hash
end
| true
|
23417e6f69f742b6f7343f2b33ea15c138ad1104
|
Ruby
|
ChewbaccaJerky/Code-Challenges
|
/practice-thy-algorithms/CTCI/lib/chapter5/5_3_flip_bit_to_win.rb
|
UTF-8
| 565
| 3.90625
| 4
|
[] |
no_license
|
=begin
You have an integer and you can flip exactly one bit from a 0 to 1.
Write code to find the length of the longest sequence of 1s you could create.
=end
def flip_bit_to_win(num)
num_str = num.to_s(2)
max = 0
num_str.each_char.with_index do |bit, i|
if bit == '0'
test_str = num_str.dup
test_str[i] = '1'
test_str.split('0').each do |bit_seq|
if bit_seq.length > max
max = bit_seq.length
end
end
end
end
max
end
| true
|
18dbc8a58cad3c2821b2fe8884175a250191147d
|
Ruby
|
inspec/train-aws
|
/test/unit/transport_test.rb
|
UTF-8
| 1,928
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# This is a unit test for the AWS Train Plugin.
# Its job is to verify that the Transport class is setup correctly.
# Include our test harness
require_relative "../helper"
# Load the class under test, the Plugin definition.
require "train-aws/transport"
# Because InSpec is a Spec-style test suite, we're going to use MiniTest::Spec
# here, for familiar look and feel. However, this isn't InSpec (or RSpec) code.
describe TrainPlugins::Aws::Transport do
# When writing tests, you can use `let` to create variables that you
# can reference easily.
# This is a long name. Shorten it for clarity.
let(:plugin_class) { TrainPlugins::Aws::Transport }
# Some tests through here use minitest Expectations, which attach to all
# Objects, and begin with 'must' (positive) or 'wont' (negative)
# See https://ruby-doc.org/stdlib-2.1.0/libdoc/minitest/rdoc/MiniTest/Expectations.html
describe "plugin definition" do
it "should be registered with the plugin registry without the train- prefix" do
# Note that Train uses String keys here, not Symbols
_(Train::Plugins.registry.keys).wont_include("train-aws")
_(Train::Plugins.registry.keys).must_include("aws")
end
it "should inherit from the Train plugin base" do
# For Class, '<' means 'is a descendant of'
_(plugin_class < Train.plugin(1)).must_equal(true)
end
it "should provide a connection() method" do
# false passed to instance_methods says 'don't use inheritance'
_(plugin_class.instance_methods(false)).must_include(:connection)
end
end
describe "Transport Options" do
let(:transport) { plugin_class.new }
it "should have the correct options" do
%i{
access_key_id
profile
region
secret_access_key
session_token
}.each do |option_name|
_(transport.options.keys).must_include(option_name)
end
end
end
end
| true
|
540250649a27b6dd56a2b5ce3b35fdd1ac2e3409
|
Ruby
|
artjomjuferov/simple_test_rails
|
/lib/group_event/all_fields_are_required.rb
|
UTF-8
| 347
| 2.5625
| 3
|
[] |
no_license
|
class GroupEvent::AllFieldsAreRequired
def initialize group_event
@group_event = group_event
end
def call
%w[user_id name description location duration date_start].each do |field|
return unless present? field
end
true
end
private
def present? key
value = @group_event.send(key)
!value.blank?
end
end
| true
|
e1174c09c2c9d9a8c057bbcde3e50cf97b33bfe6
|
Ruby
|
sarat1669/h264_bitstream_parser
|
/scantype.rb
|
UTF-8
| 3,796
| 2.5625
| 3
|
[] |
no_license
|
require 'tempfile'
require 'posix/spawn'
def run_cmd_with_response(cmd, return_exit_code=false)
include POSIX::Spawn
raw_response = `#{cmd}`
successful = true
exit_status = $?.exitstatus
if exit_status != 0
puts "cmd failed: \n#{raw_response}"
successful = false
end
return exit_status, raw_response if return_exit_code
return successful, raw_response
end
def get_video_scan_type(asset_path)
basename = File.basename(asset_path, ".ts")
temp_file = Tempfile.new(["#{basename}", ".h264"])
success, response = nil, nil
command = "ffmpeg -y -i #{asset_path} -vcodec copy #{temp_file.path} 2>&1"
response = ""
exit_status = -1
exit_status, response = run_cmd_with_response(command, true)
unless exit_status == 0
puts "Ffmpeg failed with code #{exit_status}, #{response}"
temp_file.unlink
return false
end
h264_analyze_response = Tempfile.new(["#{basename}", ".txt"])
exit_status = -1
command = "./h264_analyze #{temp_file.path} > #{h264_analyze_response.path}"
exit_status, response = run_cmd_with_response(command, true)
unless exit_status == 0
puts "h264_analyze failed with code #{exit_status}, #{response}"
temp_file.unlink
h264_analyze_response.unlink
return false
end
frame_mbs_only_flag_1_count = 0
field_pic_flag_count = 0
mb_adaptive_frame_field_flag_count = 0
field_order_entries = []
File.open(h264_analyze_response,'r').each_line do |line|
frame_mbs_only_flag_1_count += line.scan(/frame_mbs_only_flag\s*:\s*1/).length
field_pic_flag_count += line.scan(/field_pic_flag\s*:\s*1/).length
mb_adaptive_frame_field_flag_count += line.scan(/mb_adaptive_frame_field_flag\s*:\s*1/).length
field_order_entries.concat line.scan(/bottom_field_flag\s*:\s*.*/)
end
# At least one of the flags will be present in the h264 bitstream or else the input is invalid
return false, "Unable to determine scan type." if frame_mbs_only_flag_1_count == 0 and field_pic_flag_count == 0 and mb_adaptive_frame_field_flag_count == 0
is_mbaff = false
# Scan type is progressive if frame_mbs_only_flag is set to 1
if frame_mbs_only_flag_1_count > 0
# field_pic_flag and mb_adaptive_frame_field_flag should not be set to 1 if progressive
if mb_adaptive_frame_field_flag_count == 0 and field_pic_flag_count == 0
scan_type = "progressive"
else
scan_type = "mixed"
end
else
# If mb_adaptive_frame_field_flag is set to 1, and the rest of the flags are 0, the scan type is interlaced and MBAFF encoded
if mb_adaptive_frame_field_flag_count > 0 and field_pic_flag_count == 0
scan_type = "interlaced_mbaff"
# If field_pic_flag is set to 1 and all other flags are 0, the scan type is interlaced
elsif field_pic_flag_count > 0 and mb_adaptive_frame_field_flag_count == 0
scan_type = "interlaced"
else
scan_type = "mixed"
end
end
if scan_type =~ /interlaced/
invalid = false
last = nil
# According to ITU-T h264 specification, if bottom_field_flag is not present, it should be considered as `bottom_field_flag: 0` (top_field_first field_order)
if field_order_entries.length > 0
field_order = field_order_entries.first.split(':').last.to_i == 0 ? 'top_field_first' : 'bottom_field_first'
field_order_entries.each do |field|
current = field.split(':').last.to_i
invalid = true and break if current == last unless last.nil?
last = current
end
field_order = "mixed" if invalid
else
field_order = "top_field_first"
end
end
temp_file.unlink
h264_analyze_response.unlink
puts "scan_type: #{scan_type}"
puts "field_order: #{field_order}" if scan_type == "interlaced"
return true, scan_type, field_order
end
get_video_scan_type(ARGV[0])
| true
|
249806c510413fc3f73daa4ca190ff6b208af18b
|
Ruby
|
tomasc/hashtags
|
/lib/hashtags/builder.rb
|
UTF-8
| 2,017
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
module Hashtags
class Builder < Struct.new(:options)
def self.to_markup(str, options = {})
new(options).to_markup(str)
end
def self.to_hashtag(str, options = {})
new(options).to_hashtag(str)
end
def self.dom_data(options = {})
new(options).dom_data
end
def self.help(options = {})
new(options).help
end
def initialize(options = {})
super(options)
end
# collects markup from all hashtags classes
def to_markup(str)
hashtag_classes.inject(str) { |res, cls| cls.to_markup(res) }
end
# collects hashtags from all hashtags classes
def to_hashtag(str)
hashtag_classes.inject(str) { |res, cls| cls.to_hashtag(res) }
end
# render textcomplete dom data
def dom_data
{ hashtags: {
path: Engine.routes.url_helpers.hashtags_resources_path,
strategies: hashtag_strategies
} }
end
# render help string
def help
hashtag_classes.group_by(&:trigger).map do |trigger, cls|
OpenStruct.new(hashtag_classes: cls, trigger: trigger, help_values: cls.map(&:help_values).flatten.compact.sort)
end
end
def filter_classes(cls)
return [] unless cls.present?
res = cls
res &= options[:only] if options[:only]
res -= options[:except] if options[:except]
res
end
private
def hashtag_classes
filter_classes(
Resource.resource_classes +
User.user_classes +
Variable.variable_classes
)
end
def hashtag_strategies
cls = hashtag_classes.dup
# add resource type strategy if needed
cls << ResourceType if cls.any? { |c| c < Resource } && !cls.include?(ResourceType)
# remove all variable classes and replace them with one strategy
if variable_cls = cls.select { |c| c < Variable } && variable_cls.present?
cls -= variable_cls
cls << Variable
end
cls.collect { |c| c.strategy(hashtag_classes) }
end
end
end
| true
|
f8bd0efa722dd79a841b709661d27a1d094130bc
|
Ruby
|
pmacaluso3/BumpBoysServer
|
/app/models/user.rb
|
UTF-8
| 555
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
class User < ActiveRecord::Base
has_many :contacts
has_secure_password
def contacts_who_are_also_users
self.contacts.select do |contact|
User.find_by(stored_phone_number: contact.phone_number)
end
end
def has_as_contact?(test_contact)
self.contacts.select do |contact|
contact.phone_number == test_contact.phone_number
end.any?
end
def phone_number=(incoming_number)
self.stored_phone_number = incoming_number.gsub(/\D/,"").gsub(/\A1/,"")
end
def phone_number
self.stored_phone_number
end
end
| true
|
08991dc770819bef41ec7199bf2aba079f5ff43f
|
Ruby
|
alinadin09/phase-0-tracks
|
/calculator.rb
|
UTF-8
| 949
| 4.1875
| 4
|
[] |
no_license
|
def interface
puts "Push ENTER to run program (Type exit to quit)"
user_input = gets.chomp
until user_input == "done"
# Prompt the user for a calculation that the user would like to perform, and make each character an element of an array:
puts "Please enter your desired equation:"
equation = gets.chomp.split(' ')
# Make those elements become the arguments in the method. Each element will be called on by its index.
def calculate(equation)
if equation[1] == "+"
puts equation[0].to_i + equation[2].to_i
elsif equation[1] == "-"
puts equation[0].to_i - equation[2].to_i
elsif equation[1] == "*"
puts equation[0].to_i * equation[2].to_i
elsif equation[1] == "/"
puts equation[0].to_i / equation[2].to_i
end
end
# Print the result of the method:
calculate(equation)
end
puts "Push ENTER to run program again (Type quit to exit)"
user_input = gets.chomp
end
interface
| true
|
0f47e8aa669edafe95e5b4d36f622ebf6eed2c55
|
Ruby
|
tmck-code/codeeval
|
/easy/Ruby/SetIntersection/SetIntersection.rb
|
UTF-8
| 716
| 3.390625
| 3
|
[
"MIT"
] |
permissive
|
File.open(ARGV[0]).each_line do |line|
tmp = line.rstrip.split(';')
l1 = tmp[0].split(',')
l2 = tmp[1].split(',')
str = ""
n = (l1.length * l2.length)
n1 = l1.first
n2 = l2.first
for i in 1..n
if n1 == n2
str << "#{n1},"
l1.shift
l2.shift
n1 = l1.first
n2 = l2.first
elsif Integer(n1) > Integer(n2)
l2.shift
n2 = l2.first
elsif Integer(n1) < Integer(n2)
l1.shift
n1 = l1.first
end
if (n1.nil? || n2.nil?)
break
elsif (Integer(l1.last) < Integer(l2.first))
break
end
end
puts str.chop
end
| true
|
c74b65037a8ec9b5a0fc2f6aa0b27275bb3f5e41
|
Ruby
|
ayafujiaya/ofxHuez
|
/bin/tweet_to_txt.rb
|
UTF-8
| 1,295
| 2.875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
require 'oauth'
require 'JSON'
require 'uri'
path_to_txt = "/Users/Yuki/work/ofxHuez/search_result.txt"
class TwitterConnects
@@CONSUMER_KEY = ''
@@CONSUMER_SECRET = ''
@@ACCESS_TOKEN = ''
@@ACCESS_TOKEN_SECRET = ''
def getTweets(encodedQuery)
consumer = OAuth::Consumer.new(
@@CONSUMER_KEY,
@@CONSUMER_SECRET,
:site => 'http://twitter.com'
)
access_token = OAuth::AccessToken.new(
consumer,
@@ACCESS_TOKEN,
@@ACCESS_TOKEN_SECRET
)
requestAPIURL = 'http://api.twitter.com/1.1/search/tweets.json?q=' + encodedQuery
url_escape = URI.escape(requestAPIURL)
response = access_token.get(url_escape)
JSON.parse(response.body).each do |status|
status.each do |items|
if (items.instance_of?(Array))
items.each do |statusesItems|
if (statusesItems.instance_of?(Hash))
open(path_to_txt, "a") {|f| f.write(statusesItems['text'] + "\n")}
puts statusesItems['text']
end
end
end
end
end
end
end
hoge = TwitterConnects.new
puts "type search text!!"
searchText = gets()
while(true) do
puts "--------------------------------"
open(path_to_txt, "w") {|f| f.write('')}
open(path_to_txt, "a") {|f| f.write(searchText)}
hoge.getTweets(searchText)
puts "--------------------------------"
sleep(30)
end
| true
|
e884c5f72329baec44306ed62e30f9e9579216b9
|
Ruby
|
marcioaleson/Ruby
|
/threads/thread3.rb
|
UTF-8
| 226
| 3.078125
| 3
|
[] |
no_license
|
# encoding: utf-8
proc = Proc.new do |parametro|
parametro.times do |valor|
print "[#{valor+1}/#{parametro}]"
sleep 0.5
end
end
thread = nil
5.times do |valor|
thread = Thread.new(valor,&proc)
end
thread.join
puts "Terminado!"
| true
|
56be8ecf4295ac5217ca144cdcc9811720a6608d
|
Ruby
|
achempion/appsignal-ruby
|
/lib/appsignal/marker.rb
|
UTF-8
| 704
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
module Appsignal
class Marker
attr_reader :marker_data, :config
ACTION = "markers"
def initialize(marker_data, config)
@marker_data = marker_data
@config = config
end
def transmit
transmitter = Transmitter.new(ACTION, config)
puts "Notifying AppSignal of deploy with: "\
"revision: #{marker_data[:revision]}, user: #{marker_data[:user]}"
result = transmitter.transmit(marker_data)
if result == "200"
puts "AppSignal has been notified of this deploy!"
else
raise "#{result} at #{transmitter.uri}"
end
rescue => e
puts "Something went wrong while trying to notify AppSignal: #{e}"
end
end
end
| true
|
45d4368b9748ee63b4fef28c99095fac0e795077
|
Ruby
|
sshpm/sshpm-ruby
|
/lib/sshpm/tasks/builder.rb
|
UTF-8
| 463
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
module SSHPM
module Tasks
# A helper entity whose intent is to provide and idiom to task
# creation DSL
class Builder
def initialize
@attributes = {}
end
attr_reader :attributes
def method_missing(name, *args)
attributes[name] = args[0]
end
def self.build(&block)
builder = Builder.new
builder.instance_eval(&block) unless block.nil?
builder
end
end
end
end
| true
|
8e295ce0d9544cd531993db46c31011f69e0efff
|
Ruby
|
sprax/ruby
|
/fibonacci.rb
|
UTF-8
| 373
| 3.75
| 4
|
[] |
no_license
|
#!/usr/bin/ruby
#
# Sprax Lines 2007 ?
# naive recursion
def fib_rec(n)
return n if (0..1).include? n
fib_rec(n-1) + fib_rec(n-2) if n > 1
end
count = 36
if ARGV.length > 0
count = ARGV[0].to_i
end
puts "First #{count} Fibonacci numbers using naive recursion:"
count.times do |i|
f = fib_rec(i)
printf "%3d %d\n", i, f
# same as: # puts "#{i} #{f}"
end
| true
|
315eb31aa1e9d502cf29efdbd63bd68adda004db
|
Ruby
|
syounger-ut/exercism
|
/ruby/roman-numerals/roman_numerals.rb
|
UTF-8
| 1,041
| 4.03125
| 4
|
[] |
no_license
|
require 'pry'
class Fixnum
ROMAN_NUMERALS = {
'1' => 'I',
'5' => 'V',
'10' => 'X',
'50' => 'L',
'100' => 'C',
'500' => 'D',
'1000' => 'M'
}
def to_roman
# Break the number into Thousands, Hundreds, Tens and Ones, and write down each in turn.
n = self
number_of_chars = n.to_s.chars.count
case number_of_chars
when 4
# code fo 1000's
when 3
# code for 100's
when 2
# code for 10's
# binding.pry
multiple = n.digits.last
tens = combine_numerals(multiple, 'X')
single = singles(n.digits.first)
[tens, single].join
when 1
# code for 1's
singles(n)
end
end
private
def singles(n)
if n == 4
'IV'
elsif n == 5
'V'
elsif n == 6
'VI'
elsif n == 7
'VII'
elsif n == 8
'VIII'
elsif n == 9
'IX'
else
combine_numerals(n, 'I')
end
end
def combine_numerals(multiple, numeral)
multiple.times.map { |x| numeral }.join
end
end
| true
|
e68e2f5067e77578e05938cb1a5814f030f322c8
|
Ruby
|
iandeth/trials
|
/ruby/basics/cgi/erb.cgi
|
UTF-8
| 903
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/local/bin/ruby -w
require 'cgi'
require 'erb'
include ERB::Util # enable <%=h %> and <%=u %>
cgi = CGI.new 'html4'
puts cgi.header( 'charset'=>'UTF-8' )
text = '@a << 2'
url = 'http://.../?prm=あいう'
tmpl = %q{
<?xml version="1.0" encoding="euc-jp"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<HEAD>
<META CONTENT="text/html;CHARSET=UTF-8" HTTP-EQUIV="Content-Type"/>
<TITLE>erb test</TITLE>
</HEAD>
<BODY>
<h1>ERB test</h1>
<h2>HTML escaped string</h2>
<%=h text %>
<br/>
<h2>URL encoded string</h2>
<%=u url %>
<br/>
<h2>ENV.each</h2>
<% ENV.each do |k,v| %>
<%=h k %> : <%=h v %><br/>
<% end %>
</BODY>
</HTML>
}
ERB.new(
tmpl, # template string
nil, # security level
'<>' # trim mode
).run # or, .run( binding )
| true
|
275238b0a908154d73bfd2a77405fc50ef34f9f3
|
Ruby
|
twblalock/jsondiff
|
/main.rb
|
UTF-8
| 659
| 2.90625
| 3
|
[] |
no_license
|
# the goal: print both jsons side-by-side and highlight the differences
# test representation doesn't matter -- only the JSON objects are compared
require "json"
require "./jsondiff"
def readJson(filename)
begin
return JSON.parse(File.read(filename))
rescue Exception => e
puts "error parsing file: #{filename}: #{e}"
puts e.backtrace
exit 1
end
end
if ARGV.length < 2
puts "Usage: ruby jsondiff.rb file1 file2"
exit 1
end
FILE1 = ARGV[0]
FILE2 = ARGV[1]
# TODO print output side-by-side?
a = readJson(FILE1)
b = readJson(FILE2)
numMismatches = JsonDiff.diff(a, b)
if numMismatches > 0
exit 1
end
| true
|
7e0f102cf6fffb717ca9736f521356c63922a542
|
Ruby
|
belette06/ruby
|
/pyramide.rb
|
UTF-8
| 156
| 3.359375
| 3
|
[] |
no_license
|
puts "Combien d'étages veux-tu ?"
n = Integer(gets.chomp)
diese = "#"
espace = " "
(n-1).downto(0) do |k|
puts "#{espace*k}#{diese*(n-k)}"
end
| true
|
eed37b1be4131ad9232978461158a7f0a29677f2
|
Ruby
|
danivcupples/ruby_practice
|
/crayon.rb
|
UTF-8
| 222
| 4.1875
| 4
|
[] |
no_license
|
# Write a program that asks for your favorite Crayola crayon and then takes the string and yells it back in all caps and in reverse.
puts "What is your favorite Crayola crayon?"
fav = gets.chomp.upcase
puts fav.reverse
| true
|
14197fda2dd4587cb79ada19e2a0a3fda059e4f0
|
Ruby
|
jmoses/pages-to-pdf
|
/app/models/page.rb
|
UTF-8
| 563
| 2.59375
| 3
|
[] |
no_license
|
require 'open-uri'
class Page
TARGET = "QuickLook/Preview.pdf"
attr_accessor :url
def initialize( url = nil )
@url = url
end
def pdf
tempfile = fetch_file
preview( tempfile.path ).tap do
tempfile.close
end
end
protected
def fetch_file
Tempfile.new("pdfzip", Rails.root.join("tmp") ).tap do |file|
open(url, 'rb:utf-8') {|url| file << url.read }
file.rewind
end
end
def preview( path )
Zip::ZipFile.open(path) do |zipfile|
zipfile.read( TARGET )
end
end
end
| true
|
acc9ee4a6dc3f8d2b1749ebe807021cb2e1602fc
|
Ruby
|
lorenzograndi4/bootcamp
|
/buy.rb
|
UTF-8
| 1,216
| 3.90625
| 4
|
[] |
no_license
|
# selection method
def selection
puts "Which drink would you like? (1-4)"
drink_id = gets.chomp.to_i
if drink_id != 1 && drink_id != 2 && drink_id != 3 && drink_id != 4
puts "Sorry, this is not available."
selection
end
return drink_id
end
#confirmation method
def confirmation(drink_id)
puts "Add #{$drinks[drink_id - 1][:name]} to your cart? (y/n)"
answer = gets.chomp.downcase
if answer != "y"
puts "No problem!"
selection
end
puts "here we add #{$drinks[drink_id - 1][:name]} to your cart "
return drink_id
end
# defining drinks
item_vodka = {name: "Stolichnaya vodka", price: "17.99", country: "Russia", id: 1}
item_beer = {name: "Heineken beer", price: "2.99", country: "Netherlands", id: 2}
item_wine = {name: "Bordeaux wine", price: "11.99", country: "France", id: 3}
item_grappa = {name: "Nonino grappa", price: "24.99", country: "Italy", id: 4}
$drinks = [item_vodka, item_beer, item_wine, item_grappa]
#cart is an empty array
cart = []
# here the client comes in
puts "Welcome to the liquor shop. What's your pick today?"
$drinks.each do |drink|
puts "#{drink[:id]} - #{drink[:name]} - #{drink[:price]}"
end
drink_id = selection
confirmation(drink_id)
puts "Bye"
| true
|
3c5cb3eb87666f4e78a44966e8bfe1bf4285cef5
|
Ruby
|
dehormazah/test
|
/app/models/history.rb
|
UTF-8
| 2,570
| 2.71875
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: histories
#
# id :integer not null, primary key
# description :text
# genre :string
# birth_date :date
# age :integer
# weight :integer
# height :integer
# start :datetime
# num_achievements :integer
# num_diets :integer
# num_plans :integer
# num_groups :integer
# num_events :integer
# level :string
# created_at :datetime not null
# updated_at :datetime not null
# user_id :integer
#
class History < ApplicationRecord
#Relaciones, dependencias y validaciones
belongs_to :user
validates :description, presence: true, length: {maximum: 500}
validates :genre, presence: true
validates :birth_date, presence: true, timeliness: {type: :date}
validates :age, presence: true, numericality: { only_integer: true }
validates :weight, presence: true, numericality: { only_integer: true }
validates :height, presence: true, numericality: { only_integer: true }
validates :start, presence: true, timeliness: {type: :datetime}
validates :num_achievements, presence: true
validates :num_events, presence: true
validates :num_diets, presence: true
validates :num_groups, presence: true
validates :num_plans, presence: true
validates :level, presence: true
validates :user_id, presence: true
# validates_format_of :start, :with => /\d{2}\/\d{2}\/\d{4}/, :message => "^La fecha debe seguir el siguiente formato: dd/mm/aaaa"
# validates_format_of :current_time, :with => /\d{2}\/\d{2}\/\d{4}/, :message => "^La fecha debe seguir el siguiente formato: dd/mm/aaaa"
#Queries implementadas a través de scopes
#conocer el número de usuarios de cada edad que usan la aplicación
scope :usersByAge, -> {History.group(:age).count}
#conocer el numero de usuarios por genero que usan la aplicacion
scope :usersByGenre, -> {History.group(:genre).count}
#conocer el id y la edad de los usuarios que han hecho mas de 5 dietas
scope :moreThan5Diets, -> { where('num_diets > 5').select("user_id,age").all.to_a }
#conocer el id de los usuarios que han hecho más de 8 dietas y planes físicos y han conseguido más de 5 logros
scope :fitnessUsers, -> {where('num_diets > 8 AND num_plans > 8 AND num_achievements >5').pluck(:user_id)}
#seleccionar el id, el peso y el género de usuarios con una edad menor a 20 años
scope :selectAgeGenre, -> {where('age < 20').select("user_id,weight, genre").all.to_a}
end
| true
|
e95cbb61e401a38a8f696d6ba1391dfa54e196bd
|
Ruby
|
Kamiichi/tryToRuby
|
/Chapter1/comment_sample.rb
|
UTF-8
| 392
| 3.15625
| 3
|
[] |
no_license
|
# coding: utf-8
=begin
「たのしいRuby 第6版」サンプル
コメントの使い方の例
2006/06/16 作成
2006/07/01 一部コメントを追加
2006/01/01 第6版用に更新
=end
x = 10 #横
y = 20 #縦
z = 30 #高さ
#表面積と体積を計算する
area = (x*y + y*z + z*x) * 2
volume = x * y * z
# 出力する
print "表面積=", area, "\n"
print "体積=", volume, "\n"
| true
|
12f528890558d3c5c5ea444eabde4b85447b3525
|
Ruby
|
devmicka/Mardi-Week2-THP-Exo-Ruby
|
/exo_04.rb
|
UTF-8
| 164
| 3.71875
| 4
|
[] |
no_license
|
puts "Quel est votre année de naissance?"
print "> "
birth_year = gets.chomp
age= 2021-birth_year.to_i
print "Dans 100 ans vous aurez "
print age + 100
print" ans"
| true
|
bc067681fd4dde916a983b0eeac8fa4c5ea331ac
|
Ruby
|
ben-harvey/Small-problems-Ruby
|
/more topics/medium1/2.rb
|
UTF-8
| 1,254
| 3.40625
| 3
|
[] |
no_license
|
TEXT = "Eiusmod non aute commodo excepteur amet consequat ex elit. Ut excepteur ipsum
enim nulla aliqua fugiat quis dolore do minim non. Ad ex elit nulla commodo
aliqua eiusmod aliqua duis officia excepteur eiusmod veniam. Enim culpa laborum
nisi magna esse nulla ipsum ex consequat. Et enim et quis excepteur tempor ea
sit consequat cupidatat.
Esse commodo magna dolore adipisicing Lorem veniam quis ut labore pariatur quis
aliquip labore ad. Voluptate ullamco aliquip cillum cupidatat id in sint ipsum
pariatur nisi adipisicing exercitation id adipisicing qui. Nulla proident ad
elit dolore exercitation cupidatat mollit consequat enim cupidatat tempor
aliqua ea sunt ex nisi non.
Officia dolore labore non labore irure nisi ad minim consectetur non irure
veniam dolor. Laboris cillum fugiat reprehenderit elit consequat ullamco veniam
commodo."
class TextAnalyzer
def process
file = File.open('3.rb', 'r')
text = file.read
yield(text)
file.close
end
end
analyzer = TextAnalyzer.new
analyzer.process { |text| puts "#{text.split("\n\n").count} paragraphs" }
analyzer.process { |text| puts "#{text.split("\n").count} lines" }
analyzer.process { |text| puts "#{text.split(" ").count} words" }
# 3 paragraphs
# 15 lines
# 126 words
| true
|
e31b1356ebf5ac766ab9eae6a86546f01df4100d
|
Ruby
|
molotof/ear
|
/app/models/object_mapping.rb
|
UTF-8
| 848
| 2.578125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
class ObjectMapping < ActiveRecord::Base
belongs_to :task_run
def get_child
EarLogger.instance.log "Trying to find #{child_type}:#{child_id}"
begin
eval "#{child_type}.find #{child_id}"
rescue ActiveRecord::RecordNotFound => e
EarLogger.instance.log "Oops, couldn't find #{child_type}:#{child_id}"
nil
end
end
def get_parent
EarLogger.instance.log "Trying to find #{parent_type}:#{parent_id}"
begin
eval "#{parent_type}.find #{parent_id}"
rescue ActiveRecord::RecordNotFound => e
EarLogger.instance.log "Oops, couldn't find #{child_type}:#{child_id}"
nil
end
end
def to_s
"#{self.class}: #{child_type}:#{child_id} <-> #{parent_type}:#{parent_id} - (task_run: #{task_run.id})"
end
end
| true
|
165bf8e65315088372262b5c6bdff3254546e250
|
Ruby
|
hashrocket/clearance
|
/test/rails_root/vendor/plugins/facebooker/lib/facebooker/models/friend_list.rb
|
UTF-8
| 299
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
require 'facebooker/model'
module Facebooker
##
# A simple representation of a photo album.
class FriendList
include Model
attr_accessor :flid, :name
# We need this to be an integer, so do the conversion
def flid=(f)
@flid= ( f.nil? ? nil : f.to_i)
end
end
end
| true
|
4e3c1d5b705455f876f90ade6191b4433e7b74fd
|
Ruby
|
piecedigital/learn-ruby-projects
|
/02_calculator/calculator.rb
|
UTF-8
| 352
| 3.71875
| 4
|
[] |
no_license
|
def add(a,b)
a+b
end
def subtract(a,b)
a-b
end
def sum(numbers)
numbers.inject(0) { |sums, number| sums + number }
end
def multiply(numbers)
numbers.inject { |sum, number| sum * number }
end
def power(numbers)
numbers.inject { |sum, number| sum ** number }
end
def factorial(numbers)
(1..numbers).reduce(:*) || 1
end
| true
|
ca3b4e7d3983fc9b5e280ce4b41746d97fd3cefe
|
Ruby
|
cristobalparedesn/Desarrollo-de-aplicaciones-web-con-Rails
|
/Desafio2/Ejercicio1/usuario.rb
|
UTF-8
| 534
| 3.328125
| 3
|
[] |
no_license
|
require_relative('./cuentabancaria.rb')
class Usuario
attr_accessor :name_user, :cuentas
def initialize(name_user, cuentas =[])
@name_user = name_user
@cuentas = cuentas
end
def saldo_total
puts @cuentas.map {|cuentas| cuentas.saldo}.sum
end
end
cuentas_bancarias = [CuentaBancaria.new("BCI", 76245233, 850000), CuentaBancaria.new("Banco Estado", 16920292, 300000), CuentaBancaria.new("Banco Falabella", 18920292, 250000)]
usuario1 = Usuario.new("Florencia", cuentas_bancarias)
usuario1.saldo_total
| true
|
e79aa7560d0729ebb5a1998d738a94646875f128
|
Ruby
|
beccalou/ga-lab-rspec-geometry
|
/lib/triangle.rb
|
UTF-8
| 302
| 3.1875
| 3
|
[] |
no_license
|
module Geometry
class Triangle
def initialize(sideA, sideB, sideC)
@sideA = sideA
@sideB = sideB
@sideC = sideC
end
def perimeter
@sideA + @sideB + @sideC
end
def area
(0.5*(@sideA)) * @sideB
end
def angle
end
def is_triangle
end
end
end
| true
|
3faf21a7a7abd5232a484e7cf2d6b1728f865ca9
|
Ruby
|
nnnnon/rails
|
/activemodel/lib/active_model/validations/confirmation.rb
|
UTF-8
| 2,562
| 2.796875
| 3
|
[] |
no_license
|
module ActiveModel
module Validations
module ClassMethods
# Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. Example:
#
# Model:
# class Person < ActiveRecord::Base
# validates_confirmation_of :user_name, :password
# validates_confirmation_of :email_address, :message => "should match confirmation"
# end
#
# View:
# <%= password_field "person", "password" %>
# <%= password_field "person", "password_confirmation" %>
#
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
# only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
# check for the confirmation attribute:
#
# validates_presence_of :password_confirmation, :if => :password_changed?
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# method, proc or string should return or evaluate to a true or false value.
def validates_confirmation_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
configuration.update(attr_names.extract_options!)
attr_accessor(*(attr_names.map { |n| "#{n}_confirmation" }))
validates_each(attr_names, configuration) do |record, attr_name, value|
record.errors.add(attr_name, configuration[:message]) unless record.send("#{attr_name}_confirmation").nil? or value == record.send("#{attr_name}_confirmation")
end
end
end
end
end
| true
|
840fac8c536871f84c3a4bb7ba3fbee3d9c20305
|
Ruby
|
junkmechanic/SciSWING
|
/src/Features/Tf_idf.rb
|
UTF-8
| 6,034
| 2.90625
| 3
|
[] |
no_license
|
#/usr/bin/ruby
# encoding: UTF-8
### 25/05/2014 - Ankur
# TODO: This script
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/..')
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../..')
require 'json'
require 'set'
require 'lib/ptb_tokenizer'
require 'lib/stopwords/StopList'
$IDF = Hash.new
def prepare_IDF
idf_dir = "/home/ankur/devbench/scientific/SciSWING/lib/webBase/"
Dir.glob(idf_dir + "idf*.tsv") do |idf_file|
File.open(idf_file, "r") do |f|
f.each_line do |line|
begin
word = /(.+)\t(.+)/.match(line)[1]
idf = /(.+)\t(.+)/.match(line)[2]
$IDF[word] = idf.to_f
rescue Exception => e
end
end
end
end
end
def compute_word_counts document
# This will calculate the term frequencies of all the words in the document.
# All the words will be saved in a set for each section and serialized, for
# caching, into lists. This will help in the calculation of sectional -idf
# scores.
# NOTE For now, I have not used the stemmer. Once the pipeline is ready, will
# see if that improves the performance drastically.
term_freq = Hash.new
$stoplist = StopList.new
document["content"].each do |section|
word_set= Set.new
section["sentences"].values.each do |sentence|
reduced = PTBTokenizer.tokenize(sentence.downcase)
wordlist = ($stoplist.filter reduced).split
# Should stem here
# the call to the 'uniq' method might be redundant since its a set merge
word_set.merge wordlist.uniq
# update the term_freq hash
wordlist.each do |term|
# Should stem here
if term_freq.has_key? term
term_freq[term] += 1
else
term_freq[term] = 1
end
end
end
section["word_set"] = word_set.to_a
end
document["term_freq"] = term_freq
end
def get_section_idf(document, word)
# First find out the section frequency of the word in the document
sf = 0
document["content"].each do |section|
if section["word_set"].include?(word)
sf += 1
end
end
num = document["content"].length
if sf > 0
return -( Math.log(sf) - Math.log(num) )
else
return 0
end
end
def accumulate_idf(document, word)
# This will initiate the recursive function to calculate the idf for each
# word in the dependency parse of the sentence that is part of the sub tree
# whoese root node is word.
# Here, document and word should both be hashes.
web_value, sec_value, num = recursive_compute(document, word)
if web_value == 0.0 then
ret_web = 0.0
else
ret_web = web_value / num
end
if sec_value == 0.0 then
ret_sec = 0.0
else
ret_sec = sec_value / num
end
return ret_web, ret_sec
end
def recursive_compute(document, word)
term = word["word"].downcase
if $stoplist.stopwords.include?(term.downcase) or /.*[0-9].*/.match(term)
num, web_value, sec_value = 0, 0.0, 0.0
else
num = 1
sec_value = get_section_idf(document, term)
web_value = if $IDF.has_key?(term) then $IDF[term] else 0.0 end
end
# Now recurse into the children.
if word.has_key?("children")
word["children"].each do |child|
web_val, sec_val, n = recursive_compute(document, child)
web_value += web_val
sec_value += sec_val
num += n
end
end
return web_value, sec_value, num
end
def extract_features document
# Use the dependency parse to get the verb, subject and object phrases and
# compute the tf_idf statistics for each.
document["top_sentences"].each do |rank, sentence|
# the sentence variable is a hash by iteslf with "sentence" and "dep_parse"
# and "id" keys
if sentence["dep_parse"].length > 1
# Hopefully it will never come to this
error_msg = "There seem to be multiple root nodes (or orphaned nodes) "\
"in doc: #{document["actual_doc_id"]}, sentence-id : #{sentence["id"]}"
puts "WARNING : #{error_msg}"
else
verb = sentence["dep_parse"][0]["word"].downcase
# now that we have the word, we can get the tf, the idf can be extracted
# from both webBase idfs and also calculating the sectional idf
subj_node = find_node(sentence, "subj")
obj_node = find_node(sentence, "obj")
freq = if document["term_freq"].has_key?(verb) then document["term_freq"][verb] else 0.0 end
web_idf = if $IDF.has_key?(verb) then $IDF[verb] else 0.0 end
sec_idf = get_section_idf(document, verb)
sentence["features"] = {"verb_tf"=>freq,"verb_web_idf"=>web_idf,"verb_sec_idf"=>sec_idf}
if subj_node
word = subj_node["word"].downcase
freq = if document["term_freq"].has_key?(word) then document["term_freq"][word] else 0.0 end
web_idf, sec_idf = accumulate_idf(document, subj_node)
sentence["features"].merge!({"subj_tf"=>freq,"subj_web_idf"=>web_idf,"subj_sec_idf"=>sec_idf})
end
if obj_node
word = obj_node["word"].downcase
freq = if document["term_freq"].has_key?(word) then document["term_freq"][word] else 0.0 end
web_idf, sec_idf = accumulate_idf(document, obj_node)
sentence["features"].merge!({"obj_tf"=>freq,"obj_web_idf"=>web_idf,"obj_sec_idf"=>sec_idf})
end
end
end
end
def find_node(sentence, pattern)
root = sentence["dep_parse"][0]
# Matching regexp
if /#{pattern}/.match(root["dep"])
return root
end
queue = root["children"]
while queue.length > 0
child = queue.shift
if /#{pattern}/.match(child["dep"])
return child
else
if child.has_key?("children")
child["children"].each do |small_child|
queue.push(small_child)
end
end
end
end
return nil
end
ARGF.each do |l_JSN|
# Get all the IDF values from the web corpus
prepare_IDF
$g_JSON = JSON.parse l_JSN
# Compute all the word frequencies and document (section) frequencies.
$g_JSON["corpus"].each do |l_Article|
compute_word_counts l_Article
extract_features l_Article
end
puts JSON.generate $g_JSON
end
| true
|
e7edfda037098a43160e904684ecce219c132088
|
Ruby
|
juliansample/ProgrammingClass2015-2016
|
/asighnment4
|
UTF-8
| 330
| 3.75
| 4
|
[] |
no_license
|
# puts "How many hours do you work?"
# diameter = gets.to_i
# radius = diameter / 2
# puts "The radius is #{radius}"
puts "How many hour do you work?"
hours = gets.to_i
puts "How much do you make per hour?"
money = gets.to_i
puts "How many weeks did you work?"
weeks = gets.to_i
puts "I would make #{hours,money,weeks}"
| true
|
9fa686345621a0bc90478b99838ff5b54b9b7155
|
Ruby
|
wintonpc/funzip
|
/spec/funzip_spec.rb
|
UTF-8
| 1,265
| 2.859375
| 3
|
[] |
no_license
|
require 'rspec'
require 'funzip'
require 'tmpdir'
describe Funzip do
describe '::unzip' do
it 'unzips' do
%w(test windows).each do |name|
Dir.mktmpdir do |dir|
Funzip.unzip(zip_path(name), dir)
expect(content_of(dir, 'a.txt')).to eql 'a'
expect(content_of(dir, 'b/c.txt')).to eql 'c'
expect(Dir.exists?(File.join(dir, 'd/e/f'))).to be_truthy
end
end
end
it 'raises an error on failure' do
expect{Funzip.unzip(zip_path('test'), '/root')}.to raise_error StandardError, 'failed to open output file: /root/a.txt'
end
# it 'does not leak small' do
# 10000000.times do
# Dir.mktmpdir do |dir|
# Funzip.unzip(zip_path('test'), dir)
# end
# end
# end
#
# it 'does not leak big' do
# 10000.times do
# Dir.mktmpdir do |dir|
# Funzip.unzip('/home/pwinton/Downloads/iamMANOLIS - Dayte.zip', dir)
# end
# end
# end
def zip_path(name)
File.join(File.dirname(__FILE__), "fixtures/#{name}.zip")
end
def content_of(dir, file_path)
strip_newline(File.read(File.join(dir, file_path)))
end
def strip_newline(s)
s.gsub(/[\r\n]+$/m, '')
end
end
end
| true
|
e21d459dfc3b780738963b9bf8be5d102cbb3268
|
Ruby
|
AmanziTel/cpn
|
/lib/cpn/observable.rb
|
UTF-8
| 1,005
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'observer'
module CPN
module Observable
def on(ops, &block)
ops = [ ops ] unless ops.respond_to?(:each)
@observers ||= {}
ops.each do |op|
raise "Unsupported op #{op}" unless observable_event_type?(op)
@observers[op] ||= []
@observers[op] << block
end
end
def off(op = nil, &block)
if block_given?
@observers && @observers[op] && @observers[op].delete(block)
elsif op
@observers && @observers[op] = []
else
@observers = {}
end
end
def fire(op, context = self)
raise "Unsupported op #{op}" unless observable_event_type?(op)
@observers && @observers[op] && @observers[op].each do |block|
block.call(context, op)
end
end
def self.included(base)
def base.event_source(*event_types)
define_method :observable_event_type? do |type|
event_types.empty? || event_types.include?(type)
end
end
end
end
end
| true
|
0dffb73703308b6da3c78612129630d393e1eb72
|
Ruby
|
jigneshkapuriya/ruby_learning
|
/The_fetch_method.rb
|
UTF-8
| 169
| 3.203125
| 3
|
[] |
no_license
|
names = ["Pooja","Jignesh","Ravi"]
p names[2]
p names[100]
p names.fetch(2)
p names.fetch(100, "Monika")
numbers = [1,3,5,7,9,15,21,19]
p numbers[2,4]
p numbers[2..4]
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.