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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f4a8a84d6ecf06de043d696ac8b7b8f5f7faafd5 | Ruby | ada74m/grebe | /spec/models/criteria/criterion_spec.rb | UTF-8 | 5,383 | 2.640625 | 3 | [] | no_license | require 'spec_helper'
describe Criterion do
describe "when in a hierarchy" do
before(:each) do
@root = CompositeCriterion.and
@root.children << (@or = CompositeCriterion.or)
@or.children << (@built1974 = Equals.new :model => :ship, :property => :built_year, :integer_a => 1974)
@or.children << (@built_1981 = Equals.new :model => :ship, :property => :built_year, :integer_a => 1981)
@or.children << (@and = CompositeCriterion.and)
@and.children << (Equals.new :model => :ship, :property => :cranes, :integer_a => 2)
@and.children << (Equals.new :model => :ship, :property => :winches, :integer_a => 2)
@root.children << (@dwtOneMill = Equals.new :model => :ship, :property => :dwt, :integer_a => 1000000)
@root.save!
end
it "should know about its parent" do
@or.parent.should == @root
end
it "should know about its children" do
@root.children.should have(2).items
end
it "should describe itself" do
@root.description.should == "((ship.built_year equals 1974 or ship.built_year equals 1981 or (ship.cranes equals 2 and ship.winches equals 2)) and ship.dwt equals 1000000)"
end
it "should stay the same when you reload" do
original_description = @root.description
copy = Criterion.find @root.id
copy.description.should == original_description
end
end
describe "normalisation (i.e. pushing down negativity to leafs)" do
before(:each) do
@root = CompositeCriterion.and :negative => true
@root.children << (@or = CompositeCriterion.or)
@or.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1981)
@or.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1974, :negative => true)
@root.children << (@nor = CompositeCriterion.or :negative => true)
@nor.children << (Equals.new :model => :ship, :property => :dwt, :integer_a => 1000000)
@nor.children << (Equals.new :model => :ship, :property => :dwt, :integer_a => 2000000)
@root.description.should == "not ((ship.built_year equals 1981 or ship.built_year does not equal 1974) and not (ship.dwt equals 1000000 or ship.dwt equals 2000000))"
end
it "should know when it is not in normal form" do
@root.should_not be_normal
end
it "should push down the negativity into the leaves" do
@root.normalise
@root.description.should == "((ship.built_year does not equal 1981 and ship.built_year equals 1974) or (ship.dwt equals 1000000 or ship.dwt equals 2000000))"
end
it "should know when it is in normal form" do
@root.normalise
@root.should be_normal
end
it "should restore negativity" do
@root.normalise
@root.restore
@root.description.should == "not ((ship.built_year equals 1981 or ship.built_year does not equal 1974) and not (ship.dwt equals 1000000 or ship.dwt equals 2000000))"
end
end
class Spy
@messages = []
def self.clear
@messages = []
end
def self.inform message
@messages << message
end
def self.messages
@messages
end
end
describe "on loading" do
before(:each) do
Spy.clear
@root = CompositeCriterion.and :negative => true
@root.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1981)
@root.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1974)
#@root.children << (nested_or = CompositeCriterion.or)
#nested_or.children << (Equals.new :model => :ship, :property => :dwt, :integer_a => 3000)
#nested_or.children << (Equals.new :model => :ship, :property => :dwt, :integer_a => 4000)
@root.save!
class CompositeCriterion
alias :on_after_find_orig :on_after_find
def on_after_find
Spy.inform "before after_initialise was run, normal? was #{self.normal?}"
on_after_find_orig
end
end
end
after(:each) do
class CompositeCriterion
alias :on_after_find :on_after_find_orig
end
end
it "should be normal as it leaves database but not normal after being fully loaded" do
@root.reload
Spy.messages.should =~ ["before after_initialise was run, normal? was true"]
@root.should_not be_normal
end
end
describe "on saving" do
before(:all) do
Spy.clear
@root = CompositeCriterion.and :negative => true
@root.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1981)
@root.children << (Equals.new :model => :ship, :property => :built_year, :integer_a => 1974)
class CompositeCriterion
alias :on_before_save_orig :on_before_save
def on_before_save
on_before_save_orig
Spy.inform "after before_save was run, normal? was #{self.normal?}"
end
end
end
after(:all) do
class CompositeCriterion
alias :on_before_save :on_before_save_orig
end
end
it "should be normalised after before_save has run and denormalised again later" do
@root.should_not be_normal
Spy.messages.should =~ []
@root.save
Spy.messages.should =~ ["after before_save was run, normal? was true"]
@root.should_not be_normal
end
end
end | true |
92145d072875e92319ecdd5383e7685e68c26a3b | Ruby | amcrawford/web_guesser | /web_guesser.rb | UTF-8 | 776 | 3.328125 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader'
NUMBER = rand(100)
get '/' do
guess = params["guess"]
message = check_guess(guess)
erb :index, :locals =>{:number => NUMBER, :message => message, :background_color => @background_color}
end
def check_guess(guess)
variation = guess.to_i - NUMBER
if variation > 0
find_how_far(variation, "high")
elsif variation < 0
find_how_far(variation, "low")
else
@background_color = "lightgreen"
message = "The SECRET NUMBER is #{NUMBER}. You got it right!"
end
end
def find_how_far(variation, high_or_low)
@@guess - 1
if variation.abs > 5
@background_color = "crimson"
message = "Way too #{high_or_low}!"
else
@background_color = "darksalmon"
message = "Too #{high_or_low}!"
end
end
| true |
3af9fb05511ab31ca647a770d3d1652b632a4c1c | Ruby | MIsatoFujihara/game | /game.rb | UTF-8 | 3,520 | 3.421875 | 3 | [] | no_license | # カレントディレクトリにあるファイルをrequire
# maruの状態(trueかfalseか)をtableの状態(int型)にして返す
# ○がおかれていたら表の状態は1,×がおかれていたら表の状態は2
def player_state(player)
return player ? Maru : Batsu
end
# 3つそろっていたらtrue,そうでなければfalseを返す関数
# ClearCheckクラスを扱う
def call_clear(table, player)
# table[0][0]は縦横斜め方向にそろっているかを調べる
check = ClearCheck.new(0, 0, table, player)
if check.naname()||check.yoko()||check.tate()
return true
end
check2 = ClearCheck.new(1, 0, table, player)
check3 = ClearCheck.new(2, 0, table, player)
check4 = ClearCheck.new(0, 1, table, player)
check5 = ClearCheck.new(0, 2 ,table, player)
# table[1][0],table[2][0]は横方向にそろっているか調べる
return true if check2.yoko()
return true if check3.yoko()||check3.naname2()
# table[0][1],tanle[0][2]は縦方向にそろっているか調べる
return true if check4.tate()
return true if check5.tate()
# どこもそろっていなかったら0を返す
return false
end
# 出力される表の位置番号をtableの添え字に変換
def number_index(num)
x = (num - 1) % 3
y = (num - 1) / 3
return x, y
end
# tableの添え字を出力される表の位置番号に変換
def index_number(x, y)
x + 1 + y * 3;
end
# 各要素の表示
def output(i, j, mark)
(j + 1) % 3 == 0 ? third_column = true : third_row = false
if mark == Maru
print(" ○")
elsif mark == Batsu
print(" ×")
else
print(" #{index_number(j, i)} ")
end
print third_column ? "" : "|"
end
# tableの行単位に制御
def output_rows(i, *pos)
(i + 1) % 3 == 0 ? third_row = true : third_row = false
print(" ")
j = 0
pos.each do |mark|
output(i, j, mark)
j += 1
end
print("\n")
print third_row ? "\n" : " ---+---+---\n"
end
# tableの出力を列ごとに制御
def output_columns(table)
i = 0
print("\n")
table.each do |elm1, elm2, elm3|
output_rows(i, elm1, elm2, elm3)
i += 1
end
end
# Set_positioinクラスのインスタンスを扱う関数
# 入力に関する制御を行う
def call_set(num, table, player)
x, y = number_index(num)
pos = SetPosition.new(x, y, table, player)
if num > 9||num < 1||pos.check_position == false
puts("もう一度入力してください")
input(player, table)
else
# ○または×が置かれた新しいtableが帰ってくる
pos.set_position
end
end
# 入力を行う
def input(player, table)
print("今は")
puts player ? "○の番です\n":"×の番です\n"
print("入力>")
num = gets.to_i
# ○または×が置かれた新しいtableが帰ってくる
call_set(num, table, player)
end
# gameクリア画面の表示
def is_clear(player)
print("winner>")
puts player ? "○\n":"×\n"
end
# gameoverの判定
# 表が埋まっていたらgameover
def is_gameover?(i)
return i >= 9 ? true :false
end
# gameoverの表示
def view_gameover
puts("gameover")
end
# gameを行う関数
def game(player, table)
i = 0
loop do
table=input(player, table)
output_columns(table)
i += 1
# gameclearの判定を行う
if call_clear(table, player)
is_clear(player)
break
end
# gameoverの判定を行う
if is_gameover?(i)
view_gameover()
break
end
player = !player # 今の手を反転的に変更
end
end
| true |
e1840d41371c8ca67326ed610bf7c3e4e43be636 | Ruby | earl-stephens/enigma | /lib/key.rb | UTF-8 | 1,206 | 3.34375 | 3 | [] | no_license | class Key
attr_reader :random_number,
:key_array,
:converted_key_array,
:number_as_string
def initialize
@random_number = ""
@key_array =[]
@converted_key_array = []
end
def main_test_method(number)
test_random_number(number)
fill_in_zeroes
populate_key_array
convert_key_array
end
def main_method
random_number_generator
fill_in_zeroes
populate_key_array
convert_key_array
end
def random_number_generator
generator = Random.new
@random_number = generator.rand(100000)
@random_number = @random_number.to_s
return generator
end
def test_random_number(number)
@random_number = number
end
def fill_in_zeroes
@random_number = @random_number.rjust(5, "0")
@number_as_string = @random_number
@random_number
end
def populate_key_array
counter = 0
4.times do
number = @random_number[counter].concat(@random_number[counter + 1])
@key_array << number
counter += 1
end
@key_array
end
def convert_key_array
@key_array.map do |element|
@converted_key_array << element.to_i
end
@converted_key_array
end
end
| true |
0153f359436c7c0183a6b2ef8ddfa46f1ff99032 | Ruby | nickpearson/dottie | /lib/dottie/freckle.rb | UTF-8 | 1,191 | 3.40625 | 3 | [
"MIT"
] | permissive | module Dottie
class Freckle
include Methods
##
# Creates a new Freckle to wrap the supplied object.
def initialize(obj)
case obj
when Hash, Array
@_wrapped_object = obj
else
raise TypeError, 'must be a Hash or Array'
end
end
##
# Returns the wrapped Hash, and raises an error if the wrapped object is
# not a Hash.
def hash
wrapped_object(Hash)
end
##
# Returns the wrapped Array, and raises an error if the wrapped object is
# not an Array.
def array
wrapped_object(Array)
end
##
# Returns the wrapped object, and raises an error if a type class is
# provided and the wrapped object is not of that type.
def wrapped_object(type = nil)
if type.nil? || @_wrapped_object.is_a?(type)
@_wrapped_object
else
raise TypeError.new("expected #{type.name} but got #{@_wrapped_object.class.name}")
end
end
def inspect
"<Dottie::Freckle #{wrapped_object.inspect}>"
end
def method_missing(method, *args)
wrapped_object.send(method, *args)
end
end
end
| true |
157f48550720c7b1a5307199edabd1f76dbee447 | Ruby | karlwitek/launch_school_rb120 | /oop_exercises/medium2/fe_ranking_cards.rb | UTF-8 | 2,191 | 3.984375 | 4 | [] | no_license | class Card
include Comparable
attr_reader :rank, :suit
SUIT_VALUES = { 'Spades' => 4, 'Hearts' => 3, 'Clubs' => 2, 'Diamonds' => 1 }
def initialize(rank, suit)
@rank = rank
@suit = suit
end
def ranking
case @rank
when 'Jack' then 11
when 'Queen' then 12
when 'King' then 13
when 'Ace' then 14
else
@rank
end
end
def <=>(other)
val = ranking <=> other.ranking
return val if val == 1 || val == -1
suit_value <=> other.suit_value
end
def suit_value
SUIT_VALUES[suit]
end
def to_s
"#{rank} of #{suit}"
end
end
# cards = [Card.new(3, 'Hearts'),
# Card.new(3, 'Clubs'),
# Card.new(3, 'Spades')]
# puts cards.min # 3 of Clubs
# puts cards.max # 3 of Spades
cards = [Card.new(2, 'Hearts'),
Card.new(10, 'Diamonds'),
Card.new('Ace', 'Clubs')]
puts cards
puts cards.min == Card.new(2, 'Hearts')
puts cards.max == Card.new('Ace', 'Clubs')
cards = [Card.new(5, 'Hearts')]
puts cards.min == Card.new(5, 'Hearts')
puts cards.max == Card.new(5, 'Hearts')
cards = [Card.new(4, 'Hearts'),
Card.new(4, 'Diamonds'),
Card.new(10, 'Clubs')]
puts cards.min.rank == 4
puts cards.max == Card.new(10, 'Clubs')
cards = [Card.new(7, 'Diamonds'),
Card.new('Jack', 'Diamonds'),
Card.new('Jack', 'Spades')]
puts cards.min == Card.new(7, 'Diamonds')
puts cards.max.rank == 'Jack'
cards = [Card.new(8, 'Diamonds'),
Card.new(8, 'Clubs'),
Card.new(8, 'Spades')]
puts cards.min.rank == 8
puts cards.max.rank == 8
# Another example from student solutions:
# #rank_to_compare returns rank
# def rank_to_compare
# rank.is_a?(Integer) ? rank : FACES[rank]
# end
# def <=>(other)
# [rank_to_compare, VAL[suit]] <=> [other.rank_to_compare, VAL[suit]]
# end
# example of writing our own < method using our own <=> method
# def <(other)
# return true if self.<=>(other) == -1
# return false
# end
# example: <=
# def <=(other)
# val = self.<=>(other)
# return true if (val == -1) || (val == 0)
# return false
# end
| true |
f03f4f400d55fdceed28c056f18d5cd4602b096d | Ruby | TaylorWu21/school_rspec | /app/models/classroom.rb | UTF-8 | 298 | 2.765625 | 3 | [] | no_license | class Classroom < ActiveRecord::Base
validates_presence_of :name
belongs_to :school
def classroom_name
"#{name} is a cool class."
end
def classroom_size
if (size >= 50)
"Big class"
elsif (size < 50 && size > 25)
"Medium class"
else (size < 30)
"Small class"
end
end
end
| true |
ffdaadfbbd9ceace35b4e9ac9e978e44a332980b | Ruby | jpheos/batch-586 | /02-OOP/food-delivery/livecodes/food-delivery-reboot/app/repositories/customer_repository.rb | UTF-8 | 426 | 2.8125 | 3 | [] | no_license | require "csv"
require_relative "../models/customer"
require_relative "record_repository"
class CustomerRepository < RecordRepository
def update(customer)
p customer
save_csv
end
private
def row_to_record(row)
row[:id] = row[:id].to_i
Customer.new(row)
end
def record_to_row(customer)
[customer.id,customer.name,customer.address]
end
def headers
["id","name","address"]
end
end | true |
367ce26fabb3e4e47adef411330d5b16718fef4c | Ruby | SimplySorc/StatusChecker | /status_checker.rb | UTF-8 | 552 | 2.921875 | 3 | [] | no_license | # frozen_string_literal: true
require 'csv'
require 'json'
require 'net/http'
class StatusChecker
def initialize(file_path)
@results = []
CSV.foreach(file_path, headers: :first_row) do |row|
url = row.fetch('URL')
@results << { name: url, status: get_site_status(url) }
end
end
def to_json(*_args)
@results.to_json
end
def to_h
@results
end
private
def get_site_status(url)
Net::HTTP.start(url, use_ssl: true) { |http| http.head('/').code }
rescue StandardError => e
e.message
end
end
| true |
408b665403146bdaa531579dd5cc05655f140f45 | Ruby | lateralstudios/railgun_devise | /lib/railgun_devise/configuration.rb | UTF-8 | 554 | 2.59375 | 3 | [
"MIT"
] | permissive | module RailgunDevise
class Configuration
@@defaults = {
}
cattr_accessor :settings
def initialize
@@settings ||= self.class.get_from_hash(@@defaults)
end
def self.settings
@@settings
end
def method_missing(name, *args, &block)
self.settings.send(name, *args, &block)
end
def self.get_from_hash(hash)
settings = Railgun::SettingsHash.new
hash.each_pair do |key, value|
settings[key] = value.is_a?(Hash) ? self.get_from_hash(value) : value
end
settings
end
end
end | true |
6e2498b7829243042f869be3cd6024b07970ea3a | Ruby | shaoshing/projecat | /cat_feeder/devices/eating_detect_device.rb | UTF-8 | 1,377 | 2.734375 | 3 | [] | no_license | require 'pi_piper'
module CatFeeder
class EatingDetectDevice
PIN_NUM = 6
INITIAL_TIME_OUT = 5 # INITIAL_TIME_OUT * DURATION (seconds)
TIME_OUT = 20 # TIME_OUT * DURATION (seconds)
DURATION = 0.5
def self.eating?
@started_at = nil
@ended_at = nil
@pin ||= PiPiper::Pin.new(:pin => RASPI_GPIO_PINS[PIN_NUM], :direction => :in, :invert => true)
@pin.read
if @pin.off?
time_out = true
INITIAL_TIME_OUT.times do
@pin.read
if @pin.on?
time_out = false
break
end
sleep DURATION
end
return false if time_out
end
@started_at = Time.now
off_count = 0
detection_count = 0
strtime = @started_at.strftime("%d_%H:%M:%S")
`mkdir /var/www/photos/#{strtime}`
loop do
sleep DURATION
if (detection_count += 1) % 10 == 0
`fswebcam -r 1280x960 -d /dev/video0 /var/www/photos/#{strtime}/#{detection_count/10}.jpg`
end
@pin.read
if @pin.on?
off_count = 0
next
else
break if (off_count += 1) >= TIME_OUT
end
end
@ended_at = Time.now - TIME_OUT*DURATION
return true
end
def self.last_eating_times
return @started_at, @ended_at
end
end # EatingMonitor
end # CatFeeder
| true |
017c1fa796d79c85e677049df6b0a47308fe324d | Ruby | tdeo/advent_of_code | /2015/lib/22_wizard_simulator.rb | UTF-8 | 3,389 | 3.0625 | 3 | [] | no_license | # frozen_string_literal: true
require 'set'
class WizardSimulator
def initialize(input)
@input = input
@spells = [
{ name: :magic_missile, mana_cost: 53 },
{ name: :drain, mana_cost: 73 },
{ name: :shield, mana_cost: 113 },
{ name: :poison, mana_cost: 173 },
{ name: :recharge, mana_cost: 229 },
]
@callbacks = []
@turn = 0
@me = {
mana: 500,
health: 50,
armor: 0,
}
@history = []
@total_mana = 0
@boss = {
health: input.split("\n").first.split(':').last.strip.to_i,
damage: input.split("\n").last.split(':').last.strip.to_i,
}
end
def magic_missile
@boss[:health] -= 4
end
def drain
@boss[:health] -= 2
@me[:health] += 2
end
def shield
@me[:armor] += 7
@callbacks << { turn: @turn + 7, effect: :shield_effect }
end
def shield_effect
@me[:armor] -= 7
end
def poison
(1..6).each do |i|
@callbacks << { turn: @turn + i, effect: :poison_effect }
end
end
def poison_effect
@boss[:health] -= 3
end
def recharge
(1..5).each do |i|
@callbacks << { turn: @turn + i, effect: :recharge_effect }
end
end
def recharge_effect
@me[:mana] += 101
end
def win?
@boss[:health] <= 0
end
def boss
@me[:health] -= [1, @boss[:damage] - @me[:armor]].max
end
def available?(spell)
!@callbacks.map { |e| e[:effect] }.include?(:"#{spell}_effect")
end
def next_turn!(hard: false)
@turn += 1
if @turn.even? && hard
@me[:health] -= 1
@me[:health] -= 1000 if @me[:health] <= 0
end
@callbacks.each do |c|
next unless c[:turn] == @turn
__send__(c[:effect])
end
@callbacks.delete_if { |c| c[:turn] <= @turn }
end
def run_action(name)
spell = @spells.find { |s| s[:name] == name.to_sym }
@history << name
@me[:mana] -= spell[:mana_cost] unless spell.nil?
@total_mana += spell[:mana_cost] unless spell.nil?
__send__(name.to_sym)
end
def available_actions
return [] if @me[:health] <= 0
if @turn.odd?
%i[boss]
else
@spells.map { |s| s[:name] if available?(s[:name]) && @me[:mana] >= s[:mana_cost] }.compact
end
end
def dead?
@me[:health] <= 0
end
attr_reader :total_mana
def part1
self.class.part1(self)
end
def hash
[@me, @callbacks, @boss].hash
end
def self.part1(a)
queue = [a]
viewed = Set.new([a.hash])
until queue.empty?
a = queue.shift
return a.total_mana if a.win?
a.available_actions.each do |act|
b = Marshal.load(Marshal.dump(a))
b.run_action(act)
next if viewed.include?(b.hash)
viewed << b.hash
b.next_turn!
queue.push(b) unless b.dead?
end
queue.sort_by!(&:total_mana)
end
nil
end
def part2
@me[:health] -= 1 # Hard mode
self.class.part2(self)
end
def self.part2(a)
queue = [a]
viewed = Set.new([a.hash])
until queue.empty?
a = queue.shift
return a.total_mana if a.win?
a.available_actions.each do |act|
b = Marshal.load(Marshal.dump(a))
b.run_action(act)
next if viewed.include?(b.hash)
viewed << b.hash
b.next_turn!(hard: true)
queue.push(b) unless b.dead?
end
queue.sort_by!(&:total_mana)
end
nil
end
end
| true |
8ce993e9177ac2dcca7dc6f4eaaebca672712e5d | Ruby | cantorandball/centrebot | /app/models/date_outcome.rb | UTF-8 | 323 | 2.796875 | 3 | [] | no_license | class DateOutcome < Outcome
def correct_period?(incoming_date)
is_correct = true
if lower_bound
is_correct = false if incoming_date <= Date.today.prev_year(lower_bound)
end
if upper_bound
is_correct = false if incoming_date > Date.today.prev_year(upper_bound)
end
is_correct
end
end
| true |
d293614164a23d9212fce2d37bfcc281b6cf9371 | Ruby | Birdie0/glue-bot | /src/modules/commands/random.rb | UTF-8 | 1,037 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Bot
module DiscordCommands
# Picks random n songs from pre-generated playlists.
# Max 25 songs for one request.
module Random
extend Discordrb::Commands::CommandContainer
command(:random,
min_args: 1,
description: 'Picks random n songs from pre-generated playlists.',
usage: "#{BOT.prefix}rand <playlist> [n = 15]") do |event, name, n = 15|
name.downcase!
if !File.exist?("config/playlists/#{name}.json")
event << "#{name} playlist doesn't exist!"
event << "Type `#{BOT.prefix}list` for playlists list!"
else
n = '25' if n.to_i > 25
event << "```md"
event << "# Here's your random #{n} songs from #{name} playlist"
hash = Oj.load_file("config/playlists/#{name}.json")['songs']
hash.values.sample(n.to_i).each do |i|
event << "#{i}"
end
event << "```"
end
nil
end
end
end
end
| true |
ff539dabaf3716093fa705840ad71eb539572538 | Ruby | Beaulieu527/speaking-grandma-online-web-prework | /grandma.rb | UTF-8 | 379 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write a speak_to_grandma method.
speak_to_grandma = gets.chomp
# Whatever you say to grandma, she should respond with
# HUH?! SPEAK UP, SONNY!
# unless you shout it (type in all capitals).
if speak_to_grandma = "I LOVE YOU GRANDMA!"
puts "I LOVE YOU TOO PUMPKIN"
elsif speak_to_grandma != " ".upcase
puts "HUH? SPEAK UP, SONNY!"
else
puts "NO, NOT SINCE 1938!"
end
| true |
eede7cb82896c453d1a7541e408143ce64de5170 | Ruby | TheBaxes/ProductCast | /app/models/Prediction_Models/Single_Exp_Smoothing_Model.rb | UTF-8 | 1,117 | 3.03125 | 3 | [] | no_license | require_relative '../Base_Prediction_Model/base_model'
require_relative './../Data/historical_data'
require_relative './../Data/predicted_data'
require 'date'
class Single_Exp_Smoothing_Model < BaseModel
@public_name = "Suavizacion exponencial"
@parameters_list = ["Alfa"]
@local_parameters = [:Alpha]
@ecuation = 'F_{t} = \alpha D_{t-1} + (1 - \alpha) F_{t-1}'
def initialize(parameters)
super(parameters)
end
protected
def run_model(sales, num_of_predictions)
alpha = @parameters[:Alpha]
predictions = []
#Suavizacion exponencial, se inicializa suponiendo que F1 = D0 = sales[0]
previous_prediction = (sales.first * 1.0)
#Calcular y guardar F2 - Fn
for i in (2..sales.size)
predictions.push(previous_prediction)
previous_prediction = alpha * (sales[i - 1] * 1.0) + (1.0 - alpha) * previous_prediction
end
#Cargar num_of_predictions predicciones futuras
num_of_predictions.times do
predictions.push(previous_prediction)
end
return predictions
end
end
| true |
c4ae9710476a1d736b752a2d8789d72aa2ca380f | Ruby | siegy22/energy_air | /exe/energy_air | UTF-8 | 597 | 2.875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
tel_number = ARGV[0]
if tel_number.nil? || tel_number.empty?
puts <<~MSG
Please provide your telephone number to earn the tickets (don't use spaces):
$ energy_air 791234567
MSG
exit
end
require 'bundler/setup'
require 'energy_air'
puts '==== Energy Air Quiz bot ===='
puts "Version: #{EnergyAir::VERSION}"
puts 'Use Ctrl-C to stop'
puts "'.' means: Quiz played without winning a ticket."
puts "'√' means: Quiz played and won a ticket!"
puts "'×' means: There was an unknown error (skipped)"
EnergyAir::Bot.new(tel_number, visual: ARGV.include?('--visual'))
| true |
c914569f5ec10bb482d963a51787a8dbcd92a1f6 | Ruby | dalexj/ideabox | /lib/idea_box/idea.rb | UTF-8 | 615 | 2.9375 | 3 | [] | no_license | class Idea
include Comparable
attr_reader :title, :description, :rank, :id, :tags
def initialize(data = {})
@title = data["title"]
@description = data["description"]
@rank = data["rank"] || 0
@id = data["id"]
@tags = data["tags"]
end
def to_h
{
"title" => title,
"description" => description,
"rank" => rank,
"id" => id,
"tags" => tags
}
end
def like!
@rank += 1
end
def <=>(other)
other.rank <=> rank
end
def update(updated_data)
@title = updated_data["title"]
@description = updated_data["description"]
end
end
| true |
98b944cceaad6fa6dacaaa755c36d1ddfcdcfe92 | Ruby | desarrollolocal/etiquetica | /lib/product.rb | UTF-8 | 452 | 2.546875 | 3 | [] | no_license | require_relative 'indicator'
class Product
include Mongoid::Document
field :name, type: String
field :creation_date, type: Time, default: ->{ Time.now.to_i }
embeds_many :indicators
validates_presence_of [:name, :creation_date]
validates_uniqueness_of :name, message: "Ya existe un producto con ese nombre"
after_create :set_default_indicator
private
def set_default_indicator
self.indicators.push(Indicator.new)
end
end | true |
7a6747311e2d9ec11861d5bf5095ecfccb188150 | Ruby | phedders/prh-rlib | /lib/prh-tmail.rb | UTF-8 | 1,107 | 2.703125 | 3 | [] | no_license | require 'net/smtp'
class TMail::Maildir
def self.maildir?(path)
return false unless File.directory?(path)
File.directory?(path+"/cur") and File.directory?(path+"/tmp") and File.directory?(path+"/new")
end
def self.maildirmake(path, folder = nil)
if folder == true
fpath = path
elsif folder.class == String
fpath = path + "/"+".#{folder}".gsub(/\//,".")
else
fpath = path
end
[fpath, fpath+"/cur", fpath+"/new", fpath+"/tmp"].each{|d| Dir.mkdir d unless File.directory? d}
FileUtils.touch fpath+"/maildirfolder" unless File.exists? fpath+"/maildirfolder" or folder.nil?
end
def folders
TMail::Maildir.folders(self.directory)
end
def self.folders(path)
Dir.new(path).each.select{|d| d.match(/../) and maildir?(File.join(path,d))}
end
end
class TMail::Mail
def send
Net::SMTP.start( 'localhost', 25 ) do |smtpclient|
smtpclient.send_message(
self.to_s, self.from, self.to
)
end
end
end
# And add detection for File#
class File
def self.maildir?(path)
TMail::Maildir.maildir? path
end
end
| true |
9a9a05f30fbdb9c20b71fc85a330fdc71b266fe0 | Ruby | vtka/VTKA | /lesson2/purchase.rb | UTF-8 | 723 | 3.75 | 4 | [] | no_license | total_basket_price = 0
basket = {}
loop do
print "Press Enter to continue! Enter 'stop', whenever you're finished: "
stop = gets.chomp
break if stop.downcase == 'stop'
print "Enter the item name: "
item_name = gets.chomp
print "Enter the price per item: "
item_price = gets.chomp.to_f
print "How many #{item_name} have you got? "
item_quantity = gets.chomp.to_f
basket[item_name] = {quantity: item_quantity, price: item_price}
item_total_price = item_price*item_quantity
puts "The total price for #{item_quantity} #{item_name} is #{item_total_price}"
total_basket_price += item_total_price
end
puts "The total amount of your purchase is #{total_basket_price}. Thank you for your purchase!" | true |
09f17c877f3fd333dd76ea422b4fccf934c9ba3b | Ruby | marcelomaidden/jobsity-bowling-game | /lib/file_utils.rb | UTF-8 | 1,885 | 3.375 | 3 | [] | no_license | # frozen_string_literal: true
# FileValidator validates the file checking extension and file structure
class FileValidator
attr_reader :error
def initialize(filename, extension)
@filename = filename
@extension = extension
if valid_extension?
file = File.open(filename)
@lines = file.readlines.map(&:chomp)
end
rescue Errno::ENOENT
@error = "File can't be read"
rescue TypeError
@error = 'Please, provide a valid file name'
end
def check_file
return false unless valid_extension?
return false unless @error.nil?
return false if empty?
result = true
values = []
@lines.each do |line|
info = line.split(' ')
result &&= info.length == 2
result &&= info[0].split.all?(/[a-zA-Z]/)
values.push(info[1])
end
result
rescue TypeError
@error = 'Please, provide a valid file name'
end
private
def empty?
if @lines.empty?
@error = 'Empty file'
return true
end
false
end
def valid_extension?
valid = File.extname(@filename) == @extension
@error = 'Wrong file extension' unless valid
valid
rescue TypeError
@error = 'Please, provide a valid file name'
end
end
# FileReader reads game file and stores player names and points in a Hash
class FileReader
attr_reader :data, :validator
def initialize(filename, extension, validator)
@data = {}
@filename = filename
@validator = validator.new(filename, extension)
process_output if @validator.check_file
end
private
def process_output
file = File.open(@filename)
@lines = file.readlines.map(&:chomp)
@lines.each do |line|
player_throws = line.split(' ')
if @data[player_throws[0]]
@data[player_throws[0]].push(player_throws[1])
else
@data[player_throws[0]] = [player_throws[1]]
end
end
end
end
| true |
5f7a5c9c65b4465c01d83b01777cc19675863a6e | Ruby | ZephyrRS/session0202_exercises | /RichardLin_RichardLin3/exercises/d4/reverse.rb | UTF-8 | 297 | 3.75 | 4 | [] | no_license | #E1: The Road Not Taken
def reverse(array)
reversed_index = []
array.each_with_index do |spacejam, index|
new_index = array.length - 1 -index
reversed_index[new_index] = spacejam
end
reversed_index
end
random_objects = ['apples', 4, 'bananas', 'kiwis', 'pears']
puts reverse(random_objects)
| true |
46f881c585f8f25f81be1abc33bce18efdfb8d1b | Ruby | carolyn0429/dataiku | /cucumber/features/helpers/TestClient.rb | UTF-8 | 2,288 | 2.59375 | 3 | [] | no_license | require 'rubygems'
require 'selenium-webdriver'
require 'cucumber'
require 'rest-client'
class TestClient
@@URL = "http://hung.qatest.dataiku.com/"
@@username = nil
@@password = nil
def create_a_user(username, password)
response = RestClient::Request.execute(
:method => :post,
:url => @@URL+"users",
:headers => {:accept => :json, :content_type=> :json},
payload: {'username': username, 'password': password}.to_json
)
return response
end
def generate_token(username, password)
response = RestClient::Request.execute(
:method => :post,
:url => @@URL+"authenticate",
:headers => {:accept => :json, :content_type=> :json},
payload: {'username': username, 'password': password}.to_json
)
return response
end
def set_credentials(username, password)
@@username = username
@@password = password
end
def create_a_task(title, tags)
response = RestClient::Request.execute(
:method => :put,
:url => @@URL,
:headers => {:accept => :json, :content_type=> :json},
:user => @@username,
:password => @@password,
payload: {'title': title, 'tags': tags}.to_json
)
return response
end
def get_tasks()
response = RestClient.get(@@URL)
return response
end
def get_tags()
response = RestClient.get(@@URL+"tags")
return response
end
def get_task_by_id(task_id)
response = RestClient.get(@@URL+task_id)
return response
end
def get_tag_by_id(tag_id)
response = RestClient.get(@@URL+"tags/"+tag_id)
return response
end
def reset()
response = RestClient.get(@@URL+"reset")
return response
end
def update_task_by_id(task_id, title, tags)
response = RestClient::Request.execute(
:method => :patch,
:url => @@URL+task_id,
:headers => {:accept => :json, :content_type=> :json},
:user => @@username,
:password => @@password,
payload: {'title': title, 'tags': tags}.to_json
)
return response
end
def delete_task_by_id(task_id)
response = RestClient.delete(@@URL+task_id)
return response
end
def self.find_element(finder, location)
$driver.find_element(finder, location)
end
end | true |
1bdca8af05cfb53ad4d6a6899c11f5da2b596a00 | Ruby | hugobast/tipo | /lib/tipo/table/base.rb | UTF-8 | 506 | 2.71875 | 3 | [
"MIT"
] | permissive | module Tipo
module Table
class Base
attr_reader :font_header, :font
attr_accessor :name
def initialize font_header, font
@font_header = font_header
@font = font
end
def offset
seek_to_table @name
end
private
def seek_to_table tag
font.seek find_table(tag).offset
font.tell
end
def find_table tag
font_header.table_records.select { |t| t.tag == tag }.first
end
end
end
end
| true |
53d4439a60e25e1307dc40f45df73fc319e8c1ce | Ruby | AndersonMAaron/werd | /lib/werd.rb | UTF-8 | 644 | 2.796875 | 3 | [] | no_license | require 'werd/dictionary'
module Werd
def self.fail(message='')
raise message
end
def self.dictionary_in(language, min_letter_cnt=3)
Werd::Dictionary.from_file(
File.expand_path("../../dictionaries/#{language.to_s.downcase}", __FILE__),
min_letter_cnt,
)
end
end
############################################
## Standard library extensions
############################################
class Hash
# Similar to Hash.invert, but values are stored in an array to avoid overwrites
def safe_invert
each_with_object({}) do |(key, value), out|
out[value] ||= []
out[value] << key
end
end
end
| true |
4cc20021ddd8fbb7cd58ba721b3dca3932fbe67d | Ruby | reggieb/which_page | /app/tools/thesaurus.rb | UTF-8 | 453 | 2.953125 | 3 | [] | no_license | require 'bronto'
class Thesaurus
attr_reader :word
def self.nouns_matching(word)
[word] + new(word).nouns
end
def initialize(word)
@word = word
end
def lookup
@lookup ||= bronto.lookup word
end
def nouns
(lookup && lookup[:noun]) ? lookup[:noun][:syn] : []
end
def verbs
(lookup && lookup[:verb]) ? lookup[:verb][:syn] : []
end
def bronto
@bronto ||= Bronto::Thesaurus.new
end
end
| true |
757e90f72b293fcb6e71c0ae557511a937d4e3e5 | Ruby | apiaryio/apiary_blueprint_convertor | /lib/apiary_blueprint_convertor/cli.rb | UTF-8 | 1,537 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'optparse'
require 'apiary_blueprint_convertor/version'
require 'apiary_blueprint_convertor/convertor'
module ApiaryBlueprintConvertor
class CLI
attr_reader :command
def self.start
cli = CLI.new
options = cli.parse_options!(ARGV)
cli.runCommand(ARGV, options)
end
def runCommand(args, options)
command = :convert if args.first.nil? || @command.nil?
command = @command if @command
case command
when :convert
Convertor.convert(args.first)
when :version
puts ApiaryBlueprintConvertor::VERSION
else
CLI.help
end
end
def parse_options!(args)
@command = nil
options = {}
options_parser = OptionParser.new do |opts|
opts.on('-v', '--version') do
@command = :version
end
opts.on( '-h', '--help') do
@command = :help
end
end
options_parser.parse!
options
rescue OptionParser::InvalidOption => e
puts e
CLI.help
exit 1
end
def self.help
puts "Usage: apiary_blueprint_convertor <legacy ast file>"
puts "\nConvert Legacy Apiary Blueprint AST into API Blueprint AST (JSON)."
puts "If no <legacy ast file> is specified 'apiary_blueprint_convertor' will listen on stdin."
puts "\nOptions:\n\n"
puts "\t-h, --help Show this help"
puts "\t-v, --version Show version"
puts "\n"
end
end
end
| true |
3395d649f46fda72a38c832661d459d6cb0d75d1 | Ruby | sergii/AND-Digital-Golden-Shoe | /app/models/basket.rb | UTF-8 | 441 | 2.5625 | 3 | [] | no_license | class Basket < ApplicationRecord
validates :uuid, presence: true
has_many :basket_items, dependent: :destroy
def add_unit(unit)
current_item = basket_items.find_by(unit_id: unit.id)
if current_item
current_item.increment!(:quantity)
else
current_item = basket_items.create(unit_id: unit.id)
end
current_item
end
def validate_stock
basket_items.map(&:validate_stock).uniq == [true]
end
end
| true |
c2a7d79626360a5602c83109b6bb925f693e918f | Ruby | DonChilders/while-loops | /while.rb | UTF-8 | 701 | 3.953125 | 4 | [] | no_license | #while loops
# requires 3 items
# initial condition
# boolean expression that will end the loop
# some kinda statement in the loop that will modify the boolean expression
# ......need some way of ending the loop
# count from 1 through 100
# count = 1
# while count <= 100
# puts count
# #change something to end the loop
# count += 1
# end
# *******************
# * *
# * *
# * *
# * *
# * *
# * *
# *******************
print "Enter the size of the box: 1-50 "
size = gets.to_i
puts "*" * size
count = 0
while count < size - 2
puts "*" + " " * (size - 2) + "*"
count += 1
end
puts "*" * size
| true |
6d409986ac3b3f093598ff5b766c9647580c341d | Ruby | Crysicia/THP_S6 | /THP-TheGossipProject/lib/view.rb | UTF-8 | 686 | 2.921875 | 3 | [] | no_license | class View
def new_gossip
puts "--- Gossip creation interface ---"
print "| What's your name ? : "
author = gets.chomp
print "| What's your crunchy story ? : "
content = gets.chomp
return params = {'author' => author, 'content' => content}
end
def index_gossips(arr)
arr.each do |gossip|
puts gossip
end
end
def edit_gossip
print "Which gossip would you like to edit ? : "
line = gets.chomp.to_i
print "| Enter the modified content : "
content = gets.chomp
return params = [line, content]
end
def delete_gossip
print "Which gossip would you like to delete ? : "
return gets.chomp.to_i
end
end | true |
145d43af95ba7a8c7d2a164e746de61df589f84c | Ruby | zph/mri_2_0_0_zlib_troubleshooting | /wunderground-working-2_0.rb | UTF-8 | 445 | 2.8125 | 3 | [] | no_license | require 'rest-client'
require 'json'
api_key = '' # required by producing your own API key from http://www.wunderground.com/weather/api/
url = "http://api.wunderground.com/api/#{api_key}/geolookup/conditions/q/IA/Cedar_Rapids.json"
res = RestClient.get url
parsed_json = JSON.parse(res)
location = parsed_json['location']['city']
temp_f = parsed_json['current_observation']['temp_f']
print "Current temperature in #{location} is: #{temp_f}\n" | true |
443acabf46e4baad313baf328a36da8ae5083d23 | Ruby | tenshi3/MTG | /lib/game.rb | UTF-8 | 2,472 | 3.609375 | 4 | [] | no_license | require_relative "utils"
require_relative "player/_player_header"
class Game
include Utils
attr_accessor :players
attr_accessor :round_number
def initialize
self.players = []
self.round_number = 1
end
def add_player(name, deck, ai)
self.players << if ai
AiPlayer.new(name, deck)
else
HumanPlayer.new(name, deck)
end
end
def start
display_status "FINDING STARTING PLAYER"
player_to_start_index, player_to_start = find_starting_player!
sort_players_into_turn_order!(player_to_start_index)
self.players.each do |player|
player.draw_starting_hand!
end
display_status "STARTING GAME: ROUND 1"
# Take the first player's special turn
player_to_start.starting_turn
self.players.shift
player_turns
self.players.unshift(player_to_start)
self.round_number = 2
while(self.players.count > 1)
display_status "ROUND #{self.round_number}"
player_turns
self.round_number += 1
end
end
private
def player_turns
self.players.each_with_index do |player, index|
player.take_turn!
if player.dead?
self.players.remove_at(index)
end
end
end
def sort_players_into_turn_order!(start_index)
while start_index != 0
start_index -= 1
self.players << self.players.shift
end
end
def find_starting_player!
roll_for_players = lambda do |players_to_roll|
rolls = []
player_index = 0
players_to_roll.size.times do
roll = (rand * 21).floor
rolls << roll
puts " * #{players_to_roll[player_index].name} rolls #{roll}"
player_index += 1
end
max_roll = rolls.max
players_with_max_roll = []
rolls.each_with_index do |val, ind|
if val == max_roll
players_with_max_roll << ind
end
end
if players_with_max_roll.one?
winning_player_index = players_with_max_roll.first
winning_player = players_to_roll[winning_player_index]
puts " * #{winning_player.name} wins the roll"
return [players_with_max_roll.first, winning_player]
else
winning_players = players_with_max_roll.map{|ind| players_to_roll[ind]}
puts " * #{winning_players[0..-2].map(&:name).join(", ")} and #{winning_players.last.name} to roll again"
return roll_for_players.call(winning_players)
end
end
return roll_for_players.call(self.players)
end
end
| true |
8dd971b392ede25516fc9cfa04fdca7332a0a9f1 | Ruby | googleapis/google-cloud-ruby | /google-cloud-firestore/samples/transactions_and_batched_writes.rb | UTF-8 | 3,234 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | # Copyright 2020 Google, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "google/cloud/firestore"
def run_simple_transaction project_id:, collection_path: "cities"
# project_id = "Your Google Cloud Project ID"
# collection_path = "cities"
firestore = Google::Cloud::Firestore.new project_id: project_id
# [START firestore_transaction_document_update]
city_ref = firestore.doc "#{collection_path}/SF"
firestore.transaction do |tx|
new_population = tx.get(city_ref).data[:population] + 1
puts "New population is #{new_population}."
tx.update city_ref, { population: new_population }
end
# [END firestore_transaction_document_update]
puts "Ran a simple transaction to update the population field in the SF document in the cities collection."
end
def return_info_transaction project_id:, collection_path: "cities"
# project_id = "Your Google Cloud Project ID"
# collection_path = "cities"
firestore = Google::Cloud::Firestore.new project_id: project_id
# [START firestore_transaction_document_update_conditional]
city_ref = firestore.doc "#{collection_path}/SF"
updated = firestore.transaction do |tx|
new_population = tx.get(city_ref).data[:population] + 1
if new_population < 1_000_000
tx.update city_ref, { population: new_population }
true
end
end
if updated
puts "Population updated!"
else
puts "Sorry! Population is too big."
end
# [END firestore_transaction_document_update_conditional]
end
def batch_write project_id:, collection_path: "cities"
# project_id = "Your Google Cloud Project ID"
# collection_path = "cities"
firestore = Google::Cloud::Firestore.new project_id: project_id
# [START firestore_data_batch_writes]
firestore.batch do |b|
# Set the data for NYC
b.set "#{collection_path}/NYC", { name: "New York City" }
# Update the population for SF
b.update "#{collection_path}/SF", { population: 1_000_000 }
# Delete LA
b.delete "#{collection_path}/LA"
end
# [END firestore_data_batch_writes]
puts "Batch write successfully completed."
end
if $PROGRAM_NAME == __FILE__
project = ENV["FIRESTORE_PROJECT"]
case ARGV.shift
when "run_simple_transaction"
run_simple_transaction project_id: project
when "return_info_transaction"
return_info_transaction project_id: project
when "batch_write"
batch_write project_id: project
else
puts <<~USAGE
Usage: bundle exec ruby transactions_and_batched_writes.rb [command]
Commands:
run_simple_transaction Run a simple transaction.
return_info_transaction Run a transaction and get information returned.
batch_write Perform a batch write.
USAGE
end
end
| true |
15595b08c5ed0df8d11897f54397ea8d55bcce5c | Ruby | ieyasu/rbot2 | /hooks/unicode.rb | UTF-8 | 2,473 | 2.625 | 3 | [] | no_license | ASCII_CONTROL = [
'(null)',
'(start of heading)',
'(start of text)',
'(end of text)',
'(end of transmission)',
'(enquiry)',
'(acknowledge)',
'(bell)',
'(backspace)',
'(horizontal tab)',
'(NL line feed, new line)',
'(vertical tab)',
'(NP form feed, new page)',
'(carriage return)',
'(shift out)',
'(shift in)',
'(data link escape)',
'(device control 1)',
'(device control 2)',
'(device control 3)',
'(device control 4)',
'(negative acknowledge)',
'(synchronous idle)',
'(end of trans. block)',
'(cancel)',
'(end of medium)',
'(substitute)',
'(escape)',
'(file separator)',
'(group separator)',
'(record separator)',
'(unit separator)',
"' '"
]
def to_char(i)
(i < ASCII_CONTROL.length) ? ASCII_CONTROL[i] : i.chr(Encoding::UTF_8)
end
def show_hex(s, h)
reply "unicode hex #{s} -> #{to_char h.hex}"
end
def show_oct(s, o)
reply "unicode oct #{s} -> #{to_char o.oct}"
end
def show_dec(s, d)
reply "unicode dec #{s} -> #{to_char d.to_i}"
end
def show_chars(s)
s.each_char.to_a.uniq[0,5].map do |c|
cp = c.codepoints.first
os = c.bytes.to_a.map {|b| "\\%03o" % b}.join
hs = c.bytes.to_a.map {|b| "\\x%X" % b}.join
if cp >= ASCII_CONTROL.length && cp < 127
sprintf "unicode %s -> %i U+%02X \"%s\"", c, cp, cp, c
elsif cp <= 0xFFFF
sprintf "unicode %s -> %i U+%04X &#x%04X; \"\\u%04X\" \"%s\" \"%s\"",
c, cp, cp, cp, cp, os, hs
else
sprintf "unicode %s -> %i U+%08X &#x%08X; \"\\U%08X\" \"%s\" \"%s\"",
c, cp, cp, cp, cp, os, hs
end
end.each {|m| reply m}
end
match_args /\S+/, '(CHAR|CODEPOINT)'
# many different notations: http://billposer.org/Software/ListOfRepresentations.html
# \u(hex)
# \x(byte)
# \330 # => octal in ruby, python, C, etc.
# 0x99 0245 # => number like in C
# U+FFFF code point notation
# \U(hex*8) => C#
# é é html
case $args
when /&#(x)?(\h+)/ # html
$1.nil? ? show_dec($2, $2) : show_hex($2, $2)
when /(?:u\+?|\\u)[\{"'#]?(\h+)[#'"}]?/i # lots of stuff
show_hex $1, $1
when /((?:\\(?:[xX]\h\h|\d{1,3}))+)/ # ruby
s = '"' + $1 + '"'
reply "unicode escape #{s} -> #{eval(s)}"
when /(0x(\h+))/ # C-like hex number
show_hex $1, $2
when /(0(\d+))/ # C-like octal number
show_oct $1, $2
when /(\d{2,})/
show_dec $1, $1
when /^(.)/
show_chars $args
else
reply "unsupported unicode syntax '#{$args}'"
end
| true |
a0f5c743439ed706e71b60ce6585e84ba5392a69 | Ruby | GeoffreyMesnier/rails-yelp-mvp | /db/seeds.rb | UTF-8 | 996 | 2.609375 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts "Creation de 5 restaurants"
entrecote = Restaurant.new(name: "entrecote", category: "french", address: "2 rue des lilas")
entrecote.save!
quick = Restaurant.new(name: "quick", category: "belgian", address: "2 place du commerce")
quick.save!
grande_muraille = Restaurant.new(name: "grande muraille", category: "japanese", address: "rue des champs")
grande_muraille.save!
sushi = Restaurant.new(name: "sushi shop", category: "chinese", address: "rues des ponts")
sushi.save!
pizza = Restaurant.new(name: "pizza etna", category: "italian", address: "rues des chevaux")
pizza.save!
puts "Fin de la creation de 5 restaurant"
| true |
96684250909965abdce701dc0fbe80823e98b78e | Ruby | eTarget1/school-domain-noukod-000 | /lib/school.rb | UTF-8 | 479 | 3.625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
class School
# school = School.new("Bayside High School")
# school.roster = {}
# school.add_student("Zach Morris", 9)
# school.roster
def initialize(name)
@name = name
@roster = {}
end
def roster
@roster
end
def add_student(name, grade)
if @roster[grade] != nil
@roster[grade] << name
else
@roster[grade] = [name]
end
end
def grade(grade)
@roster[grade]
end
def sort
@roster.each do |key, value|
value.sort!
end
end
end
| true |
7f5300100b45d3284b19fa933f5d932ad1b033c7 | Ruby | jerome/tsearchable | /lib/tsearchable/results.rb | UTF-8 | 1,013 | 2.75 | 3 | [] | no_license | module TSearchable
class Results < Array
attr_reader :current_page, :per_page, :total_entries
def initialize(page, per_page, total = nil)
@current_page = page.to_i
@per_page = per_page.to_i
self.total_entries = total if total
end
def self.create(page, per_page, total = nil, &block)
pager = new(page, per_page, total)
yield pager
pager
end
def page_count
@total_pages
end
def previous_page
current_page > 1 ? (current_page - 1) : nil
end
def next_page
current_page < page_count ? (current_page + 1) : nil
end
def offset
(current_page - 1) * per_page
end
def total_entries=(number)
@total_entries = number.to_i
@total_pages = (@total_entries / per_page.to_f).ceil
end
def replace(array)
returning super do
if total_entries.nil? and length > 0 and length < per_page
self.total_entries = offset + length
end
end
end
end
end
| true |
33d5137d3ebdbde46478846f07d7eda94c275259 | Ruby | remm9/aa_classwork | /W3D4/firstname_lastname/lib/assessment01.rb | UTF-8 | 2,871 | 3.953125 | 4 | [] | no_license | class Array
# Write an `Array#my_inject` method. If my_inject receives no argument, then
# use the first element of the array as the default accumulator.
# **Do NOT use the built-in `Array#inject` or `Array#reduce` methods in your
# implementation.**
def my_inject(accumulator = nil, &prc)
accumulator ||= self.shift
self.each do |el|
accumulator = prc.call(accumulator, el)
end
accumulator
end
end
# Define a method `primes(num)` that returns an array of the first "num" primes.
# You may wish to use an `is_prime?` helper method.
def is_prime?(num)
return false if num < 2
(2...num).none? {|el| num % el == 0}
end
def primes(num)
result = []
i = 2
while result.length < num
result << i if is_prime?(i)
i += 1
end
result
end
# Write a recursive method that returns the first "num" factorial numbers.
# Note that the 1st factorial number is 0!, which equals 1. The 2nd factorial
# is 1!, the 3rd factorial is 2!, etc.
def factorials_rec(num)
return [1] if num == 0 || num == 1
return [1, 1] if num == 2
rest = factorials_rec(num-1)
rest << rest.last * (num-1)
end
class Array
# Write an `Array#dups` method that will return a hash containing the indices
# of all duplicate elements. The keys are the duplicate elements; the values
# are arrays of their indices in ascending order, e.g.
# [1, 3, 4, 3, 0, 3, 0].dups => { 3 => [1, 3, 5], 0 => [4, 6] }
def dups
hash = Hash.new {|h, k| h[k] = []}
self.each.with_index do |el, i|
hash[el] << i if self.count(el) > 1
end
hash
end
end
class String
# Write a `String#symmetric_substrings` method that returns an array of
# substrings that are palindromes, e.g. "cool".symmetric_substrings => ["oo"]
# Only include substrings of length > 1.
def symmetric_substrings
result = []
(0...self.length).each do |i|
(i...self.length).each do |idx|
result << self[i..idx] if (self[i..idx] == self[i..idx].reverse && self[i..idx].length > 1)
end
end
result
end
end
class Array
# Write an `Array#merge_sort` method; it should not modify the original array.
# **Do NOT use the built in `Array#sort` or `Array#sort_by` methods in your
# implementation.**
def merge_sort(&prc)
prc ||= Proc.new {|a, b| a<=>b}
return self if self.length < 2
mid = self.length / 2
left = [0...mid]
right = [mid..-1]
left_sorted = left.merge_sort(&prc)
right_sorted = right.merge_sort(&prc)
Array.merge(left_sorted, right_sorted, &prc)
end
private
def self.merge(left, right, &prc) #expects a block
# debugger
sorted = []
until left.empty? || right.empty?
if prc.call(left.first, right.first) < 0
sorted << left.shift
else
sorted << right.shift
end
end
sorted + left + right
end
end
| true |
c9c0f24ee3cd817b170e2531c59186bea454b6d8 | Ruby | white731/lunch_lady | /ui.rb | UTF-8 | 2,445 | 3.859375 | 4 | [] | no_license | class Ui
def initialize (menu)
@menu = menu
end
def print_menu
puts ""
puts "Welcome to Landon's Kitchen! You're going to love our food!"
puts "Landon's Kitchen Menu"
puts "~~~~~~~~~~~~~~~~~~~~~~"
@menu.each_with_index do |menu_item, index|
puts menu_items = "#{index+1}) #{menu_item[:menu_item]}"
end
self.get_user_choice_1
end
def get_user_choice_1
puts "please choose 2 items from above"
user_input1 = gets.strip
user_input_validation_1(user_input1)
end
def user_input_validation_1(input)
#tests whether the users input was valid
is_integer = input.to_i
if is_integer >= 1 && is_integer <= @menu.size
puts "Option #{is_integer}) #{@menu[is_integer-1][:menu_item]}"
@user_input1 = input.to_i
get_user_choice_2
else
puts "Please only enter a number between 1 and #{@menu.size}"
self.get_user_choice_1
end
# rescue ArgumentError
# puts "You've entered an invalid choice. Please only enter a number between 1 and #{@menu.size}"
# self.get_user_choice_1
end
def get_user_choice_2
puts "Choose one more"
user_input2 = gets.strip
user_input_validation_2(user_input2)
end
def user_input_validation_2(input)
#tests whether the users input was valid
is_integer = input.to_i
if is_integer >= 1 && is_integer <= @menu.size
puts "Option #{is_integer}) #{@menu[is_integer-1][:menu_item]}"
@user_input2 = input.to_i
self.display_user_choice
else
puts "Please only enter a number between 1 and #{@menu.size}"
self.get_user_choice_2
end
# rescue ArgumentError
# puts "You've entered an invalid choice. Please only enter a number between 1 and #{@menu.size}"
# self.get_user_choice_1
end
def display_user_choice
puts "hello"
puts "#{@user_input1}) #{@menu[1-@user_input1][:menu_item]} Price: #{@menu[1-@user_input1][:price]}"
puts "#{@user_input2}) #{@menu[1-@user_input2][:menu_item]} Price: #{@menu[1-@user_input2][:price]}"
puts "Total is Price: #{@menu[1-@user_input1][:price] + @menu[1-@user_input2][:price]}"
end
end | true |
d57da500a4a4bd5dffbf18e7faafadc828ba7a57 | Ruby | Sam-Levene/Rightmove | /features/steps/rightmove_step_definitions.rb | UTF-8 | 3,155 | 2.515625 | 3 | [] | no_license | Given("I can access the rightmove website") do
@rightmove_website = Rightmovewebsite.new
@rightmove_website.rightmove_homepage.load
end
Then("I can see the rightmove homepage") do
@rightmove_website.rightmove_homepage.assertVisible
end
When("I click on the {string} link") do |string|
@rightmove_website.rightmove_homepage.clickLink(string)
end
Then("I am directed to creating an account") do
@rightmove_website.rightmove_create_account.assertVisible
end
Given("I am on the Create Account page") do
@rightmove_website = Rightmovewebsite.new
@rightmove_website.rightmove_create_account.load
@rightmove_website.rightmove_create_account.assertVisible
end
When("I enter invalid user details") do
@rightmove_website.rightmove_create_account.enterInvalidDetails
end
Then("I have not created an account and am not signed in") do
end
When("I enter valid user details") do
@rightmove_website.rightmove_create_account.enterValidDetails
end
Then("I have created an account and am signed in") do
@rightmove_website.my_rightmove.assertVisible
end
Given("I am logged in to Rightmove") do
@rightmove_website = Rightmovewebsite.new
@rightmove_website.rightmove_homepage.load
@rightmove_website.rightmove_homepage.clickLogin
@rightmove_website.rightmove_login.enterValidDetails
@rightmove_website.rightmove_homepage.assertVisible
end
When("I search for a property using an invalid requirement") do
@rightmove_website.rightmove_homepage.invalidSalesSearch
end
Then("I will not see search results") do
end
When("I search for a property using a valid requirement") do
@rightmove_website.rightmove_homepage.searchSalesProperty
@rightmove_website.rightmove_filter.filterProperty
end
Then("I will see search results") do
@rightmove_website.rightmove_results.assertVisible
end
When("I click on the {string} link with a three day alert") do |string|
@rightmove_website.rightmove_results.clickAlert
end
Then("I have created an alert") do
@rightmove_website.rightmove_results.clickMyRightMove
@rightmove_website.my_rightmove.assertAlert
end
Given("I visit the {string} link") do |string|
@rightmove_website.rightmove_homepage.clickLink(string)
end
Then("I will see the alert I set up previously") do
@rightmove_website.my_rightmove.assertAlert
end
Then("I am signed out") do
@rightmove_website.rightmove_homepage.assertVisible
end
When("I search for a lettings property using an invalid requirement") do
@rightmove_website.rightmove_homepage.invalidLettingsSearch
end
When("I search for a lettings property using a valid requirement") do
@rightmove_website.rightmove_homepage.searchLettingsProperty
@rightmove_website.rightmove_filter.filterLetProperty
end
Then("I will see search lettings results") do
@rightmove_website.rightmove_results.assertLetVisible
end
When("I click on the {string} link with a seven day alert") do |string|
@rightmove_website.rightmove_results.clickSevenAlert
end
Then("I have created a lettings alert") do
@rightmove_website.rightmove_results.clickMyRightMove
@rightmove_website.my_rightmove.clickLetAlerts
@rightmove_website.my_rightmove.assertLetAlerts
end | true |
14b83b95d57904c5bc6629542ae66595a60b641d | Ruby | kwoodard22/kelsey_wdi | /practice_w01.rb | UTF-8 | 3,043 | 3.390625 | 3 | [] | no_license | # people = [
# {:name => "Stacy", :money => 5, :plays_instrument => true},
# {:name => "Daniel", :money => 10, :plays_instrument => false},
# {:name => "Oscar", :money => 80, :plays_instrument => true},
# {:name => "Kayla", :money => 20, :plays_instrument => false},
# {:name => "Brandon", :money => 20, :plays_instrument => false},
# {:name => "John", :money => 90, :plays_instrument => false},
# {:name => "Steven", :money => 10, :plays_instrument => true},
# {:name => "James", :money => 15, :plays_instrument => false},
# {:name => "Adrien", :money => 8, :plays_instrument => false},
# {:name => "Sean", :money => 7, :plays_instrument => true},
# {:name => "Max", :money => 35, :plays_instrument => true},
# {:name => "Matthew", :money => 12, :plays_instrument => true},
# {:name => "Ruchi", :money => 75, :plays_instrument => false},
# {:name => "Kenn", :money => 27, :plays_instrument => true},
# {:name => "Matt", :money => 35, :plays_instrument => true},
# {:name => "Tim", :money => 11, :plays_instrument => true},
# {:name => "Babak", :money => 15, :plays_instrument => false},
# {:name => "Erwin", :money => 7, :plays_instrument => true},
# {:name => "Camelia", :money => 35, :plays_instrument => true},
# {:name => "Lydia", :money => 102, :plays_instrument => true},
# {:name => "Paul", :money => 75, :plays_instrument => false},
# {:name => "Kelsey", :money => 17, :plays_instrument => true},
# ]
# Who has the most money?
# If we have at least 5 people that play instruments we can start a band. Can we?
# If a new drum set costs $350, do we have enough money to buy one?
# people.collect do |hash|
# hash.max_by {|k, v| v}
# end
wine_cellar = [
{:label => "Rutherford Hill", :type => "Chardonnay", :color => "white"},
{:label => "Nina Veneto", :type => "Pinot Grigio", :color => "white"},
{:label => "Wairau River", :type => "Sauvignon Blanc", :color => "white"},
{:label => "Tangley Oaks", :type => "Merlot", :color => "red"},
{:label => "Chimney Rock", :type => "Cabernet Sauvignon", :color => "red"},
{:label => "Sanford", :type => "Pinot Noir", :color => "red"},
{:label => "Alderbrook", :type => "Pinot Noir", :color => "red"},
{:label => "Colavita", :type => "Pinot Noir", :color => "red"},
{:label => "Markham", :type => "Chardonnay", :color => "white"},
{:label => "Angeline", :type => "Pinot Noir", :color => "red"}
]
# Adds a wine of your choice to the cellar
new_wine = {:label => "Alamos", :type => "Malbec", :color => "white" }
wine_cellar << new_wine
# Returns a random wine from the cellar
puts wine_cellar.sample
# Returns an array of just the white wines
puts wine_cellar.select { |wine| wine[:color] == "white" }
# Returns an array listing the unique types of wine
puts wine_cellar.uniq { |wine| wine[:type] }
# Returns an array with the all the wines that have 2-word labels
puts wine_cellar.select { |wine| wine[:label].include? " " }
puts wine_cellar.select { |wine| wine[:label].index(" ") }
# Returns an array with the labels of the wines that a type of Pinot Noir
| true |
5c2930ab2340f4f48e38f8d7f9dfce0129ea007e | Ruby | pablomontoja/activepesel | /lib/activepesel/pesel.rb | UTF-8 | 796 | 2.828125 | 3 | [
"MIT"
] | permissive | module Activepesel
class Pesel
class << self
delegate :generate, :to => "Activepesel::PeselGenerator".to_sym
end
DIGIT_WEIGHTS = [1, 3, 7, 9, 1, 3 ,7, 9, 1, 3, 1].freeze
attr_reader :number
delegate :date_of_birth, :sex, :to => :personal_data
def initialize(number)
@number = number
end
def valid?
@number[4..5].to_i < 32 && digits.size == 11 && control_value % 10 == 0
end
def digits
@number.split("").select{|digit| digit.to_i.to_s == digit}.map(&:to_i)
end
def personal_data
PersonalData.new(self) if @number
end
private
def control_value
DIGIT_WEIGHTS.each_with_index.inject(0){|sum, (factor, idx)| sum + factor * digits[idx]}
end
end
end
| true |
6413a69f81caf817b5b69ba4d545ad2bd86ae48d | Ruby | MERatio/fibonacci | /fibs_rec.rb | UTF-8 | 239 | 3.03125 | 3 | [] | no_license | # frozen_string_literal: true
def fibs_rec(num, sequence = [0, 1])
return sequence[0..num] if [0, 1].include?(num)
return sequence if sequence.length == num + 1
sequence << sequence[-1] + sequence[-2]
fibs_rec(num, sequence)
end
| true |
1b72ca860da0b9516069033773ccb9258bc1dd84 | Ruby | carney2490/jakelrthw | /ex6.rb | UTF-8 | 1,140 | 4.375 | 4 | [] | no_license | # setting types of people to 10
types_of_people = 10
# string using types of people variable
x = "There are #{types_of_people} types of people."
# setting binary to binary
binary = "binary"
# setting do_not to don't
do_not = "don't"
# setting y to string using binary and do_not variable
y = "Those who know #{binary} and those who #{do_not}."
# printing x and y string
puts x
puts y
# pringing strings using x and y string
puts "I said: #{x}."
puts "I also said: '#{y}'."
# setting halarious to false
halarious = false
# and joke_evaluation to string that has halarious variable in it
joke_evaluation = "Isn't that joke so funny?! #{halarious}"
# prints string
puts joke_evaluation
# sets w and e to two strings that make one sentence
w = "This is the left side of..."
e = "a string with a right side."
# prints strings w and e
puts w + e
# string/variable x gets put into "I said" string
# strings/variables "binary" and "don't" get put into y string/variable and that
# gets put into "I also said" string
# if you use ' and not " when you get to a conjunction the rest of the code is junk | true |
7cb442a020a5b6c93dde33ced34f0a4fe391c709 | Ruby | sproul/div_calendar_crawler | /src/div_calendar_crawler.rb | UTF-8 | 6,508 | 2.890625 | 3 | [
"MIT"
] | permissive | require 'json'
require_relative 'u.rb'
class Div_calendar_crawler
COMPANY_NAME = 'COMPANY_NAME'
SYMBOL = 'SYMBOL'
EX_DATE = 'EX_DATE'
DIVIDEND = 'DIVIDEND'
INDICATED_ANNUAL_DIVIDEND = 'INDICATED_ANNUAL_DIVIDEND'
RECORD_DATE = 'RECORD_DATE'
ANNOUNCMENT_DATE = 'ANNOUNCMENT_DATE'
PAYMENT_DATE = 'PAYMENT_DATE'
def initialize()
end
class << self
attr_accessor :date_range_start
attr_accessor :date_range_length
attr_accessor :dry_mode
attr_accessor :output_directory
def close_output_f(f)
if Div_calendar_crawler.output_directory
f.close # otherwise f == STDOUT, and we'll leave it alone
end
end
def crawl_date(date)
url = "https://www.nasdaq.com/dividend-stocks/dividend-calendar.aspx?date=#{nasdaq_date(date)}"
if !Div_calendar_crawler.dry_mode
lines = http_get_lines(url, date)
j = 0
h = Hash.new
first_hit = true
f = open_output_f(date)
while j < lines.length
if lines[j] =~ %r,<td><a href="https://www.nasdaq.com/symbol/(\w+)/dividend-history">([^&;#<>]*),
h[COMPANY_NAME] = $2
h[SYMBOL] = $1.upcase ; j += 1
h[EX_DATE] = extract_datum(lines[j]) ; j += 1
h[DIVIDEND] = extract_datum(lines[j]) ; j += 1
h[INDICATED_ANNUAL_DIVIDEND] = extract_datum(lines[j]); j += 1
h[RECORD_DATE] = extract_datum(lines[j]) ; j += 1
h[ANNOUNCMENT_DATE] = extract_datum(lines[j]) ; j += 1
h[PAYMENT_DATE] = extract_datum(lines[j]) ; j += 1
if first_hit
first_hit = false
else
f.puts ","
end
f.print(h.to_json)
end
j += 1
end
close_output_f(f)
end
end
def crawl()
if Div_calendar_crawler.output_directory
if !Dir.exist?(Div_calendar_crawler.output_directory)
raise "cannot find directory #{Div_calendar_crawler.output_directory}"
end
end
d = Div_calendar_crawler.date_range_start
0.upto(Div_calendar_crawler.date_range_length - 1) do |day_idx|
crawl_date(d)
d += (24 * 60 * 60)
end
end
def extract_datum(line)
if line =~ %r,<td.*?>(.*?)</td>,
$1
else
raise "could not find data in #{line}"
end
end
def http_get_lines(url, date)
cache_fn = "../http_cache/#{date.strftime("dividends-%Y-%m-%d")}"
if !File.exist?(cache_fn)
puts "fetching #{url}..."
z = U.rest_get(url)
File.open(cache_fn, "w") {|f| f.write(z) }
else
puts "reading cached #{url} at #{cache_fn}..."
end
IO.readlines(cache_fn)
end
def nasdaq_date(d)
d.strftime("%Y-%b-%d")
end
def open_output_f(date)
if !Div_calendar_crawler.output_directory
STDOUT
else
out_fn = "#{Div_calendar_crawler.output_directory}/#{date.strftime("dividends-%Y-%m-%d.json")}"
puts "writing #{out_fn}..."
File.open(out_fn, "w")
end
end
end
end
j = 0
Div_calendar_crawler.date_range_start = Time.new
#puts "Div_calendar_crawler.date_range_start=#{Div_calendar_crawler.date_range_start} for #{Div_calendar_crawler.date_range_length}"
Div_calendar_crawler.date_range_start = Time.parse("2018-Oct-17")
Div_calendar_crawler.date_range_length = 1
while ARGV.size > j do
arg = ARGV[j]
case arg
when "-dry"
Div_calendar_crawler.dry_mode = true
when "-for"
j += 1
Div_calendar_crawler.date_range_length = ARGV[j].to_i
when "-out"
j += 1
Div_calendar_crawler.output_directory = ARGV[j]
when "-start-on"
j += 1
Div_calendar_crawler.date_range_start = Time.parse(ARGV[j])
when "-year"
j += 1
year = ARGV[j].to_i
Div_calendar_crawler.date_range_start = Time.parse("#{year}-Jan-01")
Div_calendar_crawler.date_range_length = 365
else
raise "did not understand \"#{ARGV[j]}\""
break
end
j += 1
end
#puts "will fetch dividend info starting on #{Div_calendar_crawler.date_range_start}, going on for #{Div_calendar_crawler.date_range_length} day(s)"
Div_calendar_crawler.crawl()
#
#
#
# ruby -wS div_calendar_crawler.rb -out ../out -year 2018
#
#
| true |
90e390379c83c392f9f401bd35e1bc53af4f8ba9 | Ruby | Jhowden/rails_chess | /spec/models/game_pieces/knight_spec.rb | UTF-8 | 1,575 | 2.6875 | 3 | [] | no_license | require "rails_helper"
describe GamePieces::Knight do
let(:board) { double( chess_board: Array.new( 8 ) { |cell| Array.new( 8 ) } ) }
let(:knight) { described_class.new( { "file" => "e", "rank" => 4, "team" => :black, "board" => board } ) }
let(:knight2) { described_class.new( { "file" => "e", "rank" => 4, "team" => :white, "board" => board } ) }
describe "#determine_possible_moves" do
it "returns all possible moves" do
expect( board ).to receive( :find_knight_spaces ).with( knight ).and_return( [[3, 2], [2, 3], [5, 2], [6, 3], [3, 6], [2, 5], [5, 6], [6, 5]] )
knight.determine_possible_moves
expect( knight.possible_moves.size ).to eq ( 8 )
end
it "does NOT include positions off the board" do
expect( board ).to receive( :find_knight_spaces ).with( knight ).and_return( [[6, 4], [5, 5], [5, 7]] )
knight.determine_possible_moves
expect( knight.possible_moves.size ).to eq ( 3 )
end
it "clears possible moves when not empty" do
knight.possible_moves << ["a", 3]
allow( board ).to receive( :find_knight_spaces ).and_return( [["c", 3], ["d", 6]] )
knight.determine_possible_moves
expect( knight.possible_moves ).to eq( [["e", 4, "c", 3], ["e", 4, "d", 6]] )
end
end
context "when a black piece" do
it "displays the correct board marker" do
expect( knight.board_marker ).to eq( "♞" )
end
end
context "when a white piece" do
it "displays the correct board marker" do
expect( knight2.board_marker ).to eq( "♘" )
end
end
end | true |
19f014522d7937c810120ae28ff8ddea382d2dab | Ruby | singram/euler | /problem97/problem97.rb | UTF-8 | 575 | 3.625 | 4 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
# The first known prime found to exceed one million digits was discovered in 1999, and is a Mersenne prime of the form 2^6972593−1; it contains exactly 2,098,960 digits. Subsequently other Mersenne primes, of the form 2p−1, have been found which contain more digits.
# However, in 2004 there was found a massive non-Mersenne prime which contains 2,357,207 digits: 28433×2^7830457+1.
# Find the last ten digits of this prime number.
require 'pp'
n = 1
(1..7830457).each do
n*=2
n=n%10000000000 if n > 10000000000
end
pp (n*28433) +1
| true |
8dc7c7fe9266fbcca909df303d3a0c2293473316 | Ruby | kyudai-se/bankm_banksm | /spec/controllers/areams_controller_spec.rb | UTF-8 | 5,910 | 2.578125 | 3 | [] | no_license | require 'spec_helper'
# This spec was generated by rspec-rails when you ran the scaffold generator.
# It demonstrates how one might use RSpec to specify the controller code that
# was generated by Rails when you ran the scaffold generator.
#
# It assumes that the implementation code is generated by the rails scaffold
# generator. If you are using any extension libraries to generate different
# controller code, this generated spec may or may not pass.
#
# It only uses APIs available in rails and/or rspec-rails. There are a number
# of tools you can use to make these specs even more expressive, but we're
# sticking to rails and rspec-rails APIs to keep things simple and stable.
#
# Compared to earlier versions of this generator, there is very limited use of
# stubs and message expectations in this spec. Stubs are only used when there
# is no simpler way to get a handle on the object needed for the example.
# Message expectations are only used when there is no simpler way to specify
# that an instance is receiving a specific message.
describe AreamsController do
# This should return the minimal set of attributes required to create a valid
# Aream. As you add validations to Aream, be sure to
# adjust the attributes here as well.
let(:valid_attributes) { { } }
# This should return the minimal set of values that should be in the session
# in order to pass any filters (e.g. authentication) defined in
# AreamsController. Be sure to keep this updated too.
let(:valid_session) { {} }
describe "GET index" do
it "assigns all areams as @areams" do
aream = Aream.create! valid_attributes
get :index, {}, valid_session
assigns(:areams).should eq([aream])
end
end
describe "GET show" do
it "assigns the requested aream as @aream" do
aream = Aream.create! valid_attributes
get :show, {:id => aream.to_param}, valid_session
assigns(:aream).should eq(aream)
end
end
describe "GET new" do
it "assigns a new aream as @aream" do
get :new, {}, valid_session
assigns(:aream).should be_a_new(Aream)
end
end
describe "GET edit" do
it "assigns the requested aream as @aream" do
aream = Aream.create! valid_attributes
get :edit, {:id => aream.to_param}, valid_session
assigns(:aream).should eq(aream)
end
end
describe "POST create" do
describe "with valid params" do
it "creates a new Aream" do
expect {
post :create, {:aream => valid_attributes}, valid_session
}.to change(Aream, :count).by(1)
end
it "assigns a newly created aream as @aream" do
post :create, {:aream => valid_attributes}, valid_session
assigns(:aream).should be_a(Aream)
assigns(:aream).should be_persisted
end
it "redirects to the created aream" do
post :create, {:aream => valid_attributes}, valid_session
response.should redirect_to(Aream.last)
end
end
describe "with invalid params" do
it "assigns a newly created but unsaved aream as @aream" do
# Trigger the behavior that occurs when invalid params are submitted
Aream.any_instance.stub(:save).and_return(false)
post :create, {:aream => { }}, valid_session
assigns(:aream).should be_a_new(Aream)
end
it "re-renders the 'new' template" do
# Trigger the behavior that occurs when invalid params are submitted
Aream.any_instance.stub(:save).and_return(false)
post :create, {:aream => { }}, valid_session
response.should render_template("new")
end
end
end
describe "PUT update" do
describe "with valid params" do
it "updates the requested aream" do
aream = Aream.create! valid_attributes
# Assuming there are no other areams in the database, this
# specifies that the Aream created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
Aream.any_instance.should_receive(:update).with({ "these" => "params" })
put :update, {:id => aream.to_param, :aream => { "these" => "params" }}, valid_session
end
it "assigns the requested aream as @aream" do
aream = Aream.create! valid_attributes
put :update, {:id => aream.to_param, :aream => valid_attributes}, valid_session
assigns(:aream).should eq(aream)
end
it "redirects to the aream" do
aream = Aream.create! valid_attributes
put :update, {:id => aream.to_param, :aream => valid_attributes}, valid_session
response.should redirect_to(aream)
end
end
describe "with invalid params" do
it "assigns the aream as @aream" do
aream = Aream.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Aream.any_instance.stub(:save).and_return(false)
put :update, {:id => aream.to_param, :aream => { }}, valid_session
assigns(:aream).should eq(aream)
end
it "re-renders the 'edit' template" do
aream = Aream.create! valid_attributes
# Trigger the behavior that occurs when invalid params are submitted
Aream.any_instance.stub(:save).and_return(false)
put :update, {:id => aream.to_param, :aream => { }}, valid_session
response.should render_template("edit")
end
end
end
describe "DELETE destroy" do
it "destroys the requested aream" do
aream = Aream.create! valid_attributes
expect {
delete :destroy, {:id => aream.to_param}, valid_session
}.to change(Aream, :count).by(-1)
end
it "redirects to the areams list" do
aream = Aream.create! valid_attributes
delete :destroy, {:id => aream.to_param}, valid_session
response.should redirect_to(areams_url)
end
end
end
| true |
4fcf1320b97107c2aaf5a6de98a66e71f8b621b5 | Ruby | ryooo/timestamper | /app/models/stamp.rb | UTF-8 | 1,836 | 2.734375 | 3 | [] | no_license | class Stamp < ActiveRecord::Base
serialize :timeframes
class Timeframe
attr_reader :date
def initialize(h, date)
@in_at = h[:i]
@out_at = h[:o]
@date = date
end
def sec
((@out_at || Time.current.to_i) - @in_at)
end
def in_at
Time.at(@in_at)
end
def out_at
Time.at(@out_at) rescue nil
end
end
def timeframe_rows
@timeframe_rows ||= (self.timeframes || []).map {|e| Timeframe.new(e, self.date) }
end
def active?
last = self.timeframes&.last || {}
last[:i] != nil && last[:o] == nil
end
def total_sec
first = self.timeframe_rows.map(&:in_at).min
last = self.timeframe_rows.map(&:out_at).min rescue nil
(last || Time.current) - first
end
def total_in_sec
self.timeframe_rows.sum(&:sec)
end
def total_out_sec
total_sec - total_in_sec
end
def in(time)
self.timeframes ||= []
raise "timeframesはすでにactiveです #{self.id} #{self.timeframes}" if self.active?
raise "inが早すぎます #{self.id} #{self.timeframes}" if self.timeframes.present? && time.to_i < self.timeframes.last[:o].to_i
self.timeframes << {i: time.to_i}
end
def out(time)
raise "timeframesがactiveではありません #{self.id} #{self.timeframes}" unless self.active?
raise "outが早すぎます #{self.id} #{self.timeframes}" if time.to_i < self.timeframes.last[:i]
self.timeframes.last[:o] = time.to_i
end
def to_modal_json(user)
{
organization_name: user.organization.name,
user_name: user.name,
date: date,
timeframes: timeframes,
}.to_json
end
def as_json(options = {})
h = super({
except: [:organization_id, :updated_at, :created_at],
}.merge(options))
h[:type] = self.class.name.split("::").last.downcase
h
end
end
| true |
db89576d698f05582504219749cd6347cf4506d4 | Ruby | AJourdan/ruby_fundamentals2 | /exercise5.rb | UTF-8 | 200 | 4.3125 | 4 | [] | no_license | print "Give me a temperature in Farenheit and we will convert it to Celcius"
temp = gets.chomp
def num(temp)
(temp.to_i - 32) * 5/9
end
puts "#{temp} Farenheit is equal to #{num(temp)} in Celcius " | true |
75b8bd5ddd0b130084087645e23ac57e194b2797 | Ruby | joshuajhun/chisel | /class files/ordered_list.rb | UTF-8 | 711 | 3.234375 | 3 | [] | no_license | # require 'pry' # ~> LoadError: cannot load such file -- pry
class Ordered_list
attr_reader :input_text
def initialize (input_text)
@input_text = input_text
end
def chunk_text
text = @input_text
a = text.split("\n")
# a.chars # ~> NoMethodError: undefined method `chars' for ["1. red", "2. blue"]:Array
end
def list_compiler
information = chunk_text.map do |string|
string[3..-1]
end
information.map do |list|
"<li>#{list}</li>\n"
end.join
end
def list_compiler_final
open_l= "<ol>\n"
close_l= "</ol>"
open_l+list_compiler+close_l
# binding.pry
end
end
# Ordered_list.new("1. red\n2. blue\n").list_compiler
| true |
05f7f5978679ddcacba18139955fe91c782f779a | Ruby | dresselm/Rubot | /functions/admincommands/force.rb | UTF-8 | 486 | 2.796875 | 3 | [] | no_license | # This command will lock down the bot and only allow the admin to use it
def force
@locked = '' # Set the variable to lock/unlock
option = get_message # Get the user choice
case option
when 'lock'
@locked = true
chan_send("Set to lockdown mode.")
when 'unlock'
@locked = false
chan_send("Exiting lockdown mode.")
when 'reboot'
send_data("QUIT #{@user_name_first} made me do it...")
Kernel.exec("ruby bot.rb")
end
end
| true |
b2a865a1a386354d9c3e0f58d63851aec5625e53 | Ruby | phss/hackyventure | /situations/adventure.rb | UTF-8 | 438 | 2.859375 | 3 | [] | no_license | class Adventure
def initialize(story)
@situations = story.situations
@current = :start
@context = story.initial_context
end
def while_not_finished
while @current != :end
current_situation = @situations[@current]
current_situation.with_context(@context)
resolution = yield current_situation
@current = resolution[:next]
@context.merge!(resolution[:context])
end
end
end
| true |
3fb5697af31c5790c18f27039b96fcb7e95a8bbb | Ruby | alphagov/content-publisher | /lib/whitehall_importer/integrity_checker/unpublishing_check.rb | UTF-8 | 1,485 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | module WhitehallImporter
class IntegrityChecker::UnpublishingCheck
attr_reader :edition, :unpublishing
def initialize(edition, unpublishing)
@edition = edition
@unpublishing = unpublishing
end
def expected_type?
unpublishing["type"] == expected_type
end
def expected_type
return "withdrawal" if edition.withdrawn?
edition.status.details.redirect? ? "redirect" : "gone"
end
def expected_unpublishing_time?
return true unless edition.withdrawn?
unpublishing_time_matches?
end
def expected_unpublishing_time
edition.status.details&.withdrawn_at
end
def expected_alternative_path?
return true unless edition.removed?
unpublishing["alternative_path"] == edition.status.details.alternative_url
end
def expected_alternative_path
edition.status.details&.alternative_url
end
def expected_explanation?
Sanitize.clean(unpublishing["explanation"]).squish ==
Sanitize.clean(edition_explanation_html).squish
end
private
def unpublishing_time_matches?
IntegrityChecker.time_matches?(unpublishing["unpublished_at"],
expected_unpublishing_time&.rfc3339)
end
def edition_explanation_html
explanation = edition.status.details.try(:public_explanation) ||
edition.status.details.try(:explanatory_note)
Govspeak::Document.new(explanation).to_html
end
end
end
| true |
bcb1bbde8c4b0206024d204adab4a6deb9a79139 | Ruby | BohanHsu/leetcode2 | /3sum.rb | UTF-8 | 1,282 | 3.328125 | 3 | [] | no_license | # @param {Integer[]} nums
# @return {Integer[][]}
def three_sum(nums)
result = {}
nums.sort!
hsh = {}
nums.each_with_index do |num, i|
if !hsh.has_key?(num)
hsh[num] = []
end
hsh[num] << i
end
j = nums.length - 1
while j >= 0 && nums[j] >= 0 do
i = 0
while i < nums.length && nums[i] <= 0 do
diff = 0 - nums[i] - nums[j]
if diff.abs <= nums[i].abs && diff.abs <= nums[j].abs
if diff == 0 && nums[i] == 0 && nums[j] == 0
if hsh.has_key?(0) && hsh[0].length >= 3
arr = [0,0,0]
result[a_to_s(arr)] = arr
end
elsif diff == nums[i]
if hsh.has_key?(nums[i]) && hsh[nums[i]].length >= 2
arr = [nums[i],nums[i],nums[j]]
result[a_to_s(arr)] = arr
end
elsif diff == nums[j]
if hsh.has_key?(nums[j]) && hsh[nums[j]].length >= 2
arr = [nums[i],nums[j],nums[j]]
result[a_to_s(arr)] = arr
end
else
if hsh.has_key?(diff) && hsh[diff].length >= 1
arr = [nums[i],diff,nums[j]]
result[a_to_s(arr)] = arr
end
end
end
i += 1
end
j -= 1
end
return result.values
end
def a_to_s(arr)
return arr.join(',')
end
| true |
4eb421aa9126ca3c5141595a4ad82324f6510165 | Ruby | nicholasklick/find_by_sql_file | /lib/find_by_sql_file.rb | UTF-8 | 1,921 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'erb'
require 'active_record'
module FindBySqlFile
# This makes it a tad simpler to create a clean ERB binding context. It
# works like so:
#
# ERBJacket.wrap "A Foo is: <%= @foo -%>", :foo => 'not a bar'
#
class ERBJacket
def initialize(hash) # :nodoc:
hash.each { |k, v| instance_variable_set('@' + k.to_s, v) }
end
def wrap(erb_template) # :nodoc:
::ERB.new(erb_template, nil, '-').result binding
end
def self.wrap(erb_template = '', instance_variables = {}) # :nodoc:
new(instance_variables).wrap erb_template
end
end
def find_by_sql_with_sql_file(query_or_symbol, opts = {}) # :nodoc:
find_by_sql_without_sql_file sql_file(query_or_symbol, opts)
end
def count_by_sql_with_sql_file(query_or_symbol, opts = {}) # :nodoc:
count_by_sql_without_sql_file sql_file(query_or_symbol, opts)
end
def sql_file(query_or_symbol, opts = {}) # :nodoc:
if query_or_symbol.is_a? Symbol
file_name = Rails.root.join 'app', 'queries',
(table_name rescue 'application'), (query_or_symbol.to_s + '.sql')
bound_variables = HashWithIndifferentAccess.new(opts)
injected_locals = bound_variables.delete(:inject!) || []
query = ERBJacket.wrap File.read(file_name), injected_locals
query = replace_named_bind_variables(query, bound_variables)
query.gsub(/-- .*/, '').strip.gsub(/\s+/, ' ')
else
raise 'Additional parameters only supported when using a query' \
' file (pass a symbol, not a string)' unless opts.blank?
query_or_symbol
end
end
def find(*args)
super(*args)
end
# The equivalent of ActiveRecord::Base#find_by_sql(*args).first
def find_one_by_sql(*args)
find_by_sql(*args).first
end
end
class << ActiveRecord::Base
include FindBySqlFile
alias_method_chain :find_by_sql, :sql_file
alias_method_chain :count_by_sql, :sql_file
end | true |
5f61266830429b515658df1f46451d11f5c836c3 | Ruby | artemave/oompa-loompa | /spec/tweet_text_spec.rb | UTF-8 | 818 | 2.765625 | 3 | [] | no_license | require_relative 'spec_helper'
require_relative '../lib/tweet_text'
require_relative '../lib/models/link'
describe TweetText do
let(:link) do
Link.new(
score: 23,
title: 'this is title',
url: 'u' * 23,
comments_url: 'c' * 23,
source: 'Hn'
)
end
context "title is too long" do
before :each do
link.title = 'b'*300
end
it "makes sure text does not exceed 280 characters (urls are always 23ch long)" do
msg = TweetText.from_link link
expect(msg.size).to eq(279)
end
it "follows cut title with ..." do
msg = TweetText.from_link link
expect(msg).to match(/bbb\.\.\. /)
end
end
it "does not add ... if link.title is short enough" do
msg = TweetText.from_link link
expect(msg).not_to match(/\.\.\./)
end
end
| true |
840175ce92c7ae3e855d4d996a049a11c2dfd876 | Ruby | tilmitt11191/.dotfiles | /fonts/other_fonts/documents/pasta/generate_kml/lcl_thrput.rb | UTF-8 | 913 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env ruby
#
# pcapファイルからIPアドレスの取得@ip_list
# 取得したIPアドレスから、経度、緯度、地域の割り出す@geoip
#
require 'fileutils'
tmplog_dir = "tmp_log"
FileUtils.mkdir(tmplog_dir) unless FileTest.exist?(tmplog_dir)
require "#{File.dirname(__FILE__)}/ip_list.rb"
require "#{File.dirname(__FILE__)}/geoip.rb"
if ARGV.empty?
puts "*.pcap file set plz."
exit
end
ip_prs = IP_Prs.new
geoip_chk = GeoIP_Chk.new()
while arg = ARGV.shift
ip_prs.mk_iplist(arg)
end
geoip_chk.mk_geoip(ip_prs)
begin
File.rename("./tmp_log/ip_list", "./tmp_log/#{Time.now.strftime("%Y-%m-%d_%H:%M:%S")}-ip_list")
File.rename("./tmp_log/pcapinfo_list", "./tmp_log/#{Time.now.strftime("%Y-%m-%d_%H:%M:%S")}-pcapinfo_list")
rescue => ex
ip_prs.logger(4, "An error occurred at lcl_thrput: #{ex.message}")
ip_prs.logger(4, "#{$@}")
ip_prs.logger(4, "exit")
exit
end
| true |
fa2574e02689ff62f7590c9a21c584de60d4965b | Ruby | Saganesque/todolists_final | /app/models/profile.rb | UTF-8 | 1,123 | 2.890625 | 3 | [] | no_license | class Profile < ActiveRecord::Base
belongs_to :user
validates_inclusion_of :gender, in: %w( male female )
validate :my_happy_fname_lname_null_validator
validate :no_sue
default_scope {order birth_year: :asc}
=begin
Add a class method to the Profile class, called get_all_profiles, which:
accepts a min and max for the birth year
issues a BETWEEN SQL clause in a where clause to locate Profiles with birth years that are between min
year and max year
defends itself against SQL injection when applying the parameters to the SQL clauses
returns a collection of Profiles in ASC birth year order
=end
def self.get_all_profiles (min,max)
Profile.where(:birth_year => min..max).to_a
end
def my_happy_fname_lname_null_validator
if first_name.nil? && last_name.nil?
then
errors.add(:first_name, "Only one of either first name or last name may be empty")
errors.add(:last_name, "Only one of either first name or last name may be empty")
end
end
def no_sue
if gender == "male" && first_name== "Sue"
then
errors.add(:gender, "The man in black has a quarrel with you.")
end
end
end
| true |
a331c591cc28283f9e7b8401e00566f79a06460a | Ruby | RachaelMahon/Week3---Pairing-with-Tom- | /Battle/spec/player_spec.rb | UTF-8 | 576 | 2.546875 | 3 | [] | no_license | require 'views/player'
describe Player do
subject(:buddy) {Player.new('Buddy')}
subject(:ginger) {Player.new('Ginger')}
describe '#name' do
it 'returns the name' do
expect(buddy.name).to eq 'Buddy'
end
end
context '#hit_points' do
it 'returns the hit points' do
expect(buddy.hit_points).to eq described_class::DEFAULT_HIT_POINTS
end
end
context '#receive_damage' do
it 'reduces hit points when attacked' do
expect{buddy.receive_damage}.to change{buddy.hit_points}.by(-10)
end
end
end
| true |
a6a59e902f7983b5494a70cc46c5551156872595 | Ruby | AnthonyGarino/Chess | /rook.rb | UTF-8 | 315 | 2.59375 | 3 | [] | no_license | require_relative 'slideable.rb'
require_relative 'pieces.rb'
class Rook < Piece
include Slideable
def symbol
if color == :w
"\u2656".encode('utf-8')
else
"#{"\u265C".force_encoding('utf-8')}"
end
end
def move_dirs
LINEAR_DIRS
end
end | true |
e1402ebe415f463011a439ab4f91e1398a9b1c40 | Ruby | AkhileshwarReddy/Data-Munging | /kata-weather.rb | UTF-8 | 389 | 3.09375 | 3 | [] | no_license | weather_data = File.read('./data/weather.dat').lines
spread_min = 1.0/0
day = 0
weather_data.each_with_index do |line, index|
next if index == 0 or line.split.length == 0
line_data = line.split
spread = (line_data[1].to_i - line_data[2].to_i).abs
if spread < spread_min
spread_min = spread
day = line_data[0].to_i
end
end
puts "#{day} : #{spread_min}"
| true |
a2df3c3139c4e33964507dcef0d19313f998dd5c | Ruby | etsune/kanstat | /scripts/get_genres.rb | UTF-8 | 619 | 2.734375 | 3 | [] | no_license | require 'net/http'
require 'uri'
require 'json'
# Парсим жанры и генерим JSON result/genres.json
genres = {}
data_dir = File.expand_path("../../result/", __FILE__)
search_url = "http://yomou.syosetu.com/search.php"
search_page = Net::HTTP.get(URI.parse(search_url)).force_encoding('UTF-8')
genres_rx = /<label><input type="checkbox" id=".+?" value="(?<id>\d+)" data-parent="\d*" \/>(?<name>.+?)<\/label>/
search_page.scan(genres_rx).each do |match|
genres[match[0]] = { "jp"=>match[1], "en"=>match[1], "ru"=>match[1] }
end
File.write(data_dir+"/genres.json", genres.to_json)
puts "Complete." | true |
2c3e6c710878e6a054f6554a58242bc997c6f7fd | Ruby | misleb/opular | /app/assets/javascripts/untitled.rb | UTF-8 | 1,681 | 2.6875 | 3 | [] | no_license | $opular.module('op').constant('a', 1).constant('b', 2)
i = Op::Injector.new(['op'])
fn = ->(a, b) { a + b }
class Blah
attr_reader :result
def initialize(a, b)
puts self.inspect
@result = a + b
end
end
class A
def _get(b)
self
end
end
class B
def _get()
self
end
end
class C
def _get(a)
self
end
end
$opular.module('op').factory('aValue') do
{aKey: 42}
end.config do |_provide|
_provide.decorator('aValue') do |_delegate|
_delegate[:decoratedKey] = 43
end
end
Op::Injector.new(['op']).get('aValue')
class MyService
attr_reader :value
def initialize(theValue)
@value = theValue
end
end
$opular.module('op')
.value('theValue', 42)
.service('aService', MyService)
Op::Injector.new(['op']).get('aService')
do
{aKey: 42}
end.config do |_provide|
_provide.decorator('aValue') do |_delegate|
_delegate[:decoratedKey] = 43
end
end
Op::Injector.new(['op']).get('aValue')
class AProvider
attr_accessor :value
def initialize(_provide)
_provide.constant('b', 2)
end
def _get(b)
b + @value.to_i
end
end
$opular.module('noob', []) do |aProvider|
aProvider.value = 42
end
.provider('a', AProvider)
.run do |a|
puts "Run: #{a}"
end
i = Op::Injector.new(['op'])
puts i.get('a')
" asdf food.bar = 2".gsub(/\s+([^\.|\s]+)\s+\=[^\=]/, ' self.\1 = ')
s = Op::Scope.new
s._watch(->(scp) { scp.num }, ->(n,o,scp) { puts "#{n}, #{o}" })
s._apply("self.num = 1")
result = $opular_injector.invoke(->(_compile) {
el = Element.find(".home-index")
_compile.run(el)
})
result.data('hasCompiled')
begin
puts "ONce"
end while false
| true |
83e6fd93508f22cac07894b3a31454d828cf0428 | Ruby | LaraLaPierre/prework | /3_39_2.rb | UTF-8 | 304 | 4.09375 | 4 | [] | no_license |
# Create a function that takes in a string as its input and returns a tripled version of the string.
# So if the input is “cat”, the output should be “catcatcat”.
#Question 2:
def triple_machine(string)
output = "#{string}#{string}#{string}"
return output
end
p triple_machine("lara") | true |
285c51d0da2f7b8ce4b373acc886efb0943762bb | Ruby | javiermortiz/app-academy | /W6D2/knights_travails/knight_path_finder.rb | UTF-8 | 1,958 | 3.75 | 4 | [] | no_license | require_relative "polytreenode"
class KnightPathFinder
attr_reader :starting_pos, :considered_pos
attr_accessor :root_node
MOVES = [[1,2], [1,-2], [2,1], [2,-1], [-1,-2], [-1, 2], [-2,-1], [-2,1]]
def initialize(starting_pos)
@starting_pos = starting_pos
@considered_pos = [starting_pos]
self.build_move_tree(starting_pos)
end
def build_move_tree(starting_pos)
self.root_node = PolyTreeNode.new(starting_pos)
queue = [root_node]
until queue.empty?
current_node = queue.shift
current_pos = current_node.value
self.new_move_positions(current_pos).each do |next_pos|
child_node = PolyTreeNode.new(next_pos)
current_node.add_child(child_node)
queue << child_node
end
end
end
def self.valid_moves(pos)
possible_pos = []
x, y = pos
MOVES.each do |new_x, new_y|
possible_move = [new_x + x, new_y + y]
possible_pos << possible_move if possible_move.all? {|el| el >= 0 && el <= 7}
end
possible_pos
end
def new_move_positions(pos)
valid_moves = KnightPathFinder.valid_moves(pos)
valid_move = valid_moves.select {|move| !@considered_pos.include?(move)}
valid_move.each {|move| @considered_pos << move}
end
def find_path(end_pos)
end_node = self.root_node.bfs(end_pos)
trace_path_back(end_node)
end
def trace_path_back(end_node)
path = []
until end_node.nil?
path << end_node.value
end_node = end_node.parent
end
path.reverse
end
end
kpf = KnightPathFinder.new([0, 0])
p kpf.find_path([7, 6]) # => [[0, 0], [1, 2], [2, 4], [3, 6], [5, 5], [7, 6]]
p kpf.find_path([6, 2]) # => [[0, 0], [1, 2], [2, 0], [4, 1], [6, 2]]
# [0,4] = 2,5 , -2, 3
# MOVES = [ [2, 1]], [-2, -1] | true |
03d40ac202f5ac571364b6cb8250091d77e978a8 | Ruby | concord-consortium/lab-interactive-management | /bin/im_process.rb | UTF-8 | 1,721 | 2.578125 | 3 | [] | no_license | require 'json'
load "meta_data/interactive_metadata.rb"
#puts "interactive_meta = #{$interactive_metadata}"
# require activesupport for this?
class String
def to_underscore!
gsub!(/(.)([A-Z])/,'\1_\2') && downcase!
end
def to_underscore
dup.tap { |s| s.to_underscore! }
end
end
all_properties = []
model_attributes = []
serializables = []
migrations = []
# Rails Migration Types:
# :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.
# m_types = {'String' => 'string', 'Array' => 'text', 'Hash' => 'text', 'Float' => 'float', 'Boolean' => 'boolean', "Fixnum" => 'integer' }
$interactive_metadata.each do |k, v|
prop_name = k.to_s.to_underscore
all_properties << "#{prop_name}"
model_attributes << ":#{prop_name}"
# if v.has_key?(:defaultValue)
# default = v[:defaultValue]
# klass_name = default.class.name
# # serializables << "serialize :#{prop_name}, #{klass_name}" if %w{ Array Hash }.include?(klass_name)
# migration = "t.#{m_types[klass_name]}, #{prop_name}"
# # don't generate default for Hash and Array
# migration << ", :default => #{v}" unless %w{ Array Hash }.include?(klass_name)
# migrations << migration
# end
end
# puts "\n model attributes"
model_attributes_str = "store :json_rep, :accessor => [" << model_attributes.join(', ') << ']'
puts model_attributes_str
#puts "\n serializable properties:"
#print serializables.join("\n")
# puts "\n migrations:"
# puts migrations.join("\n")
# puts "\n all properties method:"
# all_prop_method = <<-PMETHOD.gsub(/^ {6}/, '')
# def all_properties
# %w{#{all_properties.join(', ')}}
# end
# PMETHOD
# puts all_prop_method
| true |
f9bb5458ff59bbd9881abaf76e758037a9116d77 | Ruby | ac0rn/africa | /app/controllers/mineral_stats_controller.rb | UTF-8 | 1,329 | 2.53125 | 3 | [] | no_license | require 'data_as_color'
require 'build_kml'
class MineralStatsController < ApplicationController
COUNTRY_LIST = File.open(File.join(Rails.root, "db/seeds/countries.txt"),"r:utf-8").read.strip.split("|")
def index
flash[:error] = flash[:errors] = flash[:notice] = nil
@data = COUNTRY_LIST.collect do |country|
country + ": " +
( MineralStat.last(:conditions => {:mineral => "Gold", :country => country}).try(:kg).to_i.to_s || "---" ) + " " + "kg<br />"
end
end
def new
deny_access and return unless current_user.try(:admin?)
render :new
end
def remove
deny_access and return unless current_user.try(:admin?)
render :remove
end
def create
deny_access and return unless current_user.try(:admin?)
result = MineralStat.create(params[:mineral_stat])
if result.errors.empty?
flash[:success] = "Information has been successfully saved."
else
flash[:error] = result.errors.full_messages.join
end
render :new
end
def build_kml
deny_access and return unless current_user.try(:admin?)
result = {}
COUNTRY_LIST.each do |name|
stat = MineralStat.last(:conditions => {:mineral => "Gold", :country => name}).try(:kg)
result[name] = stat if stat and stat > 0
end
BuildKML.run(DataAsColor.transform(result))
flash[:success] = "Map has been updated."
render :new
end
end
| true |
754c5e4cdc507eb1bbc8e0b7a8486e9361bbe1eb | Ruby | twitnithegirl/practice | /lib/project-euler/even_fibonacci_numbers.rb | UTF-8 | 282 | 3.703125 | 4 | [] | no_license | def even_fibonacci_sum(limit)
even_numbers(fibonacci_numbers(limit)).sum
end
def fibonacci_numbers(limit)
x = 1
y = 0
fibs = []
until (x + y) > limit do
fibs.push(x + y)
y = x
x = fibs.last
end
fibs
end
def even_numbers(fibs)
fibs.find_all(&:even?)
end | true |
764f00bc040ca2f49e3da31b7fe050512133c465 | Ruby | diegobolivar/spanish | /lib/spanish/verb.rb | UTF-8 | 677 | 2.890625 | 3 | [
"MIT"
] | permissive | module Spanish
module Features
extend self
attr_reader :person, :mood, :tense
# if no bits set, then 1st
@person = {
:second => 1 << 0,
:third => 1 << 1,
:plural => 1 << 2,
:familiar => 1 << 3
}
# if no bits set, then indicative
@mood = {
:subjunctive => 1 << 0,
:progressive => 1 << 1,
:imperative => 1 << 2,
:negative => 1 << 3 # can only be combined with imperative
}
# if no bits set, then present
@tense = {
:preterite => 1 << 0,
:imperfect => 1 << 1,
:future => 1 << 2,
:conditional => 1 << 3
}
end
class Verb
end
end
| true |
08953d2fd87bde147ed91820ba52323a59e8cb3a | Ruby | jasonLaster/DMKoans | /dm-code.rb | UTF-8 | 778 | 2.515625 | 3 | [] | no_license | require 'rubygems'
require 'data_mapper'
# setup sqlite3 connections
DataMapper.setup(:default, 'sqlite::memory:')
########################################
# MODELS ###############################
########################################
class Puppy
include DataMapper::Resource
# Properties
property :id, Serial
property :name, String
property :breed, String
property :birthday, DateTime
# Associations
# has 1, :person
end
class Person
include DataMapper::Resource
# Properties
property :id, Serial
property :name, String
# Association
# has 1, :puppy
end
class Course
include DataMapper::Resource
# Properties
property :id, Serial
property :topic, String
# Association
# has n, :puppy
end
class Enrolement
include DataMapper::Resource
end
| true |
5d63032d3476a62eb05d133d6644a7794dcbe0da | Ruby | alekvuka/cartoon-collections-v-000 | /cartoon_collections.rb | UTF-8 | 671 | 3.3125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def roll_call_dwarves(dwarfs)
dwarfs.each_with_index do |dwarf, index|
puts "#{index+1} #{dwarf}"
end
end
def summon_captain_planet(planets)
planets.map do |planet|
"#{planet.capitalize}!"
#require 'pry'
end
end
def long_planeteer_calls(calls)
calls.each do |call|
if call.size > 4
return true
end
end
return false
end
def find_the_cheese(cheeses)
#if cheeses.include?("cheddar", "gouda", "camembert")
cheeses.find do |cheese|
cheese == "cheddar" || cheese == "gouda" || cheese == "camembert"
end
#else
# return nil
#end
# cheese_types = ["cheddar", "gouda", "camembert"]
end
| true |
583ed3b367f7f648448804000186b27c1de3919d | Ruby | Seluxit/easy_fake_network | /models/utility/obj.rb | UTF-8 | 1,487 | 2.65625 | 3 | [] | no_license | module Core_Lib
module Obj
def self.remove_nil_element(hash)
case hash
when Hash
hash.compact!
hash.each_value{|v| remove_nil_element(v)}
when Array
hash.compact!
hash.each{|v| remove_nil_element(v)}
end
hash
end
def self.load(hash, symbol_keys: true)
return hash unless hash.is_a?(String)
Oj.load(hash, mode: :json, symbol_keys: symbol_keys)
end
def self.dump(hash)
Oj.dump(hash, use_as_json: true, mode: :json)
rescue StandardError => e
Core_Lib::Log.error("WRONG HASH: #{hash}")
Raven.capture_exception(e, extra: {hash: hash})
return hash.to_s
end
def self.symbolize_keys_deep(hash)
load(dump(hash))
end
def self.recursive_merge(hash1, hash2, merge_array: false)
hash = {}
keys = hash1.keys | hash2.keys
keys.each do |key|
case [!hash1[key].nil?, !hash2[key].nil?]
when [true, false]
hash[key] = hash1[key]
when [false, true]
hash[key] = hash2[key]
when [true, true]
if hash1[key].is_a?(Hash) && hash2[key].is_a?(Hash)
hash[key] = recursive_merge(hash1[key], hash2[key], merge_array: merge_array)
elsif hash1[key].is_a?(Array) && hash2[key].is_a?(Array) && merge_array
hash[key] = hash1[key] | hash2[key]
else
hash[key] = hash2[key]
end
end
end
hash
end
end
end
| true |
0f7e2d5b2a1b7fb5f071161396f327ae5587dbf1 | Ruby | philwhisenhunt/ruby-basics | /3sum.rb | UTF-8 | 617 | 3.375 | 3 | [] | no_license | def three_sum(nums)
res = []
nums = nums.sort()
nums.each_with_index do |num, index|
if index > 0 && num == nums[index - 1]
next
end
l = index + 1
r = nums.length - 1
while l < r
threeSum = num + nums[l] + nums[r]
if threeSum > 0
r -= 1
elsif threeSum < 0
l += 1
else
puts "yes"
res << [num, nums[l], nums[r]]
l += 1
while nums[l] == nums[l - 1] && l < r
l+= 1
end
end
end
end
return res
end
nums = [-1,0,1,2,-1,-4]
print three_sum(nums) | true |
0ff6e850c4997f59c487e8f0c9c42adc5a5dd9ea | Ruby | ivar/magic-search-engine | /lib/condition/condition_frame.rb | UTF-8 | 189 | 2.9375 | 3 | [] | no_license | class ConditionFrame < ConditionSimple
def initialize(frame)
@frame = frame.downcase
end
def match?(card)
card.frame == @frame
end
def to_s
"is:#{@frame}"
end
end
| true |
958e25e1d47265fd1746d14b928f524459fca9c3 | Ruby | AnthonyLebro/ruby_battle_royal | /app.rb | UTF-8 | 566 | 2.984375 | 3 | [] | no_license | require 'bundler'
Bundler.require
require_relative 'lib/game'
require_relative 'lib/player'
player1 = Player.new("Colonel Antho")
player2 = Player.new("Destructor Xabi")
puts "Voici l'état de chaque joueur :"
puts "-------------------------------"
player1.show_state
player2.show_state
puts "-------------------------------"
while player2.life_points> 0 && player1.life_points> 0
puts ""
puts "\033[1;32mPassons à la phase d'attaque :"+"\033[0m"
player2.attacks(player1)
if player1.life_points <= 0
break
else
player1.attacks(player2)
end
end
#binding.pry | true |
cd7a050fc796b6993223c5fb5aeade5bc4525211 | Ruby | albertyw/rosalind | /stronghold/perm.rb | UTF-8 | 640 | 3.453125 | 3 | [] | no_license | n = 5
# Recursively get permutations
def get_permutations(digits)
return [digits] if digits.length == 1
permutations = []
digits.each_with_index do |digit, index|
digits_left = digits.rotate(index+1)[0,digits.length-1]
permutations_left = get_permutations(digits_left)
permutations_left.map!{|permutation| [digit]+permutation}
permutations += permutations_left
end
return permutations
end
digits = (1..n).to_a
permutations = get_permutations(digits)
# Print out permutations
p permutations.length
permutations.each do |permutation|
permutation.each do |digit|
print digit.to_s+' '
end
print "\n"
end
| true |
dd98c0b32bd70abba8c595ae7b1addfa221461d0 | Ruby | molenick/chain_punk | /spec/lib/chain_punk/generator_spec.rb | UTF-8 | 4,777 | 2.734375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe ChainPunk::Generator do
subject { ChainPunk::Generator.new(frequency_table) }
let(:frequency_table) {}
let(:grapheme_count) { 0 }
let(:options) { {} }
context '#phrase' do
context 'when called with a grapheme count of zero' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 0 }
it 'returns a phrase with zero graphemes' do
expect(subject.generate(grapheme_count).length).to eq(0)
end
end
context 'when called with a grapheme count' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
it 'returns a phrase with 5 graphemes' do
expect(subject.generate(grapheme_count, options).length).to eq(5)
end
end
context 'when called with some seeds' do
let(:frequency_table) { { ['a'] => ['b', 'b'], ['b'] => ['a', 'b', 'a'] } }
let(:grapheme_count) { 1 }
let(:options) { { seeds: [['a']] } }
it 'returns a phrase starting with those graphemes' do
expect(subject.generate(grapheme_count, options)).to eq('a')
end
end
context 'when the boundary and closure are nil' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
it 'returns a phrase with no boundary or closure' do
expect(subject.generate(grapheme_count, options).length).to eq(5)
end
end
context 'when called with a boundary' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
let(:options) { { boundary: ' ' } }
it 'returns a phrase of graphemes separated by the boundary' do
expect(subject.generate(grapheme_count, options).split(' ').length).to eq 5
end
end
context 'when called with a closure' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
let(:options) { { closure: '.' } }
it 'returns a phrase terminated with the closure' do
expect(subject.generate(grapheme_count, options)[-1]).to eq('.')
end
end
context 'when the generator cannot find a grapheme that follows the current grapheme' do
let(:frequency_table) { { ['a'] => [['b']] } }
let(:grapheme_count) { 5 }
it 'returns before reaching the desired length' do
expect(subject.generate(grapheme_count, options).length).to eq(2)
end
end
context 'when called with a index size of 0' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
let(:options) { { index_size: 0 } }
it 'blows up' do
expect { subject.generate(grapheme_count, options) }.to raise_error(ZeroDivisionError)
end
end
context 'when called with a index size of 1' do
let(:frequency_table) { { ['a'] => [['b'], ['b']], ['b'] => [['a'], ['b'], ['a']] } }
let(:grapheme_count) { 5 }
let(:options) { { index_size: 1 } }
it 'returns a phrase with 5 graphemes' do
expect(subject.generate(grapheme_count, options).length).to eq(5)
end
end
context 'when called with a index size of 2' do
let(:frequency_table) { { ['a', 'b'] => [['b', 'a']], ['b', 'a'] => [['a', 'b']] } }
let(:grapheme_count) { 6 }
let(:options) { { index_size: 2 } }
it 'returns a phrase with 5 graphemes' do
expect(subject.generate(grapheme_count, options).length).to eq(6)
end
context 'when called with some seeds' do
let(:grapheme_count) { 6 }
let(:options) { { index_size: 2, seeds: [['c', 'a']] } }
it 'returns a phrase starting with those graphemes' do
expect(subject.generate(grapheme_count, options)[0, 2]).to eq('ca')
end
end
end
context 'when called with a index size that has a remainder when divided by the grapheme count' do
let(:frequency_table) { { ['a', 'b'] => [['b', 'a']], ['b', 'a'] => [['a', 'b']] } }
let(:grapheme_count) { 5 }
let(:options) { { index_size: 2 } }
it 'returns a phrase with 4 graphemes' do
expect(subject.generate(grapheme_count, options).length).to eq(4)
end
context 'when called with some seeds' do
let(:grapheme_count) { 5 }
let(:options) { { index_size: 2, seeds: [['c', 'a']] } }
it 'returns a phrase starting with those graphemes' do
expect(subject.generate(grapheme_count, options)[0, 2]).to eq('ca')
end
end
end
end
end
| true |
a5d2fd14949653a7c505c2c30607dd47f24b7394 | Ruby | wing-x/paiza | /hack/sexy.rb | UTF-8 | 78 | 3.09375 | 3 | [] | no_license | m,n= gets.split.map(&:to_i)
if m > n
puts m - n
else
puts "0"
end
| true |
b43d69e2da112d567c5c43fb2d61880a939566f1 | Ruby | jdashton/glowing-succotash | /daniel/AoC/advent01.rb | UTF-8 | 169 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative 'lib/advent01'
INPUT = IO.read('input/advent01.txt')
adv1 = Advent01.new
puts adv1.total_fuel(INPUT.lines.map(&:to_i))
| true |
cb7a0e7a8619482c94ee2bc934c4ab52e3ef9b9a | Ruby | unalterable/rails_enquiries | /sextant-altered/lib/schema_scraper.rb | UTF-8 | 875 | 3.1875 | 3 | [
"MIT"
] | permissive | class Schema_scraper
attr_reader :table_contents
def initialize(text)
@text = text
@table = false
@current_table = []
@table_contents = []
end
def scrape_schema
@text.each do |line|
end_in_line?(line)
create_table_in_line?(line)
@current_table << line[1].gsub(/[^0-9a-z]/,' ').strip if @table
end
prepare_table_contents(@table_contents)
@table_contents
end
private
def create_table_in_line?(line_text)
@table = true if line_text.include?('create_table')
end
def end_in_line?(line_text)
if line_text.include?('end')
@table = false
@current_table << "MODELLING"
@table_contents << @current_table
@current_table = []
end
end
def prepare_table_contents(array)
array.delete_if{ |a| a.length == 1}
array.each do |a|
a[0].capitalize!
end
end
end
| true |
33cf88f27512ee9a5378006ca4dedd642c56332c | Ruby | candlerb/nanoc | /lib/nanoc3/helpers/tagging.rb | UTF-8 | 2,281 | 3.171875 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
module Nanoc3::Helpers
# Nanoc3::Helpers::Tagging provides some support for managing tags added to
# items. To add tags to items, set the +tags+ attribute to an array of
# tags that should be applied to the item. For example:
#
# tags: [ 'foo', 'bar', 'baz' ]
#
# To activate this helper, +include+ it, like this:
#
# include Nanoc3::Helpers::Tagging
module Tagging
require 'nanoc3/helpers/html_escape'
include Nanoc3::Helpers::HTMLEscape
# Returns a formatted list of tags for the given item as a string. The
# tags will be linked using the `link_for_tag` function; the HTML-escaping
# rules for this function apply here as well. Several parameters allow
# customization:
#
# :base_url:: The URL to which the tag will be appended to construct the
# link URL. This URL must have a trailing slash. Defaults to
# "http://technorati.com/tag/".
#
# :none_text:: The text to display when the item has no tags. Defaults to
# "(none)".
#
# :separator:: The separator to put between tags. Defaults to ", ".
def tags_for(item, params={})
base_url = params[:base_url] || 'http://technorati.com/tag/'
none_text = params[:none_text] || '(none)'
separator = params[:separator] || ', '
if item[:tags].nil? or item[:tags].empty?
none_text
else
item[:tags].map { |tag| link_for_tag(tag, base_url) }.join(separator)
end
end
# Returns all items with the given tag.
def items_with_tag(tag)
@items.select { |i| (i[:tags] || []).include?(tag) }
end
# Returns a link to to the specified tag. The link is marked up using the
# rel-tag microformat. The `href` attribute of the link will be HTML-
# escaped, as will the content of the `a` element.
#
# +tag+:: The name of the tag, which should consist of letters and numbers
# (no spaces, slashes, or other special characters).
#
# +base_url+:: The URL to which the tag will be appended to construct the
# link URL. This URL must have a trailing slash.
def link_for_tag(tag, base_url)
%[<a href="#{h base_url}#{h tag}" rel="tag">#{h tag}</a>]
end
end
end
| true |
17348b0d9532396f7cc4339542db58c840292c99 | Ruby | thomascpan/exercises | /data_structures/new/LinkedListTest.rb | UTF-8 | 909 | 3.328125 | 3 | [] | no_license | require_relative 'LinkedList'
p "linked_list1"
# INITIALIZE
linked_list1 = LinkedList.new
# INSERT
linked_list1.insert(1)
linked_list1.insert(2)
linked_list1.insert(0,0)
# PRINT_VALUES1
linked_list1.print_values1
# GET
p linked_list1.get(0)
p linked_list1.get(1)
p linked_list1.get(2)
p linked_list1.get(3)
# DELETE
# linked_list1.delete(1)
# PRINT_VALUES2
linked_list1.print_values2
# REVERSE_PRINT
puts linked_list1.reverse_print
puts
p "linked_list2"
# INITIALIZE
linked_list2 = LinkedList.new
# INSERT
linked_list2.insert(-2)
linked_list2.insert(-1)
linked_list2.insert(0)
linked_list2.insert(1)
linked_list2.insert(2)
# PRINT_VALUES1
linked_list2.print_values1
# REVERSE1
linked_list2.reverse1
# PRINT_VALUES2
linked_list2.print_values2
# REVERSE1
linked_list2.reverse2
# PRINT_VALUES2
linked_list2.print_values2
# FIND_MERGE_POINT
p LinkedList.find_merge_point(linked_list1,linked_list2) | true |
7815f55873bbd70fcc293a5511c8af084cfdf549 | Ruby | lisataylor5472/backend_mod_1_prework | /section4/exercises/class_object.rb | UTF-8 | 1,468 | 4.09375 | 4 | [] | no_license | # Create a class called MyCar
class MyCar
attr_accessor :color
attr_reader :year
# Define instance variables year, color, model
def initialize(year, color, model)
@year = year
@color = color
@model = model
# set a starting point for a current_speed instance variable
@current_speed = 0
end
# falcor = MyCar.new(2021, "White", "Forestor")
# Create instance methods that allow the car to speed up
def speed_up(number)
@current_speed += number
puts "You gas it and increase speed by #{number} mph."
end
# car to brake
def brake(number)
@current_speed -= number
puts "You brake and decrease speed by #{number} mph."
end
# car to shut off
def shut_down
@current_speed = 0
end
def spray_paint(color)
self.color = color
puts color
end
end
falcor = MyCar.new(2021, "White", "Forester")
falcor.speed_up(20)
falcor.speed_up(20)
falcor.brake(20)
falcor.brake(20)
falcor.shut_down
# could also add in a current_speed method to evaluate how the speed changes
=begin
def current_speed
puts "You are now going #{@current_speed} mph."
end
falcor.speed_up(20)
falcor.current_speed
falcor.speed_up(20)
falcor.current_speed
falcor.brake(20)
falcor.current_speed
falcor.brake(20)
falcor.current_speed
falcor.shut_down
falcor.current_speed
=end
# Add accessor method to change color
falcor.color = 'black'
p falcor.color
# Add accessor method to view the year
p falcor.year
falcor.spray_paint('red')
| true |
14f7821e0cdf61ef89f2895a5d8f00de4a42f36b | Ruby | wayudi208012/learnmeabitcoin-code | /hexdec.rb | UTF-8 | 125 | 3.15625 | 3 | [] | no_license | #!/usr/bin/env ruby
def hexdec(hex)
dec = hex.to_i(16)
return dec
end
hex = ARGV[0] || STDIN.gets.chomp
puts hexdec(hex)
| true |
733337ae1c26aee48d903ef4fd4c06a6cc15cd39 | Ruby | ding-an-sich/batch-447 | /lectures/OOP/bank_account.rb | UTF-8 | 681 | 4.03125 | 4 | [] | no_license | # frozen_string_literal: true
# This is the Bank Account class
class BankAccount
attr_reader :money
def initialize(money, account_number, owner, bank_name)
@money = money
@account_number = account_number
@owner = owner
@bank_name = bank_name
end
def deposit(money)
change_balance(money)
end
def withdraw(money)
change_balance(- money)
end
private
def change_balance(value)
@money += value
end
end
matts_bank_account = BankAccount.new(0, "666", "Matheus", "Bradesco")
matts_bank_account.money # => 0
matts_bank_account.deposit(50)
matts_bank_account.money # => 50
matts_bank_account.withdraw(100)
puts matts_bank_account.money
| true |
61ede11379d27f77bc54a5d887411c61972083c0 | Ruby | duleorlovic/config | /bin/whereami.rb | UTF-8 | 4,655 | 3.125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
#
# TODO: find blocks inside same intent and remove in level
# FULL_PREVIOUS_IF_NOT_BEGIN_WITH_SAME_WORD
#
# Run test:
# whereami.rb test
# Specific test
# whereami.rb --name test_same_level_on_previous
# Use byebug
# ruby -rbyebug whereami.rb test --name test_only_previous
# or uncomment following line
# require 'byebug'
LEVELS = [
ONLY_PREVIOUS = 'only_previous'.freeze,
SAME_LEVEL_ON_PREVIOUS = 'same_level_on_previous'.freeze,
FULL_PREVIOUS_IF_NOT_BEGIN_WITH_SAME_WORD = 'full_previous_if_not_begin_with_same_word'.freeze,
].freeze
def read_from_file(filename, target_line)
result = []
unless File.exist? filename
puts "File #{filename} does not exists!"
exit
end
current_line = 1
File.foreach filename do |line|
result << line.rstrip
break if current_line >= target_line
current_line += 1
end
result
end
# when we jump back (indent < last_indent) than we clear all higher indents
# ONLY_PREVIOUS skip all same levels
# SAME_LEVEL_ON_PREVIOUS will keep same level but only on previous (last line
# level is skipped)
# FULL_PREVIOUS_IF_NOT_BEGIN_WITH_SAME_WORD
#
def pop_lines_greater_than_indent(lines, line_indents, indent, level, last_line)
line_indents.reverse.each do |i|
if i == indent && level == SAME_LEVEL_ON_PREVIOUS && last_line
lines.pop
line_indents.pop
elsif i == indent && level == ONLY_PREVIOUS
lines.pop
line_indents.pop
elsif i > indent && level != FULL_PREVIOUS_IF_NOT_BEGIN_WITH_SAME_WORD
lines.pop
line_indents.pop
else
# i < indent : we already cleaned that
break
end
end
end
def clear_lines(text_array, level, filename = 'test')
lines = []
line_indents = []
last_indent = 0
text_array.each_with_index do |line, index|
next if line.size.zero?
last_line = index + 1 == text_array.size
indent = line.match(/^\s*/)[0].size
pop_lines_greater_than_indent(lines, line_indents, indent, level, last_line) if indent <= last_indent
line_indents << indent
lines << format_output(line, index, filename)
last_indent = indent
end
lines
end
def format_output(line, index, filename)
"#{filename}:#{index + 1}-#{line}"
end
if ARGV[0] != 'test'
filename = ARGV[0]
target_line = ARGV[1].to_i
level = ARGV[2] || ONLY_PREVIOUS
EXAMPLE_USAGE = <<~HERE_DOC.freeze
Arguments: whereami.rb {filename} {line_number} {level}
filename is for example a.txt
line_number is 1
level options are: #{LEVELS.join(' and ')}. Default is #{ONLY_PREVIOUS}.
For example:
whereami.rb my_file.txt 1
whereami.rb my_file.txt 1 #{SAME_LEVEL_ON_PREVIOUS}
Run tests:
whereami.rb test
HERE_DOC
if filename.to_s.empty?
puts 'Please provide filename'
puts EXAMPLE_USAGE
exit
end
if target_line.zero?
puts 'Please provide the target_line number'
puts EXAMPLE_USAGE
exit
end
unless LEVELS.include? level
puts 'Please use correct level'
puts EXAMPLE_USAGE
exit
end
result = clear_lines(read_from_file(filename, target_line), level, filename).join("\n") + "\n"
puts result
else
require 'minitest/autorun'
class Test < Minitest::Test
def sample
<<~TEXT
# MyClass
class MyClass
CONST = 1
def my_c_method
c = 1
d = 1
end
# My method
def my_method
a = 1
b = 1
TEXT
.split("\n")
end
def test_only_previous
result = <<~TEXT
test:2-class MyClass
test:11- def my_method
test:13- b = 1
TEXT
assert_equal result, clear_lines(sample, ONLY_PREVIOUS).join("\n") + "\n"
end
def test_same_level_on_previous
result = <<~TEXT
test:1-# MyClass
test:2-class MyClass
test:3- CONST = 1
test:5- def my_c_method
test:8- end
test:10- # My method
test:11- def my_method
test:13- b = 1
TEXT
actual = clear_lines(sample, SAME_LEVEL_ON_PREVIOUS).join("\n") + "\n"
assert_equal result, actual
end
def test_full_previous_if_not_begin_with_same_word
result = <<~TEXT
test:1-# MyClass
test:2-class MyClass
test:3- CONST = 1
test:5- def my_c_method
test:6- c = 1
test:7- d = 1
test:8- end
test:10- # My method
test:11- def my_method
test:13- b = 1
TEXT
actual = clear_lines(sample, FULL_PREVIOUS_IF_NOT_BEGIN_WITH_SAME_WORD).join("\n") + "\n"
assert_equal result, actual
end
end
end
| true |
385be2935842f102466bc096aad5ad12dfb55e02 | Ruby | VAMelend/oxford-comma-001-prework-web | /lib/oxford_comma.rb | UTF-8 | 394 | 3.34375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | array = ["hippo,giraffe,monkey,horse"]
def oxford_comma(array)
if array.length == 1
return array.join
elsif array.length == 2
array.insert(1, "and")
array.join(" ")
elsif array.length == 3
newy= array.pop
lov= "and "+newy
yer= array.push(lov)
yer.join(", ")
elsif array.length > 3
eli= array.pop
diego= "and "+eli
john = array.push(diego)
john.join(", ")
end
end
| true |
c6a0f8697f3182c86a7523b6bc5b9a94d994f2e5 | Ruby | tlau425/blood-oath-relations-nyc-web-career-031119 | /app/models/follower.rb | UTF-8 | 514 | 3.25 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Follower
attr_accessor :name, :life_motto
attr_reader :age
@@all = []
def initialize(name, age, life_motto)
@name = name
@age = age
@life_motto = life_motto
@@all << self
end
def cults
Cult.all.select do |cult|
cult.followers.include?(self)
end
end
def join_cult(new_cult)
new_cult.followers << self
end
def self.all
@@all
end
def self.of_a_certain_age(num)
self.all.select do |follower|
follower.age >= num
end
end
end
| true |
b40fdeeefb09b51d294c0badda929b9eec2a48ab | Ruby | Jbern16/algos | /merge_meetings.rb | UTF-8 | 542 | 3.390625 | 3 | [] | no_license | def merge_meetings(meetings)
sorted_meetings = meetings.sort_by(&:first)
merged = [sorted_meetings[0]]
sorted_meetings[1..-1].each do |meeting_start, meeting_end|
prev_meeting_start, prev_meeting_end = merged[-1]
if meeting_start <= prev_meeting_end
merged[-1] = [ prev_meeting_start, ([meeting_end, prev_meeting_end].max) ]
else
merged << [ meeting_start, meeting_end ]
end
end
merged
end
puts merge_meetings([ [0, 1], [3, 5], [4, 8], [10, 12], [9, 10] ]).inspect
# [ [0, 1], [3, 8], [9, 12] ] | true |
8595e0c3be4a4b8e84ed424ac48a95ca3e44357f | Ruby | SunOfDawn/extend-validators | /lib/extend-validators/validations/hash_validator.rb | UTF-8 | 3,946 | 2.75 | 3 | [
"MIT"
] | permissive | require 'extend-validators/validations'
module ActiveModel
module Validations
class HashValidator < EachValidator
include JsonValidationHelper
attr_accessor :validators, :default_options
def initialize(options)
super
init_sub_validators
end
def init_sub_validators
@validators = {}
@default_options = filter_options(options)
@default_options.each do |members, member_options|
filter_options(member_options).each do |key, sub_options|
next unless sub_options
attributes.each do |attribute|
parse_sub_options = parse_options(sub_options, attribute)
@validators[validator_key(attribute, members, parse_sub_options)] = get_validator(key).new(parse_sub_options)
end
end
end
end
# with hash format value, you can use basic validator keywords validate every member like use in model,
# such as:
#
# class Person < ActiveRecord::Base
# validates :other, hash: {
# name: { presence: true },
# age: { numericality: { only_integer: true, greater_than: 0 } },
# [:height, :weight] => { numericality: { only_integer: true, greater_than: 0 } },
# description: { format: { with: /.*/ }, allow_blank: true }
# }, allow_nil: true
#
# With each member, you can use [:allow_nil :allow_blank] to check null,
# but not support other conditions such as [:if, :on, :unless].
# These will make the validation complex and difficult to read.
# We recommend that only use these in model attribute
def validate_each(record, attribute, value)
return record.errors.add(attribute, options[:message] || :invalid_hash_value) unless value.is_a?(Hash)
default_options.each do |members, sub_options|
Array(members).each do |member|
member_value = value[member]
next if (sub_options[:allow_nil] && member_value.nil?) || (sub_options[:allow_blank] && member_value.blank?)
filter_options(sub_options).each do |key, options|
validator_key = validator_key(attribute, members, parse_options(options, attribute))
validate_each_member(record, attribute, validators[validator_key], member, member_value)
end
end
end
end
def validate_each_member(record, attribute, validator, member, member_value)
before_errors_count = record.errors[attribute].count || 0
validator.validate_each(record, attribute, member_value)
after_errors_count = record.errors[attribute].count || 0
record.errors[attribute][-1].insert(0, "#{member} ") if after_errors_count - before_errors_count > 0
end
end
module HelperMethods
# Validates that the specified attribute matches the json context with your options
# basic usage like to other active model, for example:
#
# class Person < ActiveRecord::Base
# validates_hash_of :json_value, {
# name: { presence: true },
# age: { numericality: { only_integer: true, greater_than: 0 } },
# [:height, :weight] => { numericality: { only_integer: true, greater_than: 0 } },
# description: { format: { with: /.*/ }, allow_blank: true }
# }
# end
#
# Configuration options:
# * <tt>:message</tt> - Specifies a custom error message, but only show when checking
# value format invalid (default is: "is not included in the list").
#
# There is also two of default options supported by every validator:
# +:allow_nil+, +:allow_blank+
# See <tt>ActiveModel::Validation#validates</tt> for more information
#
def validates_hash_of(*attr_names)
validates_with HashValidator, _merge_attributes(attr_names)
end
end
end
end
| true |
fba699a1408544b6cf0334cc7dce98f74cc077ce | Ruby | evansenter/gene | /test/unit/petri_test.rb | UTF-8 | 2,056 | 2.953125 | 3 | [
"WTFPL"
] | permissive | require File.join(File.dirname(__FILE__), "..", "test_helper.rb")
class PetriTest < Test::Unit::TestCase
def setup
# Don't make a petri here.
end
def test_true
assert true
end
def test_prepare_image
petri = setup_petri
assert_equal Magick::Image, petri.target_image.class
assert_equal Point.new(600, 800), Petri.image_dimensions
end
def test_initialize__with_block
Petri.new(test_image_path) do
set_num_cells 1
set_num_genes 2
set_num_points 3
end
assert_equal 3, Petri.num_cells
assert_equal 2, Petri.num_genes
assert_equal 3, Petri.num_points
assert_raise NoMethodError do
Petri.rawr!
end
assert_raise NoMethodError do
Petri.new(test_image_path) { set_num_cells 1 }.rawr!
end
end
def test_initialize
petri = Petri.new(test_image_path)
assert_equal 30, Petri.num_cells
assert_equal 50, Petri.num_genes
assert_equal 3, Petri.num_points
assert_equal 30, petri.dish.size
assert petri.dish.all? { |cell| cell.is_a?(Cell) }
end
def test_initialize__num_cells_divisible_by_three
[1, 2, 3].each do |i|
assert_equal 3, Petri.new(test_image_path) { set_num_cells i }.num_cells
end
assert_equal 6, Petri.new(test_image_path) { set_num_cells 4 }.num_cells
end
def test_sort_by_fitness!
cells = [stub(:fitness => 0.5), stub(:fitness => 0.75), stub(:fitness => 0.25)]
petri = setup_petri
petri.instance_variable_set(:@dish, cells)
petri.send(:sort_by_fitness!)
assert_equal [0.75, 0.5, 0.25], petri.dish.map(&:fitness)
end
def test_round
petri = setup_petri
assert_equal 0, petri.round
petri.send(:next_round)
assert_equal 1, petri.round
petri.send(:next_round)
assert_equal 2, petri.round
end
private
def setup_petri
Petri.new(test_image_path) { set_num_cells 1 }
end
def test_image_path
File.join(File.dirname(__FILE__), "..", "assets", "Nova.jpg")
end
end | true |
2ac87f5863bd2fb356b45ff4ea2aba391ef2e0aa | Ruby | ycohen26/Prework | /meanaverage.rb | UTF-8 | 247 | 3.671875 | 4 | [] | no_license | puts "Please enter 5 numbers."
num1 = gets.chomp
num2 = gets.chomp
num3 = gets.chomp
num4 = gets.chomp
num5 = gets.chomp
puts
answer = (num1.to_i+num2.to_i+num3.to_i+num4.to_i+num5.to_i)/5.to_f
puts "The mean average of your numbers is #{answer}"
| true |
83e5ee894398b59f3919bda0ef0ea35d8f72c17a | Ruby | Grynet/DYPL | /assignment2/code_generation.rb | UTF-8 | 3,253 | 3.21875 | 3 | [] | no_license | module Model
def self.generate(filepath)
file = File.open(filepath)
array_of_lines = file.readlines
file.close()
title_line = array_of_lines[0].split(" ")
title_line[1].slice! ":"
class_name = title_line[1]
attribute_hash = Hash.new()
constraint_hash = Hash.new()
for line in array_of_lines
if line.start_with?("attribute")
attribute_line = line.split(" ")
attribute_line[1].slice! ":"
attribute_line[1].slice! ","
attribute_hash[attribute_line[1]] = attribute_line[2]
constraint_hash[attribute_line[1]] = Array.new()
end
end
for line in array_of_lines
if line.start_with?("constraint")
line.slice! "constraint :"
constraint_line = line.split(", ")
value_array = constraint_hash[constraint_line[0]]
value_array << constraint_line[1].strip
end
end
# create a new empty and nameless class
my_class = Class.new
# adding the nameless class to the constants will also make it take the name that we give it
my_class.class.const_set("#{class_name}", my_class)
# Class has a private method "define_method". It could be used from another method inside the
# class itself, but since we weren't allowed to use "def" we can't define that other helper method.
# Another way of circumventing information hiding that we have mentionet is the method "send"
attribute_hash.each do |attribute, type|
my_class.send(:define_method,(attribute+"=").to_sym, lambda{|arg|
if arg.class.to_s == type
constraint_array = constraint_hash[attribute]
for constraint in constraint_array
if constraint.start_with?("%{")
constraint.sub! "%{", ""
constraint.chop!
end
if constraint.start_with?("%(")
constraint.sub! "%(", ""
constraint.chop!
end
constraint.gsub! "\"", ""
constraint.gsub! "\'", ""
new_constraint = constraint
if arg.class == "String".class
new_constraint = constraint.gsub(attribute, "\""+arg+"\"")
else
new_constraint = constraint.gsub(attribute, arg.to_s)
end
if not eval(new_constraint)
raise RuntimeError.new("Illegal Argument Error")
end
end
eval("@#{attribute} = arg")
else
raise RuntimeError.new("Illegal Type Error")
end})
my_class.send(:define_method, attribute.to_sym, lambda{
eval("@#{attribute}")})
end
my_class.send(:define_method, "load_from_file".to_sym, lambda{ | filepath |
yamlContent = YAML.load_file(filepath)
object_array = Array.new
yamlContent.each do | content |
content[1].each do | entries |
object = my_class.new
class_variable_exists = true
entries.each do | key, value |
equation = ""
controll_variable = "object.#{key}"
if value.class == Fixnum
equation = "object.#{key}=(#{value})"
else
equation = "object.#{key}=('#{value}')"
end
if defined? eval("#{controll_variable}") == method
begin
eval("#{equation}")
rescue RuntimeError
class_variable_exists = false
end
else
class_variable_exists = false
end
end
if class_variable_exists
object_array << object
end
end
end
return object_array
})
return my_class.new
end
end | true |
c7484642c6659554bfaf06b6b6f382866664636a | Ruby | Florent2/Puzzle-Node--14 | /lib/user.rb | UTF-8 | 1,083 | 3.265625 | 3 | [] | no_license | class User
require "set"
attr_reader :name, :mentioned_names
def initialize(name)
@name = name
@mentioned_names = SortedSet.new
@connections = Array.new
end
def ==(other_user)
name == other_user.name
end
def <=>(other_user)
name <=> other_user.name
end
def add_mentioned_names(names)
@mentioned_names.merge names
end
def connections(users, order)
@connections[order] ||=
case order
when 0
SortedSet.new [self]
when 1
SortedSet.new users.select { |user| mentions?(user.name) && user.mentions?(name) }
else
connections_of_previous_orders = (0..(order - 1)).inject(SortedSet.new) { |connections, i| connections.merge connections(users, i) }
found_connections = connections(users, order - 1).inject(SortedSet.new) { |found_connections, connection| found_connections.merge connection.connections(users, 1) }
found_connections.subtract connections_of_previous_orders
end
end
def mentions?(name)
@mentioned_names.include? name
end
end
| true |
b779759338fa57e0d6d0076e6978323930953ac2 | Ruby | survivingknowledge/twlms | /app/helpers/sessions_helper.rb | UTF-8 | 1,718 | 2.703125 | 3 | [] | no_license | module SessionsHelper
# Logs in given user by setting session key
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in persistent session
def remember(user)
user.remember
# cookie is encrypted and expires in 20 years
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the current logged-in user (if any) else null
def current_user
#@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
# first check for user by session
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
# if no session, check for cookie with digest token
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated_cookie?(cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Forgets a persistent session
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out given user
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# Page access requires logged-in user else redirects to login page
def authenticate!
if !logged_in?
flash.now[:notice] = 'Page access requires you to log in'
redirect_to sign_in_path
end
end
# Force user to not be logged_in to view page (signin/signup)
def force_no_login
if logged_in?
redirect_to root_path, notice: 'You are already logged in'
end
end
end
| true |
6f18aaaa04d3c4b8242b2267a2c1f110178c5963 | Ruby | Christopher-Steel/freecycle-sofa-harvester | /harvest.rb | UTF-8 | 1,162 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'rest-client'
require_relative 'harvested_page'
API_URL = 'https://groups.freecycle.org'.freeze
class Harvester
def initialize
@api = RestClient::Resource.new(API_URL)
@sofas = []
end
def harvest_group(group)
@api["group/#{group}/posts/search"].post(
{
search_words: 'corner sofa couch settee',
include_offers: 'on',
date_start: '',
date_end: '',
resultsperpage: 100
},
content_type: 'application/x-www-form-urlencoded'
) do |res|
return HarvestedPage.new(res.body).to_sofas
end
end
def group_list
%w(
HampsteadUK
kentishtown_freecycle
camdensouth_freecycle
Islington-North-Freecycle
Islington-South-Freecycle
Islington-East-Freecycle
islington-west-freecycle
KensingtonandChelseaFreecycle
HackneyUK
HaringeyUK
freecyclebarnet
)
end
def harvest
group_list.each do |group|
puts "<h3>#{group}</h3>"
sofas = harvest_group(group)
sofas.each { |s| puts s.to_html }
end
end
end
Harvester.new.harvest
| true |
f10efd327bd7945d87e31be5e541eda0143b3332 | Ruby | sahyoni/RubyDoc | /inh_classes.rb | UTF-8 | 428 | 3.46875 | 3 | [] | no_license | class Animals
attr_accessor :color,:voice
def get_voice
return @voice
end
def get_color
return @color
end
end
class Dog< Animals
attr_accessor :owner
def get_owner
return @owner
end
end
def main
my_dog=Dog.new
my_dog.color=" black"
puts my_dog.get_color
my_dog.owner="hussein"
puts my_dog.get_owner
animals=Animals.new
animals.color="white"
puts animals.get_color
end
main() | true |
607ffd3103af6c64bc0f179969006b390eb4520d | Ruby | edfallon/day_two_test | /ruby_functions_practice.rb | UTF-8 | 1,214 | 3.890625 | 4 | [] | no_license | def return_10
return 10
end
def add(num_1, num_2)
return num_1 + num_2
end
def subtract(num_1, num_2)
return num_1 - num_2
end
def multiply(num_1, num_2)
return num_1 * num_2
end
def divide(num_1, num_2)
return num_1 / num_2
end
def length_of_string(string_to_check)
return string_to_check.length
end
def join_string(string_1, string_2)
return string_1 + string_2
end
def add_string_as_number(string_1, string_2)
return string_1.to_i + string_2.to_i
end
def number_to_full_month_name(month_number)
month_string = case month_number
when 1
month_string = "January"
when 3
month_string = "March"
when 9
month_string = "September"
end
return month_string
end
def number_to_short_month_name(short_month_number)
short_month_string = case short_month_number
when 1
short_month_string = "Jan"
when 3
short_month_string = "Mar"
when 9
short_month_string = "Sep"
end
return short_month_string
end
def volume_of_cube(length)
return length ** 3
end
def volume_of_sphere(radius)
puts Math::PI
return (4.0 / 3.0) * (Math::PI) * (radius ** 3)
end
def fahrenheit_to_celsius(value_of_fahrenheit)
return (value_of_fahrenheit - 32.0) * (0.5556)
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.