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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f69a3e6888939daffec435d125ee7d9c1c53a709 | Ruby | bleavs/ruby-collaborating-objects-lab-web-080717 | /lib/song.rb | UTF-8 | 376 | 3.375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Song
attr_accessor :name, :artist
def initialize(name)
@name = name
end
def artist_name=(name)
@artist = Artist.find_or_create_by_name(name)
end
def self.new_by_filename(file_name)
arr = file_name.split(" - ")
new_song = Song.new(arr[1])
new_song.artist_name=(arr[0])
new_song.artist.add_song(new_song)
new_song
end
end
| true |
5d2d81a9711c686f918563c195909f2d1b19dbba | Ruby | funkorogashi/programming_ideas | /chapter2/04_decode_msg/01.rb | UTF-8 | 1,140 | 3.453125 | 3 | [] | no_license | # アルファベットと記号
ALPHABET_L = [*'A'..'Z']
ALPHABET_S = [*'a'..'z']
MARKS = ["!", "?", ",", ".", " ", ";", "\"", "'"]
# モード一覧
MODE_ALPHABET_L = "1"
MODE_ALPHABET_S = "2"
MODE_MARKS = "3"
def decode_message(message)
message_array = message.split(",")
decoded_message = ""
mode = MODE_ALPHABET_L
numval = 27
message_array.length.times do |i|
value = message_array[i].to_i % numval
if value != 0
decoded_message << get_char(mode, value)
else
mode = check_mode(mode)
numval = check_numval(mode)
end
end
decoded_message
end
private
def check_mode(mode)
case mode
when MODE_ALPHABET_L then MODE_ALPHABET_S
when MODE_ALPHABET_S then MODE_MARKS
when MODE_MARKS then MODE_ALPHABET_L
end
end
def check_numval(mode)
case mode
when MODE_ALPHABET_L then 27
when MODE_ALPHABET_S then 27
when MODE_MARKS then 9
end
end
def get_char(mode, value)
case mode
when MODE_ALPHABET_L then ALPHABET_L[value - 1]
when MODE_ALPHABET_S then ALPHABET_S[value - 1]
when MODE_MARKS then MARKS[value - 1]
end
end
puts decode_message("33,54,21,68,38,42,45,69,34,28,46,62,90,27,28,81,31,54,32,46,21")
| true |
d05831ece1e10d5636c15b763753cc819321fb86 | Ruby | carynkeffer/nom_nom_nom | /lib/pantry.rb | UTF-8 | 562 | 3.09375 | 3 | [] | no_license | require './lib/ingredient'
class Pantry
attr_reader :ingredients
def initialize
@ingredients = []
end
def stock
{}
end
def stock_check(ingredient)
if @ingredients.include?(ingredient)
@ingredients
else
0
end
end
def restock(ingredient, amount)
ingredient = Ingredient.new({
name: @name,
unit: @unit,
calories: @calories})
@ingredients << ingredient
ingredient
require "pry"; binding.pry
end
end
| true |
115beb89921232540bc2279fe7c152c432a8953b | Ruby | c0nspiracy/advent-of-code-2019 | /day_22/part_2.rb | UTF-8 | 1,088 | 3.609375 | 4 | [] | no_license | # frozen_string_literal: true
# Calculates large integer powers with the Exponentation by squaring method
# https://en.wikipedia.org/wiki/Exponentiation_by_squaring
def exp_by_squaring(a, b, exponent, deck_size)
return [1, 0] if exponent.zero?
if exponent.even?
exp_by_squaring(a * a % deck_size, (a * b + b) % deck_size, exponent / 2, deck_size)
else
c, d = exp_by_squaring(a, b, exponent - 1, deck_size)
[a * c % deck_size, (a * d + b) % deck_size]
end
end
deck_size = 119_315_717_514_047
shuffles = 101_741_582_076_661
position = 2020
a = 1
b = 0
File.readlines('input.txt', chomp: true).reverse_each do |instruction|
case instruction
when /cut (-?\d+)/
n = Regexp.last_match[1].to_i
b = (b + n) % deck_size
when /deal with increment (\d+)/
n = Regexp.last_match[1].to_i
z = n.pow(deck_size - 2, deck_size)
a = a * z % deck_size
b = b * z % deck_size
when 'deal into new stack'
a = -a
b = deck_size - b - 1
end
end
a, b = exp_by_squaring(a, b, shuffles, deck_size)
answer = (position * a + b) % deck_size
puts answer
| true |
3c669140bc6bac2e830ffd0c25dd9aa8cbcac91f | Ruby | dengsauve/College-Work | /2017 Spring/CIS283/jukebox/Jukebox.rb | UTF-8 | 1,826 | 3.875 | 4 | [] | no_license | ############################################################
#
# Name: Dennis Sauve
# Date: 04/22/2017
# Assignment: Jukebox
# Class: CIS 283
# Description: Jukebox holds the Jukebox class which has
# an array of song objects.
# [X] Write another class called Jukebox which handles
# storing multiple songs into an array that is
# INSIDE the Jukebox class.
# An object created from this class should respond to:
# [X] adding
# [X] deleting
# [X] updating
# [X] listing all of the Song objects stored inside of it.
#
############################################################
class Jukebox
def initialize
@library = []
end
def archive_songs
@library
end
def add(track)
@library << track
"\n#{track.info} added to Library.\n\n"
end
def delete(song_index)
@library.delete_at(song_index)
end
def contents
ret_str = ''
@library.each_with_index do |song, index|
ret_str += (index+1).to_s + ".\t"
ret_str += song.details + "\n"
end
ret_str
end
def songs_longer_than(seconds)
ret_str = ''
@library.each do |song|
if song.length.to_i > seconds
ret_str += song.details + "\n"
end
end
ret_str
end
def songs_by_artist(artist, ret_str='')
@library.each do |song|
if song.artist.downcase == artist.downcase
ret_str += '=> ' + song.details + "\n"
end
end
ret_str
end
def play_song(song_selection)
@library[song_selection].play
end
def details_by_index(song_index)
@library[song_index].details
end
def load_songs(song_array)
@library = song_array
end
def count
@library.length
end
end | true |
fb788c3f04b4dd2691ec9fc2dd5429db94b33c2b | Ruby | thesleevecode621/school-domain-online-web-pt-051319 | /lib/school.rb | UTF-8 | 377 | 3.4375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class School
attr_accessor :name, :roster
def initialize(name)
@name = name
@roster = {}
end
def add_student(name, grade)
roster[grade] = [] unless roster[grade]
roster[grade] << name
end
def grade (i)
roster[i]
end
def sort
sorted = {}
roster.each do |key, values|
sorted[key] = values.sort
end
sorted
end
end | true |
560e19d527672f4ec05e63ab4ec958d9a1087927 | Ruby | mt3/vnews | /lib/vnews/opml.rb | UTF-8 | 1,360 | 2.625 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'vnews/feed'
require 'vnews/constants'
class Vnews
class Opml
CONCURRENCY = 18
def self.import(opml)
sqlclient = Vnews.sql_client
doc = Nokogiri::XML.parse(opml)
feeds = []
doc.xpath('/opml/body/outline').each_slice(CONCURRENCY) do |xs|
xs.each do |n|
begin
Timeout::timeout(Vnews::TIMEOUT) do
if n.attributes['xmlUrl']
feeds << Vnews::Feed.fetch_feed(n.attributes['xmlUrl'].to_s)
else
folder = n.attributes["title"].to_s
$stderr.print "Found folder: #{folder}\n"
n.xpath("outline[@xmlUrl]").each do |m|
feeds << Vnews::Feed.fetch_feed(m.attributes['xmlUrl'].to_s, folder)
end
end
end
rescue Timeout::Error
puts "TIMEOUT ERROR: #{feed_url}"
end
end
end
$stderr.puts "Making database records"
feeds.each do |x|
feed_url, f, folder = *x
folder ||= "Misc"
if f.nil?
$stderr.print "\nNo feed found for #{feed_url}\n"
else
Vnews::Feed.save_feed(feed_url, f, folder)
end
end
$stderr.puts "\nDone."
end
end
end
if __FILE__ == $0
opml = STDIN.read
Vnews::Opml.import(opml)
end
| true |
b1d73c85ce0105e212b8bc7018d96ad756322ad1 | Ruby | IrinaSTA/oystercard_day3 | /lib/oystercard.rb | UTF-8 | 995 | 3.390625 | 3 | [] | no_license | require 'pry'
require 'journey'
class Oystercard
attr_reader :balance, :start_station, :trips
MINIMUM_BALANCE = 1
MAXIMUM_BALANCE = 90
MINIMUM_FARE = 1
def initialize
@balance = 0
@trips = []
end
def topup(amount)
raise "Cannot topup £#{amount}: maximum balance of £#{MAXIMUM_BALANCE}" if (MAXIMUM_BALANCE - @balance) < amount
@balance += amount
end
def touch_in(station)
raise 'Insufficient funds' if @balance < MINIMUM_BALANCE
deduct(@current_journey.fare) if @current_journey != nil
start_journey(station)
end
def touch_out(station)
deduct(MINIMUM_FARE)
end_journey(station)
end
# def in_journey?
# !@current_journey.complete?
# end
private
def deduct(amount)
@balance -= amount
end
def start_journey(station)
@current_journey = Journey.new(station)
end
def end_journey(station)
@current_journey.finish(station)
@trips << @current_journey.trip
@current_journey = nil
end
end
| true |
24d3a60d97d1f0d6eaa7eca37bd51b4750892ddc | Ruby | wayne5540/trikeapps | /app/big_five_results_text_serializer.rb | UTF-8 | 1,559 | 3.15625 | 3 | [
"MIT"
] | permissive | class BigFiveResultsTextSerializer
SCORE_KEYS = ['EXTRAVERSION', 'AGREEABLENESS', 'CONSCIENTIOUSNESS', 'NEUROTICISM', 'OPENNESS TO EXPERIENCE'].freeze
def initialize(text)
@text = text
end
def hash
basic_info.merge score_info
end
private
def basic_info
{
'NAME' => my_name,
'EMAIL' => email
}
end
def score_info
SCORE_KEYS.each_with_object({}) do |key, obj|
obj[key] = score(key)
end
end
def my_name
'Wayne'
end
def email
'wayne.5540@gmail.com'
end
def score(key)
{
'Overall Score' => overall(key),
'Facets' => facets(key)
}
end
def overall(key)
remove_non_digits(usefull_texts[index(key)]).to_i
end
def facets(key)
index = index(key)
6.times.with_object({}) do |i, obj|
obj[remove_dots remove_digits usefull_texts[index + i + 1]] = remove_non_digits(usefull_texts[index + i + 1]).to_i
end
end
def index(key)
usefull_texts.find_index { |text| text.include?(key) } || raise("Can't find key #{key}")
end
def remove_dots(string)
string.gsub('.', '')
end
def remove_digits(string)
string.gsub(%r(\d), '')
end
def remove_non_digits(string)
string.gsub(%r(\D), '')
end
def usefull_texts
@usefull_texts ||= @text.split("\n").keep_if { |paragraph| has_usefull_info?(paragraph) }
end
def has_usefull_info?(paragraph)
keywords.any? { |keyword| paragraph.include? keyword }
end
def keywords
[facet_prefix_sign].concat(SCORE_KEYS)
end
def facet_prefix_sign
'..'
end
end | true |
ac985881a4497d40ed9ba89e2dec38b351e1d9ef | Ruby | drunkwater/leetcode | /medium/ruby/c0223_442_find-all-duplicates-in-an-array/00_leetcode_0223.rb | UTF-8 | 589 | 3.3125 | 3 | [] | no_license | # DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#442. Find All Duplicates in an Array
#Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
#Find all the elements that appear twice in this array.
#Could you do it without extra space and in O(n) runtime?
#Example:
#Input:
#[4,3,2,7,8,2,3,1]
#Output:
#[2,3]
## @param {Integer[]} nums
## @return {Integer[]}
#def find_duplicates(nums)
#end
# Time Is Money | true |
8a1fe5ba0c7b1b8ba876d5f5424d53c5ca7b1d70 | Ruby | ryoqun/wavefile | /lib/wavefile/buffer.rb | UTF-8 | 4,919 | 3.359375 | 3 | [
"MIT"
] | permissive | module WaveFile
# Error that is raised when an attempt is made to perform an unsupported or undefined
# conversion between two sample data formats.
class BufferConversionError < StandardError; end
# Represents a collection of samples in a certain format (e.g. 16-bit mono).
# Reader returns sample data contained in Buffers, and Writer expects incoming sample
# data to be contained in a Buffer as well.
#
# Contains methods to convert the sample data in the buffer to a different format.
class Buffer
# Creates a new Buffer. You are on the honor system to make sure that the given
# sample data matches the given format.
def initialize(samples, format)
@samples = samples
@format = format
end
# Creates a new Buffer containing the sample data of this Buffer, but converted to
# a different format.
#
# new_format - The format that the sample data should be converted to
#
# Examples
#
# new_format = Format.new(:mono, 16, 44100)
# new_buffer = old_buffer.convert(new_format)
#
# Returns a new Buffer; the existing Buffer is unmodified.
def convert(new_format)
new_samples = convert_buffer(@samples.dup, @format, new_format)
return Buffer.new(new_samples, new_format)
end
# Converts the sample data contained in the Buffer to a new format. The sample data
# is converted in place, so the existing Buffer is modified.
#
# new_format - The format that the sample data should be converted to
#
# Examples
#
# new_format = Format.new(:mono, 16, 44100)
# old_buffer.convert!(new_format)
#
# Returns self.
def convert!(new_format)
@samples = convert_buffer(@samples, @format, new_format)
@format = new_format
return self
end
# The number of channels the buffer's sample data has
def channels
return @format.channels
end
# The bits per sample of the buffer's sample data
def bits_per_sample
return @format.bits_per_sample
end
# The sample rate of the buffer's sample data
def sample_rate
return @format.sample_rate
end
attr_reader :samples
private
def convert_buffer(samples, old_format, new_format)
unless old_format.channels == new_format.channels
samples = convert_buffer_channels(samples, old_format.channels, new_format.channels)
end
unless old_format.bits_per_sample == new_format.bits_per_sample
samples = convert_buffer_bits_per_sample(samples, old_format.bits_per_sample, new_format.bits_per_sample)
end
return samples
end
def convert_buffer_channels(samples, old_channels, new_channels)
# The cases of mono -> stereo and vice-versa are handled specially,
# because those conversion methods are faster than the general methods,
# and the large majority of wave files are expected to be either mono or stereo.
if old_channels == 1 && new_channels == 2
samples.map! {|sample| [sample, sample]}
elsif old_channels == 2 && new_channels == 1
samples.map! {|sample| (sample[0] + sample[1]) / 2}
elsif old_channels == 1 && new_channels >= 2
samples.map! {|sample| [].fill(sample, 0, new_channels)}
elsif old_channels >= 2 && new_channels == 1
samples.map! {|sample| sample.inject(0) {|sub_sample, sum| sum + sub_sample } / old_channels }
elsif old_channels > 2 && new_channels == 2
samples.map! {|sample| [sample[0], sample[1]]}
else
raise BufferConversionError,
"Conversion of sample data from #{old_channels} channels to #{new_channels} channels is unsupported"
end
return samples
end
def convert_buffer_bits_per_sample(samples, old_bits_per_sample, new_bits_per_sample)
shift_amount = (new_bits_per_sample - old_bits_per_sample).abs
more_than_one_channel = (Array === samples.first)
if old_bits_per_sample == 8
if more_than_one_channel
samples.map! do |sample|
sample.map! {|sub_sample| (sub_sample - 128) << shift_amount }
end
else
samples.map! {|sample| (sample - 128) << shift_amount }
end
elsif new_bits_per_sample == 8
if more_than_one_channel
samples.map! do |sample|
sample.map! {|sub_sample| (sub_sample >> shift_amount) + 128 }
end
else
samples.map! {|sample| (sample >> shift_amount) + 128 }
end
else
operator = (new_bits_per_sample > old_bits_per_sample) ? :<< : :>>
if more_than_one_channel
samples.map! do |sample|
sample.map! {|sub_sample| sub_sample.send(operator, shift_amount) }
end
else
samples.map! {|sample| sample.send(operator, shift_amount) }
end
end
return samples
end
end
end
| true |
8aabb1750efd3a6bec07b484b6c872fe82090af7 | Ruby | jjshanks/adventofcode-legacy | /2015/day14/part2.rb | UTF-8 | 3,524 | 3.59375 | 4 | [] | no_license | =begin
--- Day 14: Reindeer Olympics ---
This year is the Reindeer Olympics! Reindeer can fly at high speeds, but must rest occasionally to recover their energy. Santa would like to know which of his reindeer is fastest, and so he has them race.
Reindeer can only either be flying (always at their top speed) or resting (not moving at all), and always spend whole seconds in either state.
For example, suppose you have the following Reindeer:
Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds.
Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds.
After one second, Comet has gone 14 km, while Dancer has gone 16 km. After ten seconds, Comet has gone 140 km, while Dancer has gone 160 km. On the eleventh second, Comet begins resting (staying at 140 km), and Dancer continues on for a total distance of 176 km. On the 12th second, both reindeer are resting. They continue to rest until the 138th second, when Comet flies for another ten seconds. On the 174th second, Dancer flies for another 11 seconds.
In this example, after the 1000th second, both reindeer are resting, and Comet is in the lead at 1120 km (poor Dancer has only gotten 1056 km by that point). So, in this situation, Comet would win (if the race ended at 1000 seconds).
Given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, what distance has the winning reindeer traveled?
--- Part Two ---
Seeing how reindeer move in bursts, Santa decides he's not pleased with the old scoring system.
Instead, at the end of each second, he awards one point to the reindeer currently in the lead. (If there are multiple reindeer tied for the lead, they each get one point.) He keeps the traditional 2503 second time limit, of course, as doing otherwise would be entirely ridiculous.
Given the example reindeer from above, after the first second, Dancer is in the lead and gets one point. He stays in the lead until several seconds into Comet's second burst: after the 140th second, Comet pulls into the lead and gets his first point. Of course, since Dancer had been in the lead for the 139 seconds before that, he has accumulated 139 points by the 140th second.
After the 1000th second, Dancer has accumulated 689 points, while poor Comet, our old champion, only has 312. So, with the new scoring system, Dancer would win (if the race ended at 1000 seconds).
Again given the descriptions of each reindeer (in your puzzle input), after exactly 2503 seconds, how many points does the winning reindeer have?
=end
t = 2503
time_dis = {}
points = {}
File.read("input").lines.each do |line|
parts = line.match(/([A-Za-z]+) can fly ([0-9]+) .* ([0-9]+) .* ([0-9]+)/)
name = parts[1]
vel = parts[2].to_i
vt = parts[3].to_i
rt = parts[4].to_i
# func to get distance moved this second
l = lambda do |t|
mt = t % (vt + rt)
(mt > 0 and mt <= vt) ? vel : 0
end
time_dis[name] = []
points[name] = 0
dist = 0
# calc current position for every second
for ts in (1..t)
dist += l.call(ts)
time_dis[name] << dist
end
end
for ts in (0..(t-1))
lead = []
max = 0
for name in points.keys
# no leader yet
if lead.empty?
lead << name
max = time_dis[name][ts]
else
dis = time_dis[name][ts]
# replace leader/s
if dis > max
lead = [name]
max = dis
# tied leaders
elsif dis == max
lead << name
end
end
end
for name in lead
points[name] += 1
end
end
p points.values.max
| true |
08e21451adfb22762c457f2300c3fa2dbd084e7a | Ruby | javsterati/ruby-oo-object-relationships-has-many-through-atlanta-web-111819 | /lib/customer.rb | UTF-8 | 910 | 3.703125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Customer
#has many meals
#has many waiters thru said meals
attr_accessor :name
@@all = []
def initialize(name, age)
@name = name
@age = age
@@all << self
end
def new_meal(waiter,total, tip=0)
Meal.new(waiter, self, total, tip)
end
def meals
Meal.all.select do |meals|
meals.customer == self
end
end
def self.all
@@all
end
def waiters
#wouldnt this just return an array of "true"'s?
#why use map over select
meals.map do |meals|
meals.waiter
end
end
end
# def meals
# Meal.all.select do |meal|
# meal.customer == self
# end
# end
# def waiters
# meals.map do |meal|
# meal.waiter
# end
# end
# def new_meal(waiter, total, tip=0)
# Meal.new(waiter, self, total, tip)
# end | true |
82ba88a4ada4ba6eba41c5a89cfd6ca65f1a7b58 | Ruby | mgn200/imdb_playfield | /lib/imdb_playfield/netflix_dsl.rb | UTF-8 | 688 | 2.765625 | 3 | [] | no_license | module ImdbPlayfield
# DSL for easier use of filters.
# @example
# Filters movie collection stored in Netflix with DSL
# Netflix.by_country.usa => Array of movies created in USA
# @see Netflix#initilize
# @see NetflixReference
module NetflixDSL
# @param keys [Array] keys from {MovieCollection::KEYS}
# @return [NetflixReference] stores auto created by_(movie_attribute) methods, so that you can filter collection like MovieCollection.by_country "USA"
def make_attr_filters(keys)
keys.each do |key|
self.class.send(:define_method, "by_#{key}") do
ImdbPlayfield::NetflixReference.new(self, key)
end
end
end
end
end
| true |
902e83c2013a0b359dfe2e56490546d7f821e157 | Ruby | 7omich/AtCoder | /codeFlyer/B_洋菓子店.rb | UTF-8 | 265 | 3.546875 | 4 | [] | no_license | # AC
a, b, n = gets.chomp.split(' ').map(&:to_i)
x = gets.chomp
x.each_char do |c|
if c == 'S'
a -= 1 if a > 0
elsif c == 'C'
b -= 1 if b > 0
elsif c == 'E'
if a >= b && a > 0
a -= 1
elsif b > 0
b -= 1
end
end
end
p a
p b
| true |
07c035198d4ec58b24a37d4f77d076f988785096 | Ruby | ukutaht/farkle | /lib/farkle/die.rb | UTF-8 | 446 | 3.25 | 3 | [] | no_license | module Farkle
class Die
attr_accessor :scored, :value
alias_method :scored?, :scored
def initialize(opts = {})
@scored = opts.fetch(:scored) { false }
@value = opts.fetch(:value) { rand(6) + 1 }
end
def roll
self.value = rand(6) + 1
end
def mark_unscored!
self.scored = false
end
def mark_scored!
self.scored = true
end
def to_s
value.to_s
end
end
end | true |
c0c2c859e2ca124bf00b7802765d198523275cdf | Ruby | alansparrow/learningruby | /seekfileexample1.rb | UTF-8 | 153 | 2.96875 | 3 | [] | no_license | f = File.new("test1.txt", "r")
while a = f.getc
puts a.chr
f.seek(5, IO::SEEK_CUR)
end
t = File.mtime("test1.txt")
puts t.hour
puts t.min
puts t.sec | true |
42da82525aca3c9eaf676b146050e6a9edb6dc4a | Ruby | cmsrrent/ruby-training | /ex_oop_3.rb | UTF-8 | 655 | 4.28125 | 4 | [] | no_license | class Thing
# short hand way of getters and setters
# also creates class variables of same name
attr_reader :description
attr_writer :description
def initialize( aName, aDescription )
@name = aName
@description = aDescription
end
# long hand way of getters and setters
# get accessor
def name
return @name
end
# set accessor
def name=( aName )
@name = aName
end
end
t = Thing.new("The Thing", "a lovely, glittery thing")
print(t.name)
print( " is ")
puts (t.description)
t.name = "A thing"
t.description = "thats is great"
print("It has now changed its name to ")
puts t.name
print ("I would describe it as ")
puts t.description | true |
8e8878b044f4153a2400ae9ea938b02b559a3a79 | Ruby | PlasticLizard/Cubicle | /lib/cubicle/duration.rb | UTF-8 | 1,962 | 2.703125 | 3 | [
"MIT"
] | permissive | module Cubicle
class Duration < Measure
attr_accessor :duration_unit, :begin_milestone, :end_milestone, :timestamp_prefix
def initialize(*args)
super
self.duration_unit = options(:in) || :seconds
self.timestamp_prefix = options :timestamp_prefix, :prefix
self.expression_type = :javascript
#only one item should be left in the hash, the duration map
raise "duration must be provided with a hash with a single entry, where the key represents the starting milestone of a duration and the value represents the ending milestone." if options.length != 1
self.begin_milestone, self.end_milestone = options.to_a[0]
self.name ||= "#{begin_milestone}_to_#{end_milestone}_#{aggregation_method}".to_sym
end
def default_aggregation_method
:average
end
def condition
cond = " && (#{super})" unless super.blank?
"#{milestone_js(:begin)} && #{milestone_js(:end)}#{cond}"
end
def expression
#prefix these names for the expression
# prefix = "#{self.timestamp_prefix}#{self.timestamp_prefix.blank? ? '' : '.'}"
# ms1,ms2 = [self.begin_milestone,self.end_milestone].map{|ms|ms.to_s=='now' ? "new Date(#{Time.now.to_i*1000})" : "this.#{prefix}#{ms}"}
@expression = "(#{milestone_js(:end)}-#{milestone_js(:begin)})/#{denominator}"
end
private
def milestone_js(which)
prefix = "#{self.timestamp_prefix}#{self.timestamp_prefix.blank? ? '' : '.'}"
ms = self.send("#{which.to_s}_milestone")
ms.to_s=='now' ? "new Date(#{Time.now.to_i*1000})" : "this.#{prefix}#{ms}"
end
def denominator
#Date math results in milliseconds in javascript
case self.duration_unit || :seconds
when :weeks then "1000/60/60/24/7.0"
when :days then "1000/60/60/24.0"
when :hours then "1000/60/60.0"
when :minutes then "1000/60.0"
else "1000.0"
end
end
end
end | true |
dd6d84dc386902bf077ba73a3b347f1e52908d8c | Ruby | silvanagv/my-select-001-prework-web | /lib/my_select.rb | UTF-8 | 200 | 3.375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_select(collection)
select_ary = []
x = 0
while x < collection.length
if yield collection[x]
select_ary << collection[x]
end
x = x + 1
end
return select_ary
end
| true |
fae11cc9b6f10660c0b341d45303608e5b21b80e | Ruby | hhouston/appacademy-prep-master | /w2/w2d4/exercises/lib/board.rb | UTF-8 | 2,913 | 4.21875 | 4 | [] | no_license | require 'byebug'
class Board
attr_accessor :grid, :winner, :marks
def self.new_grid
Array.new(3) { Array.new(3)}
end
def initialize(grid = Board.new_grid)
@grid = grid
@winner = nil
@marks = [:X, :O]
end
def [](pos)
row, col = pos
grid[row][col]
end
def []=(pos, value)
row, col = pos
grid[row][col] = value
end
def empty?(pos)
row, col = pos
if grid[row][col] == nil
true
else
false
end
end
def place_mark(pos, mark)
if empty?(pos)
row, col = pos
@grid[row][col] = mark
end
over?
end
def winner
if row? == true || col? == true || diag? == true
@winner
else
nil
end
end
def over?
grid.flatten.none? { |pos| pos.nil? } || winner
end
def row?
(0..2).each do |i|
x_idx = 0
o_idx = 0
(0..2).each do |j|
if grid[i][j] == :X
x_idx += 1
if x_idx == 3
@winner = :X
return true
end
elsif grid[i][j] == :O
o_idx += 1
if o_idx == 3
@winner = :O
return true
end
end
end
end
false
end
def col?
(0..2).each do |j|
x_idx = 0
o_idx = 0
(0..2).each do |i|
if grid[i][j] == :X
x_idx += 1
if x_idx == 3
@winner = :X
return true
end
elsif grid[i][j] == :O
o_idx += 1
if o_idx == 3
@winner = :O
return true
end
end
end
end
false
end
def diag?
x_idx = 0
o_idx = 0
(0..2).each do |i|
if grid[i][i] == :X
x_idx += 1
if x_idx == 3
@winner = :X
return true
end
elsif grid[i][i] == :O
o_idx += 1
if o_idx == 3
@winner = :O
return true
end
elsif grid[i][2-i] == :X
x_idx += 1
if x_idx == 3
@winner = :X
return true
end
elsif grid[i][2-i] == :O
o_idx += 1
if o_idx == 3
@winner = :O
return true
end
end
end
false
end
end
# board = Board.new
# #
# board.place_mark([0,0], :O)
# board.place_mark([0,1], :O)
# board.place_mark([0,2], :O)
#
#
# #
# #
# board.over?
# p board.winner
# p board
#
# place_mark, which takes a position such as [0, 0] and a mark such as :X as arguments. It should throw an error if the position isn't empty.
# empty?, which takes a position as an argument
# winner, which should return a mark
# over?, which should return true or false
# If you want to be a little fancy, read the attached bracket-methods reading.
# def [](pos)
# row, col = pos
# @grid = [row][col]
# p "[] called"
# end
# def []=(pos, value)
# row, col = pos
# @grid[row][col] = value
# end | true |
80b95aad8f40bc5e010ef41e6fa1ad1bbb30a50d | Ruby | marwahaha/rasta | /label.rb | UTF-8 | 966 | 2.765625 | 3 | [] | no_license | class Label < String
def fetch_as_constant env
context = env.lookup("self")
case self
when /\A::/
self.gsub(/\A::/, '').fetch_as_constant Kernel
when /::/
self.split(/::/).inject(context) do |m, e|
m.const_get(e)
end
else
context.const_get(self)
end
end
def lispeval env, forms
if self[/\A(::)|[A-Z]/]
fetch_as_constant env
elsif self[/\A(@.+)=/]
proc{|value| env.lookup("self").instance_variable_set($1, value)}
elsif self[/\A@.+/]
env.lookup("self").instance_variable_get(self)
else
normal_lookup = env.lookup(self) # this is so we can lookup "nil" in env and receive nil
if (normal_lookup == false and self != "false")
return forms.lookup(self) || env.lookup("self").method(self) # if the symbol isn't found we call it as a method on the context
else
return normal_lookup
end
end
end
def print_form
self
end
end
| true |
5876d0fefb4a1d400394c544e45a653e6b387ca6 | Ruby | marcallan34/learn_ruby | /01_temperature/temperature.rb | UTF-8 | 168 | 3.609375 | 4 | [] | no_license | #write your code here
def ftoc(fahrenheit)
final = (fahrenheit - 32)/1.8
return final.ceil
end
def ctof(celsius)
final = (celsius * 1.8) + 32
return final
end
| true |
2eb3fcac06a6c393f5e12e43ef903df885cdfbf0 | Ruby | SHiroaki/Ruby | /prac/control.rb | UTF-8 | 660 | 4.125 | 4 | [] | no_license | # coding: utf-8
=begin
真:falseとnil以外すべて
偽:falseとnil
真偽値を返すメソッドの末尾には?をつける
=end
a = 20
if a >= 10 then
print("bigger\n")
end
#if 条件 then(thenは省略できる)
# do
#end(忘れがち)
#が基本
a = 8
if a > 10 then
print "bigger\n"
else
print "smaller\n"
end
#繰り返し
i = 1
while i <= 10
print i, "\n"
i += 1
end
# times 繰り返す回数が決まっている場合の処理
# イテレータ
=begin
繰り返す回数.times do
処理
end
=end
10.times do
print "Apple\n"
end
# メソッドの作成
def hello
print "hello\n"
end
5.times do
print hello()
end
| true |
47be8c45b2911c76fac1a598f6c563a26640f178 | Ruby | psagan/slackbot-rubydoc | /lib/client/websocket_request_data.rb | UTF-8 | 1,570 | 3.03125 | 3 | [] | no_license | # This class is responsible for handling websocket request data - which will be
# send to websocket
module Client
class WebsocketRequestData
# instance attribute on singleton's class
@id = 0
# here we have class method
class << self
# Public: returns incremented id - to have it
# unique within one bot run
#
# Returns Integer
def id
@id += 1
end
end
# Public: initialize
#
# Hash - with params which are required:
# :message - message to send
# :data - data from websocket as Parameter Object
#
def initialize(params)
@data = params.fetch(:data)
@message = params.fetch(:message)
end
# Public: responsible for preparing data to send to websocket
#
# String - response from bot
#
# Returns String.
def data_to_send
output_data = {
id: id,
type: 'message', # hardcoded type here as not needed to on this stage
# to have additional layer for handling that
channel: data.channel,
text: message
}
prepare_outcome_data(output_data)
end
private
# Internal: responsible for preparing outcome data
# which should be in JSON format in this case.
#
# Returns String.
def prepare_outcome_data(data)
JSON.generate(data)
end
# Internal: Instance proxy for using class method to fetch id
#
# Returns Integer.
def id
self.class.id
end
attr_reader :data, :message
end
end | true |
e580aa9c216116e566715ac292afb9a1c6a29bdc | Ruby | chelsten/mini-project-2 | /mp2.rb | UTF-8 | 1,500 | 3.828125 | 4 | [] | no_license | require 'csv'
require './crud_function'
class Employee
def show_menu
puts "Welcome to Company Directory Management System: "
puts "1 - Add new employee"
puts "2 - Read existing employee"
puts "3 - Update existing employee"
puts "4 - Delete existing employee"
input = gets.chomp
case input
when '1'
add
when '2'
read
when '3'
update
when '4'
delete
end
end
# done
def add
crud_function = CrudFunction.new
puts "Type in your name here:"
name = gets.chomp
puts "Type in your age here:"
age = gets.chomp
puts "Type in your department here:"
dept = gets.chomp
emp = [name, age, dept]
crud_function.save_to_csv(emp)
puts "Employee record has been added. #{name} from department."
end
# done
def read
crud_function = CrudFunction.new
crud_function.read_from_csv
end
def update
crud_function = CrudFunction.new
puts "Enter employee to update: "
employee = gets.chomp
puts "Update new name:"
name = gets.chomp
puts "Update age:"
age = gets.chomp
puts "Update department:"
dept = gets.chomp
emp = [name, age, dept]
crud_function.update_csv(employee, emp)
end
def delete
crud_function = CrudFunction.new
puts "Type the employee you want to delete:"
name = gets.chomp
crud_function.destroy(name)
puts "Employee #{name} have been deleted."
end
end
start = Employee.new
start.show_menu | true |
ae28b79f11bf013d73db88f5006c8bee1e144037 | Ruby | danielacodes/numerology-app | /spec/people_show_spec.rb | UTF-8 | 794 | 2.5625 | 3 | [] | no_license | require 'spec_helper'
describe "Our Person Show Route" do
include SpecHelper
before (:all) do
@person = Person.create(first_name: "Miss", last_name: "Piggy", birthday: DateTime.now.utc - 40.years )
@birth_path_num = Person.get_birth_path_number(@person.birthday.strftime("%m%d%Y"))
end
after (:all) do
@person.delete
end
it "displays a page with the person's name when we visit /people/:id" do
get("/people/#{@person.id}")
expect(last_response.body.include?("#{@person.first_name} #{@person.last_name}")).to be(true)
end
it "displays the numerology result on /people/:id page" do
get("/people/#{@person.id}")
message = SpecHelper::NUMEROLOGY["#{@birth_path_num}"][:message]
expect(last_response.body.include?(message)).to be(true)
end
end
| true |
2c843598663e012f009b213f4dea744095208cfb | Ruby | mattdillabough/reddish_rails | /app/models/user.rb | UTF-8 | 1,072 | 2.515625 | 3 | [] | no_license | class User < ActiveRecord::Base
has_many :votes
has_many :links, through: :votes
has_one :reset_token
RE_USERNAME = /\A[A-Za-z0-9_.]+\z/
RE_EMAIL = /\A[A-Za-z0-9_.]+@[A-Za-z0-9_.]+\z/
# This association declaration is the inverse of the "belongs_to" on the link.rb
# It indicates that a given object of type User, let's call him user_a, has a collection
# of links. So:
#
# user_a.links
#
# Is valid code. There are lots of methods that get added to the User class by creating
# a has_many association. Search Google for "Rails has_many methods".
has_many :links
validates :email, presence: true, uniqueness:true, format: {with: RE_EMAIL, message: "must be a valid email"}
validates :username, presence: true, uniqueness: true, length: {minimum: 4, maximum: 20}, format: {with: RE_USERNAME, message: "must contain only letters, digits and underscore"}
has_secure_password
def self.find_by_email_or_username(email_or_username)
User.find_by(email: email_or_username) || User.find_by(username: email_or_username)
end
end | true |
6dee57af474eae4bd7e4ff73e07ab5f649c6931d | Ruby | brenufernandes/Homework3 | /Hw3.rb | UTF-8 | 2,036 | 4.59375 | 5 | [] | no_license | =begin
Breno Fernandes de Andrade - CS270. Assignment #3
Description: Checkout of books using class concept
input: Book's title and name
Output: Checkout book's name
=end
#The class book is used for the constructor to attribute the variable book name and the writer
class Book
#User the method attr_reader and attr_acessor to read and provide acessor methods for the istance variable
attr_reader :title, :writer
attr_accessor :title, :checked_out
#Initialize take the information of the construction and put in the variable
def initialize(bookName,writer)
@title = bookName
@writer = writer
end
#This method is used to set the status of the book: True= book off, False= book on.
def self.checked_out
@@checked_out = false
end
end
######################## # Book class goes here, # before Library class ########################
# Library: manages Books as an array
# public methods: add, checkout, which_out? # instance variables: @books (Array)
class Library
# constructor: initializes an empty array # parameters: n/a
# return value: n/a
def initialize
@books = Array.new
end
# add: shifts a Book onto the @books Array # parameters: a Book
# return value: n/a
def add(b)
@books << b
end
# checkout: sets the checked_out flag to true for a Book # parameters: a Book
# return value: n/a
def checkout(b)
@books.each do |book|
book.checked_out = true if book.title == b
end
end
# which_out?: prints out a list of Books that are checked out # parameters: n/a
# return value: n/a
def which_out?
@books.each do |book|
puts book.title if book.checked_out
end
end
end
# initialize a new Library
lib = Library.new
# create some Books
book1 = Book.new("The Wind in the Willows", "Kenneth Grahame")
book2 = Book.new("The Hobbit", "J. R. R. Tolkien")
book3 = Book.new("Clear Waters Rising", "Nicholas Cane")
# add those Books to the Library
lib.add(book1)
lib.add(book2)
lib.add(book3)
# checkout a couple Books by title
lib.checkout(book2.title)
lib.checkout(book1.title)
# list which Books are out
lib.which_out? | true |
66e0c1c69d8e80960e121ee6ee67ad473cda2b3d | Ruby | Javier-Machin/music-beast-manager-api | /app/controllers/concerns/response.rb | UTF-8 | 577 | 2.609375 | 3 | [] | no_license | module Response
def json_response(object, status = :ok, serializer = '')
if (serializer == 'index')
object[:tracks] = object[:tracks].map do |track|
{
id: track.id,
title: track.title,
artist: track.artist,
created_by: track.created_by
}
end
end
if (serializer == 'lyrics')
filtered_track = {
lyrics: object.lyrics,
title: object.title,
artist: object.artist
}
object = filtered_track
end
render json: object, status: status
end
end | true |
a398e0159181cbb34055d1f34c0da311c536dab5 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/grade-school/61441e359cc945efb5ee9c79d20a1994.rb | UTF-8 | 312 | 3.34375 | 3 | [] | no_license | class School
attr_reader :db
def initialize
@db = Hash.new { Array.new }
end
def add(name, grade)
db[grade] = db[grade] + [name]
end
def grade(grade)
db[grade]
end
def sort
Hash[
db.map { |grade, students| [grade, students.sort] }.sort
]
end
end
| true |
2e19646b3ad163a94c81a8c92e4a537a482d51c9 | Ruby | kathleen-carroll/flash_cards | /lib/deck.rb | UTF-8 | 440 | 3.4375 | 3 | [] | no_license | class Deck
attr_reader :deck, :cards
def initialize(cards)
@cards = cards
#@deck = []
end
# def add_card(cards)
# @deck << cards
# end
def count
@deck.count
end
def cards_in_category(category)
@cards.find_all do |card|
#require "pry"; binding.pry
category == card.category
end
end
end
# cards = [@card1, @card2, @card3]
# deck = Deck.new(@cards)
# p deck.cards_in_category(:STEM)
| true |
16be7c8ee2e6e41c6ae7b263ca9476bb220568fd | Ruby | halo/LinkLiar | /lib/macs/vendor.rb | UTF-8 | 2,357 | 2.59375 | 3 | [
"LicenseRef-scancode-free-unknown",
"MIT"
] | permissive | module Macs
class Vendor
def initialize(name:)
@name = name
@prefixes = []
end
def name
return 'Cisco' if @name == 'Cisco Systems'
return 'Huawei' if @name == 'Huawei Technologies'
return 'Samsung' if @name == 'Samsung Electronics'
return 'HP' if @name == 'Hewlett Packard'
return 'TP-Link' if @name == 'TP-LINK Technologies'
return 'LG' if @name == 'Lg Electronics Mobile Communications'
return 'Vivo' if @name == 'Vivo Mobile Communication'
return 'Asustek' if @name == 'Asustek Computer'
return 'Sony' if @name == 'Sony Mobile Communications'
return 'Motorola' if @name == 'Motorola Mobility Llc A Lenovo Company'
return 'D-link' if @name == 'D-link International'
return 'Xiaomi' if @name == 'Xiaomi Communications'
@name
end
def id
return 'cocacola' if name.include?('Coca')
name.gsub(/[^0-9a-z ]/i, '').downcase.split.first
end
def to_s
[name, id, prefixes.count].join(' – ')
end
def to_swift
# E.g. `"ibm": ["IBM": [0x3440b5,0x40f2e9,0x98be94,0xa897dc]],`
%| // #{@name} #{prefixes.join(',')}| + "\n" +
%| "#{id}": ["#{name}": [#{prefixes.map { "0x#{_1.to_i(16).to_s(16).to_s.rjust(6, '0')}" }.join(',')}]],|
end
def add_prefix(prefix)
prefixes.push prefix.downcase
end
def popular?
return true if name == 'Coca Cola Company' # I think this is just funny
return true if name == 'Nintendo' # This too, really
return true if name == '3com'
return true if name == 'HTC'
return true if name == 'Ibm'
return true if name == 'Ericsson'
return false if denylist.any? { name.include?(_1) }
return false if name == 'Huawei Device' # Honestly don't know what it is
return true if prefixes.count > 50
end
def <=>(other)
other.count <=> count
end
def count
prefixes.count
end
private
attr_reader :prefixes
# Excluding what naturally could not be a Mac.
def denylist
%w[
Arris
IEEE
Foxconn
Juniper
Fiberhome
Sagemcom
Private
Guangdong
Nortel
Amazon
Ruckus
Technicolor
Liteon
Avaya
Espressif
]
end
end
end
| true |
01418731f7ea96bcbcc8e6b56e9a602e2a30321b | Ruby | DYDamaschke/Launch_School | /exercises_small_problems/Easy_3/arithmetic.rb | UTF-8 | 301 | 3.4375 | 3 | [] | no_license | operators = %w(+ - / * % **)
puts "=> Please enter the first number: "
number1 = gets.chomp.to_f
puts "=> Please enter the second number: "
number2 = gets.chomp.to_f
operators.each do |operator|
puts "#{number1} #{operator} #{number2} = " +
"#{eval("#{number1}#{operator}#{number2}")}"
end | true |
7aa4e2de68f0a8f9cf21d14382b6a943330071a3 | Ruby | threedaymonk/uk_postcode | /spec/giro_postcode_spec.rb | UTF-8 | 2,088 | 2.875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"OGL-UK-3.0"
] | permissive | require "uk_postcode/giro_postcode"
describe UKPostcode::GiroPostcode do
let(:subject) { described_class.instance }
describe ".parse" do
it "parses the canonical form" do
pc = described_class.parse("GIR 0AA")
expect(pc).to be_instance_of(described_class)
end
it "parses transcribed 0/O and 1/I" do
pc = described_class.parse("G1R OAA")
expect(pc).to be_instance_of(described_class)
end
it "handles extra spaces" do
pc = described_class.parse(" GIR 0AA ")
expect(pc).to be_instance_of(described_class)
end
it "handles no spaces" do
pc = described_class.parse("GIR0AA")
expect(pc).to be_instance_of(described_class)
end
it "is case-insensitive" do
pc = described_class.parse("gir 0aa")
expect(pc).to be_instance_of(described_class)
end
it "returns nil if unable to parse" do
pc = described_class.parse("Can't parse this")
expect(pc).to be_nil
end
end
describe "#area" do
it "is nil" do
expect(subject.area).to be_nil
end
end
describe "#district" do
it "is nil" do
expect(subject.district).to be_nil
end
end
describe "#sector" do
it "is nil" do
expect(subject.sector).to be_nil
end
end
describe "#unit" do
it "is nil" do
expect(subject.unit).to be_nil
end
end
describe "#outcode" do
it "is GIR" do
expect(subject.outcode).to eq("GIR")
end
end
describe "#incode" do
it "is 0AA" do
expect(subject.incode).to eq("0AA")
end
end
describe "#to_s" do
it "is the canonical form" do
expect(subject.to_s).to eq("GIR 0AA")
end
end
describe "#full?" do
it "is true" do
expect(subject).to be_full
end
end
describe "#valid?" do
it "is true" do
expect(subject).to be_valid
end
end
describe "#full_valid?" do
it "is true" do
expect(subject).to be_full_valid
end
end
describe "#country" do
it "is England" do
expect(subject.country).to eq(:england)
end
end
end
| true |
69d63087e50c062ef132e40b0925d849f54b03ec | Ruby | akoliag/katas | /CODEWARS/Exercise_53_add_words.rb | UTF-8 | 821 | 3.96875 | 4 | [] | no_license | # https://www.codewars.com/kata/adding-words-part-i/train/ruby
class Arith
def initialize(base)
@base = base
end
def add(word)
collection = {
1=> "one",
2=> "two",
3=> "three",
4=> "four",
5=> "five",
6=> "six",
7=> "seven",
8=> "eight",
9=> "nine",
10=> "ten",
11=> "eleven",
12=> "twelve",
13=> "thirteen",
14=> "fourteen",
15=> "fifteen",
16=> "sixteen",
17=> "seventeen",
18=> "eighteen",
19=> "nineteen",
20=> "twenty"
}
result = collection.key(word) + collection.key(@base)
collection[result]
end
end
| true |
5f3a0ec6ab622a97747a1e1152822c58b3ad0e5e | Ruby | ezy023/easy_challenges | /41.rb | UTF-8 | 244 | 3.0625 | 3 | [] | no_license | puts "Enter a sentence to see it pretty"
sentence = gets.chomp
puts '*' * (sentence.length+4)
puts '*' + (' ' * (sentence.length+2)) + '*'
puts '* ' + sentence + ' *'
puts '*' + (' ' * (sentence.length+2)) + '*'
puts '*' * (sentence.length+4)
| true |
bce5f90e4892cb9b7c65a790a7f286dd5553bcf9 | Ruby | mintyfresh/pone-points | /app/forms/create_group_form.rb | UTF-8 | 937 | 2.53125 | 3 | [] | no_license | # frozen_string_literal: true
class CreateGroupForm < ApplicationForm
# @return [Pone]
attr_accessor :owner
attribute :name, :string
attribute :description, :string
validates :owner, presence: true
validates :name, presence: true, length: { maximum: Group::NAME_MAX_LENGTH }
validates :description, length: { maximum: Group::DESCRIPTION_MAX_LENGTH }
validate :must_be_verified_to_create_groups
# @return [Group]
def perform
super do
owner.with_lock do
enforce_maximum_owned_groups_limit!
owner.owned_groups.create!(name: name, description: description)
end
end
end
private
# @return [void]
def must_be_verified_to_create_groups
errors.add(:base, :must_be_verified) unless owner.verified?
end
# @return [void]
def enforce_maximum_owned_groups_limit!
errors.add(:base, :too_many_owned_groups) and throw(:abort) if owner.owned_groups.count >= 5
end
end
| true |
264653c10fb5a4470cc4ff4b685cafc97a8c4219 | Ruby | sparsons808/W2D5 | /todo/item.rb | UTF-8 | 834 | 3.140625 | 3 | [] | no_license | class Item
attr_accessor :title, :description
attr_reader :deadline
def self.valid_date?(date_str)
month = ('01'..'12').to_a
day = ('01'..'31').to_a
if month.include?(date_str[5..6]) && day.include?(date_str[-2..-1])
return true
else
return false
end
end
def initialize(title, deadline, description='')
if Item.valid_date?(deadline)
@deadline = deadline
else
raise 'error invalid date try entering YYYY-MM-DD'
end
@title = title
@description = description
end
def deadline=(new_deadline)
if Item.valid_date?(new_deadline)
@deadline = new_deadline
else
raise 'error invalid date try entering YYYY-MM-DD'
end
end
end | true |
3bc59a3d633c26274790b5ebfaa2784ba080672a | Ruby | garcia50/idea_box | /spec/features/users/authentication_user_spec.rb | UTF-8 | 3,150 | 2.59375 | 3 | [] | no_license | require 'rails_helper'
describe "As an unathenticted use" do
describe "when I visit the landing page I see a create a new user link" do
scenario "when I click on the link I can create an account" do
visit root_path
click_on 'Create An Account'
expect(current_path).to eq(new_user_path)
expect(page).to have_content("If its free its fo me!")
fill_in "user[name]", with: "Ed"
fill_in "user[email]", with: "muf@fin.com"
fill_in "user[password]", with: "muffin"
click_on "Create User"
expect(current_path).to eq(user_path(User.last))
expect(page).to have_content("Welcome, Ed!")
end
end
describe "when a user signs up with an existing account" do
scenario "the user is redirected to the new_path with a prompt to enter a new username" do
visit new_user_path
User.create!(name: "luisg", email: "woot", password: "test")
fill_in "user[name]", with: "luisg"
fill_in "user[email]", with: "woot"
fill_in "user[password]", with: "test"
click_on "Create User"
expect(page).to have_content("This email already exists in our database!")
end
end
describe "As an athenticated user" do
describe "when I visit homepage I see a sign in link" do
scenario "when I click on the link I can access the existing users account" do
user = User.create!(name: "luisg", email: "woot", password: "test")
visit root_path
click_on 'Login'
expect(current_path).to eq(login_path)
fill_in "name", with: user.name
fill_in "email", with: user.email
fill_in "password", with: user.password
click_on "Log In"
expect(current_path).to eq(user_path(user))
expect(page).to have_content("Welcome, #{user.name}!")
expect(page).to have_content("Logout")
end
end
end
describe "As an athenticated user" do
describe "when I login I see a logout link" do
scenario "when I click on logout my session is closed" do
user = User.create!(name: "luisg", email: "woot", password: "test")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit user_path(user)
click_on 'Logout'
expect(current_path).to eq(root_path)
expect(page).to have_content("Login")
expect(page).to have_content("Create An Account")
end
end
end
describe "As an athenticated user" do
describe "when I log into a new session" do
scenario "I cannot visit another users session" do
user = User.create!(name: "luisg", email: "woot", password: "test")
user_2 = User.create!(name: "dang", email: "toot", password: "pass")
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
visit user_path(user)
expect(page).to have_content(user.name)
visit '/users/2'
expect(page).to have_content(user.name)
expect(page).to have_content(user.name)
end
end
end
end
| true |
b4f801ae5571a02a27689fc3923823243e29b905 | Ruby | dallinder/small_problems_ls | /easy_7/3.rb | UTF-8 | 153 | 3.40625 | 3 | [] | no_license | def word_cap(string)
words = string.split
words.map do |word|
word.capitalize!
end
words.join(' ')
end
puts word_cap('four score and seven') | true |
a21ac32d7c186a97bcca3044adade16c345b9cac | Ruby | brunoao86/radar-talentos-wine | /09_iteracoes/1_while.rb | UTF-8 | 64 | 3.3125 | 3 | [] | no_license | x = 10
while x > 0 do
puts "valor de x: #{ x }"
x -= 1
end
| true |
4ab0e65b8594bd5e7cc4a3e917bc3b6415c3eb22 | Ruby | chrisswk/advanced_calculator | /simplifiers/evaluation_simplifier.rb | UTF-8 | 228 | 2.765625 | 3 | [
"MIT"
] | permissive | class EvaluationSimplifier
def self.run(tree)
if tree.operator? && tree.left.numeric? && tree.right.numeric?
tree.class.new tree.operator.call(tree.left.value, tree.right.value)
else
tree
end
end
end
| true |
77efb98bd3baafdb01138c3108672451e456998d | Ruby | panjiw/Team-Player | /app/controllers/users_controller.rb | UTF-8 | 7,016 | 2.515625 | 3 | [] | no_license | #
# TeamPlayer -- 2014
#
# This file deals with creating a user and signing him in.
# It returns a status code indicating success or failure,
# as well as a list of reasons for failure if necessary
#
class UsersController < ApplicationController
before_action :signed_in_user, only: [:viewgroup, :view_pending_groups, :edit_password, :edit_username, :edit_name, :edit_email, :finduseremail, :update]
# Create a new user and sign user in
def create
@user = User.new(user_params)
if @user.save
# adding a self group
name = 'Me (' + params[:user][:username] + ')'
@user.groups.create(name: name, description: 'Assign task/bills to the Me group, if those task/bills are for yourself',
creator: @user.id, self: true)
token = view_context.sign_in @user
render :json => {:token => token}, :status => 200
else
render :json => @user.errors.full_messages, :status => 400
end
end
# changes password
# Edit a signed-in user's information
# Input:
# :edit => { :password => (old password), :new_password => (new password), :new_password_confirmation => (new password)}
# Output:
# If correct old password and new passwords match and are the correct length, changes the password with status 200
# Else, returns the JSON error with status 400
def edit_password
@user = current_user
if @user.authenticate(params[:edit][:password])
userinfo = {:username => @user.username, :firstname => @user.firstname, :lastname => @user.lastname, :email => @user.email,
:password => params[:edit][:new_password], :password_confirmation => params[:edit][:new_password_confirmation]}
if @user.update_attributes(userinfo)
render :json => {}, :status => 200
else
render :json => @user.errors.full_messages, :status => 400
end
else
render :json => ["incorrect password"], :status => 400
end
end
# edit username
# Edit a signed-in user's information
# Input:
# :edit => { :password => (password), :username => (new username)}
# Output:
# If correct password and username is not taken, changes the username with status 200
# Else, returns the JSON error with status 400
def edit_username
@user = current_user
if @user.authenticate(params[:edit][:password])
userinfo = {:username => params[:edit][:username], :firstname => @user.firstname, :lastname => @user.lastname, :email => @user.email,
:password => params[:edit][:password], :password_confirmation => params[:edit][:password]}
if @user.update_attributes(userinfo)
group = Group.find_by(:creator => @user.id, :self => true)
name = 'Me (' + params[:edit][:username] + ')'
gpinfo = {:name => name,
:description => 'Assign task/bills to the Me group, if those task/bills are for yourself',
:creator => group.creator,
:self => group.self}
group.update_attributes(gpinfo)
render :json => {}, :status => 200
else
render :json => @user.errors.full_messages, :status => 400
end
else
render :json => ["incorrect password"], :status => 400
end
end
# edit name
# Edit a signed-in user's information
# Input:
# :edit => { :password => (password), :firstname => (new firstname), :lastname => (new lastname)}
# Output:
# If correct password, changes the username with status 200
# Else, returns the JSON error with status 400
def edit_name
@user = current_user
if @user.authenticate(params[:edit][:password])
userinfo = {:username => @user.username, :firstname => params[:edit][:firstname], :lastname => params[:edit][:lastname], :email => @user.email,
:password => params[:edit][:password], :password_confirmation => params[:edit][:password]}
if @user.update_attributes(userinfo)
render :json => {}, :status => 200
else
render :json => @user.errors.full_messages, :status => 400
end
else
render :json => ["incorrect password"], :status => 400
end
end
# edit email
# Edit a signed-in user's information
# Input:
# :edit => { :password => ( password), :email => (new email)}
# Output:
# If correct password and new email is not taken and is an email format, changes the password with status 200
# Else, returns the JSON error with status 400
def edit_email
@user = current_user
if @user.authenticate(params[:edit][:password])
userinfo = {:username => @user.username, :firstname => @user.firstname, :lastname => @user.lastname, :email => params[:edit][:email],
:password => params[:edit][:password], :password_confirmation => params[:edit][:password]}
if @user.update_attributes(userinfo)
render :json => {}, :status => 200
else
render :json => @user.errors.full_messages, :status => 400
end
else
render :json => ["incorrect password"], :status => 400
end
end
# # Updates user information after editting
# # If update is successful, status 200.
# # Else, status 400
# def update
# @user = current_user
# if @user.update_attributes(user_params)
# render :json => {}, :status => 200
# else
# render :json => @user.errors.full_messages, :status => 400
# end
# end
# find user by email
def finduseremail
@user = User.where("email = ?", params[:find][:email])
if !@user.empty?
render :json => @user.first.to_json(:except => [:created_at, :updated_at,
:password_digest, :remember_token]), :status => 200
#:json => {:user => @user :except=>
# [:created_at, :updated_at,
# :password_digest, :remember_token]
# }
#, :status => 200
else
render :nothing => true, :status => 400
end
end
#viewgroup-> give all groups login user is in, and for each group includes all
# t he users of that group, excluding private infos
def viewgroup
groups = current_user.groups
render :json => groups.to_json(:include => {
:users => {:except => [:created_at, :updated_at, :password_digest, :remember_token]},
:pending_users => {:except => [:created_at, :updated_at,:password_digest, :remember_token]
}}), :status => 200
end
def viewpendinggroups
groups = current_user.pending_groups
render :json => groups.to_json(:include => {
:users => {:except => [:created_at, :updated_at, :password_digest, :remember_token]},
:pending_users => {:except => [:created_at, :updated_at,:password_digest, :remember_token]
}}), :status => 200
end
private
# Make sure the params sent in is valid (see User Rep Inv)
def user_params
params.require(:user).permit(:username, :firstname, :lastname, :email, :password, :password_confirmation)
end
# Requires sigged-in user
def signed_in_user
redirect_to '/', notice: "Please sign in." unless signed_in?
end
end
| true |
1f202f404d958ac0d1f97cb6319aa44042acde88 | Ruby | arjunchib/aoc2020 | /day2/part1.rb | UTF-8 | 399 | 3.0625 | 3 | [] | no_license | def process(file)
lines = File.readlines(file)
lines.map {|line| validate(line) ? 1 : 0}.sum
end
def validate(line)
policy,password = line.split(': ')
range,term = policy.split(' ')
lower,upper = range.split('-').map {|a| a.to_i}
count = password.count(term)
lower <= count and count <= upper
end
if __FILE__ == $0
# puts process('example.txt')
puts process('passwords.txt')
end
| true |
f6532596934455fe89f673f5dba041769fd9e267 | Ruby | Brahimndaw/simple-loops-001-prework-web | /simple_looping.rb | UTF-8 | 848 | 4.15625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # REMEMBER: print your output to the terminal using 'puts'
def loop_iterator(number_of_times)
phrase = "Welcome to Flatiron School's Web Development Course!"
count = 0
loop do
puts phrase
count += 1
break if count == 7
end
end
def times_iterator(number_of_times)
7.times do
puts "Welcome to Flatiron School's Web Development Course!"
end
end
def while_iterator(number_of_times)
count = 0
while count < 7
puts "Welcome to Flatiron School's Web Development Course!"
count += 1
end
end
def until_iterator(number_of_times)
phrase = "Welcome to Flatiron School's Web Development Course!"
count= 0
until count == 7
puts phrase
count += 1
end
end
def for_iterator(number_of_times)
phrase = "Welcome to Flatiron School's Web Development Course!"
for i in (1..7) do
puts phrase
end
end
| true |
6d0a43bcc93ab95f83492264bf7fe900eb158a0e | Ruby | learn-co-students/atlanta-web-021720 | /05-oo-review/tools/console.rb | UTF-8 | 329 | 2.6875 | 3 | [] | no_license | require_relative '../config/environment.rb'
# Recipes
recipe_one = Recipe.new("rice_casserole")
recipe_two = Recipe.new("hot_dog")
recipe_three = Recipe.new("beans")
# Users
user_one = User.new("sam", "thomas")
# Ingredients
beans = Ingredient.new("beans")
# Allergies
peanut = Allergy.new(user_one, beans)
binding.pry
| true |
997972565a6b2b615f3dce73cb5c98a7edc7f8fd | Ruby | elinaDangol/jan24 | /spec/app/models/book_spec.rb | UTF-8 | 547 | 3.125 | 3 | [] | no_license | # Book.length("computer science")
# => 16
require 'rails_helper'
describe Book do
describe '.length' do
context 'when user provides book name' do
subject(:length) { described_class.length("computer science") }
it 'gives length of the book' do
expect(length).to eql(16)
end
end
context 'when user provides other than string' do
subject(:length) { described_class.length(11) }
it 'gives error message' do
expect(length).to eql('Invalid name')
end
end
end
end | true |
22842b193d39217bd36e0cf6855c1da287ae14a5 | Ruby | mitcha16/SalesEngine | /test/invoice_items_repo_test.rb | UTF-8 | 5,318 | 2.59375 | 3 | [] | no_license | require_relative '../test/test_helper'
class InvoiceItemsRepoTest < Minitest::Test
def setup
@file = File.expand_path("../test/fixtures/invoice_items.csv", __dir__)
end
def test_it_can_hold_a_new_invoice_item
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
refute repo.instances.empty?
end
def test_it_can_return_correct_size
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
result = repo.all
assert_equal 13 , result.size
end
def test_it_returns_all_invoice_items
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
result = repo.all
result.map do |invoice|
assert_equal InvoiceItem, invoice.class
end
end
def test_it_can_find_random
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.instances
random = repo.random
invoice_items.delete(random)
refute repo.all.include?(random)
end
def test_it_can_find_an_instance_based_off_of_id
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_id(2)
assert_equal 9, result.quantity
end
def test_it_can_find_an_instance_based_off_of_quantity
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_quantity(9)
assert_equal 2, result.id
end
def test_it_can_find_all_instances_based_off_of_quantity
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_all_by_quantity(5)
assert_equal 3 , result.size
end
def test_it_can_find_all_instances_based_off_of_unit_price
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_all_by_unit_price(BigDecimal.new("136.35"))
assert_equal 4 , result.size
end
def test_it_can_find_an_instance_based_off_of_unit_price
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_unit_price(BigDecimal.new("233.24"))
assert_equal 2 , result.item_id
end
def test_it_can_find_an_instance_based_off_of_invoice_id
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_invoice_id(8)
assert_equal 5 , result.quantity
end
def test_it_can_find_all_instances_based_off_of_invoice_id
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_all_by_invoice_id(1)
assert_equal 1 , result.size
end
def test_it_can_find_an_instance_based_off_of_created_at
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_created_at("2012-03-27 14:54:09 UTC")
assert_equal 1, result.id
end
def test_it_can_find_an_instance_based_off_updated_at
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_by_updated_at("2012-03-27 14:54:09 UTC")
assert_equal 1, result.id
end
def test_it_can_find_all_instances_based_off_of_id
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoices_items = repo.manage
result = repo.find_all_by_id(2)
assert_equal 9, result[0].quantity
end
def test_it_can_find_all_instances_based_off_of_created_at
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_all_by_created_at("2012-03-27 14:54:09 UTC")
assert_equal 13, result.size
end
def test_it_can_find_all_instances_based_off_of_updated_at
data = FileReader.new.read(@file)
repo = InvoiceItemsRepository.new(data, "sales_engine")
invoice_items = repo.manage
result = repo.find_all_by_updated_at("2012-03-27 14:54:09 UTC")
assert_equal 13, result.size
end
def test_it_can_move_instances_up_to_its_sales_engine_for_items
engine = Minitest::Mock.new
repo = InvoiceItemsRepository.new([{id: 2, name: "Joe", unit_price:"455555", created_at: "2012-03-26 09:54:09 UTC",
updated_at: "2012-03-26 09:54:09 UTC"}], engine)
engine.expect(:find_an_invoice_by_invoice_id, [], [2])
repo.find_an_invoice_by_invoice_id(2)
engine.verify
end
def test_it_can_move_instances_up_to_its_sales_engine_for_items
engine = Minitest::Mock.new
repo = InvoiceItemsRepository.new([{id: 2, name: "Joe", item_id: 3, unit_price:"455555", created_at: "2012-03-26 09:54:09 UTC",
updated_at: "2012-03-26 09:54:09 UTC"}], engine)
engine.expect(:find_an_item_by_item_id, [], [3])
repo.find_an_item_by_item_id(3)
engine.verify
end
end
| true |
34905e4cf83b5c0d0ae923f766c1e0d0e27c76f8 | Ruby | LeoBorquez/Stock | /app/models/stock.rb | UTF-8 | 535 | 2.578125 | 3 | [] | no_license | class Stock < ApplicationRecord
has_many :user_stocks
has_many :users, through: :user_stocks
def self.find_by_ticker(ticker_symbol)
where(ticker: ticker_symbol).first
end
def self.new_from_lookup(ticker_symbol)
begin
StockQuote::Stock.new(api_key: ENV["API_KEY"])
lookep_up_stock = StockQuote::Stock.quote(ticker_symbol)
new(name: lookep_up_stock.company_name, ticker: lookep_up_stock.symbol, last_price: lookep_up_stock.latest_price)
rescue Exception => e
return nil
end
end
end
| true |
7d3915ca30da136bf10f2ef1acc06e13b3cb37c8 | Ruby | amso100/livescript-declarations | /obj.rb | UTF-8 | 239 | 2.5625 | 3 | [] | no_license | class Obj < Node
def parseNextNode(ast_json)
@items = []
ast_json["items"].each { |inner_prop|
@items << parseAstFromJsonToNodes(inner_prop)
}
end
def get_vars()
@items.each { |item| item.get_vars() }
end
end | true |
c79f42487f8e044310d4ca6690b1e08f9155eb98 | Ruby | Hiromi-Kai/TEA_YOURSELF | /tea_yourself.rb | UTF-8 | 524 | 3.328125 | 3 | [] | no_license | require 'telegraph'
module TEAYOURSELF
class << self
public
def do(text)
delete_last_space(delete_space(tuu_to_yourself(tonn_to_tea(Telegraph.text_to_morse(text)))))
end
private
def tonn_to_tea(text)
text.gsub('.','TEA ')
end
def tuu_to_yourself(text)
text.gsub('-','YOURSELF ')
end
def delete_space(text)
text.gsub(/\s{2,}/,' ')
end
def delete_last_space(text)
text[0..-2]
end
end
end
if __FILE__==$0
p TEAYOURSELF.do('TEA YOURSELF')
end | true |
4eb89463491576611cbdd4827b1bcc58341e32e7 | Ruby | yune-kotomi/dokusho-biyori-ishibashi | /bin/bot/operation/comics.rb | UTF-8 | 551 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'cgi'
# grep -h "<abstract>" jawiki-latest-abstract* |grep '漫画作品'>comic_src.txt
open(ARGV[1], 'w') do |f|
open(ARGV[0]).read.split("\n").
map{|s| s.gsub(/<.?abstract>/,'') }.
map{|s| CGI.unescapeHTML(s) }.
map{|s| s.gsub(/[((].+[))]/, '') }.
map{|s| s.split(/[』」 ]/).first }.
map{|s| s.sub(/[『「]/, '') }.
map{|s| s.split(/は、.+の.+作品/).first }.
uniq.compact.
map{|s| if s.include?('漫画作品'); s.split(/と?は.+漫画/).first; else; s; end }.
each{|s| f.puts s }
end
| true |
08d6018a83d38b86ea1561823b624e9984a96652 | Ruby | rails/sprockets | /lib/sprockets/context.rb | UTF-8 | 9,078 | 2.609375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'rack/utils'
require 'set'
require 'sprockets/errors'
require 'delegate'
module Sprockets
# They are typically accessed by ERB templates. You can mix in custom helpers
# by injecting them into `Environment#context_class`. Do not mix them into
# `Context` directly.
#
# environment.context_class.class_eval do
# include MyHelper
# def asset_url; end
# end
#
# <%= asset_url "foo.png" %>
#
# The `Context` also collects dependencies declared by
# assets. See `DirectiveProcessor` for an example of this.
class Context
# Internal: Proxy for ENV that keeps track of the environment variables used
class ENVProxy < SimpleDelegator
def initialize(context)
@context = context
super(ENV)
end
def [](key)
@context.depend_on_env(key)
super
end
def fetch(key, *)
@context.depend_on_env(key)
super
end
end
attr_reader :environment, :filename
def initialize(input)
@environment = input[:environment]
@metadata = input[:metadata]
@load_path = input[:load_path]
@logical_path = input[:name]
@filename = input[:filename]
@dirname = File.dirname(@filename)
@content_type = input[:content_type]
@required = Set.new(@metadata[:required])
@stubbed = Set.new(@metadata[:stubbed])
@links = Set.new(@metadata[:links])
@dependencies = Set.new(input[:metadata][:dependencies])
end
def metadata
{ required: @required,
stubbed: @stubbed,
links: @links,
dependencies: @dependencies }
end
def env_proxy
ENVProxy.new(self)
end
# Returns the environment path that contains the file.
#
# If `app/javascripts` and `app/stylesheets` are in your path, and
# current file is `app/javascripts/foo/bar.js`, `load_path` would
# return `app/javascripts`.
attr_reader :load_path
alias_method :root_path, :load_path
# Returns logical path without any file extensions.
#
# 'app/javascripts/application.js'
# # => 'application'
#
attr_reader :logical_path
# Returns content type of file
#
# 'application/javascript'
# 'text/css'
#
attr_reader :content_type
# Public: Given a logical path, `resolve` will find and return an Asset URI.
# Relative paths will also be resolved. An accept type maybe given to
# restrict the search.
#
# resolve("foo.js")
# # => "file:///path/to/app/javascripts/foo.js?type=application/javascript"
#
# resolve("./bar.js")
# # => "file:///path/to/app/javascripts/bar.js?type=application/javascript"
#
# path - String logical or absolute path
# accept - String content accept type
#
# Returns an Asset URI String.
def resolve(path, **kargs)
kargs[:base_path] = @dirname
uri, deps = environment.resolve!(path, **kargs)
@dependencies.merge(deps)
uri
end
# Public: Load Asset by AssetURI and track it as a dependency.
#
# uri - AssetURI
#
# Returns Asset.
def load(uri)
asset = environment.load(uri)
@dependencies.merge(asset.metadata[:dependencies])
asset
end
# `depend_on` allows you to state a dependency on a file without
# including it.
#
# This is used for caching purposes. Any changes made to
# the dependency file will invalidate the cache of the
# source file.
def depend_on(path)
if environment.absolute_path?(path) && environment.stat(path)
@dependencies << environment.build_file_digest_uri(path)
else
resolve(path)
end
nil
end
# `depend_on_asset` allows you to state an asset dependency
# without including it.
#
# This is used for caching purposes. Any changes that would
# invalidate the dependency asset will invalidate the source
# file. Unlike `depend_on`, this will recursively include
# the target asset's dependencies.
def depend_on_asset(path)
load(resolve(path))
end
# `depend_on_env` allows you to state a dependency on an environment
# variable.
#
# This is used for caching purposes. Any changes in the value of the
# environment variable will invalidate the cache of the source file.
def depend_on_env(key)
@dependencies << "env:#{key}"
end
# `require_asset` declares `path` as a dependency of the file. The
# dependency will be inserted before the file and will only be
# included once.
#
# If ERB processing is enabled, you can use it to dynamically
# require assets.
#
# <%= require_asset "#{framework}.js" %>
#
def require_asset(path)
@required << resolve(path, accept: @content_type, pipeline: :self)
nil
end
# `stub_asset` blacklists `path` from being included in the bundle.
# `path` must be an asset which may or may not already be included
# in the bundle.
def stub_asset(path)
@stubbed << resolve(path, accept: @content_type, pipeline: :self)
nil
end
# `link_asset` declares an external dependency on an asset without directly
# including it. The target asset is returned from this function making it
# easy to construct a link to it.
#
# Returns an Asset or nil.
def link_asset(path)
asset = depend_on_asset(path)
@links << asset.uri
asset
end
# Returns a `data:` URI with the contents of the asset at the specified
# path, and marks that path as a dependency of the current file.
#
# Uses URI encoding for SVG files, base64 encoding for all the other files.
#
# Use `asset_data_uri` from ERB with CSS or JavaScript assets:
#
# #logo { background: url(<%= asset_data_uri 'logo.png' %>) }
#
# $('<img>').attr('src', '<%= asset_data_uri 'avatar.jpg' %>')
#
def asset_data_uri(path)
asset = depend_on_asset(path)
if asset.content_type == 'image/svg+xml'
svg_asset_data_uri(asset)
else
base64_asset_data_uri(asset)
end
end
# Expands logical path to full url to asset.
#
# NOTE: This helper is currently not implemented and should be
# customized by the application. Though, in the future, some
# basic implementation may be provided with different methods that
# are required to be overridden.
def asset_path(path, options = {})
message = <<-EOS
Custom asset_path helper is not implemented
Extend your environment context with a custom method.
environment.context_class.class_eval do
def asset_path(path, options = {})
end
end
EOS
raise NotImplementedError, message
end
# Expand logical image asset path.
def image_path(path)
asset_path(path, type: :image)
end
# Expand logical video asset path.
def video_path(path)
asset_path(path, type: :video)
end
# Expand logical audio asset path.
def audio_path(path)
asset_path(path, type: :audio)
end
# Expand logical font asset path.
def font_path(path)
asset_path(path, type: :font)
end
# Expand logical javascript asset path.
def javascript_path(path)
asset_path(path, type: :javascript)
end
# Expand logical stylesheet asset path.
def stylesheet_path(path)
asset_path(path, type: :stylesheet)
end
protected
# Returns a URI-encoded data URI (always "-quoted).
def svg_asset_data_uri(asset)
svg = asset.source.dup
optimize_svg_for_uri_escaping!(svg)
data = Rack::Utils.escape(svg)
optimize_quoted_uri_escapes!(data)
"\"data:#{asset.content_type};charset=utf-8,#{data}\""
end
# Returns a Base64-encoded data URI.
def base64_asset_data_uri(asset)
data = Rack::Utils.escape(EncodingUtils.base64(asset.source))
"data:#{asset.content_type};base64,#{data}"
end
# Optimizes an SVG for being URI-escaped.
#
# This method only performs these basic but crucial optimizations:
# * Replaces " with ', because ' does not need escaping.
# * Removes comments, meta, doctype, and newlines.
# * Collapses whitespace.
def optimize_svg_for_uri_escaping!(svg)
# Remove comments, xml meta, and doctype
svg.gsub!(/<!--.*?-->|<\?.*?\?>|<!.*?>/m, '')
# Replace consecutive whitespace and newlines with a space
svg.gsub!(/\s+/, ' ')
# Collapse inter-tag whitespace
svg.gsub!('> <', '><')
# Replace " with '
svg.gsub!(/([\w:])="(.*?)"/, "\\1='\\2'")
svg.strip!
end
# Un-escapes characters in the given URI-escaped string that do not need
# escaping in "-quoted data URIs.
def optimize_quoted_uri_escapes!(escaped)
escaped.gsub!('%3D', '=')
escaped.gsub!('%3A', ':')
escaped.gsub!('%2F', '/')
escaped.gsub!('%27', "'")
escaped.tr!('+', ' ')
end
end
end
| true |
404b4f07b9e8e9417477f76d92e63199b1b11538 | Ruby | RReiso/ruby-practice | /concepts/string-regex.rb | UTF-8 | 2,146 | 3.515625 | 4 | [] | no_license | # gsub
p '1 esmu26 5'.sub(/\d+/) { |num| num.next } #"2 esmu26 5" First occurance
p '1 esmu26 5'.gsub(/\d+/) { |num| num.next } #"2 esmu27 6"
p '1 esmu26 5'.gsub(/\d+/, &:next) #"2 esmu27 6"
# regex
p /abcde/.match("hello abcd") # nil
p /abc/.match("hello abcd") #<MatchData "abc">
p /abc/.match?("hello abcd") # true
p "hello abcd".match?(/abc/) # true
p /abc/=~ "hello abcd" # 6
# Escape characters
p /\/home\/ruta/.match?("C:/home/ruta") #true
p %r[/home/ruta].match?("C:/home/ruta") #true
p /.ine/.match?("dine") # true
p /[md]ine/.match?("dine") # true
p /[md]ine/.match?("mine") # true
p /[f-p]ine/.match?("mine") # true
p /[a-e]ine/.match?("mine") # false
# numbers
p /\d/.match?("d7u66") # true
p /[0-9]/.match?("d7u66") # true
# \d+ - 1 or more digits
# \w - any digit, letter or underscore [0-9a-zA-Z]
# \s - whitespace
# \D - any char that is not a digit
# \W - any char that is not a digit, letter or underscore
# \S - any char that is not a whitespace
# ? - 0 or 1
# * - 0 or more
# + - 1 or more
# {3} - exactly 3 chars
# {1,10} - 1 to 10 chars
# {3, } - 3 or more chars
# \A - beginning of a string
# \Z - end of a string
# ^ - beginning of a line
# $ - end
# i - case insensitive
# /\d.\d/ - nr, any char, nr
# /\d\.\d/ - nr, . , nr
# /^\d+$/ - string has only nr
string = 'My phone number is (123) 555-1234.'
phone_regex = /\((\d{3})\)\s+(\d{3})-(\d{4})/
m = phone_regex.match(string)
3.times { |index| puts "Capture ##{index + 1}: #{m.captures[index]}" }
p "Mani sauc Arturs".scan(/[aeiou]/i) # ["a", "i", "a", "u", "A", "u"]
p "Mani sauc 34 Arturs p5".scan(/\w+/) # ["Mani", "sauc", "34", "Arturs", "p5"]
p "hello".methods.grep(/case/).sort # Displays methods with "case" in them
p "a-bb-cccc-dddd".split("-") # ["a", "bb", "cccc", "dddd"]
a = "hello"
a.freeze
# a[0]="H" # Exception
p "hello".itself
arr = %w[red blue green yellow]
change = Regexp.union(arr)
p "red blue yellow red purple green blue white".gsub(change, "?")
# "? ? ? ? purple ? ? white"
p "aba4764aba"=~/[0-9]/ # 3 (first index)
p "abaaba"=~/[0-9]/ # nil
p "Labdien. Ko tu teici? Nezinu!".split(/\.|\?|!/) # ["Labdien", " Ko tu teici", " Nezinu"] | true |
c76a122748a53680b1488f8ee3e4fedd441a25bb | Ruby | Ezmyrelda/ezmy-tarot | /tarot.rb | UTF-8 | 1,651 | 3.6875 | 4 | [] | no_license | #!/usr/bin/ruby
print "You would like your fortune? Please tell me your name; or should I read that as well?"
name = gets.chomp
print "How many cards would you like? "
reading = gets.chomp
deck = [
0 => 'zed',
1 => 'one',
2 => 'two',
3 => 'three',
4 => 'four',
5 => 'five',
6 => 'six',
7 => 'seven',
8 => 'eight',
9 => 'nine',
10 => 'ten',
11 => 'eleven',
12 => 'twelve',
13 => 'thirteen',
14 => 'fourteen',
15 => 'fifteen',
16 => 'sixteen',
17 => 'seventeen',
18 => 'eighteen',
19 => 'nineteen',
20 => 'twenty',
21 => 'twentyone',
22 => '♣ace',
23 => '♣two',
24 => '♣three',
25 => '♣four',
26 => '♣five',
27 => '♣six',
28 => '♣seven',
29 => '♣eight',
30 => '♣nine',
31 => '♣ten',
32 => '♣page',
33 => '♣knight',
34 => '♣king',
35 => '♣queen',
36 => '♦ace',
37 => '♦two',
38 => '♦three',
39 => '♦four',
40 => '♦five',
41 => '♦six',
42 => '♦seven',
43 => '♦eight',
44 => '♦nine',
45 => '♦ten',
46 => '♦page',
47 => '♦knight',
48 => '♦king',
49 => '♦queen',
50 => '♥ace',
51 => '♥two',
52 => '♥three',
53 => '♥four',
54 => '♥five',
55 => '♥six',
56 => '♥seven',
57 => '♥eight',
58 => '♥nine',
59 => '♥ten',
60 => '♥page',
61 => '♥knight',
62 => '♥king',
63 => '♥queen',
64 => '♠ace',
65 => '♠two',
66 => '♠three',
67 => '♠four',
68 => '♠five',
69 => '♠six',
70 => '♠seven',
71 => '♠eight',
72 => '♠nine',
73 => '♠ten',
74 => '♠page',
75 => '♠knight',
76 => '♠king',
77 => '♠queen'
]
| true |
3a8f9e0867477d5022eb98600904ad2e11c0c1e3 | Ruby | mfham/chartjs_sample | /create_data_for_chartjs.rb | UTF-8 | 752 | 2.875 | 3 | [] | no_license | require 'csv'
require 'optparse'
require 'time'
opt = OptionParser.new
params = ARGV.getopts("i:")
raise StandardError, 'Please specify -i option' if params['i'].nil?
h_date = Hash.new {|h, k| h[k] = 0 }
h_person = Hash.new {|h, k| h[k] = 0 }
CSV.foreach("data/#{params['i']}", :headers => [:page_id, :yyyymmdd, :name]) do |row|
yyyymm = Time.parse(row[:yyyymmdd]).strftime('%Y/%m')
h_date[yyyymm] += 1
h_person[row[:name]] += 1
end
arr_date = []
arr_person = []
h_date.keys.sort.each do |k|
arr_date << {date: k, v: h_date[k]}
end
h_person.keys.sort.each do |k|
arr_person << {name: k, v: h_person[k]}
end
puts arr_date.to_s.gsub(/=>/, ' ').gsub(/:(\w+)/) { $1 + ':' }
puts arr_person.to_s.gsub(/=>/, ' ').gsub(/:(\w+)/) { $1 + ':' }
| true |
2d2e2aee3247bd73b8797bc8442b6ee07a7b6c3f | Ruby | andrewpetrenko1/codebreaker_web | /lib/codebreaker_web.rb | UTF-8 | 3,131 | 2.578125 | 3 | [] | no_license | module RakeWeb
class CodebreakerWeb
def self.call(env)
new(env).response.finish
end
@@game = CodebreakerAp::Game.new
def initialize(env)
@request = Rack::Request.new(env)
end
def response
case @request.path
when '/' then Rack::Response.new(render('menu.html.erb'))
when '/set_game_instance' then set_game_instance
when '/rules' then Rack::Response.new(render('rules.html.erb'))
when '/game' then Rack::Response.new(render('game.html.erb'))
when '/hint' then hint
when '/submit_answer' then submit_answer
when '/statistics' then Rack::Response.new(render('statistics.html.erb'))
when '/save_stats' then save_statistic
when '/win' then Rack::Response.new(render('win.html.erb'))
when '/lose' then Rack::Response.new(render('lose.html.erb'))
else Rack::Response.new('Not Found', 404)
end
end
def save_statistic
@@game.save_stats(@request.cookies['player_name'], @@game.difficulty)
Rack::Response.new do |response|
response.redirect('/win')
end
end
def apply_game_level
if(@request.params['level'])
return @request.params['level']
elsif @request.cookies['level']
return @request.cookies['level']
end
end
def set_game_instance
Rack::Response.new do |response|
set_player_cookies(response)
level = apply_game_level
@@game = CodebreakerAp::Game.new
@@game.difficulty.initialize_difficulty(level)
set_game_cookies(response)
response.redirect('/game')
end
end
def set_player_cookies(response)
return unless @request.params['player_name'] && @request.params['level']
response.set_cookie('player_name', @request.params['player_name'])
response.set_cookie('level', @request.params['level'])
end
def set_game_cookies(response)
response.set_cookie('game_lvl', @@game.difficulty.level)
response.set_cookie('secret_code', @@game.secret_code.join)
response.set_cookie('hint', nil)
response.set_cookie('checked_answer', nil)
end
def hint
Rack::Response.new do |response|
game_hint = @@game.take_hint
if @request.cookies['hint'] && (game_hint.is_a? Integer)
response.set_cookie('hint', @request.cookies['hint'] + game_hint.to_s)
elsif game_hint.is_a? Integer
response.set_cookie('hint', game_hint)
end
response.redirect('/game')
end
end
def submit_answer
Rack::Response.new do |response|
if @request.params['number']
checked_answer = @@game.check_answer(@request.params['number'])
response.set_cookie('checked_answer', checked_answer)
end
if @@game.win? then response.redirect('/win')
elsif @@game.difficulty.attempts.zero? then response.redirect('/lose')
else response.redirect('/game')
end
end
end
def render(template)
path = File.expand_path("views/#{template}", __dir__)
ERB.new(File.read(path)).result(binding)
end
end
end
| true |
8317fc157865d1cdc77522c032027c9626d4c30e | Ruby | michaelbyrd/opal-rails-example | /app/assets/javascripts/greeter.js.rb | UTF-8 | 282 | 2.828125 | 3 | [] | no_license | # app/assets/javascripts/greeter.js.rb
class Sample
def initialize(num)
@num = num
end
def num
@num
end
end
s = Sample.new(4)
puts s.num
# Dom manipulation
require 'opal-jquery'
Document.ready? do
Element.find('body > header').html = '<h1>Hi there!</h1>'
end
| true |
bd1b9aeb0e7a9ba28e6cd2ed6907670a7f410663 | Ruby | spotswoodb/podcast_cli | /lib/podcast/scraper.rb | UTF-8 | 546 | 2.734375 | 3 | [
"MIT"
] | permissive | class Scraper
def self.get_data
html = URI.open("https://toppodcast.com/top-podcasts/")
doc = Nokogiri::HTML(html)
container = doc.css('div.allTopPodcasts div.podcastRow')
container.each do |el|
title = el.css('h3').text.strip
description = el.css('div.podcast-short-description').text
category = Category.new(el.css('span.category-box').text)
Podcast.new(title, description, category)
end
end
end
| true |
6aed4331fe71e57238dc61620f5df491e4b8cd0e | Ruby | Shopify/chroma | /lib/chroma/rgb_generator/from_string.rb | UTF-8 | 3,099 | 2.640625 | 3 | [
"ISC"
] | permissive | module Chroma
module RgbGenerator
class FromString < Base
# Returns the regex matchers and rgb generation classes for various
# string color formats.
#
# @api private
# @return [Hash<Symbol, Hash>]
def self.matchers
@matchers ||= begin
# TinyColor.js matchers
css_int = '[-\\+]?\\d+%?'
css_num = '[-\\+]?\\d*\\.\\d+%?'
css_unit = "(?:#{css_num})|(?:#{css_int})"
permissive_prefix = '[\\s|\\(]+('
permissive_delim = ')[,|\\s]+('
permissive_suffix = ')\\s*\\)?'
permissive_match3 = "#{permissive_prefix}#{[css_unit] * 3 * permissive_delim}#{permissive_suffix}"
permissive_match4 = "#{permissive_prefix}#{[css_unit] * 4 * permissive_delim}#{permissive_suffix}"
hex_match = '[0-9a-fA-F]'
{
rgb: { regex: /rgb#{permissive_match3}/, class_name: :FromRgbValues },
rgba: { regex: /rgba#{permissive_match4}/, class_name: :FromRgbValues },
hsl: { regex: /hsl#{permissive_match3}/, class_name: :FromHslValues },
hsla: { regex: /hsla#{permissive_match4}/, class_name: :FromHslValues },
hsv: { regex: /hsv#{permissive_match3}/, class_name: :FromHsvValues },
hsva: { regex: /hsva#{permissive_match4}/, class_name: :FromHsvValues },
hex3: { regex: /^#?#{"(#{hex_match}{1})" * 3}$/, class_name: :FromHexStringValues, builder: :from_hex3 },
hex6: { regex: /^#?#{"(#{hex_match}{2})" * 3}$/, class_name: :FromHexStringValues, builder: :from_hex6 },
hex8: { regex: /^#?#{"(#{hex_match}{2})" * 4}$/, class_name: :FromHexStringValues, builder: :from_hex8 }
}.freeze
end
end
# @param format [Symbol] unused
# @param input [String] input to parse
def initialize(format, input)
@input = normalize_input(input)
end
# Generates a {ColorModes::Rgb}.
# @return [ColorModes::Rgb]
def generate
get_generator.generate
end
private
def get_generator
if color = Chroma.hex_from_name(@input)
format = :name
elsif @input == 'transparent'
return FromRgbValues.new(:name, 0, 0, 0, 0)
else
format = nil
color = @input
end
match = nil
_, hash = matchers.find do |_, h|
!(match = h[:regex].match(color)).nil?
end
if match.nil?
raise UnrecognizedColor, "Unrecognized color `#{color}'"
end
build_generator(match[1..-1], hash[:class_name], hash[:builder], format)
end
def build_generator(args, class_name, builder, format)
builder ||= :new
klass = RgbGenerator.const_get(class_name)
klass.__send__(builder, *([format] + args))
end
def normalize_input(input)
input.clone.tap do |str|
str.strip!
str.downcase!
end
end
def matchers
self.class.matchers
end
end
end
end
| true |
4cc158f199ee80266bafbad7160269a6effbce74 | Ruby | stevenjackson/finances | /features/support/test_database.rb | UTF-8 | 1,555 | 2.609375 | 3 | [
"MIT"
] | permissive | require 'fig_newton'
require 'sequel'
class TestDatabase
def initialize
@db = Sequel.connect(DB_URI)
end
def insert_category(category, amount)
@db[:categories].insert :name => category, :budget => amount
end
def debit_category(category, amount, date_applied=Time.now)
@db[:debits].insert :category => category, :amount => amount, :date_applied => date_applied
end
def credit_category(category, amount, date_applied=Time.now)
@db[:credits].insert :category => category, :amount => amount, :date_applied => date_applied
end
def insert_transaction(amount)
@db[:transactions].insert :description => "Trans", :amount => "-#{amount}", :posted_at => Time.now, :account_id => first_account[:id]
end
def insert_deposit(amount)
@db[:transactions].insert :description => "Deposit", :amount => amount, :posted_at => Time.now
end
def insert_account(account, balance=0)
@db[:accounts].insert :name => account, :balance => balance
end
def debit_account(account, amount, date=Time.now)
account_id = @db[:accounts][:name => account][:id]
@db[:transactions].insert :description => "Trans", :amount => "-#{amount}", :account_id => account_id, :posted_at => date
end
def store_balance(account, amount, date)
account_id = @db[:accounts][:name => account][:id]
@db[:account_balances].insert :account_id => account_id, :balance => amount, :date => date
end
def first_account
unless @db[:accounts].first
acct = insert_account('test')
end
@db[:accounts].first
end
end
| true |
5ef5f065488cebed11f0c62ebcd1a3a8e1aff451 | Ruby | Anthorage/Necrolis | /world1.rb | UTF-8 | 2,808 | 2.59375 | 3 | [] | no_license | require_relative 'world'
class World1 < World
def update(dt)
super(dt)
game_logic(dt)
@wavesys.update(dt)
if @state == 0 || @state == 1 || @state == 8
self.next_text() if @adv_timer.update(dt)
elsif @state == 2
if @units.size > 0
self.next_text()
end
elsif @state == 3
if @units.first.is_moving?
@adv_timer.pause(false)
end
self.next_text() if @adv_timer.update(dt)
elsif @state == 4
if @units.size > 2
self.next_text()
end
elsif @state == 5
if @wavesys.wave_number == 2 && @wavesys.finished_summoning?
@wavesys.wait!
if @wavesys.group_empty?
self.next_text()
end
end
elsif @state == 6
self.next_text() unless @wavesys.group_empty?
elsif @state == 7
if @wavesys.group_empty?
self.next_text()
end
end
end
def next_text()
@state += 1
if @state == 1
self.set_message("Base")
elsif @state == 2
PlayerMaster.PLAYER_1.energy += UnitMaster.get.bring(UnitMaster::SKELETON).energy_cost
PlayerMaster.PLAYER_1.corpses += UnitMaster.get.bring(UnitMaster::SKELETON).corpses_cost
self.add_summon( UnitMaster::SKELETON )
self.set_message("Summon")
elsif @state == 3
self.set_message("Orders")
@adv_timer.pause()
@adv_timer.set_time(5.0)
elsif @state == 4
self.set_message("MoreSummoning")
PlayerMaster.PLAYER_1.energy += UnitMaster.get.bring(UnitMaster::SKELETON).energy_cost*2
PlayerMaster.PLAYER_1.corpses += UnitMaster.get.bring(UnitMaster::SKELETON).corpses_cost*2
elsif @state == 5
self.set_message("Enemies")
@wavesys.summon!
elsif @state == 6
self.set_message("AlmostOver")
@wavesys.resume!
PlayerMaster.PLAYER_1.energy += UnitMaster.get.bring(UnitMaster::SKELETON).energy_cost
elsif @state == 7
self.set_message("FinalBattle")
elsif @state == 8
@adv_timer.set_time(4.0)
self.set_message("Victory")
elsif @state == 9
@adv_timer.pause()
@victory = true
end
end
def load
super
reg = @regions["hstart"]
targ = @regions["target"]
@wavesys = self.create_wave_system(reg, PlayerMaster::P2, 1.0, targ.centerx, targ.centery)
@state = 0
@adv_timer = SimpleTimer.new(20, true)
self.set_message("Start")
end
end
| true |
c5c40528f9a1187d1db6a7c65f1e16e020a5e836 | Ruby | kishaningithub/udacity-ruby-nanodegree-projects | /rbnd-udacitask-part1-master/Udacitask/todolist.rb | UTF-8 | 2,951 | 3.46875 | 3 | [] | no_license | require 'yaml'
class TodoList
PERSISTENCE_DIR = "persisted_list"
attr_reader :title, :items
def initialize(list_title)
if persisted? list_title then
todo_lst = get_persisted_todo_lst(list_title)
@title = todo_lst.title
@items = todo_lst.items
else
@title = list_title
@items = [] # Starts empty! No Items yet!
end
end
def add_item(new_item, options = {sub_items: [], due_date: nil})
item = Item.new(new_item)
if ! options[:sub_items].empty? then
item.add_subitems(options[:sub_items])
end
if options[:due_date] then
item.due_date = options[:due_date]
end
@items.push(item)
end
def delete_item_at(index)
@items.delete_at(index - 1) # Just to make it more "human friendly (delete first item)"
end
def update_completion_status_at(index)
item = @items[index - 1] # Just to make it more "human friendly (Update the completion status of first item)"
item.update_completion_status
end
def rename(new_title)
@title = new_title
end
def persisted?(list_title) # Function ending with ?
File.exist? persisted_file_path list_title
end
def persisted_file_path(list_title)
"#{PERSISTENCE_DIR}/#{list_title}.txt"
end
def persist
Dir.mkdir PERSISTENCE_DIR unless File.exist? PERSISTENCE_DIR
File.open(persisted_file_path(@title), "w") {|f| f.write(YAML.dump(self))}
end
def get_persisted_todo_lst(list_title)
YAML.load(File.read(persisted_file_path(list_title)))
end
def to_s
header_divider = "-" * 20
print_lst = []
print_lst << header_divider
print_lst << @title
print_lst << header_divider
@items.each.with_index(1) do |item, index|
print_lst << "#{index} - #{item}"
end
print_lst << " "
print_lst.join("\n")
end
end
class Item
attr_accessor :due_date
def initialize(item_description)
@description = item_description
@completed_status = false
@sub_items = []
end
def update_completion_status
@completed_status = ! @completed_status
end
def add_subitem(item_description)
@sub_items << Item.new(item_description)
end
def add_subitems(item_description_arr)
item_description_arr.each { |item_description| add_subitem(item_description) }
end
def to_s
print_lst = []
print_lst << "#{@description} Completed: #{@completed_status} #{if due_date then "Due date :#{due_date}" end }"
print_lst << "Subtasks" unless @sub_items.empty?
@sub_items.each.with_index(1) {|item, index| print_lst << "#{index} #{item}"}
print_lst.join("\n")
end
end
| true |
2d4eca67b1f9fede7cd5edabd6ea0126364cbe75 | Ruby | zoeabryant/ma-airport | /lib/airport.rb | UTF-8 | 631 | 3.34375 | 3 | [] | no_license | require_relative 'weather'
class Airport
include Weather
def planes
@planes ||= []
end
def allow_landing?(plane)
currently_good_weather = is_good_weather?
if currently_good_weather
puts "Landing successful! What a beautiful clear day!"
planes << plane
else
puts "Landing not permitted, wait until the storm has passed."
end
end
def allow_take_off?(plane)
currently_good_weather = is_good_weather?
if currently_good_weather
puts "Take off successful! What a beautiful clear day!"
planes.delete(plane)
else
puts "Take off not permitted, wait until the storm has passed."
end
end
end | true |
20f05f4a33e521bde4ecfd1ea1a3448343a5bb8c | Ruby | sano2019/rails-longest-word-game | /app/controllers/games_controller.rb | UTF-8 | 1,350 | 3.15625 | 3 | [] | no_license | class GamesController < ApplicationController
def new
@letters = Array.new(10) { ('A'..'Z').to_a.sample }
end
def score
@answer = ""
if included?
check_api
if @response["found"] == true
@score = @response["length"].to_i
@answer = "Congratulations! #{params['word']} is a valid English word! You have #{@score} points"
elsif
@response["found"] == false
@answer = "Sorry but #{params['word']} does not seem to be a valid English word"
end
else @answer = "Sorry but #{params['word']} can't be built out of #{params['letters']}"
end
end
private
def check_api
require 'json'
require 'open-uri'
url = "https://wagon-dictionary.herokuapp.com/#{params[:word]}"
@response = JSON.parse(open(url).read)
end
def included?
word = params["word"].split("")
word.all? { |letter| word.count(letter) <= params['letters'].count(letter) }
end
end
# check that the word can be formed from the current array of letters
# IF FALSE print "Sorry but WORD can't be built out of @letters"
# check that the word is true in the check API
# IF FALSE print "Sorry but WORD does not seem to be a valid English word"
# => <ActionController::Parameters {"authenticity_token"=>"wpgY3sXtrprwwCZGOx2VKxyvkI4FIYGqC0Toq+vEYPjpL++gTKTNOpnG1AkViCc3rKGEGOSpJmrTVtOozhdkWw==",
# "word"=>"KNOL", "controller"=>"games", "action"=>"score"} permitted: false>
| true |
21f39a88b57c22e9e0eee03012e462e359106d74 | Ruby | raphael27atm/find_user_github | /app/models/user.rb | UTF-8 | 413 | 2.625 | 3 | [] | no_license | class User
include HTTParty
base_uri "https://api.github.com"
attr_accessor :name
def initialize(name)
@options = {query: {q: name}}
end
def search
response = self.class.get("/search/users", @options)
if response.success?
response['items']
else
raise response
end
end
def self.repos(name)
response = get("/users/" + name + "/repos")
response
end
end
| true |
21e8ac6f78946642de7d12ef9636cc024ecdeb21 | Ruby | erikabalbino/codecore_may2018 | /week4/Day20_Ruby_OOP/labs/Animals/animal_example.rb | UTF-8 | 196 | 3.40625 | 3 | [] | no_license | require "./animal.rb"
require "./dog.rb"
require "./cat.rb"
dog1 = Dog.new("Erika", "Red")
cat1 = Cat.new("Juliana", "Black", 2)
puts "Dogs:"
dog1.eat
dog1.walk
puts "Cats"
cat1.eat
cat1.walk
| true |
61620f5f844cdc250477be15a2d1cfc6f95e9b7b | Ruby | philipd97/ruby_on_rails | /section2/crud.rb | UTF-8 | 846 | 2.796875 | 3 | [] | no_license | module Crud
require 'bcrypt'
puts "Module CRUD activated"
# def self.create_hash_digest(password)
def create_hash_digest(password = nil)
BCrypt::Password.create(respond_to?(:password) ? self.password : password)
end
# def self.verify_hash_digest(password)
def verify_hash_digest
BCrypt::Password.new(self.password)
end
def self.create_secure_users(list_of_users)
list_of_users.each do |user_record|
user_record[:password] = Class.include(Crud).create_hash_digest(user_record[:password])
end
list_of_users
end
# def self.authenticate_user(username, password, list_of_users)
def authenticate_user(list_of_users = [])
list_of_users.find { |user_record|
user_record[:username] == self.username && user_record[:password] == self.password
} || "Credentials were not correct"
end
end
| true |
343d50a6992b0827a12e1c751a0dce2fc064cbb0 | Ruby | TheMartonfi/math_game | /Player.rb | UTF-8 | 246 | 3.46875 | 3 | [] | no_license | class Player
attr_accessor :name, :current_lives, :total_lives
def initialize(n, l)
self.name = n
self.current_lives = l
self.total_lives = self.current_lives
end
def get_answer
print "> "
$stdin.gets.chomp
end
end | true |
92285104c4a70cba3c779cb2d3ae3761c574d9a1 | Ruby | vidriloco/wikicleta-Left-panel | /app/models/bike_status.rb | UTF-8 | 1,012 | 2.625 | 3 | [] | no_license | class BikeStatus < ActiveRecord::Base
belongs_to :bike
validates_presence_of :bike_id, :concept
def self.find_all_for_bike(bike_id)
categories = Bike.category_list_for(:statuses).invert
find(:all, :conditions => {bike_id: bike_id }).each do |bike_status|
categories[Bike.category_symbol_for(:statuses, bike_status.concept)] = bike_status
end
categories.each_key do |key|
categories[key] = BikeStatus.new if(categories[key].is_a? Integer)
end
end
def self.create_with_bike(bike_id, params)
BikeStatus.create(params.merge(:bike_id => bike_id))
end
def self.update_with(id, params)
bike_status = self.find(id)
if bike_status
params.delete(:concept) && bike_status.update_attributes(params)
end
bike_status
end
def humanized_status
Bike.humanized_category_for(:statuses, concept)
end
def status
Bike.category_symbol_for(:statuses, concept)
end
def is_available?
availability == true
end
end
| true |
f84703a84619ea1af2d952a50c3eaae000db80e0 | Ruby | askay/coding_standards_setup | /prep.rb | UTF-8 | 1,322 | 2.515625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# try to determine the root of the project
# if there's .git, then bail
if !(Dir.exists? '.git')
print "Can't find project root\n"
abort
end
require 'fileutils'
print "Installing clang-format\n"
system("brew install clang-format")
scriptDirectory = File.dirname(__FILE__)
binDirectory = File.join(ENV['HOME'], "bin")
gitLangFile = File.join(binDirectory, "git-clang-format")
if !(File.exists? gitLangFile)
if !(Dir.exists? binDirectory)
print "Creating $HOME/bin directory\n"
FileUtils.mkdir_p binDirectory
end
FileUtils.cp(File.join(scriptDirectory, "git-clang-format"), gitLangFile)
system("chmod +x #{gitLangFile}")
print "Installed git clang-format\n"
end
if (File.exists? '.clang-format')
print ".clang-format already exists and will not be overridden\n"
else
configFile = File.join(scriptDirectory, "clang-format")
FileUtils.cp(configFile, "./.clang-format")
print "copied .clang-format to project root\n"
end
if (File.exists? '.git/hooks/pre-commit')
print "A pre-commit hook already exists. Don't know how to handle this\n"
abort
else
precommitHookFile = File.join(scriptDirectory, "check_formatting.sh")
FileUtils.cp(precommitHookFile, ".git/hooks/pre-commit")
system("chmod +x .git/hooks/pre-commit")
print "Installed pre-commit hook\n"
end
| true |
7cfe63de5b99d256f3ac796bc4a8dcb99c084485 | Ruby | qqdipps/LeetCode-DS-Algos-Other | /string/reverse_words_in_a_string_iii_557.rb | UTF-8 | 1,043 | 3.90625 | 4 | [] | no_license | # Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
#
# Example 1:
# Input: "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
# Note: In the string, each word is separated by single space and there will not be any extra space in the string.
# @param {String} s
# @return {String}
def reverse_words(s)
s = s.split(" ")
s.length.times do |i|
(s[i].length/2).times do |j|
s[i][j], s[i][(s[i].length - 1) - j] = s[i][(s[i].length - 1) - j], s[i][j]
end
end
s*" "
end
s = "lets check Some other s things wow xas"
p reverse_words(s)
# Notes to self for later:
# 13. Loop swaps first and last indexes then moves in one index on each side until middle is reached.
# 14. By declaring on single line indexes can be reassigned to eachother prior to being updated. Alternativly could use a temp var to hold a value then assign on seperate lines.
# 17. Flattens outer array with space between each element.
| true |
a2703f850334e75c1b245f3e9005e86336322be6 | Ruby | mohammadaliawan/ls-prep | /ruby_basics/debugging/confucius_says.rb | UTF-8 | 840 | 4.21875 | 4 | [] | no_license | def get_quote(person)
if person == 'Yoda'
'Do. Or do not. There is no try.'
elsif person == 'Confucius'
'I hear and I forget. I see and I remember. I do and I understand.'
elsif person == 'Einstein'
'Do not worry about your difficulties in Mathematics. I can assure you mine are still greater.'
end
end
puts 'Confucius says:'
puts '"' + get_quote('Confucius') + '"'
"The problem with the above code is that the last line executed in the method
definition is the last if statement which returns nil. So every time the method is called
all the if statements conditions are checked and if the last one is false then nil will be returned by the method
We need to use an if-elsif-else structure so that once a condition matches the corresponding quote will be
returned and the rest of the conditions will not be checked" | true |
fc8db7257239b4737ec2b8028cabacdd748d66ff | Ruby | LesOsorio/parrot-ruby-online-web-prework | /spec/parrot_spec.rb | UTF-8 | 629 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative './spec_helper'
require_relative '../parrot.rb' # Code your solution in this file
def '#parrot'(default)
puts "please let me pass"
end
it 'should return the default phrase, "Squawk!" when called without any arguments' do
phrase = parrot
expect(phrase).to eq("Squawk!")
end
it 'should output the given phrase when called with an argument' do
expect($stdout).to receive(:puts).with("Pretty bird!")
parrot("Pretty bird!")
end
it 'should return the given phrase when called with an argument' do
phrase = parrot("Pretty bird!")
expect(phrase).to eq("Pretty bird!")
end
end
| true |
3901d955306948bdfc93b3f3019fe071bdd02c0f | Ruby | bih/stripe-ruby | /lib/stripe/reader.rb | UTF-8 | 760 | 2.890625 | 3 | [
"MIT"
] | permissive | module Stripe
class Reader
def self.parse(reader_string, additional_params = {})
parsed = reader_string.to_s.split(/(%B)([0-9]{16})(\^)([a-zA-Z ]*)(\/)([a-zA-Z ]*)(\^)([0-9]{2})([0-9]{2})(.)*?$/)
card = Hash.new
card[:number] = parsed[2].to_s
card[:name] = "#{parsed[6]} #{parsed[4]}".upcase
card[:exp_month] = parsed[9].to_s
card[:exp_year] = parsed[8].to_s
card[:cvc] = ""
card.merge!(additional_params)
raise Stripe::StripeError.new("Could not parse through the reader") if card.values.join("").strip.length == 0
card
end
def self.read(additional_params = {})
# print "Scan your credit card using the USB reader: "
parse(gets, additional_params)
end
end
end
| true |
88b2f34b1942cf3e64c78f187b2de438ca0c9808 | Ruby | sagemlee/war_or_peace | /war_or_peace_runner.rb | UTF-8 | 3,868 | 3.28125 | 3 | [] | no_license | require './lib/card'
require './lib/deck'
require './lib/player'
require './lib/turn'
require './lib/game'
require 'pry'
# suits = [hearts, spades, diamonds, clubs]
# values = ["ace", "2","3","4","5","6","7","8","9","10","jack","queen","king"]
# ranks = [2,3,4,5,6,7,8,9,10,11,12,13,14]
standard_deck = []
standard_deck << card1 = Card.new(:heart, 'Ace', 14)
standard_deck << card2 = Card.new(:heart, '2', 2)
standard_deck << card3 = Card.new(:heart, '3', 3)
standard_deck << card4 = Card.new(:heart, '4', 4)
standard_deck << card5 = Card.new(:heart, '5', 5)
standard_deck << card6 = Card.new(:heart, '6', 6)
standard_deck << card7 = Card.new(:heart, '7', 7)
standard_deck << card8 = Card.new(:heart, '8', 8)
standard_deck << card9 = Card.new(:heart, '9', 9)
standard_deck << card10 = Card.new(:heart, '10', 10)
standard_deck << card11 = Card.new(:heart, 'Jack', 11)
standard_deck << card12 = Card.new(:heart, 'Queen', 12)
standard_deck << card13 = Card.new(:heart, 'King', 13)
standard_deck << card14 = Card.new(:diamond, 'Ace', 14)
standard_deck << card15 = Card.new(:diamond, '2', 2)
standard_deck << card16 = Card.new(:diamond, '3', 3)
standard_deck << card17 = Card.new(:diamond, '4', 4)
standard_deck << card18 = Card.new(:diamond, '5', 5)
standard_deck << card19 = Card.new(:diamond, '6', 6)
standard_deck << card20 = Card.new(:diamond, '7', 7)
standard_deck << card21 = Card.new(:diamond, '8', 8)
standard_deck << card22 = Card.new(:diamond, '9', 9)
standard_deck << card23 = Card.new(:diamond, '10', 10)
standard_deck << card24 = Card.new(:diamond, 'Jack', 11)
standard_deck << card25 = Card.new(:diamond, 'Queen', 12)
standard_deck << card26 = Card.new(:diamond, 'King', 13)
standard_deck << card27 = Card.new(:spade, 'Ace', 14)
standard_deck << card28 = Card.new(:spade, '2', 2)
standard_deck << card29 = Card.new(:spade, '3', 3)
standard_deck << card30 = Card.new(:spade, '4', 4)
standard_deck << card31 = Card.new(:spade, '5', 5)
standard_deck << card32 = Card.new(:spade, '6', 6)
standard_deck << card33 = Card.new(:spade, '7', 7)
standard_deck << card34 = Card.new(:spade, '8', 8)
standard_deck << card35 = Card.new(:spade, '9', 9)
standard_deck << card36 = Card.new(:spade, '10', 10)
standard_deck << card37 = Card.new(:spade, 'Jack', 11)
standard_deck << card38 = Card.new(:spade, 'Queen', 12)
standard_deck << card39 = Card.new(:spade, 'King', 13)
standard_deck << card40 = Card.new(:club, 'Ace', 14)
standard_deck << card41 = Card.new(:club, '2', 2)
standard_deck << card42 = Card.new(:club, '3', 3)
standard_deck << card43 = Card.new(:club, '4', 4)
standard_deck << card44 = Card.new(:club, '5', 5)
standard_deck << card45 = Card.new(:club, '6', 6)
standard_deck << card46 = Card.new(:club, '7', 7)
standard_deck << card47 = Card.new(:club, '8', 8)
standard_deck << card48 = Card.new(:club, '9', 9)
standard_deck << card49 = Card.new(:club, '10', 10)
standard_deck << card50 = Card.new(:club, 'Jack', 11)
standard_deck << card51 = Card.new(:club, 'Queen', 12)
standard_deck << card52 = Card.new(:club, 'King', 13)
deck1 = Deck.new(standard_deck.shuffle)
deck2 = Deck.new(standard_deck.shuffle)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
turn_count = 0
loop do
turn.type
winner = turn.winner
turn.pile_cards
turn_count +=1
turn.award_spoils(winner)
if player1.has_lost?
p "#{player2.name} has won the game!"
break
elsif player2.has_lost?
p "#{player1.name} has won the game!"
break
elsif turn_count == 1000000
p "DRAW"
break
end
end
# binding.pry
#
# p "Welcome to War! (or Peace) This game will be played with 52 cards."
# p "The players today are Megan and Aurora."
# p "Type 'GO' to start the game!"
# p "------------------------------------------------------------------"
#
# gets.chomp
#
# if gets.chomp = "GO"
| true |
6874f648863470fac22c14b8a9a5bcd08479951e | Ruby | gnmerritt/bitbar-plugins | /Lifestyle/todoNotePlan.15m.rb | UTF-8 | 6,824 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env ruby
# coding: utf-8
# <bitbar.title>NotePlan Todo in Colour</bitbar.title>
# <bitbar.version>v1.0</bitbar.version>
# <bitbar.author>Richard Guay</bitbar.author>
# <bitbar.author.github>raguay</bitbar.author.github>
# <bitbar.desc>A todo list taken from NotePlan and displayed with customizable color-code. Mark tasks "done" simply by clicking on them in the menubar drop-down list. This was based on "Todo Colour" plugin by Srdgh.</bitbar.desc>
# <bitbar.dependencies>ruby</bitbar.dependencies>
# <bitbar.image>http://customct.com/images/NotePlanPlugin-01.png</bitbar.image>
# <bitbar.abouturl>http://customct.com/bitbar</bitbar.abouturl>
#
# Modifications by Guillaume Barrette
# 2017/05/20:
# - Added Black and White NotePlan menubar icon
# - Repaired a bug when there was no newline on the last line the done task would get appended to the last line instead of a new line at the end
# - Added the time in the @done(YYYY-MM-DD HH:MM) so it's like NotePlan preference
# - Added User Parameters so it's easy to determine if we want to append the @done(...) string at the end of the done task and if we want the black or white menubar icon
# - Changed the menubar icon to a templateImage so the color changes automatically when using a dark menubar (removed the white icon)
# - Removed 'use_black_icon' parameters since now it's automatic
# - Changed encoding method and removed the use of 'force_encoding("utf-8")'
# - Repaired a bug if there was no file already created for that day in NotePlan
#
# Modifications by Richard Guay
# 05/20/2017:
# - Added using emoji option
# - fixed character encoding on removing an item
# - Proper parsing of [ ] in the todo.
# - cleanup
require 'date'
#################################
# User Parameters:
insert_date_on_done_task = TRUE
use_emoji = FALSE # If true, will show emoji, otherwise it will use the black or white icon.
use_star = FALSE # if true, will look for and use '*' instead of '-'
use_icloud = TRUE # If true, files will be checked from iCloud. Otherwise:
use_container = TRUE # If true and not iCloud, it will treat as MAS store version. Otherwise, it is non-MAS store version
#################################
Encoding.default_internal = Encoding::UTF_8
Encoding.default_external = Encoding::UTF_8
todo_file_loc = ''
if use_icloud
todo_file_loc = File.expand_path('~/Library/Mobile Documents/iCloud~co~noteplan~NotePlan/Documents/Calendar/' + Date.today.strftime('%Y%m%d') + '.txt')
else
if use_container
todo_file_loc = File.expand_path('~/Library/Containers/co.noteplan.NotePlan/Data/Library/Application Support/co.noteplan.NotePlan/Calendar/' + Date.today.strftime('%Y%m%d') + '.txt')
else
todo_file_loc = File.expand_path('~/Library/Application Support/co.noteplan/Calendar/' + Date.today.strftime('%Y%m%d') + '.txt')
end
end
if ARGV.empty?
#
# Add further priority labels here
#
priority_labels = ['@Urgent', '@due']
#
# Change priority color here
#
priority_color = 'red'
#
# Customise label color-code here:
#
labels = {
'@Work' => 'orange',
'@Play' => 'yellow',
'@home' => 'green',
'@daily' => 'blue',
'@Health' => 'cadetblue',
'@church' => 'lightblue',
'@tutorials' => 'violet',
'@Envato' => 'darkorange',
'@workflow' => 'purple',
'@tutorial' => 'cobaltblue'
}
linesInFile = []
if File.exist?(todo_file_loc.to_s)
linesInFile = IO.readlines(todo_file_loc.to_s)
end
lines = []
#
# Remove all lines that are not a todo. Stop at the first empty line.
#
linesInFile.each_index do |key|
#
# Clean out leading and trailing white spaces (space, tabs, etc)
#
line = linesInFile[key].force_encoding('utf-8').gsub(/^\s+/, '').gsub(/\s+$/, '')
if (line != '') && (!line.include? '[x]')
#
# It's a todo line to display. Remove the leading '-' and add
# to the list.
#
if use_star
lines.push(line.gsub(/^\*\s*(\[ \]\s*)*/, ''))
else
lines.push(line.gsub(/^\-\s*(\[ \]\s*)*/, ''))
end
end
end
#
# Give the header. It's an emoji briefcase with the number of items todo
#
iconBase64 = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAViAAAFYgBxNdAoAAABCRpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iCiAgICAgICAgICAgIHhtbG5zOmV4aWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20vZXhpZi8xLjAvIgogICAgICAgICAgICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgICAgICAgICAgIHhtbG5zOnhtcD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLyI+CiAgICAgICAgIDx0aWZmOlJlc29sdXRpb25Vbml0PjI8L3RpZmY6UmVzb2x1dGlvblVuaXQ+CiAgICAgICAgIDx0aWZmOkNvbXByZXNzaW9uPjU8L3RpZmY6Q29tcHJlc3Npb24+CiAgICAgICAgIDx0aWZmOlhSZXNvbHV0aW9uPjE0MDwvdGlmZjpYUmVzb2x1dGlvbj4KICAgICAgICAgPHRpZmY6T3JpZW50YXRpb24+MTwvdGlmZjpPcmllbnRhdGlvbj4KICAgICAgICAgPHRpZmY6WVJlc29sdXRpb24+MTQwPC90aWZmOllSZXNvbHV0aW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFhEaW1lbnNpb24+MzI8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpDb2xvclNwYWNlPjE8L2V4aWY6Q29sb3JTcGFjZT4KICAgICAgICAgPGV4aWY6UGl4ZWxZRGltZW5zaW9uPjMyPC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgICAgPGRjOnN1YmplY3Q+CiAgICAgICAgICAgIDxyZGY6QmFnLz4KICAgICAgICAgPC9kYzpzdWJqZWN0PgogICAgICAgICA8eG1wOk1vZGlmeURhdGU+MjAxNzowNToyMCAwMDowNToyMDwveG1wOk1vZGlmeURhdGU+CiAgICAgICAgIDx4bXA6Q3JlYXRvclRvb2w+UGl4ZWxtYXRvciAzLjY8L3htcDpDcmVhdG9yVG9vbD4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+CpI9t/8AAAPASURBVFgJtZdLSFRRGMfn/aJRZ5wITQwqCAkzUlrYJrGCLITIateiRbugh7iQCKqVm2pRywgLitBFtchFCVlERQshowckSIllIc44Os44r35nune4c71z5s5gB86c73W+/3e+851zz9gta9wCgUCj2+0+ZrVa51KpVBT3WRmEXaYsRxcMBtsBvgzwDebZnE5nq9frnYrH479lfhwypRmd3+/f43A4+rLZbJfNZnMwJuijSiAf8DEh82OTKUvovKR7AHAB1o1tbjGAjxBIMzI3dEcJH5aKAqihAT4MSB8AAiiHw5hC9pzxqJBBt4VCIb8siEoCcON4kN6lAqsA8K8ymUwdGdigyBooxC2q3mgsOwAW3w94tx4cmfD/BPAeVYfMAb/VCFiVlVWEpL2Zib0qgOqEMYXsNYBiC7Zp9WSkQWO3iiwrAzg+B4BP9QJtQTZG3+1yuQ4hXwVGAO2qvdFoOgBSvwnAI9rVQYvquxQOh8dnZ2eX0un0I0RJHVC1ji9gTQcAeBe9pmD2Pya3+YJErwcX4jfip1gzVQOsvgUHZ7SrVxyCaR2gNk4r/C1Gp0LnBrvd/lXL6+l89HqFyldXV++jkh/Ah1SZwRhXZB6dLpFMJnctLi5+0snzrDQDrHwnK7yPtQxcONMDi+0QBfoecGkGitZAVVVVECeD9PX5cMskCOA2U9KyaUUDYO+uAL7DYN9l/vI65k3wdRzKC4oQhjXA6g/ykXlaKThY4mLq4Xg+LoKbFxu+B7hURG1ElPRXsgUTgF/Ah/QxIqIw3IJoNPolEolc5EHRxk12ALuXwriMtoxtxoy99BTMzMzEcPKM05AgG2NmHGJnIWj1WJacYpgB/ayVlZVv7GlCL5fwUxJdgcpMAE6PxxNgVj89LFaobXpe0Y1rbWR0yQC4CU+y+ocU1TVutXbSeweHSwrwNPxd+B9qINimkb2VgZrW1dfX+9j/SV68vdpJ8NvpJ2prazcKOd+CRuyGkGWhJxF5tfYyWlqEsVhsP9+BzaxKvO/zjc9ujBU3kZXcRTM/P/8d5XGCOMsYpItTYKpJAyCVvwAawVOr1hu35CmCEi/hqxp5loCua3hTpLQGFhYW3uFF3GrTwpvP56sjzcOQ5wnuJqP0nhdzSjVpAEx20VvYhkXxvOZuF+BNBPSCi+peKedm9IVnSjdDfBGVB8VHtmIdwG5MDnMalvnM/tGZV8SWqgHxrLbQ9wL+k7Fzbm5OFNyaNekW8AdTXMEp0Eb5g9EB+Oc1QzbpyMFF1ImtqIX/0v4CwBRdmE9e8GAAAAAASUVORK5CYII='
if use_emoji
puts "💼#{lines.length}"
else
puts "#{lines.length} |templateImage=#{iconBase64}"
end
puts '---'
cfn = File.expand_path(__FILE__)
#
# Create the list of items to do in the menu.
#
line_number = 0
lines.each do |item|
line_number += 1
line_color = ''
line = item.chomp
priority_labels.each do |priority_label|
if line.include?(priority_label)
#
# If line contains priority label, display in priority color
#
line_color = priority_color
else
#
# If line contains no priority label, cycle through labels hash,
# and if line contains a label display in corresponding color
#
labels.each { |label, label_color| line_color = label_color if line.include?(label) }
end
end
#
# If the line contains no label, display in default color. Otherwise, in
# chosen color. Clicking line launches this script with line number as
# the parameter.
#
line_color.empty? ? puts("#{line} | bash='#{cfn}' param1=#{line_number} terminal=false refresh=\n") : puts("#{line} | color=#{line_color} bash='#{cfn}' param1=#{line_number} terminal=false refresh=\n")
end
puts '---'
puts "Click an item to mark 'done'"
puts 'Refresh | refresh='
else
#
# This is what to do when clicking on an item. We want to move
# the item to the Archive section and set it as done. If there
# isn't an Archive area, create it and add the task to it.
#
# Get the task number to archive.
#
doNum = ARGV[0].to_i
#
# Get the list of todos and setup variables
#
todo_file = File.open(todo_file_loc.to_s)
linesInFile = IO.readlines(todo_file)
task = ''
lines = []
line_number = 0
linesInFile[-1] = linesInFile[-1] + "\n" unless linesInFile[-1].include? "\n"
#
# Process the todo list lines.
#
linesInFile.each do |line|
line_number += 1
if line_number != doNum
#
# It is one of the other lines. Just push it into the stack.
#
lines.push(line)
else
#
# Get the line to be moved to the archive area.
#
if insert_date_on_done_task
tm = Time.new
task = line.chomp + " @done(#{tm.strftime('%Y-%m-%d %H:%M')})\n"
else
task = line.chomp + "\n"
end
task = if use_star
task.gsub(/^\*\s*(\[ \]\s*)*/, '* [x] ')
else
task.gsub(/^\-\s*(\[ \]\s*)*/, '- [x] ')
end
end
end
#
# Add the task to the bottom.
#
lines.push(task)
#
# Save the file.
#
IO.write(todo_file, lines.join)
end
| true |
61a0f9755f619af518cb72b4d6e2b8262c84f6cc | Ruby | KravchenkoDS/Thinknetica | /Lesson6/lib/train.rb | UTF-8 | 2,538 | 3.296875 | 3 | [] | no_license | require_relative '../lib/instance_counter'
require_relative '../lib/manufacturer'
class Train
include Manufacturer
include InstanceCounter
attr_reader :type, :speed, :route, :wagons, :number
FORMAT_NUMBER = /^[a-zа-я\d]{3}[-]?[a-zа-я\d]{2}$/i
FORMAT_NUMBER__ERROR = 'Неверный формат номера'
EMPTY_NUMBER_ERROR = 'Введен пустой номер'
@@trains = {}
def initialize(number, type)
@number = number
@type = type
@speed = 0
@wagons = []
validate!
@@trains[number] = self
register_instance
end
def self.all
@@trains.values
end
def self.find(number)
@@trains[number]
end
def increase_speed(speed)
@speed += speed if speed > 0
end
def decrease_speed(speed)
if @speed - speed < 0
@speed = 0
else
@speed -= speed
end
end
def stop
@speed = 0
end
def add_wagon(wagon)
@wagons << wagon if attachable_wagon?(wagon)
end
def remove_wagon(remove_wagon)
# Удаление только из массива @wagons для поезда, вагон продолжает существовать
# в массиве с аналогичном названием в MainMenu.
@wagons.delete(remove_wagon)
end
def set_route(route)
@route = route
@current_station_index = 0
route.first_station.accept_train(self)
end
def move_to_next_station
if next_station
current_station.send_train(self)
next_station.accept_train(self)
@current_station_index += 1
end
end
def move_to_previous_station
if previous_station
current_station.send_train(self)
previous_station.accept_train(self)
@current_station_index -= 1
end
end
protected
=begin
Три метода поиска станций не должны быть открыты для кода извне, вызов
только внутри методов объекта класса, и используются
в наследуемых классах (CargoTrain, PassengerTrain) - protected
=end
def current_station
route.stations[@current_station_index]
end
def previous_station
route.stations[@current_station_index - 1] unless @current_station_index == 0
end
def next_station
route.stations[@current_station_index + 1]
end
def valid?
validate!
true
rescue
false
end
def validate!
raise EMPTY_NUMBER_ERROR if @number.nil?
raise FORMAT_NUMBER__ERROR if @number !~ FORMAT_NUMBER
end
end
| true |
f56084b5678453dc53b86a1e8ae96a4b116327d1 | Ruby | carlosmendes/ruby_miscrosoft_sql | /app.rb | UTF-8 | 938 | 2.65625 | 3 | [] | no_license | require 'sinatra'
require 'tiny_tds'
require_relative 'models/player.rb'
# connect with Microsoft SQL Server
DB = TinyTds::Client.new dataserver: 'DESKTOP-9CE4NKO\SQLEXPRESS', database: 'jm_players'
# sinatra defines the available endpoints
# localhost:4567/
# home of the app
get '/' do
erb :home
end
# localhost:4567/players
# list all players
get '/players' do
@players = Player.all
erb :index
end
# localhost:4567/players/new
# form to create new player
get '/players/new' do
erb :new
end
# localhost:4567/players/1
# show player info
get '/players/:id' do
@player = Player.find(params[:id])
erb :show
end
# localhost:4567/players
# save the new player info
post '/players' do
@player = Player.new(params)
@player.save
redirect "/players/#{@player.id}"
end
# localhost:4567/players/1/delete
# delete player
get '/players/:id/delete' do
@player = Player.find(params[:id])
@player.destroy
redirect "/players"
end | true |
d23d3bf8fa6b13df6882381cf687dcb2c3be00fb | Ruby | tiffanyhoodprice/Assignments | /11_2_group_names.rb | UTF-8 | 856 | 3.765625 | 4 | [] | no_license | puts "Enter all names. Type 'done' when all names entered."
pool = []
while true
name = gets.chomp
if name.downcase == "done"
break
#same as break if name.downcase == "done" but wouldn't need 'end'
end
pool << name
end
pool.shuffle!
pool.each_with_index do |person, i|
if pool.size.odd? && i == pool.size - 3
puts "Group: #{person} #{pool[i + 1]} #{pool[i + 2]}"
elsif i.even?
puts "Group: #{person} #{pool[i +1]}"
end
end
#CONCATENATED & edited with info from Mark's notes
# puts "Enter all names. Type 'done' when all names entered."
# pool = []
# while true
# name = gets.chomp
# break if name.downcase == "done"
# pool << name
# end
# pool.shuffle!
# until pool.length == 0
# if pool.length == 3
# group = pool.pop(3)
# else
# group = pool.pop(2)
# end
# puts "Group: #{group.join(", ")}"
# end | true |
2217402fff28d7a402b1a3fc46d5c3136c616f55 | Ruby | byskyline/ruby-exercise | /basic/basic_ex3.rb | UTF-8 | 209 | 3.046875 | 3 | [] | no_license | movies = { apple: 1975,
bird: 2004,
cat: 2013,
dog: 2001,
evil: 1981 }
puts movies[:apple]
puts movies[:bird]
puts movies[:cat]
puts movies[:evil]
puts movies[:dog] | true |
581cffd34069dec2a287bbb3e827acda95b78934 | Ruby | dpep/amenable_rb | /spec/amenable_spec.rb | UTF-8 | 4,412 | 2.9375 | 3 | [
"MIT"
] | permissive | describe Amenable do
describe '.call' do
let(:fn) { proc {|x, y = :y, a:, b: 2| [ [ x, y ], { a: a, b: b } ] } }
it 'takes args and kwargs as expected' do
expect(fn).to receive(:call).with(:x, :y, a: 1, b: 2)
Amenable.call(fn, :x, :y, a: 1, b: 2)
end
it 'removes excessive parameters' do
expect(fn).to receive(:call).with(:x, :y, a: 1, b: 2)
Amenable.call(fn, :x, :y, :z, a: 1, b: 2, c: 3)
end
it 'works with splat operator' do
args = [ :x, :y, :z ]
kwargs = { a: 1, b: 2, c: 3 }
expect(fn).to receive(:call).with(:x, :y, a: 1, b: 2)
Amenable.call(fn, *args, **kwargs)
end
it 'works with default args' do
expect(fn).to receive(:call).with(:x, a: 1).and_call_original
expect(Amenable.call(fn, :x, a: 1)).to eq([
[ :x, :y ],
{ a: 1, b: 2 },
])
end
it 'raises if required arguments are not passed' do
expect {
Amenable.call(fn, :x)
}.to raise_error(ArgumentError)
expect {
Amenable.call(fn, :x, :y)
}.to raise_error(ArgumentError)
expect {
Amenable.call(fn, :x, :y, b: 2)
}.to raise_error(ArgumentError)
expect {
Amenable.call(fn, a: 1, b: 2)
}.to raise_error(ArgumentError)
end
context 'with var args' do
let(:fn) { proc {|x, *z, a:, **c| [ x, z, a, c ] } }
it 'works with just enough args' do
expect(fn).to receive(:call).with(:x, a: 1).and_call_original
expect(Amenable.call(fn, :x, a: 1)).to eq([
:x, [], 1, {},
])
end
it 'fails without enough args' do
expect {
Amenable.call(fn, :x)
}.to raise_error(ArgumentError)
expect {
Amenable.call(fn, a: 1)
}.to raise_error(ArgumentError)
end
it 'passes through all args' do
expect(Amenable.call(fn, :x, :y, :z, a: 1, b: 2, c: 3)).to eq([
:x, [ :y, :z ], 1, { b: 2, c: 3 },
])
end
end
context 'with a method' do
before do
def test_fn(x, a:, &block)
[ x, a, block ]
end
end
it 'works all the same' do
test_block = proc {}
expect(Amenable.call(method(:test_fn), :x, a: 1, &test_block)).to eq([
:x, 1, test_block
])
end
end
context 'with a method that does not take params' do
before do
def test_fn; end
end
it 'works without args' do
expect(Amenable.call(method(:test_fn))).to be_nil
end
it 'works with args' do
expect(Amenable.call(method(:test_fn), :x, :y)).to be_nil
end
it 'works with kwargs' do
expect(Amenable.call(method(:test_fn), a: 1, b: 2)).to be_nil
end
end
context 'with a method that only takes args' do
before do
def test_fn(arg)
arg
end
end
it 'fails without args' do
expect {
Amenable.call(method(:test_fn))
}.to raise_error(ArgumentError)
end
it 'works with args' do
expect(Amenable.call(method(:test_fn), :x, :y)).to be :x
end
it 'works with kwargs' do
expect(Amenable.call(method(:test_fn), :x, a: 1, b: 2)).to be :x
end
end
context 'with a method that only takes varargs' do
before do
def test_fn(*args)
args
end
end
it 'works without args' do
expect(Amenable.call(method(:test_fn))).to eq []
end
it 'works with args' do
expect(Amenable.call(method(:test_fn), :x, :y)).to eq [ :x, :y ]
end
it 'works with kwargs' do
expect(Amenable.call(method(:test_fn), :x, :y, a: 1, b: 2)).to eq [ :x, :y ]
end
end
context 'with a method that only takes keywords' do
before do
def test_fn(a:)
a
end
end
it 'fails without args' do
expect {
Amenable.call(method(:test_fn))
}.to raise_error(ArgumentError)
end
it 'works with args' do
expect(Amenable.call(method(:test_fn), :x, a: 1)).to be 1
end
it 'works with kwargs' do
expect(Amenable.call(method(:test_fn), a: 1, b: 2)).to be 1
end
end
it 'requires a Method or Proc' do
expect {
Amenable.call(:foo)
}.to raise_error(ArgumentError)
end
end
end
| true |
23baeec3c37e51a4f8c318ccb8930c05ecce39ef | Ruby | RubyPearls/recipebox | /app.rb | UTF-8 | 2,213 | 2.59375 | 3 | [] | no_license | require("bundler/setup")
Bundler.require(:default)
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each { |file| require file }
get('/') do
erb(:index)
end
get("/recipes") do
@recipes = Recipe.all()
@categories = Category.all()
# # ... VERY general 'pseudo-code' on how to iterate
# # ... thru categories and all recipes tied to them
# @categories = Category.all()
#
# @categories.each() do |category|
# category.name() + '\n'
# category.recipes().each() do |recipe|
# '\t' + recipe.name() + '\n'
# end
# end
erb(:recipe)
end
post("/recipes") do
recipe_name = params.fetch("recipe_name")
recipe_desc = params.fetch("recipe_desc")
recipe = Recipe.create({ :name => recipe_name,
:description => recipe_desc })
category = Category.find(params.fetch("category_id").to_i())
recipe.categories().push(category)
redirect("/recipes")
end
get("/recipes/:id") do
@recipe = Recipe.find(params.fetch("id").to_i)
@ingredients = @recipe.ingredients()
@instructions = @recipe.instructions()
erb(:recipe_detail)
end
patch("/recipes/:id") do
recipe_id = params.fetch("id").to_i()
recipe_name = params.fetch("recipe_name")
@recipe = Recipe.find(recipe_id)
@recipe.update({:name => recipe_name})
redirect("/recipes/" + recipe_id.to_s())
end
delete("/recipes/:id") do
recipe_id = params.fetch("id").to_i()
@recipe = Recipe.find(recipe_id)
@recipe.delete()
redirect("/recipes")
end
post("/recipes/:id/ingredients") do
ingredient_name = params.fetch("ingredient_name")
recipe_id = params.fetch("id").to_i()
@recipe = Recipe.find(recipe_id)
@recipe.ingredients().create({ :name => ingredient_name })
redirect("/recipes/" + recipe_id.to_s())
end
post("/recipes/:id/instructions") do
instruction_name = params.fetch("instruction_name")
recipe_id = params.fetch("id").to_i()
@recipe = Recipe.find(recipe_id)
@recipe.instructions().create({ :name => instruction_name })
redirect("/recipes/" + recipe_id.to_s())
end
get("/categories") do
@categories = Category.all()
erb(:category)
end
post("/categories") do
category_name = params.fetch("category")
Category.create({ :name => category_name })
redirect("/categories")
end
| true |
95b8ac55ab6e9ac12b8dd602916ddfac2d9e6b24 | Ruby | iwasaki-y/ruby-training | /Lesson5/loop2.rb | UTF-8 | 81 | 3.53125 | 4 | [] | no_license | i = 0
loop do
if i > 5 then
break
end
puts(i)
i = i + 1
end | true |
8c3f5a8546b806468c5d4bd9ce3a695ddf8e98e1 | Ruby | nvalchanov96/english-numbers | /english_numbers_spec.rb | UTF-8 | 1,745 | 3.546875 | 4 | [
"MIT"
] | permissive | require_relative "english_numbers"
RSpec.describe EnglishNumber do
describe "#in_english" do
it "translate singles" do
expect(EnglishNumber.new(2).in_english).to eq("two")
end
it "translate negative singles" do
expect(EnglishNumber.new(-2).in_english).to eq("minus two")
end
it "translate tens" do
expect(EnglishNumber.new(20).in_english).to eq("twenty")
end
it "translate negative tens" do
expect(EnglishNumber.new(-20).in_english).to eq("minus twenty")
end
it "translate teens" do
expect(EnglishNumber.new(16).in_english).to eq("sixteen")
end
it "translate teens" do
expect(EnglishNumber.new(-16).in_english).to eq("minus sixteen")
end
it "returns nil if the number is bigger than 99" do
expect(EnglishNumber.new(100).in_english).to eq(nil)
end
it "returns nil if the number is smaller than 99" do
expect(EnglishNumber.new(-100).in_english).to eq(nil)
end
it "combines tens and singles" do
expect(EnglishNumber.new(81).in_english).to eq("eighty-one")
end
it "combines negative tens and singles" do
expect(EnglishNumber.new(-81).in_english).to eq("minus eighty-one")
end
it "combines tens and singles and ignores the decimal point" do
expect(EnglishNumber.new(81.5).in_english).to eq("eighty-one")
end
it "combines negative tens and singles and ignores the decimal point" do
expect(EnglishNumber.new(-81.5).in_english).to eq("minus eighty-one")
end
it "translate zero" do
expect(EnglishNumber.new(0).in_english).to eq("zero")
end
it "translate 27.1" do
expect(EnglishNumber.new(27.1).in_english).to eq("twenty-seven")
end
end
end
| true |
dfffee41e9035686728f9e0a9a720d16a927dbf1 | Ruby | Nekototori/toolkit | /facts/ensure_package.rb | UTF-8 | 790 | 2.5625 | 3 | [] | no_license | ###################
# package_version #
###################
#
# This fact will use the Puppet RAL to query whether a package has been
# installed (using the default package provider). If it is, the version string
# that Puppet is aware of will be reported. If not, this fact will be absent.
#
# To specify the name of the package you're looking for, just change the
# "package" variable below from 'bash' to the package name as known by the
# default package provider.
#
require 'puppet/type/package'
Facter.add(:centrify) do
setcode do
package = 'bash'
instance = Puppet::Type.type('package').instances.select { |pkg| pkg.name == package }.first
if instance
ensure_property = instance.property(:ensure)
instance.retrieve[ensure_property]
end
end
end
| true |
b212dd18f47d4940008f8da400137293accff9b8 | Ruby | sonchez/course_101 | /101_109_small_problems/easy_5/after_midnight_1.rb | UTF-8 | 489 | 3.421875 | 3 | [] | no_license |
def time_of_day(minutes)
hours_in_day = 24
minutes_in_day = 1440
return "00:00" if minutes == 0
base_minutes = minutes%minutes_in_day
hours = (base_minutes/60)
minutes = base_minutes - (hours*60)
"#{format("%002d", hours) }:#{format("%002d", minutes)}"
end
p time_of_day(0) == "00:00"
p time_of_day(-3) == "23:57"
p time_of_day(35) == "00:35"
p time_of_day(-1437) == "00:03"
p time_of_day(3000) == "02:00"
p time_of_day(800) == "13:20"
p time_of_day(-4231) == "01:29"
| true |
e3afe6f1633482ca19a40720ce53ea280b5ccd1a | Ruby | nfukasawa/lgtm | /lgtm_cli.rb | UTF-8 | 1,750 | 2.875 | 3 | [
"MIT"
] | permissive | require 'RMagick'
require 'optparse'
class LGTMBuilder
LGTM_IMAGE_WIDTH = 1_000
def initialize(in_filepath)
@sources = Magick::ImageList.new(in_filepath)
end
def build(out_filepath, options = {})
images = Magick::ImageList.new
@sources.each_with_index do |source, index|
target = source
target = blur(target) if options[:blur]
target = lgtmify(target, options)
target = glitch(target) if options[:glitch]
target.delay = source.delay
images << target
end
images.iterations = 0
images.
optimize_layers(Magick::OptimizeLayer).
write(out_filepath)
end
private
def width
@sources.first.columns
end
def height
@sources.first.rows
end
def lgtm_image(options)
return @lgtm_image if @lgtm_image
scale = width.to_f / LGTM_IMAGE_WIDTH
if options[:with_comments]
path = './images/lgtm_with_comments.gif'
else
path = './images/lgtm.gif'
end
@lgtm_image = ::Magick::ImageList.new(path).scale(scale)
end
def glitch(source)
colors = []
color_size = source.colors
blob = source.to_blob
color_size.times do |index|
colors << blob[20 + index, 3]
end
color_size.times do |index|
blob[20 + index, 3] = colors.sample
end
Magick::Image.from_blob(blob).first
end
def blur(source)
source.blur_image(0.0, 5.0)
end
def lgtmify(source, options)
source.composite!(
lgtm_image(options),
::Magick::CenterGravity,
::Magick::OverCompositeOp
)
end
end
opts = ARGV.getopts('i:o:gbc')
LGTMBuilder.new(opts['i']).build(
opts['o'],
{
:glitch => opts['g'],
:blur => opts['b'],
:with_comments => opts['c']
}
)
| true |
7d13ddeef7bdef1c02f472263a71725ab53b5b5e | Ruby | dgrahn/baregrades | /app/helpers/courses_helper.rb | UTF-8 | 1,457 | 2.71875 | 3 | [] | no_license | module CoursesHelper
#Create a Temp calendar file and download it
def download_course_calendar(course)
# create a temporary file named after the course name
require 'date'
require 'tempfile'
file = Tempfile.new(["#{course.name} ", ".ics"])
begin
# Write the calendar to the file
file.write("BEGIN:VCALENDAR\n");
file.write("PRODID:-//BareGrades//BareGrades Calendar 1.1//EN\n");
file.write("VERSION:2.0\n");
file.write("\n");
# Find all of the assignments in the course
course.assignments.each do |assignment|
# Get the Date of the event
date = assignment.due_date
if date.blank?
date = course.end_date
end # if
# Change the date format
date = date.strftime("%Y%m%d")
# Begin the assingmment event
file.write("BEGIN:VEVENT\n");
file.write("DTSTART;VALUE=DATE:#{date}T000000Z\n"); # Start time
file.write("DTEND;VALUE=DATE:#{date}T000000Z\n"); # End time
file.write("SUMMARY;ENCODING=QUOTED-PRINTABLE:#{assignment.name}\n"); # Class identifier
file.write("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:#{assignment.description}\n"); # course name
# End the assignment event
file.write("END:VEVENT\n");
file.write("\n");
end # each do
file.write("END:VCALENDAR\n");
# Download the file
send_file(file);
ensure # forcefully close and delete the file
file.close
file.unlink
end # begin
end # download_calendar
end | true |
7f5b7a954d5c6212e625fbbe1cbb74d9a5a312cd | Ruby | hokkai7go/study_ruby_silver | /array.rb | UTF-8 | 708 | 3.296875 | 3 | [] | no_license | String
String.superclass
String.superclass.superclass
Array
[1, 5, 9]
[1, 5, 9].class
ary = [1, 5, 9]
ary.all
ary.all?
ary.all? {|v| v> 0}
ary.all? {|v| v > 0}
ary.all? {|v| v < 0}
bry = [1, nil, 4]
bry.all?
bry = [1, false, 4]
bry.all?
ary.map {|n| n**2 / 2}
ary.map {|n| n**2 / 2.0}
cry = []
cry.cycle
cry.cycle()
dry.cycle
cry = [1, 2, 3, 4, 5, 6, 7, 8, 8]
cry.find
cry.find(2)
cry.find {|i| i > 3}
cry.detect {|i| i > 3}
cry.detect(ifnone = nil) {|i| i > 3}
cry.detect(ifnone = nil) {|i| i > 100}
cry
cry.drip
cry.drop(4)
ary & bry
ary
bry
cry
ary & cry
ary.sep
ary.sep(*)
ary.sep('*')
Array#sep
$ Array#sep
? Array#sep
? Array#*
$ Array#*
ary * 3
ary + 2
ary + [2]
ary + [3]
ary
ary - [5]
? Object#eql?
| true |
8795c95d57cda0f80bb4cac3b443363b0c5009a6 | Ruby | julianGallegos/algorithm_practice | /find_duplicate.rb | UTF-8 | 252 | 3.265625 | 3 | [] | no_license |
def show_all_duplicates(input_array)
@amount_of_times_repeated = Hash.new(0)
input_array.each do |num|
@amount_of_times_repeated[num] += 1
end
return @amount_of_times_repeated
end
p show_all_duplicates([1,2,3,4,5,6,7,8,8,8,8,9,1,2,3,4,5,6,7]) | true |
5bb4a0d6208cb8c9d8cdcf0c3a97db1f5ca63c5a | Ruby | a-nickol/bullet_journal | /lib/bullet_journal/calendar/layouts/collector.rb | UTF-8 | 842 | 2.734375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module BulletJournal
##
# Class which records all methods calls.
#
class CollectorProxy < BasicObject
def initialize(recorder)
@recorder = recorder
end
private
# rubocop:disable Style/MethodMissing
def method_missing(method, *_args, &block)
@recorder[method] = block
end
# rubocop:enable Style/MethodMissing
def respond_to_missing?(_method_name, _include_private = false)
true
end
end
##
# The Collector records a block given and is able to playback the
# called methods.
#
class Collector
def initialize(&block)
@recorder = {}
record_block(&block) if block
end
def record_block
proxy = CollectorProxy.new @recorder
yield proxy
end
def recorded_methods
@recorder
end
end
end
| true |
c5796396d65faaf272e678cc5983ef8760b79519 | Ruby | saulomendonca/live-bolao | /app/models/prediction.rb | UTF-8 | 842 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | # == Schema Information
#
# Table name: predictions
#
# id :integer not null, primary key
# home_team_goal :integer
# away_team_goal :integer
# game_id :integer
# user_id :integer
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_predictions_on_game_id (game_id)
# index_predictions_on_user_id (user_id)
#
class Prediction < ActiveRecord::Base
belongs_to :game
belongs_to :user
validates :home_team_goal, numericality: { only_integer: true, greater_than: -1 }
validates :away_team_goal, numericality: { only_integer: true, greater_than: -1 }
validates :game, presence: true
validates :user, presence: true
def draw?
self.home_team_goal == self.away_team_goal
end
def home_team_winner?
self.home_team_goal > self.away_team_goal
end
end
| true |
6c9c7d873c7afb2248622cc98c1676d2c6126ee8 | Ruby | etdev/algorithms | /0_code_wars/credit_card_mask.rb | UTF-8 | 153 | 2.734375 | 3 | [
"MIT"
] | permissive | # http://www.codewars.com/kata/5412509bd436bd33920011bc
# --- iteration 1 ---
def maskify(cc)
cc.length > 4 ? cc[-4,4].rjust(cc.length, "#") : cc
end
| true |
3a2495568539c60797cbe177b14998c2a4be92ab | Ruby | khakimov/id_encoder | /lib/id_encoder.rb | UTF-8 | 3,377 | 3.34375 | 3 | [
"MIT"
] | permissive | # Short URL Generator
# ===================
# Ruby implementation for generating Tiny URL- and bit.ly-like URLs.
# A bit-shuffling approach is used to avoid generating consecutive, predictable
# URLs. However, the algorithm is deterministic and will guarantee that no
# collisions will occur.
# The URL alphabet is fully customizable and may contain any number of
# characters. By default, digits and lower-case letters are used, with
# some removed to avoid confusion between characters like o, O and 0. The
# default alphabet is shuffled and has a prime number of characters to further
# improve the results of the algorithm.
# The block size specifies how many bits will be shuffled. The lower BLOCK_SIZE
# bits are reversed. Any bits higher than BLOCK_SIZE will remain as is.
# BLOCK_SIZE of 0 will leave all bits unaffected and the algorithm will simply
# be converting your integer to a different base.
# The intended use is that incrementing, consecutive integers will be used as
# keys to generate the short URLs. For example, when creating a new URL, the
# unique integer ID assigned by a database could be used to generate the URL
# by using this module. Or a simple counter may be used. As long as the same
# integer is not used twice, the same short URL will not be generated twice.
# The module supports both encoding and decoding of URLs. The min_length
# parameter allows you to pad the URL if you want it to be a specific length.
# Sample Usage:
#
# gem install id_encoder
#
# >> require 'id_encoder'
# => true
# >> IdEncoder::UrlEncoder.encode_url(10)
# => "csqsc"
# >> IdEncoder::UrlEncoder.decode_url('csqsc')
# => 10
#
# Use the functions in the top-level of the module to use the default encoder.
# Otherwise, you may create your own UrlEncoder object and use its encode_url
# and decode_url methods.
# Author of Python version: Michael Fogleman
# Link: http://code.activestate.com/recipes/576918/
# License: MIT
# Author of Ruby version: Ruslan Khakimov
# Link: http://github.com/khakimov/id_encoder
# License: MIT
require "id_encoder/version"
DEFAULT_ALPHABET = 'mn6j2c4rv8bpygw95z7hsdaetxuk3fq'
DEFAULT_BLOCK_SIZE = 24
MIN_LENGTH = 4
module IdEncoder
class UrlEncoder
@alphabet = DEFAULT_ALPHABET
@block_size = DEFAULT_BLOCK_SIZE
@mask = (1 << @block_size) - 1 # left-shift
@mapping = (0..(@block_size-1)).to_a.reverse!
def self.encode_url(n, min_length=MIN_LENGTH)
enbase(encode(n), min_length)
end
def self.decode_url(n)
decode(debase(n))
end
def self.encode(n)
(n & ~@mask) | _encode(n & @mask)
end
def self.decode(n)
(n & ~@mask) | _decode(n & @mask)
end
def self._encode(n)
result = 0
@mapping.each_with_index { |item, index|
if n & (1 << index) != 0
result = result | (1 << item)
end
}
result
end
def self._decode(n)
result = 0
@mapping.each_with_index { |item, index|
if n & (1 << item) != 0
result = result | (1 << index)
end
}
result
end
def self.enbase(x, min_length=MIN_LENGTH)
_enbase(x)
end
def self._enbase(x)
n = @alphabet.size
if x < n
return @alphabet[x]
end
_enbase(x/n) + @alphabet[x % n]
end
def self.debase(x)
n = @alphabet.size
result = 0
a = x.split('').reverse
a.each_with_index {|item, i|
result += @alphabet.index(item) * (n ** i)
}
result
end
end
end | true |
0dc70326435e3949cca60c173f8c0cd7c60af0d3 | Ruby | youmuyou/huginn_zh | /app/models/agents/commander_agent.rb | UTF-8 | 1,924 | 2.640625 | 3 | [
"MIT"
] | permissive | module Agents
class CommanderAgent < Agent
include AgentControllerConcern
cannot_create_events!
description <<-MD
Commander Agent由时间计划或传入的事件触发,并命令其他代理(“目标”)运行,禁用,配置或启用自身
# 操作类型
将`action`设置为以下某个操作类型:
* `run`: 触发此代理时会运行目标代理.
* `disable`: 触发此代理时,将禁用目标代理(如果未禁用)
* `enable`: 触发此代理时,将启用目标代理(如果未启用).
* `configure`: 目标代理使用`configure_options`的内容更新其选项。
这是一个提示:您可以使用 [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid)模板动态确定操作类型。 例如:
- 要创建一个CommanderAgent,每天早上从WeatherAgent接收一个事件,以启动仅在天气晴朗时才有用的代理流程,请尝试以下操作: `{% if conditions contains 'Sunny' or conditions contains 'Cloudy' %}` `run{% endif %}`
- 同样,如果您有为雨天特制的预定代理流程,请尝试以下方法: `{% if conditions contains 'Rain' %}enable{% else %}disabled{% endif %}`
- 如果要基于UserLocationAgent更新WeatherAgent,可以使用'action':'configure'并将'configure_options'设置为 `{ 'location': '{{_location_.latlng}}' }`.
- 在模板中,您可以使用变量目标来引用每个目标代理,它具有以下属性: #{AgentDrop.instance_methods(false).map { |m| "`#{m}`" }.to_sentence}.
# 目标
从此CommanderAgent中选择要控制的代理.
MD
def working?
true
end
def check
control!
end
def receive(incoming_events)
incoming_events.each do |event|
interpolate_with(event) do
control!
end
end
end
end
end
| true |
747958186d5340088087c2454e89c0df46fed79a | Ruby | nyc-rock-doves-2016/oop_inheritance_module | /super.rb | UTF-8 | 435 | 3.796875 | 4 | [] | no_license | class Bicycle
attr_reader :seat
def initialize(gear)
@wheels = 2
@seat = 1
@gear = gear
end
def to_s
"wheels - #{@wheels}, seat - #{@seat}, gear- #{@gear}"
end
end
class Tandem < Bicycle
def initialize(gear)
super(gear)
@seat = self.seat + 2
@color = "white"
end
def to_s
super + ", color - #{@color}"
end
end
b = Bicycle.new(3)
p b.to_s
tandem = Tandem.new(6)
p tandem.to_s
| true |
88e0f38b75721eeab090454adb1fe08789a3a8ba | Ruby | 0x-CHUN/CSE341 | /practice/partC.rb | UTF-8 | 442 | 3.421875 | 3 | [] | no_license | class Point
attr_accessor :x, :y
def initialize(x,y)
@x = x
@y = y
end
def distFromOrigin # direct field access
Math.sqrt(@x*@x + @y*@y)
end
def distFromOrigin2 # use getters
Math.sqrt(x*x + y*y)
end
end
class ColorPoint < Point
attr_accessor :color
def initialize(x,y,c)
super(x,y)
@color = c
end
end
p = Point.new(0,0)
cp = ColorPoint.new(0,0,"red")
| true |
05f90d3bab23b743dad4bf2aff4c486540a11632 | Ruby | MonalisaC/hotel | /lib/block.rb | UTF-8 | 281 | 2.578125 | 3 | [] | no_license | require 'date'
require_relative 'booking'
require_relative 'invalid_duration_error'
module BookingSystem
class Block < Booking
attr_reader :rooms, :rate
def initialize(input)
super(input)
@rooms = input[:rooms]
@rate = input[:rate]
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.