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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cb0decd3d863dcaac407e263a748fb6fd48e9d27
|
Ruby
|
verdammelt/Greyhawk-Weather
|
/spec/precipitation_occurance_spec.rb
|
UTF-8
| 4,070
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'precipitationoccurance'
describe PrecipitationOccurance do
it "returns array of precipitation" do
roller = make_roller(13)
precip_occur = PrecipitationOccurance.new({(0..20) => mock(:PrecipitationInfo).as_null_object,
(21..100) => mock(:PrecipitationInfo).as_null_object})
precip_occur.type(roller).should be_instance_of Array
precip_occur.type(roller)[0].should be_instance_of Precipitation
end
it "determines precipitation" do
snowstorm = create_test_precipitation(:light_snowstorm)
rainstorm = create_test_precipitation(:light_rainstorm)
precip_occur = PrecipitationOccurance.new({(0..20) => snowstorm,
(21..100) => rainstorm})
{ 13 => :light_snowstorm,
57 => :light_rainstorm
}.each_pair { |roll, precip|
precip_occur.type(make_roller(roll))[0].name.should == precip
}
end
it "loads from file" do
precip_occur = PrecipitationOccurance.load("data/precipitationoccurance.yml")
precip_occur.type(make_roller(22))[0].name.should == "Sleetstorm"
end
it "defaults to null precipitation" do
PrecipitationOccurance.new.type(make_roller(13))[0].name.should == NullPrecipitationInfo.new.name
end
it "checks for and computes continuing precipitation" do
snowstorm = create_test_precipitation(:light_snowstorm)
rainstorm = create_test_precipitation(:light_rainstorm)
precip_occur = PrecipitationOccurance.new({(0..20) => snowstorm,
(21..100) => rainstorm})
precip_occur.type(make_roller(35, 5, 1, 5, 10, 5, 5, 100)).map{ |p| p.name }.should ==
[:light_rainstorm, :light_snowstorm, :light_rainstorm, :light_rainstorm]
end
it "checks terrain for precipitation" do
precip = mock(:PrecipitationInfo)
precip.stub(:not_allowed_in).and_return([:desert])
precip_occur = PrecipitationOccurance.new({ (0..20) => precip})
precip_occur.type(make_roller(10), nil, :desert).first.name.should == NullPrecipitationInfo.new.name
end
it "does no reroll if temp_range is ok" do
precip = create_test_precipitation(:foo, 0, [10,50])
precip_occur = PrecipitationOccurance.new({(0..20) => precip})
roller = make_roller(10)
roller.should_receive(:roll).exactly(1)
precip_occur.type(roller, (20..40))
end
it "rerolls if temp is too low" do
precip = create_test_precipitation(:foo, 0, [20,20])
precip_occur = PrecipitationOccurance.new({(0..20) => precip})
roller = make_roller(10)
roller.should_receive(:roll).exactly(2)
precip_occur.type(roller, (0..10))
end
it "rerolls if temp is too high" do
precip = create_test_precipitation(:foo, 0, [20,20])
precip_occur = PrecipitationOccurance.new({(0..20) => precip})
roller = make_roller(10)
roller.should_receive(:roll).exactly(2)
precip_occur.type(roller, (50..60))
end
it "checks temp ranges for continuing weather" do
precipcold = create_test_precipitation(:cold, 0, [20,20])
precipwarm = create_test_precipitation(:warm, 10, [30,30])
precip_occur = PrecipitationOccurance.new({(0..20) => precipcold, (30..50) => precipwarm})
roller = make_roller(40, 10, 10)
roller.should_receive(:roll).exactly(3)
precipitations = precip_occur.type(roller, (30..30))
precipitations.collect { |p| p.name }.should == [:warm, "No Precipitation"]
end
private
def make_roller(*rolls)
roller = mock(:DieRoller)
roller.stub(:roll).and_return(*rolls)
roller
end
def create_test_precipitation (name, chance_to_continue = 10, min_max = [0, 100])
precip = mock(:Precipitation)
precip.stub(:not_allowed_in).and_return([])
precip.stub(:min_temp).and_return(min_max[0])
precip.stub(:max_temp).and_return(min_max[1])
precip.stub(:name).and_return(name)
precip.stub(:chance_of_rainbow).and_return(0)
precip.stub(:chance_to_continue).and_return(chance_to_continue)
precip
end
end
| true
|
3e455f10bbbe95e97751bf21fc0b2339c305f91b
|
Ruby
|
adjeielias90/ruby-crypto
|
/caesar.rb
|
UTF-8
| 898
| 3.28125
| 3
|
[] |
no_license
|
require_relative 'formatting.rb'
class Array
def caesar_shift n
map do |letter|
if letter =~ /[^A-Za-z]/ then letter
else ((letter.downcase.to_alphabet_order + n) % 26).to_ascii_char.in_same_case_as(letter)
end
end.join
end
def in_cipher_alphabet char
caesar_shift(char.downcase.ord - 97)
end
def caesar_shift_map mapping
caesar_shift (mapping.keys[0].upcase.ord - mapping.values[0].upcase.ord).abs
end
def all_caesar_shifts
('A'..'Z').map { |letter| in_cipher_alphabet(letter) }
end
def caesar_candidates
all_caesar_shifts.select.with_index do |text, i|
print "[ #{i} ] Checking for words in {a => #{('a'..'z').to_a[i]}}: #{text.slice(0, 20)}... "
found_words = text.downcase.gsub(/[^A-Za-z ]/, '').words.take(3).join(" ").any_nontrivial_words?
puts found_words ? "\u2713" : "X"
found_words
end
end
end
| true
|
30ce4465f8e395536336060903065d231ad2538f
|
Ruby
|
myoan/bowling
|
/score.rb
|
UTF-8
| 1,098
| 3.390625
| 3
|
[] |
no_license
|
class Score
class UndefinedTerm < RuntimeError; end
def initialize(data = "")
@row = data.gsub('-', '0').split('')
@stack = [] # data stack
@pc = @row.size-1 # program counter
@score = 0 # result
end
def score
while @pc >= 0 do
ch = @row[@pc]
case ch
when '0'..'9'
@stack.push(ch.to_i)
@score += (ch.to_i)
when 'X' # strike
if @stack.size >= 2
@nnext = @stack[-2]
@next = @stack[-1]
@score += (10 + @next + @nnext)
end
@stack.push(10)
when '/' # spare
if @stack.size >= 1
@next = @stack[-1]
@score += @next
end
spr_ch = @row[@pc-1]
@stack.push(10 - spr_ch.to_i)
@score += 10 - spr_ch.to_i
else
raise UndefinedTerm
end
#print("row: ", @row, "\n");
#print("stk: ", @stack, "\n");
#print("ch: ", ch, "(", @pc, ")\n")
#print("scr: ", @score, "\n");
@pc -= 1
end
return @score
end
end
@score = Score.new('XXXXXXXXXXXX')
@score = Score.new('9-9-9-9-9-9-9-9-9-9-')
#@score = Score.new('5/5/5/5/5/5/5/5/5/5/5')
print("score: ", @score.score, "\n")
| true
|
7cecbaf0d02a84709232202916625c7060c2d154
|
Ruby
|
IanPFoertsch/Proposition
|
/lib/proposition/sentence/n_ary/n_ary_sentence.rb
|
UTF-8
| 737
| 3.15625
| 3
|
[] |
no_license
|
require_relative "../sentence"
require_relative "../logic"
module Proposition
class NArySentence < Sentence
def initialize(sentences)
sorted = sentences.sort_by { |s| s.in_text }
@sentences = sorted
end
def conjoin(other)
raise "other sentence is not an NArySentence" unless other.is_a?(NArySentence)
self.class.new(@sentences + other.sentences)
end
def sentences
Marshal.load(Marshal.dump(@sentences))
end
def operator
raise NotImplementedError
end
def in_text
"(#{sentences.map {|s| s.in_text}.join(' ' + operator + ' ')})"
end
def ==(other)
in_text == other.in_text
end
def eql?(other)
self == other
end
end
end
| true
|
87d07593d2da7a95e88d41d4dc637911c22aff1d
|
Ruby
|
stevieing/courtbooking
|
/lib/setup/permitted_attributes.rb
|
UTF-8
| 993
| 2.65625
| 3
|
[] |
no_license
|
class PermittedAttributes
##
# = Permitted Attributes
#
# These should be loaded from a yaml file in the following format:
# model_a:
# whitelist:
# - :attr_a
# - :attr_b
# - :model_ids: []
# nested:
# :model_b:
# - :attr_c
# - :attr_d
# virtual:
# - :attr_e
#
# All attributes should be symbols
#
# == Whitelist
# These are the main top level attributes which should be permitted.
# You can permit a belongs to relationship with :model_ids: []
#
# == Nested
# Any attributes permitted via associations. Usually has many through
# Each sub category name will be the association.
#
# == Virtual
# Virtual attributes are those which need permitting but are not attached to a model
#
#
#
def initialize(file)
@struct = DeepStruct.new(YAML.load_file(file))
@struct.to_h.keys.each do |key|
define_singleton_method key, proc { @struct.send(key.to_sym) }
end
end
end
| true
|
8d73326adcd89058b69062ef30ee097ac6f0d229
|
Ruby
|
podral3/rubyProjects
|
/stockPicker.rb
|
UTF-8
| 192
| 3.453125
| 3
|
[] |
no_license
|
def stock_picker(arr)
while arr[0] == arr.max &&
arr.shift
end
while arr[arr.length-1] == arr.min
arr.pop
end
end
stock_picker([17,16,3,6,9,15,8,6,2,10,1,1])
| true
|
02ddbef801266afa9812afc1885b15375d6479b3
|
Ruby
|
hankeliu2015/the-bachelor-todo-nyc-web-102918
|
/lib/bachelor.rb
|
UTF-8
| 1,952
| 3.71875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
def get_first_name_of_season_winner(data, season) # review the index i.
winner_first_name = ""
data.each do |seasons, season_data|
if seasons == season
season_data.each do |contestants_data|
i = 0
contestants_data.each do |key, value|
if value == "Winner"
winner_first_name = data[seasons][i]["name"].split(" ").first
i += 1 # array contain ladies_data. Need to find the array index.
end
end
end
end
end
winner_first_name
end
def get_contestant_name(data, occupation)
name = ""
data.each do |seasons, season_data|
i = 0 #consultant_data is an big array. need [index] then get to ["name"]
season_data.each do |contestants_data|
contestants_data.each do |key, value|
if value == occupation
name = data[seasons][i]["name"]
end
end
i += 1
end
end
name
end
def count_contestants_by_hometown(data, hometown)
i = 0
data.each do |seasons, season_data|
season_data.each do |contestants_data|
contestants_data.each do |key, value|
if value == hometown
i += 1
end
end
end
end
i
end
def get_occupation(data, hometown)
occupation = ""
data.each do |seasons, season_data|
season_data.each do |contestants_data|
contestants_data.each do |key, value|
if value == hometown
#binding.pry
return contestants_data["occupation"] # the occupation = not working.
end
end
end
end
# occupation not working for some reason. Has to put return inside the loop.
end
def get_average_age_for_season(data, season)
average = 0
total_age = 0
i = 0
#binding.pry
data[season].each do |contestants_data|
total_age += (contestants_data["age"]).to_i
i += 1
end
(total_age/i.to_f).round(0)
end
| true
|
4ca747e272400a5640699b845cca1ce3cd485b3d
|
Ruby
|
social-snippet/social-snippet
|
/lib/social_snippet/repository/drivers/driver_base.rb
|
UTF-8
| 1,915
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
module SocialSnippet::Repository
# Repository base class
# usage: class GitDriver < DriverBase
class Drivers::DriverBase
attr_reader :url
# @example
# driver = Driver.new(url, ref)
# driver.fetch
# driver.cache # => save data into storage
def initialize(new_url)
@url = new_url
end
# Returns latest version
#
# @param pattern [String] The pattern of version
# @return [String] The version
def latest_version(pattern = "")
pattern = "" if pattern.nil?
matched_versions = versions.select {|ref| ::SocialSnippet::Version.is_matched_version_pattern(pattern, ref)}
::VersionSorter.rsort(matched_versions).first
end
# Returns all versions
#
# @return [Array<String>] All versions of repository
def versions
refs.select {|ref| ::SocialSnippet::Version.is_version(ref) }
end
def each_ref(&block)
refs.each &block
end
def has_versions?
not versions.empty?
end
def refs
raise "not implemented"
end
def snippet_json
raise "not implemented"
end
def rev_hash(ref)
raise "not implemented"
end
def current_ref
raise "not implemented"
end
def fetch
raise "not implemented"
end
def each_directory(ref)
raise "not implemented"
end
def each_file(ref)
raise "not implemented"
end
class << self
def target?(url)
if is_local_path?(url)
target_local_path?(url)
elsif is_url?(url)
target_url?(url)
end
end
def target_url?(url)
raise "not implemented"
end
def target_path?(path)
raise "not implemented"
end
def is_local_path?(s)
not /^[^:]*:\/\// === s
end
def is_url?(s)
::URI.regexp === s
end
end
end # DriverBase
end # SocialSnippet
| true
|
dc054348253684027fef69c78322d5148103ef71
|
Ruby
|
abineko2/app
|
/app/helpers/users_helper.rb
|
UTF-8
| 208
| 2.515625
| 3
|
[] |
no_license
|
module UsersHelper
#基本時間などの値を、指定書式にフォーマットしてかえす
def format_basic_time(datetime)
format("%.2f",((datetime.hour*60)+datetime.min)/60.0)
end
end
| true
|
f282d3d51fc1f754abbe009da68eceb83195b5c9
|
Ruby
|
litencatt/ruby-design-patterns
|
/www.techscore.com/iterator.rb
|
UTF-8
| 1,353
| 4.125
| 4
|
[] |
no_license
|
# 集約オブジェクトの要素
class Student
attr_reader :name, :sex
def initialize(name, sex)
@name = name
@sex = sex
end
end
# 集約オブジェクト
class StudentList
attr_reader :students, :last
def initialize
@students = []
end
def gt_student_at(index)
@students[index]
end
def add(student)
@students << student
end
def length
@students.length
end
def iterator
StudentListIterator.new(self)
end
end
class StudentListIterator
def initialize(student_list)
@student_list = student_list
@index = 0
end
def has_next?
@index < @student_list.length
end
def next_student
student = self.has_next? ? @student_list.gt_student_at(@index) : nil
@index += 1
student
end
end
class Teacher
def create_student_list
@student_list = StudentList.new
@student_list.add(Student.new("赤井亮太", 1))
@student_list.add(Student.new("赤羽里美", 2))
@student_list.add(Student.new("岡田未央", 2))
@student_list.add(Student.new("西森俊介", 1))
@student_list.add(Student.new("中ノ森玲奈", 2))
end
def call_students
iterator = @student_list.iterator
while iterator.has_next?
student = iterator.next_student
puts student.name
end
end
end
t = Teacher.new
t.create_student_list
t.call_students
| true
|
6e2ec650aa149277ec88735fac778172e0afc4b7
|
Ruby
|
nick-and-raquel-do-internet-things/date-night
|
/app/models/relationship.rb
|
UTF-8
| 232
| 2.53125
| 3
|
[] |
no_license
|
class Relationship < ApplicationRecord
belongs_to :person_a, class_name: 'User'
belongs_to :person_b, class_name: 'User'
def other_person(user)
if user == person_a
person_b
else
person_a
end
end
end
| true
|
7f40e64c1e8b516f52d8302bec803c222f585630
|
Ruby
|
eddiepr/MySecondRepository
|
/engine_exercise_car_class.rb
|
UTF-8
| 353
| 3.0625
| 3
|
[] |
no_license
|
require_relative("engine_exercise_engine1_class")
require_relative("engine_exercise_engine2_class")
require_relative("engine_exercise_engine3_class")
class Car
def initialize(car_sound, engine)
@car_sound = car_sound
@engine = engine
end
def start
@engine.sound
puts @car_sound#other sound that a car makes aside from the engine
end
end
| true
|
fb38ef748b3ee7ce3ad3001f468419cddec6e782
|
Ruby
|
ducc/dablang
|
/src/compiler/nodes/node_symbol.rb
|
UTF-8
| 648
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'node_literal.rb'
class DabNodeSymbol < DabNodeLiteral
attr_reader :symbol
def initialize(symbol)
raise "empty symbol (#{symbol})" if symbol.to_s.empty?
super()
@symbol = symbol
add_source_parts(symbol)
end
def extra_dump
":#{symbol}"
end
def extra_value
symbol
end
def escaped_symbol
if symbol =~ /^[a-z_]+$/i
symbol
else
"\"#{symbol}\""
end
end
def compile_constant(output)
output.print('CONSTANT_SYMBOL', escaped_symbol)
end
def my_type
DabTypeSymbol.new
end
def compile(output)
output.print('PUSH_SYMBOL', escaped_symbol)
end
end
| true
|
4b0b4a5da5ec2a41aeddd01e0fc36b4dc81a394d
|
Ruby
|
mindreframer/ruby-stuff
|
/github.com/russolsen/design_patterns_in_ruby_code/05/ex10_consistent_demo.rb
|
UTF-8
| 446
| 3.078125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require '../example'
require 'ex10_consistent'
example %q{
fred = Employee.new("Fred", "Crane Operator", 30000)
fred.salary = 1000000
# Warning! Inconsistent state here!
fred.title = 'Vice President of Sales'
}
example %q{
fred = Employee.new("Fred", "Crane Operator", 30000)
# Don't inform the observers just yet
fred.salary = 1000000
fred.title = 'Vice President of Sales'
# Now inform the observers!
fred.changes_complete
}
| true
|
127758f25b303ef17ae0863903ffa131b356c11c
|
Ruby
|
JoevinCanet/JoevinCanet
|
/reboot/calculator/interface.rb
|
UTF-8
| 560
| 3.578125
| 4
|
[] |
no_license
|
require_relative "calculator"
choise = "y"
while choise == "y"
p "Entrez le premier chiffre de votre opération"
first_number = gets.chomp.to_f
p "Entrez le second chiffre de votre opération"
second_number = gets.chomp.to_f
p "Entrez le type d'opération souhaité (+, -, /, *)"
operation = gets.chomp
result = calculate(first_number, second_number, operation)
if result
puts "Votre résultat est #{result}"
else
puts "Résultat invalide."
end
puts "Veux-tu continuer ? (y/n)"
choise = gets.chomp
end
È
| true
|
3fab56442798ea8d0f630cc95ebecb1fde34da22
|
Ruby
|
Suylo/Discord-Bot
|
/src/modules/commands/helpCmd.rb
|
UTF-8
| 1,569
| 2.78125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
# HelpCmd display all commands available on this bot
module HelpCmd
extend Discordrb::EventContainer
extend Discordrb::Commands::CommandContainer
command :help do |channel|
user_name = channel.user.username
user_distinct = channel.user.distinct
user_avatar_url = channel.user.avatar_url('png')
server_name = channel.server.name
server_icon_url = channel.server.icon_url
channel.send_embed do |embed|
embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: user_name, url: nil, icon_url: user_avatar_url)
embed.title = 'Liste of commands'
embed.description = 'List of all commands available and possible to execute'
embed.colour = '#FF0000'
embed.thumbnail = Discordrb::Webhooks::EmbedThumbnail.new(url: server_icon_url)
# embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://www.ruby-lang.org/images/header-ruby-logo.png')
embed.add_field(name: '> !servericon', value: 'Displays the URL and ID of the server icon.', inline: true)
embed.add_field(name: '> !thanks', value: 'Allows you to thank someone, a counter is displayed.', inline: true)
embed.add_field(name: '> !ping', value: 'Displays the Bot\'s latency time.', inline: true)
embed.add_field(name: '> !shutdown', value: 'Allows the Owner to shutdown the Bot.', inline: true)
embed.add_field(name: '> !say', value: 'Allows you to speak instead of the Bot.', inline: true)
end
puts "HelpCmd executed by #{user_distinct} on the server : #{server_name}"
end
end
| true
|
c2e0ee059c3381ac85c978c79e5a32c78bb8319d
|
Ruby
|
aakrutishitut/online_cab_booking
|
/Location.rb
|
UTF-8
| 239
| 3.203125
| 3
|
[] |
no_license
|
class Location
Location_d=Struct.new(:x,:y)
attr_accessor :x
attr_accessor :y
def initialize(x,y)
@x=x
@y=y
end
def distance(l1) # location of the cab is passed in argument
return ((x-l1.x)*(x-l1.x)+(y-l1.y)*(y-l1.y))
end
end
| true
|
082c233d6fb2de8fdfe6c588ca4c8efac8534099
|
Ruby
|
DingChiLin/RubyExercise
|
/Algorithms/ClosestPair/FindClosestPairTest.rb
|
UTF-8
| 645
| 2.90625
| 3
|
[] |
no_license
|
require 'test/unit'
require './ClosestPairFinder'
class TestSimpleSorts < Test::Unit::TestCase
def setup
@pairs = []
File.open("pairs.txt","r") do |file|
file.each_line do |line|
@pairs.push(line.split(" ").map(&:to_i))
end
end
@expect = [[5, 5],[6, 6]]
end
def teardown
end
def testBruteForceWayToFindClosestPairProperly
cp = ClosestPairFinder.new
actual = cp.bruteFind(@pairs)
assert_equal @expect.sort,actual.sort
end
def testFastWayToFindClosestPairProperly
cp = ClosestPairFinder.new
actual = cp.find(@pairs)
assert_equal @expect.sort,actual.sort
end
end
| true
|
b4757af69674da435abef4b3c73adbefece19916
|
Ruby
|
gzim921/Car
|
/spec/my_car_spec.rb
|
UTF-8
| 1,235
| 2.734375
| 3
|
[] |
no_license
|
RSpec.describe Car::MyCar do
let(:bmw) { Car::MyCar.new('BMW', 2015, 'Blue') }
let(:defects) { 'Water pump, Oil leak' }
it 'creates new instance' do
expect(bmw).to be_instance_of(Car::MyCar)
end
it 'has current speed defined 0' do
expect(bmw.current_speed).to eq(0)
end
it 'speeding up' do
bmw.speed_up(80)
expect(bmw.current_speed).to eq(80)
end
it 'speeding by default' do
bmw.speed_up
expect(bmw.current_speed).to eq(Car::MyCar::SPEED_OFFSET)
end
it 'slowing down' do
bmw.slow_down
expect(bmw.current_speed).to eq(-Car::MyCar::SPEED_OFFSET)
end
it 'paints the car' do
bmw.spray_paint :green
expect(bmw.color).to eq(:green)
end
it 'has no defects' do
expect(bmw.defects).to be_empty
end
it 'showing defects' do
bmw.add_defect(defects)
expect(bmw.service_info).to include(defects)
puts bmw.service_info
end
it 'will lists all defect' do
bmw.add_defect(defects)
expect(bmw.service_info).to include("Defects to be fixed: #{defects}")
puts bmw.service_info
end
it 'will remove water pump defect' do
bmw.add_defect(defects)
bmw.repair('water pump')
expect(bmw.defects).not_to include('Oil leak')
end
end
| true
|
35a3c0c470eda46d8fc0307eef719aff1755dff1
|
Ruby
|
pemacy/Launch_School
|
/Coursework/100/120/TwentyOne/twenty_one_game.rb
|
UTF-8
| 3,632
| 3.8125
| 4
|
[] |
no_license
|
module Hand
def display_cards(game_over = false)
if type == :player
puts cards
else
hidden = [cards.first]
(cards.size - 1).times { hidden << "Hidden Card" }
puts hidden unless game_over
puts cards if game_over
end
end
def hand_amount
num_aces = 0
sum = 0
cards.each { |c, _| num_aces += 1 if c.split.first == 'Ace' }
cards.each { |card| sum += Deck::TOTAL_VALUES[card] }
num_aces.times { |_| hand -= 10 if hand > 21 }
sum
end
def bust?
hand_amount > 21
end
end
class Player
include Hand
attr_accessor :cards, :score, :type, :name
def initialize(type = :player)
self.type = type
self.name = ''
reset
end
def player_hit?
puts ""
puts "Hit or Stand? (h/s)"
answer = gets.chomp.downcase
answer.start_with?('h')
end
def reset
self.cards = []
self.score = 0
end
end
class Deck
SUITES = %w(Hearts Spades Diamonds Clubs)
CARDS = %w(2 3 4 5 6 7 8 9 10 Jack Queen King Ace)
VALUES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
TOTAL_VALUES = SUITES.each_with_object(hsh = Hash.new) do |s, hsh|
CARDS.each_with_index do |c, i|
hsh["#{c} of #{s}"] = VALUES[i]
end
end
attr_accessor :deck
def initialize
reset
end
def reset
@deck = new_deck.shuffle
end
def new_deck
deck = []
SUITES.map { |s| CARDS.each { |c| deck << "#{c} of #{s}" } }
deck
end
def card_value(card)
TOTAL_VALUES[card]
end
end
class Game
attr_reader :human, :computer, :deck
def initialize
@human = Player.new
@computer = Player.new(:dealer)
@deck = Deck.new
reset
end
def play
welcome
loop do
deal_cards
display_all_hands
player_hit
human.bust? ? display_winner : computer_hit
puts display_winner
puts ""
display_all_hands
break unless play_again?
reset
end
goodbye
end
def reset
clear
deck.reset
human.reset
computer.reset
@game_over = false
end
def play_again?
puts ""
puts "Would you like to play again?"
gets.chomp.downcase.start_with?('y')
end
def deal_cards
2.times do
human.cards << deck.deck.pop
computer.cards << deck.deck.pop
end
end
def player_hit
loop do
break unless human.player_hit?
human.cards << deck.deck.pop
system "clear"
display_all_hands
return if human.bust?
end
end
def computer_hit
loop do
break if computer.hand_amount > 17
computer.cards << deck.deck.pop
clear
display_all_hands
sleep 1
end
end
def hit
if type == :player
player_hit
else
computer_hit
end
end
def display_winner
@game_over = true
clear
return "Player Bust! You Lost." if human.bust?
return "Dealer Bust! You Won!" if computer.bust?
if human.hand_amount > computer.hand_amount
"You Won!"
else
"Dealer Won!"
end
end
def display_all_hands
puts "===== #{human.name}'s' Hand: #{human.hand_amount} ====="
human.display_cards
puts ""
puts "===== Dealer Hand#{": #{computer.hand_amount}" if @game_over} ====="
computer.display_cards(@game_over)
end
def clear
system "clear"
end
def welcome
clear
puts "Welcome to 21 Blackjack."
loop do
puts "What's your name?"
human.name = gets.chomp.capitalize
break unless human.name.empty?
puts "Sorry, must enter a value"
end
clear
end
def goodbye
clear
puts "Thank you for playing, good bye."
end
end
Game.new.play
| true
|
982494442b365955d7a705780fb0f77912e505ef
|
Ruby
|
DinoSaulo/Learning-Ruby
|
/Estrutura de controle/if.rb
|
UTF-8
| 133
| 3.203125
| 3
|
[] |
no_license
|
dia = "Domingo"
#dia = "Segunda"
almoco = 'Frango'
if dia == 'Domingo'
almoco = 'Bife'
end
puts "O almoço hoje é #{almoco}"
| true
|
08200e5b80431f419d4160eac3348860f6c7508c
|
Ruby
|
rschultheis/rosalind
|
/ruby/grph/grph.rb
|
UTF-8
| 355
| 2.546875
| 3
|
[] |
no_license
|
require_relative '../lib/rosalind.rb'
include Rosalind
dnas = parse_fasta_file ARGV[0]
ids = dnas.keys
adjacents = []
ids.each_index do |i|
ids.each_index do |j|
next if i==j
if is_adjacent?(dnas[ids[i]], dnas[ids[j]], 3)
adjacents << ids[i] + ' ' + ids[j]
end
end
end
output = adjacents.join("\n")
puts output
write_file output
| true
|
b8d8cf8d4c87bfa405cc1fdfcae01bf462bc9082
|
Ruby
|
mizukmb/animeStaffCompare
|
/test/controllers/anime_controller_test.rb
|
UTF-8
| 411
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require 'rails_helper'
describe AnimeController do
it "should get scrape" do
hash = AnimeController.new
data= hash.scrape(5292) # SHIROBAKO
expect(data['タイトル']).to eq 'SHIROBAKO'
end
it "404ページは abort する" do
hash = AnimeController.new
begin
data = hash.scrape(9999) # 404 Not Found
rescue SystemExit=>e
expect(e.status).to eq(1)
end
end
end
| true
|
bf99f93c1b1dd8d7fa790b3d8e7406e980adb2c6
|
Ruby
|
jonkchan/Product-Type-CLI
|
/spec/product_spec.rb
|
UTF-8
| 1,300
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require_relative './spec_helper.rb'
require_relative '../lib/product.rb'
require_relative '../lib/json_parser.rb'
describe Product do
describe 'class properties' do
before(:example) do
json = JSONParser.parse_json('./spec/json/test_data.json')
@test_product = Product.new(json[0])
end
it 'expect id property to be available' do
expect(@test_product).to respond_to(:id)
end
it 'expect type property to be available' do
expect(@test_product).to respond_to(:type)
end
it 'expect options property to be available' do
expect(@test_product).to respond_to(:options)
end
end
describe '.create_products_from_json' do
before(:example) do
json = JSONParser.parse_json('./spec/json/test_data.json')
@product_array = Product.create_products_from_json(json)
end
it 'expects to return an array of Products objects from valid JSON file' do
expect(@product_array.length.positive?).to eq(true)
end
it 'expects to return valid Product objects within array' do
expect(@product_array[0].id).to eq(1)
expect(@product_array[0].type).to eq('poster')
expect(@product_array[0].options.key?('genre')).to eq(true)
expect(@product_array[0].options.key?('size')).to eq(true)
end
end
end
| true
|
5a039a0285df9c4458bba8970d9613f20d069557
|
Ruby
|
dmbf29/word-frequencies
|
/interface.rb
|
UTF-8
| 166
| 2.640625
| 3
|
[] |
no_license
|
require_relative 'frequencies'
text = File.open('speech.txt').read
histogram = word_counter(text)
histogram.each do |word, count|
puts "#{word}: #{count}"
end
| true
|
b5a59b2a23660121d8b7ae9030d61411674346f1
|
Ruby
|
dhanyanarendra/rubyexercise
|
/2.rb
|
UTF-8
| 74
| 3.46875
| 3
|
[] |
no_license
|
puts "what is your name"
name=gets.chomp
puts name
puts "hello #{name}!"
| true
|
512a19ef11b6cc1a2e95efa778155d0dfe75f17f
|
Ruby
|
AlexNisnevich/splooshed
|
/lib/splooshed/water_data.rb
|
UTF-8
| 1,010
| 3.03125
| 3
|
[] |
no_license
|
class WaterData
include Singleton
def initialize
@data = load_water_data
end
def search(term)
# list all food names that don't have illegal characters ("?") and have gallons_per_kg defined
# and that match search term, if any
@data.select {|k, v| (!term || k.include?(term)) && !k.include?("?") && v && v["gallons_per_kg"] }.keys
end
def gallons_per_kg(food)
begin
@data[food]["gallons_per_kg"]
rescue
throw "No water usage data found for food: #{food}"
end
end
def fuzzy_food_lookup(food)
key = FuzzyMatch.new(@data.keys, :threshold => 0.1).find(food) || FuzzyMatch.new(@data.keys, :threshold => 0.2).find(food.split(" ").last)
unless key
throw "No water usage data found for food: #{food}"
end
key
end
private
def load_water_data
data = YAML.load(open("water_data.yaml"))
data["synonyms"].each do |synonym, definition|
data["data"][synonym] = data["data"][definition]
end
data["data"]
end
end
| true
|
45135c2b6a876514d87238ac0e26ef9d64508ee7
|
Ruby
|
glenn0/in_the_wild
|
/app/services/github/repo_fetcher.rb
|
UTF-8
| 2,004
| 2.546875
| 3
|
[] |
no_license
|
module Github
class RepoFetcher
def initialize(project, submitter)
@project = project
@submitter = submitter
end
def retrieve
if github_up?
fetch_repo_owner_and_name
if valid_repo?
get_additional_repo_attributes
generate_rspec_tags
if @project.save
Submission.create(user_id: @submitter.id, project_id: @project.id)
ServiceResponse.success
else
ServiceResponse.error_with_message("Hmmm... that's not a URL I can understand at the moment.")
end
else
ServiceResponse.error_with_message("Hmmm... that's not a URL I can understand at the moment.")
end
else
ServiceResponse.error_with_message("Bother, looks like <a href='https://status.github.com/' class='alert-link'> GitHub is down</a> at the moment")
end
end
def github_up?
Octokit.github_status.status == "good"
end
def fetch_repo_owner_and_name
repo_from_url = Octokit::Repository.from_url(@project.url)
@project.repo_owner = repo_from_url.owner
@project.repo_name = repo_from_url.name
@project.repo_owner_url = "https://github.com/#{repo_from_url.owner}"
@project.repo_url = "https://github.com/#{repo_from_url.owner}/#{repo_from_url.name}"
end
def valid_repo?
Octokit.repository?("#{@project.repo_owner}/#{@project.repo_name}")
end
def get_additional_repo_attributes
repo = Octokit.repository("#{@project.repo_owner}/#{@project.repo_name}")
@project.repo_owner_avatar = repo.owner.gravatar_id
@project.repo_description = repo.description
end
def generate_rspec_tags
spec_contents = Octokit.contents("#{@project.repo_owner}/#{@project.repo_name}", path: 'spec')
spec_contents.each do |i|
if i.type == "dir"
dir_name = i.name
@project.tags << Tag.where(name: dir_name).first_or_create
end
end
end
end
end
| true
|
21809f437890b4a8eeb967ef66578440714fc626
|
Ruby
|
khrystynaklochko/cli-superheroes
|
/main.rb
|
UTF-8
| 826
| 2.859375
| 3
|
[] |
no_license
|
require_relative "http_connector"
require_relative "json_parser"
@parser = JsonParser.new()
def card_commands(option)
case option
when "-h"
puts "Available commands"
puts " -cards-set List of cards grouped by set."
puts " -cards-set-rarity List of cards grouped by set and within each set grouped by rarity."
puts " -cards-ktk List of cards from the Khans of Tarkir (KTK) set that ONLY have the colours red AND blue."
exit
when "-cards-set"
fetch_cards
@parser.parse_by_set
when "-cards-set-rarity"
fetch_cards
@parser.parse_by_set_rarity
when "-cards-ktk"
fetch_cards
@parser.parse_by_ktk
end
end
@options = {}
ARGV.each do |option|
puts "Enter -h for help" unless ["-cards-set", "-cards-set-rarity", "-cards-ktk"].include?(option)
card_commands(option)
end
| true
|
c6368e70cf4268934e23b32e0be20f41768c210b
|
Ruby
|
louisbooth/introduction-to-programming
|
/flow-control/flow_control_1.rb
|
UTF-8
| 347
| 3.234375
| 3
|
[] |
no_license
|
=begin
1. (32 * 4) >= 129
2. false != !true
3. true == 4
4. false == (847 == '874')
5. (!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false
1. false
2. false
3. ?
4. true
5. true
3 is false
integer 4 is a truthy value which means when used in a conditional value
it will evaluate to true, but it is not equal to the boolean true
=end
| true
|
fececd1ff11201b477a111295ec63a76b9ea853e
|
Ruby
|
buithehoa/rspec-3-book
|
/book-code/15-using-test-doubles-effectively/24/sales_tax/lib/invoice.rb
|
UTF-8
| 388
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
require 'my_app'
require 'sales_tax'
class Invoice
def initialize(address, items, sales_tax: SalesTax.new)
@address = address
@items = items
@sales_tax = sales_tax
end
def calculate_total
subtotal = @items.map(&:cost).inject(0, :+)
taxes = subtotal * tax_rate
subtotal + taxes
end
private
def tax_rate
@sales_tax.rate_for(@address.zip)
end
end
| true
|
3a4761ebd218d1b235d0f42f06a9ad4627bc1063
|
Ruby
|
JoshCheek/binary_example
|
/spec/bin_spec.rb
|
UTF-8
| 1,381
| 2.875
| 3
|
[] |
no_license
|
require 'open3'
describe 'the binary' do
def execute_binary(filename)
binary_path = File.expand_path '../../bin/sort_words', __FILE__
Open3.capture3(binary_path, filename)
end
context 'when given a valid filename' do
let(:filename) { File.expand_path '../input_file', __FILE__ }
before { File.write filename, "c\na\nb" }
after { File.delete filename }
it 'prints the words in the file out in sorted order' do
stdout, stderr, status = execute_binary(filename)
stdout.should == "a\nb\nc\n"
end
it 'prints nothing to stderr' do
stdout, stderr, status = execute_binary(filename)
stderr.should == ""
end
it 'exits with a status of 0' do
stdout, stderr, status = execute_binary(filename)
status.should be_success
end
end
context 'when given an invalid filename' do
let(:nonexistent_filename) { '/i_dont_exist' }
it 'prints nothing to stdout' do
stdout, stderr, status = execute_binary(nonexistent_filename)
stdout.should == ""
end
it 'prints "no such file" to stderr' do
stdout, stderr, status = execute_binary(nonexistent_filename)
stderr.should == "no such file\n"
end
it 'exits with a status of 1' do
stdout, stderr, status = execute_binary(nonexistent_filename)
status.should_not be_success
end
end
end
| true
|
87fadfbacf700f4d7eb4c5e7815f5ca87503eadf
|
Ruby
|
nbhandari/depot
|
/test/unit/cart_item_test.rb
|
UTF-8
| 961
| 2.640625
| 3
|
[] |
no_license
|
require 'test_helper'
class CartItemTest < ActiveSupport::TestCase
test "initialize" do
product = products(:one)
cart_item = CartItem.new product
assert_equal products(:one), cart_item.product
assert_equal 1, cart_item.quantity
end
test "increment_quantity" do
product = products(:one)
cart_item = CartItem.new product
cart_item.increment_quantity
assert_equal 2, cart_item.quantity
end
test "title" do
product = products(:one)
cart_item = CartItem.new product
assert_equal product.title, cart_item.product.title
end
test "price one quantity" do
product = products(:one)
cart_item = CartItem.new product
assert_equal product.price, cart_item.price
end
test "price two quantity" do
product = products(:one)
cart_item = CartItem.new product
cart_item.increment_quantity
assert_equal (2 * product.price), cart_item.price
end
end
| true
|
0d9d55be543f9fbeea6f4efad6c9a48dec2ce489
|
Ruby
|
blax/hackkrk-tanks
|
/client.rb
|
UTF-8
| 3,036
| 3.015625
| 3
|
[] |
no_license
|
# requires rest-client installed: gem install rest-client
require 'rest-client'
require 'yaml'
require 'time'
require 'json'
SERVER = "http://10.12.202.141:9999"
TIMEOUT = 300000
TOURNAMENT_ID = "master"
AUTHORIZATION_TOKEN = "ResponsibleBrownMallardAlligator"
STD_ANGLE = 5.0
STD_MOVE = 30.0
POWER = 80
USERNAME = "choke"
TANK_SIZE = 30
LEFT_BOUND = -500
RIGHT_BOUND = 500
LOWER_BOUND = 0
UPPER_BOUND = 500
RESPONSES_DIR = './responses'
def save_response_to_file(action_name, response)
filename = "#{action_name}_#{Time.now.to_i}"
File.open("#{RESPONSES_DIR}/#{filename}.json", 'w') { |file| file.write(response) }
end
class RestClientWrapper < Struct.new(:tournamentId, :authorization)
def post_move(params)
url = "#{SERVER}/tournaments/#{tournamentId}/moves"
headers = { 'Authorization' => authorization, 'content-type' => 'application/json' }
RestClient::Request.execute(method: :post, payload: params.to_json, url: url, headers: headers, timeout: TIMEOUT)
rescue => e
p ["Move Failed", e]
nil
end
def wait_for_game()
url = "#{SERVER}/tournaments/#{tournamentId}/games/my/setup"
headers = { 'Authorization' => authorization, 'content-type' => 'application/json' }
RestClient::Request.execute(method: :get, url: url, headers: headers, timeout: TIMEOUT)
rescue => e
retry
end
end
class Bot < Struct.new(:rest_client)
def perform_move(angle, power, distance)
payload = {
"shotAngle" => "#{angle}",
"shotPower" => "#{power}",
"moveDistance" => "#{distance}"
}
response = rest_client.post_move(payload)
save_response_to_file("perform_move_#{angle}_#{power}_#{distance}", response)
JSON.parse(response)
end
def wait_for_game()
response = rest_client.wait_for_game()
save_response_to_file('wait_for_game', response)
JSON.parse(response)
rescue => e
retry
end
end
class Tank < Struct.new(:name, :pos_x, :pos_y); end
class Tanks
attr_reader :tanks
def initialize(tanks)
@tanks = []
tanks.each do |tank|
@tanks << Tank.new(tank["name"], tank["position"]["x"].to_f, tank["position"]["y"].to_f)
end
end
def my_tank
@tanks.find { |t| t.name == USERNAME }
end
end
rest_client = RestClientWrapper.new(TOURNAMENT_ID, AUTHORIZATION_TOKEN)
bot = Bot.new(rest_client)
p "Bot initialized"
# move_direction = 1
MOVES = (1..100).to_a.select{|x| x % 5 == 0}.map{|x| [[x, 30], [x, -30], [x, 45], [x, -45], [x, 60], [x, -60]]}.flatten(1)
turn = 0
while true
p "--- waiting for game"
game = bot.wait_for_game()
p "--- Joining game #{game['name']}"
game_in_progress = true
while game_in_progress
power, angle = MOVES[turn % MOVES.size]
p "Shooting with power #{power} [#{angle}]"
response = bot.perform_move(angle, power, 0)
tanks = Tanks.new(response["tanks"])
if tanks.my_tank
p "My position x: #{tanks.my_tank.pos_x}"
turn += 1
game_in_progress = ! response['last']
else
game_in_progress = false
end
end
p " --- game finished"
end
| true
|
15fae454697ef48022ee17ef774613e73d932c53
|
Ruby
|
kipcole9/calendrical-ruby
|
/lib/calendrical/calendars/egyptian.rb
|
UTF-8
| 1,190
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
module Calendar
module Egyptian
def self.Date(*args)
Egyptian::Date[*args]
end
class Date < Calendrical::Calendar
extend Calendrical::Mpf
extend Calendrical::Days
# see lines 520-525 in calendrica-3.0.cl
def self.epoch
fixed_from_jd(1448638)
end
def inspect
"#{year}-#{month}-#{day} Egyptian"
end
def to_s
month_name = I18n.t('egyptian.months')[month - 1]
"#{day} #{month_name}, #{year}"
end
# see lines 527-536 in calendrica-3.0.cl
# Return the fixed date corresponding to Egyptian date 'e_date'.
def to_fixed(e_date = self)
mmonth = e_date.month
dday = e_date.day
yyear = e_date.year
epoch + (365*(yyear - 1)) + (30*(mmonth - 1)) + (dday - 1)
end
# see lines 538-553 in calendrica-3.0.cl
def to_calendar(f_date = self.fixed)
days = f_date - epoch
yyear = 1 + quotient(days, 365)
mmonth = 1 + quotient((days % 365), 30)
dday = days - (365*(yyear - 1)) - (30*(mmonth - 1)) + 1
Calendrical::Calendar::Date.new(yyear, mmonth, dday)
end
end
end
end
| true
|
92c8e2e13afc2d33ad0c3bdb5c38e1b02a5418ad
|
Ruby
|
esoto/blog_without_gems
|
/lib/csv_manager.rb
|
UTF-8
| 839
| 3.25
| 3
|
[] |
no_license
|
require 'csv'
class CSVManager
attr_accessor :id
def self.all
posts = read_post_file
posts.map{|post_attr| set_up_posts(post_attr) }
end
def self.create post
post.assign_id
CSV.open("lib/posts.csv", "ab") do |csv|
csv << [post.id, post.title, post.post_body]
end
end
def self.find id
posts = read_post_file
posts.each do |post|
return set_up_posts(post) if post[0]==id
end
return nil
end
def assign_id
self.id = File.exist?("lib/posts.csv") ? (read_post_file.last[0].to_i + 1) : 1
end
private
def self.read_post_file
CSV.read("lib/posts.csv")
end
def read_post_file
CSV.read("lib/posts.csv")
end
def self.set_up_posts post_attr
post = Post.new(title: post_attr[1], post_body: post_attr[2])
post.id = post_attr[0]
post
end
end
| true
|
2a44d47948db6eb37f3cffe3cd196c74d5ed6e79
|
Ruby
|
samara-islam/intro-ruby
|
/flow_control/all_caps.rb
|
UTF-8
| 711
| 4.59375
| 5
|
[] |
no_license
|
# flow control
# exercise question 2
#
# write method that takes a string as argument.
# Method should return a new, all-caps version of the string,
# but only if the string is longer than 10 characters
# cute try but not quite:
#
#print "Enter a string: "
#user_input = gets.chomp
# test 1: is string longer than 10 characters?"
#if user_input.length < 10
# puts "need a longer string, chief."
#else
# puts user_input.upcase!
#end
#attempt #2, paying closer attention to the directions this time
def allcaps(user_string)
if user_string.length > 10
puts user_string.upcase!
else puts "less than 10 characters."
end
end
allcaps("hello world")
allcaps("momomomomomo")
allcaps("lesthan10")
| true
|
53161729c66501809fa40d2daca206e21d471eb8
|
Ruby
|
kakuda/myfiles
|
/tdiary/misc/plugin/a.rb
|
UTF-8
| 3,112
| 2.703125
| 3
|
[] |
no_license
|
# a.rb $Revision: 1.7 $
#
# Create anchor easily.
#
# 1. Usage
# a(url, name)
#
# a "http://www.hoge.com/diary/", "Hoge Diary"
#
# a(key, option_or_name = "", name = nil)
# Use dictionary file. You need to create the dictionary
# file with a CGI.
# a "home"
# a "home", "20020329.html", "Here"
#
# a("name|key:option")
# Use dictionary file. You need to create the dictionary
# file with a CGI.
#
# a "key"
# a "key:20020329.html"
# a "key:20020329.html|Here"
# a "Hoge Diary|http://www.hoge.com/diary/"
# a "Hoge Diary|20020201.html#p01" #=> Same as "my" plugin
#
# 4. Documents
# See URLs below for more details.
# http://ponx.s5.xrea.com/hiki/a.rb.html (English)
# http://ponx.s5.xrea.com/hiki/ja/a.rb.html (Japanese)
#
# Copyright (c) 2002,2003 MUTOH Masao <[email protected]>
# You can redistribute it and/or modify it under GPL2.
#
require 'nkf'
A_REG_PIPE = /\|/
A_REG_COLON = /\:/
A_REG_URL = /:\/\//
A_REG_CHARSET = /euc|sjis|jis/
A_REG_CHARSET2 = /sjis|jis/
A_REG_CHARSET3 = /euc/
A_REG_MY = /^\d{8}/
if @options and @options["a.path"]
a_path = @options["a.path"]
else
a_path = @cache_path + "/a.dat"
end
@a_anchors = Hash.new
if FileTest::exist?(a_path)
open(a_path) do |file|
file.each_line do |line|
key, baseurl, *data = line.split(/\s+/)
if data.last =~ A_REG_CHARSET
charset = data.pop
else
charset = ""
end
@a_anchors[key] = [baseurl, data.join(" "), charset]
end
end
end
def a_separate(word)
if A_REG_PIPE =~ word
name, data = $`, $'
else
name, data = nil, word
end
option = nil
if data =~ A_REG_URL
key = data
elsif data =~ A_REG_COLON
key, option = $`, $'
else
key = data #Error pattern
end
[key, option, name]
end
def a_convert_charset(option, charset)
return "" unless option
return option unless charset
if charset =~ A_REG_CHARSET2
ret = CGI.escape(NKF::nkf("-#{charset[0].chr}", option))
elsif charset =~ A_REG_CHARSET3
ret = CGI.escape(option)
else
ret = option
end
ret
end
def a_anchor(key)
data = @a_anchors[key]
if data
data.collect{|v| v ? v.dup : nil}
else
[nil, nil, nil]
end
end
def a(key, option_or_name = nil, name = nil, charset = nil)
url, value, cset = a_anchor(key)
if url.nil?
key, option, name = a_separate(key)
url, value, cset = a_anchor(key)
option_or_name = option unless option_or_name;
end
charset = cset unless charset
value = key if value == ""
if url.nil?
url = key
if name
value = name
url += a_convert_charset(option_or_name, charset)
elsif option_or_name
value = option_or_name
else
value = key
end
else
url += a_convert_charset(option_or_name, charset)
value = name if name
end
if key =~ A_REG_MY
option_or_name = key unless option_or_name
return my(option_or_name, name)
end
if @options["a.tlink"]
if defined?(tlink)
url.untaint
result = tlink(url, value)
else
result = "tlink is not available."
end
else
result = %Q[<a href="#{CGI.escapeHTML(url)}">#{value}</a>]
end
result
end
def navi_a(name = "a.rb conf")
"<span class=\"adminmenu\"><a href=\"a_conf.rb\">#{name}</a></span>\n"
end
| true
|
5f8ef53ed93c2a7dadfb73708316c290a0558df5
|
Ruby
|
DavidEGrayson/redstone-bot2
|
/spec/item_spec.rb
|
UTF-8
| 2,252
| 2.828125
| 3
|
[] |
no_license
|
# coding: ASCII-8BIT
require 'redstone_bot/models/item'
# TODO: remove this after we figure out the gzip problem
describe "basic problem with Ruby's GZipWriter" do
it "does not let you set mtime to 0" do
sio = StringIO.new
writer = Zlib::GzipWriter.new(sio)
writer.mtime = 0
writer.write "hello world"
writer.close
gzdata = sio.string
reader = Zlib::GzipReader.new(StringIO.new gzdata)
expect(reader.mtime.to_i).to be_within(1).of(Time.now.to_i)
end
it "can be worked around by modifying the gzip header" do
sio = StringIO.new
writer = Zlib::GzipWriter.new(sio)
writer.write "hello world"
writer.close
gzdata = sio.string
gzdata[4..7] = "\x00\x00\x00\x00"
reader = Zlib::GzipReader.new(StringIO.new gzdata)
expect(reader.mtime.to_i).to eq(0)
end
end
describe RedstoneBot::Item do
it "matches spots that hold the same item" do
item = RedstoneBot::ItemType::Wood * 1
spot = RedstoneBot::Spot.new(RedstoneBot::ItemType::Wood * 1)
expect(item).to be === spot
end
it "encodes and reads some dummy data correctly" do
item0 = described_class.new(RedstoneBot::ItemType::Bow, 1, 9, { :infinity => 15000, :fire_aspect => -4 })
item = test_stream($e.encode_item(item0)).read_item
expect(item).to eq(item0)
end
context "given an enchanted axe" do
let (:binary_data) do
"\x01\x02" + # item type = IronAxe
"\x01\x00" + # count = 1
"\x0C" + # damage = 12
"\x00\x37" + # nbt length
"\x1F\x8B\x08\x00\x00\x00\x00\x00\x00\x00\xE3\x62\x60\x2E\x49\x4C\xE7\x64\x60" +
"\x49\xCD\x4B\xCE\xE0\x62\x60\x60\x60\x64\x62\x60\xCA\x4C\x61\x50\x62\x62\x60" +
"\xCE\x29\xCB\x61\x60\x64\x60\x00\x00\x69\xB7\x3B\x24\x23\x00\x00\x00"
end
before do
@item = test_stream(binary_data).read_item
end
specify { expect(@item.item_type).to eq(RedstoneBot::ItemType::IronAxe) }
specify { expect(@item.damage).to eq(12) }
specify { expect(@item.enchantments).to eq({ unbreaking: 1 }) }
specify { expect(@item.to_s).to eq("IronAxe(damage=12 unbreaking=1)") }
it "re-encodes the same way" do
expect($e.encode_item(@item)).to eq(binary_data)
end
end
end
| true
|
2d19eab98dc1ab3985861e8cf96f1d0664f5f69b
|
Ruby
|
bger/csv_cat
|
/lib/csv_cat/printer.rb
|
UTF-8
| 909
| 3.046875
| 3
|
[] |
no_license
|
module CsvCat
# Responsible for rendering data into given stream
#
class Printer
attr_reader :stdout, :data_stream, :stdin, :widths, :show_by
def initialize(parser:, stdout: $stdout, stdin: $stdin, show_by: 3)
@data_stream = parser.content
@widths = parser.widths
@stdout = stdout
@stdin = stdin
@show_by = show_by
end
def print
stdout.puts(cover)
data_stream.each_slice(show_by) do |sections|
render = sections.map {|section| section.render.append(horizontal_line) }
stdout.puts(render)
stdin.getch
end
end
private
def horizontal_line
@horizontal_line ||= "+#{line_bulkheads.join('+')}+"
end
def cover
@cover ||= "+#{line_bulkheads.join('-')}+"
end
def line_bulkheads
@line_bulkheads ||= widths.map {|width| '-' * width}
end
end
end
| true
|
1609c7d9f915ce246d287dc40558194d4349bdeb
|
Ruby
|
renanorodrigues/lessons-ruby
|
/algorithms/dijkstra_1_exec.rb
|
UTF-8
| 1,003
| 2.5625
| 3
|
[] |
no_license
|
grafo = {}
grafo = {
inicio: {a: 5, b: 2},
a: {d: 4, c: 2},
b: {a: 8, c: 7},
c: {fim: 1},
d: {c: 6, fim: 3},
fim: {}}
custs = {}
custs = {a: 6, b: 2, c: Float::INFINITY, d: Float::INFINITY, fim: Float::INFINITY}
fathers = {}
fathers = {a: :inicio, b: :inicio, c: nil, d: nil, fim: nil}
processeds_nodes = []
def select_low_cust(custs, processeds)
low_cust = Float::INFINITY
nodo_low_cust = nil
custs.each do |key, value|
cust = custs[key]
if cust < low_cust && !processeds.include?(key)
low_cust = cust
nodo_low_cust = key
end
end
nodo_low_cust
end
nodo = select_low_cust(custs, processeds_nodes)
while nodo != nil do
cust = custs[nodo]
neighbors = grafo[nodo]
neighbors.each do |key, value|
new_cust = cust + neighbors[key]
if custs[key] > new_cust
custs[key] = new_cust
fathers[key] = nodo
end
end
processeds_nodes.append(nodo)
nodo = select_low_cust(custs, processeds_nodes)
end
print fathers
| true
|
5c94d72f9d87a5e8af18024dd2832a7760a87ab7
|
Ruby
|
Tuland/Rescribo
|
/.metadata/.plugins/org.rubypeople.rdt.launching/1290503595867/lib/namedescriptor.rb
|
UTF-8
| 872
| 3.296875
| 3
|
[] |
no_license
|
=begin
-------------------------------------------------- Class: NameDescriptor
Break argument into its constituent class or module names, an
optional method type, and a method name
------------------------------------------------------------------------
Class methods:
--------------
new
Instance methods:
-----------------
full_class_name
Attributes:
class_names, is_class_method, method_name
=end
class NameDescriptor < Object
def method_name
end
def is_class_method
end
def class_names
end
# ----------------------------------------- NameDescriptor#full_class_name
# full_class_name()
# ------------------------------------------------------------------------
# Return the full class name (with '::' between the components) or ""
# if there's no class name
#
def full_class_name
end
end
| true
|
690187505e34bb528b8f2915a3b5c8209ffa1349
|
Ruby
|
castor4bit/leetcode
|
/0000/001.Two_Sum/001.rb
|
UTF-8
| 282
| 3.25
| 3
|
[] |
no_license
|
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
i = 0
nums.each do |n|
j = i + 1
nums2 = nums.slice(j..-1)
nums2.each do |m|
return [i, j] if n + m == target
j = j.succ
end
i = i.succ
end
end
| true
|
1c01f39e94a6188f679860d3dae317e8b9284970
|
Ruby
|
Sahhm/07-09-API
|
/models/groupmember.rb
|
UTF-8
| 580
| 3.03125
| 3
|
[] |
no_license
|
require_relative "ClassMethods.rb"
class Groupmember
extend DatabaseClassMethods
attr_reader :id
attr_accessor :name
#initializes a new course object
#sets object attributes to whatever was entered
def initialize(work_options={})
@id = work_options["id"]
@name = work_options["name"]
end
#method turns new inputs into arguments to update a single line of a database
def self.save(new_name, member_id)
CONNECTION.execute("UPDATE courses SET name = '#{new_name}' WHERE id = #{member_id};")
return self
end
end
| true
|
66e932b715f6f716dc2fc78caaec3fa7d61eb0eb
|
Ruby
|
foreverLoveWisdom/computer_science_knowledge_practice_in_ruby
|
/hash_table.rb
|
UTF-8
| 1,316
| 3.890625
| 4
|
[] |
no_license
|
class HashTable
attr_accessor :data
def initialize(size)
@data = Array.new(size)
end
def set(key, value)
address = get_hash(key)
unless data[address]
data[address] = []
end
data[address].push([key, value])
end
def get(key)
address = get_hash(key)
data[address]&.each do |pairs|
return pairs.last if pairs.first == key
end
end
def keys
# Time complexity could be O(n^2) theoretically. However, it is unlikely to happen
# Because in order for that to happen, they hash collision happens for all of the keys.
# Something must be wrong with the hash function then.
hash_keys = []
data.each do |dt|
next unless dt
dt.each do |pair|
hash_keys << pair[0]
end
end
hash_keys
end
private
def get_hash(key)
hash = 0
key = key.is_a?(String) ? key : key.to_s
key.chars.each_with_index do |char, index|
hash = (hash + char.ord * index) % key.size
end
hash
end
end
key = 'grapes'
hash_table = HashTable.new(2)
puts "The computed key is: #{hash_table.instance_eval { get_hash(key) }}"
hash_table.set(key, 5)
hash_table.set('grape', 15)
hash_table.set('grapes', 888)
hash_table.set('google', 99)
print hash_table.data
print "\n"
print hash_table.keys
| true
|
ccf8b1cf58fb6076676051d968a2eb4f4e910e53
|
Ruby
|
jasonayre/saruman
|
/lib/saruman/cli.rb
|
UTF-8
| 5,900
| 2.546875
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
require 'thor'
require 'saruman'
require "highline/import"
require 'saruman/generators/saruman'
module Saruman
class CLI < Thor
desc "extension", "Creates a new magento extension"
def extension
options = Hash.new
options[:command] = __method__
options[:namespace] = ask("Enter extension namespace:") { |q| q.default = "Saruman" }
options[:name] = ask("Enter extension name:") { |q| q.default = "Wizard" }
options[:author] = ask("Author of extension:") { |q| q.default = "Jason Ayre www.bravenewwebdesign.com" }
options[:version] = ask("Version number (Format - 0.0.1):") { |q| q.default = "0.0.1" }
options[:combined_namespace] = "#{options[:namespace]}_#{options[:name]}"
say("Would you like to create a controller?")
choose do |menu|
menu.choice(:yes) { options[:controller] = true }
menu.choice(:no) { options[:controller] = false }
end
if(options[:controller])
options[:controller_front_name] = ask("Enter Front Name of controller (will match www.yourmagentoinstall.com/frontname)") { |q| q.default = "extension_name" }
if(options[:controllers]).nil?
options[:controllers] = Array.new
end
begin
question = Saruman::ControllerBuilder.new(options)
options[:controllers] << question.output
end while agree("Create another controller?")
end
say("Would you like to create an observer?")
choose do |menu|
menu.choice(:yes) { options[:observer] = true }
menu.choice(:no) { options[:observer] = false }
end
if(options[:observer])
say("Choose the events you would like to observe")
begin
choose do |menu|
if(options[:observer_events]).nil?
options[:observer_events] = Array.new
end
if @observer_menu_builder.nil?
@observer_menu_builder = Saruman::ObserverMenuBuilder.new(menu)
else
@observer_menu_builder.display_choices(menu)
end
end
end while agree("Observe another event?")
options[:observer_events] = @observer_menu_builder.decisions
end
say("Would you like to create a model?")
choose do |menu|
menu.choice(:yes) { options[:model] = true }
menu.choice(:no) { options[:model] = false }
end
if(options[:model])
if(options[:models]).nil?
options[:models] = Array.new
end
begin
question = Saruman::ModelBuilder.new(options)
options[:models] << question.output
end while agree("Create another model?")
end
say("Would you like to create a helper?")
choose do |menu|
menu.choice(:yes) { options[:helper] = true }
menu.choice(:no) { options[:helper] = false }
end
Saruman::Generators::Extension.start([options])
if options[:model]
Saruman::Generators::Model.start([options])
end
if options[:controller]
Saruman::Generators::Controller.start([options])
end
end
desc "model", "Creates a new magento model"
def model
options = Hash.new
options[:command] = __method__
options[:namespace] = ask("Enter extension namespace:") { |q| q.default = "Saruman" }
options[:name] = ask("Enter extension name:") { |q| q.default = "Wizard" }
options[:combined_namespace] = "#{options[:namespace]}_#{options[:name]}"
if(options[:models]).nil?
options[:models] = Array.new
end
begin
question = Saruman::ModelBuilder.new(options)
options[:models] << question.output
end while agree("Create another model?")
Saruman::Generators::Model.start([options])
end
desc "observer", "Creates a new observer for an extension"
def observer
options = Hash.new
options[:command] = __method__
options[:namespace] = ask("Enter extension namespace:") { |q| q.default = "Saruman" }
options[:name] = ask("Enter extension name:") { |q| q.default = "Wizard" }
say("Choose the events you would like to observe")
begin
choose do |menu|
if(options[:observer_events]).nil?
options[:observer_events] = Array.new
end
if @observer_menu_builder.nil?
@observer_menu_builder = Saruman::ObserverMenuBuilder.new(menu)
else
@observer_menu_builder.display_choices(menu)
end
end
end while agree("Observe another event?")
options[:observer_events] = @observer_menu_builder.decisions
Saruman::Generators::Observer.start([options])
end
desc "controller", "Creates a new magento controller"
def controller
options = Hash.new
options[:command] = __method__
options[:namespace] = ask("Enter extension namespace:") { |q| q.default = "Saruman" }
options[:name] = ask("Enter extension name:") { |q| q.default = "Wizard" }
options[:controller_front_name] = ask("Enter Front Name of controller (will match www.yourmagentoinstall.com/frontname)") { |q| q.default = "extension_name" }
options[:combined_namespace] = "#{options[:namespace]}_#{options[:name]}"
if(options[:controllers]).nil?
options[:controllers] = Array.new
end
begin
question = Saruman::ControllerBuilder.new(options)
options[:controllers] << question.output
end while agree("Create another Controller?")
Saruman::Generators::Controller.start([options])
end
end
end
| true
|
4de276d84278e8f6814d58836aac193ad6e4c632
|
Ruby
|
davetron5000/weird-ruby
|
/weird/spec/person_spec.rb
|
UTF-8
| 2,004
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'weird/basic_object'
require 'weird/nil_like_sentinel'
require 'weird/person'
describe Person do
before(:each) do
class << Person
if methods.include?(:greet)
undef_method :greet
end
end
end
describe "naive" do
before do
load "weird/person_greet_naive.rb"
end
describe "#greet" do
it "should greet with a title" do
p = Person.new("Bob",24,"Mr")
p.greet.should == "Hello Mr Bob"
end
it "should greet without a title" do
p = Person.new("Bob",24)
p.greet.should == "Hello Bob"
end
it "should greet incorrectly" do
p = Person.new("Bob",24,NoValue)
p.greet.should == "Hello NoValue Bob"
end
end
end
describe "better" do
before do
load "weird/person_greet_better.rb"
end
describe "#greet" do
it "should greet with a title" do
p = Person.new("Bob",24,"Mr")
p.greet.should == "Hello Mr Bob"
end
it "should greet without a title" do
p = Person.new("Bob",24)
p.greet.should == "Hello Bob"
end
it "should greet correctly" do
p = Person.new("Bob",24,NoValue)
p.greet.should == "Hello Bob"
end
end
end
describe "known_naive" do
before do
load "weird/person_greet_known_naive.rb"
end
describe "#greet" do
[Unassigned,Unassigned].each do |nil_like|
it "should greet when #{nil_like}" do
p = Person.new("Bob",24,nil_like)
p.greet.should == "Not sure how to greet you, Bob"
end
end
end
end
describe "known_better" do
before do
load "weird/person_greet_known_better.rb"
end
describe "#greet" do
[Unassigned,Unassigned].each do |nil_like|
it "should greet when #{nil_like}" do
p = Person.new("Bob",24,nil_like)
p.greet.should == "Not sure how to greet you, Bob"
end
end
end
end
end
| true
|
3b3cfe3a05b058cb91358788d670c1146adb23a2
|
Ruby
|
daveheitzman/raylib-ruby
|
/lib/raylib/custom/vector4.rb
|
UTF-8
| 1,722
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
module Raylib
class Vector4
ray_alias_static :QuaternionIdentity, :identity # Returns identity quaternion
ray_alias_object :QuaternionLength, :length # Computes the length of a quaternion
ray_alias_object :QuaternionNormalize, :normalize # Normalize provided quaternion
ray_alias_object :QuaternionInvert, :invert # Invert provided quaternion
ray_alias_object :QuaternionMultiply, :* # Calculate two quaternion multiplication
ray_alias_object :QuaternionLerp, :lerp # Calculate linear interpolation between two quaternions
ray_alias_object :QuaternionNlerp, :nlerp # Calculate slerp-optimized interpolation between two quaternions
ray_alias_object :QuaternionSlerp, :slerp # Calculates spherical linear interpolation between two quaternions
ray_alias_object :QuaternionToMatrix, :to_matrix # Returns a matrix for a given quaternion
ray_alias_object :QuaternionToAxisAngle, :axis_angle # Returns the rotation angle and axis for a given quaternion
ray_alias_static :QuaternionFromEuler, :from_euler # Returns he quaternion equivalent to Euler angles
# Return the Euler angles equivalent to quaternion (roll, pitch, yaw)
# NOTE: Angles are returned in a Vector3 struct in degrees
ray_alias_object :QuaternionToEuler, :to_euler
ray_alias_object :QuaternionTransform, :transform # Transform a quaternion given a transformation matrix
def to_s
format "#{self.class.name} [%3.3f, %3.3f, %3.3f, %3.3f]", x, y, z, w
end
end
end
| true
|
0271f6058b0f9f124d23d845031364459879cb01
|
Ruby
|
danimetz/Solar-System
|
/main.rb
|
UTF-8
| 3,860
| 3.859375
| 4
|
[] |
no_license
|
require_relative 'planet'
require_relative 'solar_system'
def main
#... Do stuff with planets ..
solar_system = SolarSystem.new("Sol")
earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e8, 'Only planet known to support life')
saturn = Planet.new('Saturn','rust',5.683e26,1.433e9,"Saturn has at least 53 moons, 9 moons awaiting confirmation")
mars = Planet.new('Mars', 'red', 6.39e23, 227.9e6, 'The planet is named after Mars, the Roman god of war. ')
solar_system.add_planet(earth)
solar_system.add_planet(saturn)
solar_system.add_planet(mars)
# puts earth.name
# puts earth.color
# puts saturn.name
# puts saturn.color
# puts earth.summary
# puts saturn.summary
print "What do you want to do next, 'list planets', 'planet details','add planet', 'exit'>> "
option = gets.chomp.downcase
until option == "exit"
if option == "list planets"
list = solar_system.list_planets
puts list
print "What do you want to do next, 'list planets', 'planet details','add planet','distance between' 'exit'>> "
option = gets.chomp.downcase
#PLANET DETAILS ----------------------------
elsif option == "planet details"
print "What planet do you wish to learn more about? >> "
planet = gets.chomp
found_planet = solar_system.find_planet_by_name(planet)
until found_planet != nil
list = solar_system.list_planets
print "That planet is not in our solar system!\n"
puts list
print "\nPlease choose another >>"
planet = gets.chomp
found_planet = solar_system.find_planet_by_name(planet)
end
puts found_planet.summary
print "What do you want to do next, 'list planets', 'planet details','add planet','distance between' 'exit'>> "
option = gets.chomp.downcase
#ADD PLANET ----------------------------
elsif option == "add planet"
print "What's the planet name? >> "
new_name = gets.chomp
print "What color is #{new_name}? >> "
new_color = gets.chomp
print "What is the mass of the #{new_name}? >>"
new_mass_kg = gets.chomp.to_f
until new_mass_kg > 0
print "Please insert a mass greater than 0 >> "
new_mass_kg = gets.chomp.to_f
end
print "How far away is #{new_name} from the sun? >> "
new_distance_from_sun_km = gets.chomp.to_f
until new_distance_from_sun_km > 0
print "Please insert a distance greater than 0 >> "
new_distance_from_sun_km = gets.chomp.to_f
end
print "Do you know a fun fact about #{new_name}? >> "
new_fun_fact = gets.chomp
new_planet = Planet.new(new_name,new_color,new_mass_kg,new_distance_from_sun_km,new_fun_fact)
solar_system.add_planet(new_planet)
print "What do you want to do next, 'list planets', 'planet details','add planet','distance between' 'exit'>> "
option = gets.chomp.downcase
#DISTANCE BETWEEN ----------------------------
elsif option == "distance between"
print "What 2 planets do you want to know the distance between?\n\\Planet 1: >> "
planet1 = gets.chomp!
print "Planet 2: >> "
planet2 = gets.chomp!
distance = solar_system.distance_between(planet1,planet2)
puts "The total distance between #{planet1} and #{planet2} is #{distance} km."
print "What do you want to do next, 'list planets', 'planet details','add planet','distance between' 'exit'>> "
option = gets.chomp.downcase
else
print "I'm sorry, please select a valid option:'list planets','planet details','add planet' 'exit'>> "
option = gets.chomp.downcase
end
end
end
main
#earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e8, 'Only planet known to support life')
#saturn = Planet.new('Saturn','rust',5.683e26,1.433e9,"Saturn has at least 53 moons, 9 moons awaiting confirmation")
| true
|
8355168b1575ccc0b863fe4eea309f5f628eddd3
|
Ruby
|
intokozo/Thinknetica
|
/Lession_9/accessors.rb
|
UTF-8
| 884
| 3.0625
| 3
|
[] |
no_license
|
module Acсessors
def attr_accessor_with_history(*names)
names.each do |name|
accessor(name)
end
end
def accessor(name)
var_name = "@#{name}".to_sym
arr_name = "@#{name}_history".to_sym
define_method(name) { instance_variable_get(var_name) }
define_method("#{name}_history") { instance_variable_get(arr_name) || [] }
define_method("#{name}=") do |value| instance_variable_set(var_name, value)
instance_variable_set(arr_name, instance_eval("#{name}_history") << value)
end
end
def strong_attr_accessor(name, type)
var_name = "@#{name}".to_sym
define_method(name.to_sym) { instance_variable_get(var_name) }
define_method("#{name}=".to_sym) do |value|
raise ArgumentError, "Класс не соответствует #{type}" unless value.is_a? type
instance_variable_set(var_name, value)
end
end
end
| true
|
5c3b07a5f4cb036648292accfe248a1dbfbb9a08
|
Ruby
|
Bratela/snitko_lessons
|
/lesson9.rb
|
UTF-8
| 185
| 3.6875
| 4
|
[] |
no_license
|
#Methods
puts "Yours name is:"
name = gets.chomp
def hello_world(name)
puts "Hello world!"
puts "My name is #{name}"
end
hello_world(name)
hello_world("Denis")
hello_world("Roman")
| true
|
864825310673e34680f13bb251b7ce9a08598546
|
Ruby
|
ching-wang/oo-email-parser-london-web-100719
|
/lib/email_parser.rb
|
UTF-8
| 362
| 3.28125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Build a class EmailParser that accepts a string of unformatted
# emails. The parse method on the class should separate them into
# unique email addresses. The delimiters to support are commas (',')
# or whitespace (' ')
class EmailAddressParser
def initialize(csv)
@csv = csv
end
def parse
split_email = (@csv.split(/[\s,]+/)).uniq
end
end
| true
|
92d0d28dbf7aeafe8a17e1b29363ebbbbb039584
|
Ruby
|
7digital/7Fi
|
/src/seven_digital/artwork/artist_photograph.rb
|
UTF-8
| 236
| 2.5625
| 3
|
[] |
no_license
|
class ArtistPhotograph
attr_reader :url, :size
def initialize(url, size)
@url = url
@size = size
end
end
class Size
attr_reader :width, :height
def initialize(width=0, height=0)
@width = width
@height = height
end
end
| true
|
059b447f18c3df44625630379f33a88d5e760ac7
|
Ruby
|
brett11/music
|
/spec/models/album_spec.rb
|
UTF-8
| 1,127
| 2.6875
| 3
|
[] |
no_license
|
require 'rails_helper'
require 'pry'
RSpec.describe Album, type: :model do
let(:album) { build(:album) }
it "is valid with valid attributes" do
expect(album).to be_valid
end
it "is not valid with no album name" do
album.name = ""
expect(album).to_not be_valid
end
it "is not valid with album name longer than 100 characters" do
album.name = 'a' * 101
expect(album).to_not be_valid
end
it "is not valid with no release date" do
album.release_date = ""
expect(album).to_not be_valid
end
#must use build because create will fail because of validation
#must use empty artist_array as opposed to nil, because source code tries to call each, which causes error when called on nil
it "is not valid with no artist" do
artist_array = []
album = build(:album, artists: artist_array)
expect(album).to_not be_valid
end
it "is valid with a newly created artist" do
artist2 = create(:artist, name_stage: "Kevin Morby")
album.artists.clear
album.artists << artist2
expect(album).to be_valid
expect(album.errors).to be_empty
#binding.pry
end
end
| true
|
42eec194c248ea3c2e9059960c27e9ae30e3bc94
|
Ruby
|
marcbobson2/my_programs
|
/exercises/roman.rb
|
UTF-8
| 718
| 3.859375
| 4
|
[] |
no_license
|
POS_HASH = { 1 => ["I", "V", "X"], 10 => ["X", "L", "C"], 100 => ["C", "D", "M"], 1000 => ["M", "M", "M"] }
class Fixnum
def to_roman
number = self
positions = number.to_s.split("").map(&:to_i).reverse
final_roman = []
positions.each_with_index do |num, index|
final_roman << determine_roman(10 ** index, num)
end
final_roman.reverse.join
end
def determine_roman(place, num)
lower = POS_HASH[place][0]
middle = POS_HASH[place][1]
upper = POS_HASH[place][2]
case num
when 1..3
lower * num
when 4
lower + middle
when 5..8
middle + lower * (num - 5)
when 9
lower + upper
end
end
end
#3000.to_roman
| true
|
a15ab89d13c5fbaadb39bdb3c1bb0a5a1d6ebb8c
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/cs169/1130/source/4533.rb
|
UTF-8
| 335
| 3.375
| 3
|
[] |
no_license
|
def combine_anagrams(words)
groups = Hash.new()
words.each do |w|
key = w.downcase.chars.sort.join
if !groups.has_key?(key)
groups[key] = []
end
groups[key] += [w]
end
return groups.values
end
#puts combine_anagrams(['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']).to_s
| true
|
9835542409bbbbc59cc8626ebf21810c6b09abf5
|
Ruby
|
kykalelker/phase-0-tracks
|
/ruby/santa.rb
|
UTF-8
| 1,960
| 3.828125
| 4
|
[] |
no_license
|
class Santa
attr_reader :reindeer_ranking
attr_accessor :gender, :age, :ethnicity
def initialize (gender, ethnicity)
puts "Initializing Santa instance ..."
@gender = gender
@ethnicity = ethnicity
@reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
@age = 0
end
def about
puts "There is a #{@gender} santa who is of #{@ethnicity} ethnicity and is #{@age} yrs old"
end
def speak
puts "Ho, ho, ho! Haaaappy holidays!"
end
def eat_milk_and_cookies (cookie)
puts "That was a good #{cookie}!"
end
def celebrate_method
@age += 1
puts "This santa just turned #{@age} today! Happy Birthday!"
end
def get_mad_at (reindeer)
puts "This santa is mad at #{reindeer}, so he will move to the bottom of the list as follows"
reindeer_index = @reindeer_ranking.index(reindeer)
final_index = @reindeer_ranking.length-1
@reindeer_ranking[reindeer_index] = @reindeer_ranking[final_index]
@reindeer_ranking[final_index] = reindeer
p @reindeer_ranking
end
end
example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"]
example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"]
100.times do
gender = example_genders.sample
ethnicity = example_ethnicities.sample
manta = Santa.new(gender, ethnicity)
manta.age = rand(0..140)
reindeer = manta.reindeer_ranking.sample
manta.about
manta.speak
manta.eat_milk_and_cookies("cracker")
manta.celebrate_method
manta.get_mad_at(reindeer)
manta.about
end
=begin
santaclaus = Santa.new("female", "asian")
santaclaus.speak
santaclaus.eat_milk_and_cookies("biscuit")
santaclaus.about
santaclaus.celebrate_method
santaclaus.get_mad_at ("Vixen")
santaclaus.gender="male"
santaclaus.about
puts "This santa's age is #{santaclaus.age} and ethnicity is #{santaclaus.ethnicity}"
=end
| true
|
476fa5ae648bbd6b3434deaf09378fbbfc76644a
|
Ruby
|
bridgegade/PigLatinTranslator
|
/pig_latin_translator.rb
|
UTF-8
| 2,755
| 4.0625
| 4
|
[
"MIT"
] |
permissive
|
##
# This class holds methods for translating text to Pig Latin
module PigLatinTranslator
##
# Translates a single line of text with words separated by spaces
def self.translate_line(line)
line = line.strip
words_array = line.split(" ")
translated_words = words_array.map{|word| translate_word(word)}
return translated_words.join(" ")
end
##
# Translates a single word
def self.translate_word(word)
has_capital = false
all_caps = false
has_no_chars = false
end_ay = "ay"
# check if word doesn't contain any alphabetical characters
if word.scan(/[A-Za-z]/).empty?
has_no_chars = true
end
# if word doesn't contain any alphabetical characters
if !has_no_chars
# if word is longer than a letter and is all caps
if word == word.upcase && word.length > 1
all_caps = true
# else if word is capitalized
elsif word == word.capitalize
has_capital = true
end
# find position of last alphabetical character
last_char_index = word.rindex(/[A-Za-z]/)
# if last alphabetical character is at the end of the word, there are no non alphabetical characters to append to end
if last_char_index == word.length - 1
non_characters = ""
else
non_characters = word[(last_char_index+1)..-1]
end
word = word[0..last_char_index]
# find position of first vowel
first_vowel_index = word.index(/[aeiouyAEIOUY]/)
# handles the y case, if y is not followed by a vowel, treat y as a consonant
if word[first_vowel_index].downcase == "y" && first_vowel_index < (word.length-1) && word[first_vowel_index+1].scan(/[aeiouAEIOU]/).empty?
# find position of the next vowel
first_vowel_index = word.index(/[aeiouAEIOU]/)
# handles qu case, if 'u' proceeds a 'q' and the combined 'qu' is followed by a vowel, treat 'u' as a consonant
elsif word[first_vowel_index].downcase == "u" && first_vowel_index > 0 && word[first_vowel_index-1].downcase == "q" && first_vowel_index < (word.length-1) && !word[first_vowel_index+1].scan(/[aeiouyAEIOUY]/).empty?
first_vowel_index+=1
end
# if there are no vowels, assume first it is at first index
if first_vowel_index.nil?
first_vowel_index = 0
# if vowel is at first index, end ay is changed to way.
elsif first_vowel_index == 0
end_ay = "way"
end
word.downcase!
# combine second portion of word up to first found vowel and first portion of word combined with appropriate ay
word = word[first_vowel_index..-1] + (word[0...first_vowel_index]+end_ay)
if all_caps
word.upcase!
elsif has_capital
word.capitalize!
end
return word + non_characters
# return the word itself if no alphabetical characters are found
else
return word
end
end
end
| true
|
5c0fc422bd65c2f6f2acbeb81ef39bb2b22aa3df
|
Ruby
|
mbwcogic/programming-univbasics-4-array-simple-array-manipulations-online-web-prework
|
/lib/intro_to_simple_array_manipulations.rb
|
UTF-8
| 929
| 3.546875
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require "pry"
def using_push(rainbow_array, next_color)
#binding.pry
rainbow_array.push(next_color)
end
def using_unshift(boros, new_boro)
boros.unshift(new_boro)
end
def using_pop(rainbow_array)
rainbow_array.pop
end
def using_shift(favorite_ice_creams)
favorite_ice_creams.shift
end
def pop_with_args(snoop)
snoop.pop(2)
end
def shift_with_args(favorite_ice_creams)
favorite_ice_creams.shift(2)
end
def using_concat(things_i_like, things_i_love)
things_i_like.concat(things_i_love)
end
def using_insert(time_now_array, time_later)
time_now_array.insert(4, time_later)
end
def using_uniq(double)
(double).uniq
end
def using_delete(lax_array, string)
lax_array.delete(string)
end
def using_delete_at(famous_centers, shaq)
famous_centers.delete_at(2)
end
def using_flatten(lakers_array)
lakers_array.flatten
end
| true
|
47db6c2f94dd76b5da54f009722f033ff850d5af
|
Ruby
|
reneecruz/learn-co-sandbox
|
/case.rb
|
UTF-8
| 573
| 3.953125
| 4
|
[] |
no_license
|
# Conclusion: Now you have one more way of communicating selection to Ruby, the case statement. For simple values, use ternary. For an if with an else and maybe an elsif use an if. For multiple cases, use a case statement.
greeting = "friendly_greeting"
case greeting
when "unfriendly greeting"
puts "What do you want?"
when "friendly_greeting"
puts "Hi! How are you?"
end
current_weather = "raining"
case current_weather
when "sunny"
puts "grab some sunscreen!"
when "raining"
puts "grab an umbrella!"
when "snowing"
puts "bundle up"
end
| true
|
a10af15b9e994b8cb6acbb47d541bcfa50979f1a
|
Ruby
|
Grekz/coding-problems-ruby
|
/lib/mx/grekz/leetcode/easy/E111_MinimumDepthofBinaryTree.rb
|
UTF-8
| 647
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
class E111_MinimumDepthofBinaryTree
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer}
def min_depth(root)
return 0 if(root == nil)
def drill( walk, lvl )
return 2147483647 if(walk == nil)
return lvl if(walk.left == nil and walk.right == nil)
return [drill(walk.left, lvl+1), drill(walk.right, lvl+1)].min
end
return drill(root, 1)
end
end
| true
|
e6c0e03b376f2763537ab7b6f0f40ecb3a6c3806
|
Ruby
|
Yeison2020/Backend-sinatra-spendy-app
|
/app/controllers/application_controller.rb
|
UTF-8
| 3,562
| 2.53125
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class ApplicationController < Sinatra::Base
set :default_content_type, 'application/json'
# Bill Routers---------------------------------------------
get "/" do
{ message: "Howdy I'm working! 🚀🚀🚀 Please don't break me " }.to_json
end
#gets all bills
get "/bill" do
bills = Bill.all
bills.to_json
end
#gets a specific bill
get "/bill/:id" do
a_bill = Bill.find(params[:id])
a_bill.to_json
end
#deletes a specific bill
delete "/bill/:id" do
a_bill = Bill.find(params[:id])
a_bill.destroy
a_bill.to_json
end
#creates a new bill
post "/bill" do
make_bill = Bill.create(
bill_name: params[:bill_name],
bill_amount: params[:bill_amount],
category_name: params[:category_name],
wallet_id: params[:wallet_id]
)
make_bill.to_json
end
# edits a specific bill
patch "/bill/:id" do
a_bill = Bill.find(params[:id])
a_bill.update(
bill_name: params[:bill_name],
bill_amount: params[:bill_amount],
category_name: params[:category_name]
)
a_bill.to_json
end
#Wallet Routers------------------------------------------------------
#gets all wallets
get "/wallet" do
all_wallets = Wallet.all
all_wallets.to_json
end
#gets a specific wallet
get "/wallet/:id" do
a_wallet = Wallet.find(params[:id])
a_wallet.to_json
end
get "/wallet/total/:id" do
a_wallet = Wallet.find(params[:id])
a_wallet.total_amount.to_json
end
#gets all bills from a specific wallet
get "/wallet/bills/:id" do
wallet_bills = Wallet.find(params[:id]).bills
wallet_bills.to_json
end
#deletes a specific wallet
delete "/wallet/:id" do
a_wallet = Wallet.find(params[:id])
a_wallet.destroy
a_wallet.to_json
end
#creates a new wallet
post "/wallet" do
make_wallet = Wallet.create(
wallet_name: params[:wallet_name],
amount: params[:amount]
)
make_wallet.to_json
end
# edits a specific wallet
patch "/wallet/:id" do
a_wallet = Wallet.find(params[:id])
a_wallet.update(
wallet_name: params[:wallet_name],
amount: params[:amount]
)
a_wallet.to_json
end
#User Routers---------------------------------------------
get "/user" do
a_user = User.all
a_user.to_json
end
get "/user/:id" do
a_user = User.find(params[:id])
a_user.to_json
end
delete "/user/:id" do
a_user.find(params[:id])
a_user.destroy
a_user.to_json
end
patch "/user/:id" do
a_user = User.find(params[:id])
a_user.update(
name: params[:name],
password: params[:password]
# logged_in: !logged_in
)
a_user.to_json
end
post "/user/login" do
user = User.create(
name: params[:name],
password: params[:password]
)
user.to_json
end
# Grabs a particular users and their wallet
get "/user/wallets/bills/:username" do
user = User.find_by(name: params[:username])
user.to_json(:include => {:wallets => {:include => :bills}})
end
get "/user/wallets/:username" do
userWallet = User.find_by(name: params[:username])
userWallet.to_json(include: :wallets)
end
get "/user/wallets/bills/total/:username" do
user = User.find_by(name: params[:username])
wallet = Wallet.find_by(user_id: user.id)
wallet.total_amount.to_json
end
post "/user/wallets/bills/:username" do
bill = Bill.create(
bill_name: params[:bill_name],
bill_amount: params[:bill_amount],
category_name: params[:category_name],
wallet_id: params[:wallet_id]
)
bill.to_json
end
# user = User.create(
# name: params[:name],
# password: params[:password]
# )
# user.to_json
end
| true
|
7977d31b5838745ab475ccaa7fff819000bff33c
|
Ruby
|
assemblyline/sidekicks
|
/lib/sidekicks/elb.rb
|
UTF-8
| 1,480
| 2.515625
| 3
|
[] |
no_license
|
require 'fog'
require 'open-uri'
require 'sidekicks/logger'
module Sidekicks
class ELB
def initialize
self.name = ENV['AWS_ELB_NAME']
self.tag = ENV['AWS_ELB_TAG']
self.region = ENV.fetch 'AWS_REGION'
self.key = ENV.fetch 'AWS_ACCESS_KEY'
self.secret = ENV.fetch 'AWS_SECRET_KEY'
end
def interval
60
end
def work
register_if_required
end
def shutdown
deregister_if_required
end
protected
attr_accessor :name, :region, :key, :secret, :tag
private
def register_if_required
elbs.each do |elb|
next if elb.instances.include? instance
Logger.log "registering instance #{instance} with elb #{elb.id}"
elb.register_instances [instance]
end
end
def deregister_if_required
elbs.each do |elb|
next unless elb.instances.include? instance
Logger.log "deregistering instance #{instance} with elb #{elb.id}"
elb.deregister_instances [instance]
end
end
def elbs
if tag
all_elbs.select { |elb| elb.tags[tag] }
elsif name
[all_elbs.get(name)]
end
end
def all_elbs
Fog::AWS::ELB.new(
aws_access_key_id: key,
aws_secret_access_key: secret,
region: region,
).load_balancers
end
def instance
@_instance ||= OpenURI.open_uri('http://169.254.169.254/latest/meta-data/instance-id').read
end
end
end
| true
|
fcccfeeff46d6caec9edfe5255d65c9bdfeb7f16
|
Ruby
|
Wayzyk/csv_parser
|
/csv_builder.rb
|
UTF-8
| 1,541
| 3.109375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require './teams'
require 'csv'
TEAMS_FILE = 'data/Teams.csv'.freeze
PLAYERS_FILE = 'data/Batting.csv'.freeze
class CsvBuilder
def initialize
@team = Teams.new(TEAMS_FILE)
end
def call(options = {})
@options = options
results = []
data = []
last_row = {}
CSV.foreach(PLAYERS_FILE, headers: true, col_sep: ',') do |row|
next if filter_year && row['yearID'].to_i != filter_year.to_i
next if filter_team && team.find_by_id(row['teamID']) != filter_team
unless last_row.empty?
if last_row['playerID'] != row['playerID'] || last_row['yearID'] != row['yearID']
results << calculate(data)
data = []
end
end
last_row = row
data << row
end
results << calculate(data)
results.sort_by { |header| header[3] }.reverse!
end
private
attr_reader :options, :team
def filter_year
@filter_year ||= options.fetch(:year, false)
end
def filter_team
@filter_team ||= options.fetch(:team, false)
end
def calculate(data = [])
return unless data.any?
row = data.first
ba = data.collect { |csv_row| csv_row['H'].to_f / (csv_row['AB'].to_f <= 0 ? 1 : csv_row['AB'].to_f) }.reduce(&:+) / data.count
teams = data.collect { |csv_row| find_team(csv_row['teamID']) }.reject(&:nil?).uniq
[
row['playerID'],
row['yearID'].to_i,
teams,
ba.round(3)
]
end
def find_team(id)
team_name = team.find_by_id(id)
team_name
end
end
| true
|
5a25975cd5613c996511689c161daccaecc5f74e
|
Ruby
|
francois/linked_list
|
/lib/linked_list/node.rb
|
UTF-8
| 539
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
class LinkedList
# Implements a single node of the linked list.
class Node
attr_accessor :cdr, :value
def initialize(value, cdr)
@cdr, @value = cdr, value
end
# Two nodes are equal if their values are equal and their cdr's are equal too.
def ==(other)
cdr == other.cdr && value == other.value
end
# Returns a nice-looking string.
# node = LinkedList::Node.new("a", nil)
# node.inspect
# #=> ("a" nil)
def inspect
"(#{value.inspect} #{cdr.inspect})"
end
end
end
| true
|
209b21a5937f3d6be308408aecf126c1606576db
|
Ruby
|
pathsny/algo-class
|
/p4/scc.rb
|
UTF-8
| 2,642
| 3.21875
| 3
|
[] |
no_license
|
class DFS
def initialize(vertices)
@vertices = vertices
end
def search(options)
visited = {}
stack = []
visited_callback =
completed_callback = options[:completed_callback]
order = options[:order]
if (!order)
order = (@vertices.size-1).downto(1)
get_vertex = lambda {|i| @vertices[i]}
else
get_vertex = lambda {|label| vertex(label)}
end
order.each do |i|
cur_node = get_vertex.call(i)
next if visited[cur_node]
visited[cur_node] = true
options[:visited_callback].call(cur_node) if options[:visited_callback]
stack.push(cur_node)
until stack.empty?
node = stack.last
new_nodes_exist = false
node[options[:direction]].each do |e|
head_node = vertex(e)
next if visited[head_node]
visited[head_node] = true
options[:visited_callback].call(head_node) if options[:visited_callback]
stack.push(head_node)
new_nodes_exist = true
end
unless new_nodes_exist
options[:completed_callback].call(stack.pop)
end
end
end
end
def vertex(label)
@vertices[label - 1]
end
def visit(node, direction)
return if @visited[node]
@visited[node] = true
@visited_callback.call(node) if @visited_callback
node[direction].each do |e|
visit(vertex(e), direction)
end
@completed_callback.call(node) if @completed_callback
end
end
def create_vertex(label)
{label: label, out_edges: [], in_edges: []}
end
def build_graph(data)
vertices = []
data.each do |d|
v1, v2 = d.split(' ').map(&:to_i)
vertex_1 = vertices[v1-1] || create_vertex(v1)
vertex_1[:out_edges].push(v2)
vertices[v1-1] = vertex_1
vertex_2 = vertices[v2-1] || create_vertex(v2)
vertex_2[:in_edges].push(v1)
vertices[v2-1] = vertex_2
end
vertices
end
data = File.read('SCC.txt').split("\n")
vertices = build_graph(data)
dfs = DFS.new(vertices)
finish_stack = []
dfs.search :direction => :in_edges, :visited_callback => nil, :completed_callback => lambda { |node| finish_stack.push(node[:label])}
leaders = Hash.new {|hash, key| hash[key] = []}
current_leader = nil
dfs.search :direction => :out_edges, :order => finish_stack.reverse_each, :visited_callback =>
lambda {|node| current_leader = node[:label] unless current_leader}, :completed_callback =>
lambda { |node|
leaders[current_leader].push(node[:label])
current_leader = nil if node[:label] == current_leader
}
puts leaders.values.map(&:size).sort.inspect
| true
|
137302296c718466c1f64b954d2e7d0f3b9efa09
|
Ruby
|
CodeJusto/hacker-news-scraper
|
/lib/comment.rb
|
UTF-8
| 138
| 2.84375
| 3
|
[] |
no_license
|
class Comment
attr_reader :user, :text, :time
def initialize(user, text, time)
@user, @text, @time = user, text, time
end
end
| true
|
2414d2539b3fe85520c9b1a34e7cb7899208c60d
|
Ruby
|
GeorgeYan/op_rb
|
/block1.rb
|
UTF-8
| 155
| 3.5
| 4
|
[] |
no_license
|
def my_block
yield 1,100
end
my_block { |a,b| p "This number is #{1} + #{100}"}
def call_block(&block)
block.call
end
call_block { p "hello world"}
| true
|
5efb2a95d2f5112258505fa304a181aaef477162
|
Ruby
|
zklamm/ruby-small-problems
|
/exercises/second_pass/easy_07/04.rb
|
UTF-8
| 739
| 4.59375
| 5
|
[] |
no_license
|
# Write a method that takes a string as an argument and returns a new string in
# which every uppercase letter is replaced by its lowercase version, and every
# lowercase letter by its uppercase version. All other characters should be unchanged.
# input: str
# output: new str with char case swapped
# You may not use String#swapcase; write your own version of this method.
# logic: iterate thru str, looking at each char. If char.downcase == char return char.upcase
# else return char.downcase
# Example:
def swapcase(str)
new_str = str.chars.map do |char|
char.downcase == char ? char.upcase : char.downcase
end
new_str.join
end
p swapcase('CamelCase') == 'cAMELcASE'
p swapcase('Tonight on XYZ-TV') == 'tONIGHT ON xyz-tv'
| true
|
ffab264891792ae393108a41670f9f6ff797bc63
|
Ruby
|
spenguinlui/react-native-foods
|
/csv_to_json.rb
|
UTF-8
| 6,508
| 2.890625
| 3
|
[] |
no_license
|
require 'csv'
require 'json'
data = File.open('./20_2.csv').read
csv_data = CSV.parse(data, :headers => true)
csv_data = csv_data.map{|row| row.to_a.to_h}
json_data = {}
nutrient_content_list = ['分析項分類', '分析項', '含量單位', '每單位含量', '每100克含量', '每單位重', '每單位重含量', '樣本數', '標準差']
# count = 0
# 不用這種方式會讀不到食品分類
csv_data.each do |data|
# break if count > 3
# count += 1
nutrient_content_object = {}
if json_data[data['整合編號']].nil?
json_data[data['整合編號']] = {}
json_data[data['整合編號']][:nutrient_content] = []
data.each do |key, value|
key.match(/['整合編號]{4,}/) && json_data[data['整合編號']][:id] = value
key.match(/['食品分類]{4,}/) && json_data[data['整合編號']][:food_type] = value
key.match(/['資料類別]{4,}/) && json_data[data['整合編號']][:data_type] = value
key.match(/['樣品名稱]{4,}/) && json_data[data['整合編號']][:name] = value
key.match(/['俗名]{2,}/) && json_data[data['整合編號']][:common_name] = value
key.match(/['樣品英文名稱]{6,}/) && json_data[data['整合編號']][:en_name] = value
key.match(/['內容物描述]{5,}/) && json_data[data['整合編號']][:description] = value
key.match(/['廢棄率]{3,}/) && json_data[data['整合編號']][:abandonment_rate] = value
key.match(/['每單位重]{4,}/) && json_data[data['整合編號']][:unit_weight] = value
if nutrient_content_list.include? key
key.match(/['分析項分類]{5,}/) && nutrient_content_object[:type] = value
key.match(/['分析項]{3,}/) && nutrient_content_object[:name] = value
key.match(/['含量單位]{4,}/) && nutrient_content_object[:unit_content] = value
key.match(/['每單位含量]{5,}/) && nutrient_content_object[:per_content] = value
key.match(/['每100克含量]{7,}/) && nutrient_content_object[:per_100_content] = value
key.match(/['每單位重]{4,}/) && nutrient_content_object[:per_weight] = value
key.match(/['每單位重含量]{6,}/) && nutrient_content_object[:per_weight_content] = value
key.match(/['樣本數]{3,}/) && nutrient_content_object[:sample_count] = value
key.match(/['標準差]{3,}/) && nutrient_content_object[:standard_deviation] = value
end
end
else
data.each do |key, value|
key.match(/['分析項分類]{5,}/) && nutrient_content_object[:type] = value
key.match(/['分析項]{3,}/) && nutrient_content_object[:name] = value
key.match(/['含量單位]{4,}/) && nutrient_content_object[:unit_content] = value
key.match(/['每單位含量]{5,}/) && nutrient_content_object[:per_content] = value
key.match(/['每100克含量]{7,}/) && nutrient_content_object[:per_100_content] = value
key.match(/['每單位重]{4,}/) && nutrient_content_object[:per_weight] = value
key.match(/['每單位重含量]{6,}/) && nutrient_content_object[:per_weight_content] = value
key.match(/['樣本數]{3,}/) && nutrient_content_object[:sample_count] = value
key.match(/['標準差]{3,}/) && nutrient_content_object[:standard_deviation] = value
end
end
json_data[data['整合編號']][:nutrient_content] << nutrient_content_object
# json_data[data['整合編號']][:food_type] === '魚貝類' && json_data_with_type[:seafood] << json_data[data['整合編號']]
end
json_data_with_type = {
'fruit': [], # 水果類
'prepared_and_other': [], # 加工調理食品及其他類
'meat': [], # 肉類
'legume': [], # 豆類
'milk': [], # 乳品類
'fat': [], # 油脂類
'nut': [], # 堅果及種子類
'egg': [], # 蛋類
'seafoods': [], # 魚貝類
'mushroom': [], # 菇類
'drink': [], # 飲料類
'grains': [], # 穀物類
'vegetable': [], # 蔬菜類
'seasoning': [], # 調味料及香辛料類
'starch': [], # 澱粉類
'pastry': [], # 糕餅點心類
'sugar': [], # 糖類
'alga': [], # 藻類
'undefined': [] # 沒歸類到的(可能是新資料)
}
json_data = json_data.values
json_data.each do |data|
case data[:food_type]
when '水果類'
json_data_with_type[:fruit] << data
when '加工調理食品及其他類'
json_data_with_type[:prepared_and_other] << data
when '肉類'
json_data_with_type[:meat] << data
when '豆類'
json_data_with_type[:legume] << data
when '乳品類'
json_data_with_type[:milk] << data
when '油脂類'
json_data_with_type[:fat] << data
when '堅果及種子類'
json_data_with_type[:nut] << data
when '蛋類'
json_data_with_type[:egg] << data
when '魚貝類'
json_data_with_type[:seafoods] << data
when '菇類'
json_data_with_type[:mushroom] << data
when '飲料類'
json_data_with_type[:drink] << data
when '穀物類'
json_data_with_type[:grains] << data
when '蔬菜類'
json_data_with_type[:vegetable] << data
when '調味料及香辛料類'
json_data_with_type[:seasoning] << data
when '澱粉類'
json_data_with_type[:starch] << data
when '糕餅點心類'
json_data_with_type[:pastry] << data
when '糖類'
json_data_with_type[:sugar] << data
when '藻類'
json_data_with_type[:alga] << data
else
json_data_with_type[:undefined] << data
end
end
# csv_data.each do |data|
# new_content = {
# type: data['分析項分類'],
# name: data['分析項'],
# unit_content: data['含量單位'],
# per_content: data['每單位含量'],
# per_100_content: data['每100克含量'],
# per_weight: data['每單位重'],
# per_weight_content: data['每單位重含量'],
# sample_count: data['樣本數'],
# standard_deviation: data['標準差']
# }
# if json_data[data['整合編號']].nil?
# json_data[data['整合編號']] = {
# food_type: data['食品分類'],
# data_type: data['資料類別'],
# id: data['整合編號'],
# name: data['樣品名稱'],
# common_name: data['俗名'],
# en_name: data['樣品英文名稱'],
# description: data['內容物描述'],
# abandonment_rate: data['廢棄率'],
# unit_weight: data['每單位重'],
# nutrient_content: [new_content]
# }
# else
# json_data[data['整合編號']][:nutrient_content] << new_content
# end
# end
json_string = json_data_with_type.to_json
File.open('./food_data.json','w') do |f|
f.puts(json_string)
end
| true
|
9ccefec4fb7a0c3fa65085d4cb262889e9eae250
|
Ruby
|
AndyWendt/exercism
|
/ruby/matrix/matrix.rb
|
UTF-8
| 200
| 3.21875
| 3
|
[] |
no_license
|
class Matrix
def initialize(grid)
@grid = grid
end
def rows
rows = @grid.split("\n")
rows.map { |row| row.split(" ").map(&:to_i) }
end
def columns
rows.transpose
end
end
| true
|
fd6eec89fc3f29a9166f1cd2a3169141abb05156
|
Ruby
|
sgpl/sinatra
|
/ch1/main_v00_from_ch2.rb
|
UTF-8
| 1,269
| 2.796875
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader' if development?
get '/' do
erb :home # this is known as a view.
# just like route handlers, except that instead of finishing with a string that's
# sent back to the browser, we finish with erb :home
# it's a reference to what is known as a view (which is a representation of data, such as markup )
#
end
get '/about' do
erb :about, :layout => :special # can do this for special layout which
# we'll have to create using @@special
end
get '/contact' do
erb :contact
end
__END__
@@layout
<!doctype html>
<% title = "Songs By Sinatra".swapcase.next %>
<html lang="en">
<head>
<title><%= title %></title>
<meta charset="utf-8">
</head>
<body>
<header>
<h1><%= title%></h1>
<nav>
<ul>
<li><a href="/" title="Home">Home</a></li>
<li><a href="/about" title="About">About</a></li>
<li><a href="/contact" title="Contact">Contact</a></li>
</ul>
</nav>
</header>
<section>
<%= yield %>
</section>
</body>
</html>
@@home
<p>Welcome to this website all about the songs of the great Frank Sinatra</p>
@@about
<p>this page is about frank sinatra. helloooOOO!!!</p>
@@contact
<p>Ok this is the contact page.</p>
<p><b>Give Sinatra</b> a call at 000-999-9332</p>
| true
|
761f5459dcc0c538c5cef7ab3d9c73ffa0f97f7d
|
Ruby
|
tlowande/TwO-O-Player-Math-Game-
|
/game.rb
|
UTF-8
| 1,058
| 3.546875
| 4
|
[] |
no_license
|
require './player'
class Game
# FOR REFERENCE
# def initialize player1, player2
# @player1 = player1
# @player2 = player2
# @curr = @player1
# end
@@player = 0;
# def game (player)
def start(players)
puts "----- NEW TURN -----"
question = Question.new
puts "#{players[0].long}: #{question.qs}"
print "> "
answer = $stdin.gets.chomp
if answer.to_i == question.number1 + question.number2
puts "#{players[0].long}: YES! You're correct."
else
players[0].loose_points
puts "#{players[0].long}: Seriously? No!"
end
# if player[@@player].score == 0
# puts "ITS OVER"
# else
# @@player = @@player == 0 ? 1 : 0
# start(players)
# end
if players[0].score == 0
puts "#{players[1].long} wins with a score of #{players[1].final_score} \n----- GAME OVER -----\nGood Bye"
else
players.reverse!
"#{players[1].short}: #{players[1].final_score} vs #{players[0].short}: #{players[0].final_score}"
start(players)
end
end
end
| true
|
e73e50a9a6af8669a132e8120802196be051c5fd
|
Ruby
|
davejpatel/configparser
|
/config_parser_spec.rb
|
UTF-8
| 2,064
| 3
| 3
|
[] |
no_license
|
require_relative 'config_parser'
describe "ConfigParser" do
let(:config_file) { "#{File.expand_path(File.dirname(__FILE__))}/config_file.txt" }
let(:config_parser) { ConfigParser.new }
describe "#boolean_like" do
it "should return true if string contains boolean type" do
value = config_parser.send(:boolean_like, "true")
expect(value).to be(true)
value = config_parser.send(:boolean_like, "false")
expect(value).to be(true)
value = config_parser.send(:boolean_like, "on")
expect(value).to be(true)
value = config_parser.send(:boolean_like, "off")
expect(value).to be(true)
value = config_parser.send(:boolean_like, "yes")
expect(value).to be(true)
value = config_parser.send(:boolean_like, "no")
expect(value).to be(true)
end
end
describe "#make_boolean" do
it "should convert a 'true' string to true" do
value = config_parser.send(:make_boolean, "true")
expect(value).to be(true)
end
it "should convert a 'false' string to false" do
value = config_parser.send(:make_boolean, "false")
expect(value).to be(false)
end
end
describe "#numeric_like" do
it "should return true if string is numeric" do
value = config_parser.send(:numeric_like, "123")
expect(value).to be(true)
end
it "should return false if string is non numeric" do
value = config_parser.send(:numeric_like, "abc")
expect(value).to be(false)
end
end
describe "#make_numeric" do
it "should convert an integer string to an integer" do
value = config_parser.send(:make_numeric, "123")
expect(value).to eq("123".to_i)
end
it "should convert a float string to a float" do
value = config_parser.send(:make_numeric, "123.123")
expect(value).to eq("123.123".to_f)
end
end
describe ".format" do
it "should ignore commented config lines" do
config = config_parser.send(:format, config_file)
expect(config_file).to_not include("#")
end
end
end
| true
|
e789f5094ddfae8367fe36d84d17006f20775e57
|
Ruby
|
tkosuga/tiikitter.jp
|
/app/lib/cache_server.rb
|
UTF-8
| 675
| 2.65625
| 3
|
[] |
no_license
|
require 'memcache'
require 'singleton'
class CacheServer
include Singleton
def initialize
memcache_options = {
:c_threshold => 10_000,
:compression => true,
:debug => false,
:namespace => 'tiikitter',
:readonly => false,
:urlencode => false
}
@cache = MemCache.new memcache_options
@cache.servers = 'localhost:11211'
end
#
# 600秒間キャッシュします
#
def put(key, content, expired = 600)
@cache.set(key.hash.to_s, content, expired)
end
#
# キャッシュを返します
#
def get(key)
@cache[key.hash.to_s]
end
end
| true
|
35e59ca14e96f22bf9c0776927511de60721b0cf
|
Ruby
|
melari/entity
|
/lib/evaluators/variable_assignment_statement.rb
|
UTF-8
| 1,022
| 2.9375
| 3
|
[] |
no_license
|
class VariableAssignmentStatementEval < StatementEval
def initialize(variable_path_eval, expression_eval, type)
@variable_path_eval = variable_path_eval
@expression_eval = case type
when '='
expression_eval
when '+='
DoubleOperandExpressionEval.new('+', @variable_path_eval, expression_eval)
when '-='
DoubleOperandExpressionEval.new('-', @variable_path_eval, expression_eval)
when '*='
DoubleOperandExpressionEval.new('*', @variable_path_eval, expression_eval)
when '/='
DoubleOperandExpressionEval.new('/', @variable_path_eval, expression_eval)
end
end
def required_variables
return [] unless @variable_path_eval.is_local?
[{
:name => @variable_path_eval.name,
:type => @expression_eval.type
}]
end
def eval
variable_path = Entity::Compiler.capture { @variable_path_eval.eval }
expression = Entity::Compiler.capture { @expression_eval.eval }
Entity::Compiler.out("#{variable_path} = #{expression};")
end
end
| true
|
2b9a1084054c54b6fe33a2307dc8c0e1a38bbf89
|
Ruby
|
kwikiel/lsruby
|
/basic/f55289ff.rb
|
UTF-8
| 136
| 3.546875
| 4
|
[] |
no_license
|
say_hello = true
count = 1
while say_hello
count+=1
puts 'Hello!'
say_hello = false
if count<=5
say_hello = true
end
end
| true
|
97a739a00819e2358a443c69b2faee7bac600de0
|
Ruby
|
sean1rose/blackjack
|
/procedural_blackjack.rb
|
UTF-8
| 3,505
| 4.0625
| 4
|
[] |
no_license
|
# test comment
def begin_game
puts "Welcome to the Blackjack Table. What's your name???"
user_name = gets.chomp
suits = ['of Clubs', 'of Diamonds', 'of Hearts', 'of Spades']
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King', 'Ace']
# Implemented concept of using product of 2 separate arrays (1 for suit, 1 for cards) from the 1st solution video.
deck = cards.product(suits)
deck.shuffle!
user_total = 0
dealer_total = 0
def calculate_total(total, card)
card_value = card[0]
if card_value == 'Jack' || card_value == 'Queen' || card_value == 'King' # if a face card
card_value = 10
total += card_value
#total = total + card_value
elsif card_value == 'Ace' # if an Ace
if total >= 11 # if current total is already at 11 or higher, ace must equal 1
card_value = 1
else # if total is less than 11, ace equals 11
card_value = 11
end
total += card_value
#total = total + card_value
else # not an A or face card
total += card_value
#total = total + card_value
end
end
puts ""
user_first_card = deck.pop
user_total = calculate_total(user_total, user_first_card)
dealer_first_card = deck.pop
dealer_total = calculate_total(dealer_total, dealer_first_card)
puts ">>>Dealer shows one card, a #{dealer_first_card}."
user_second_card = deck.pop
user_total = calculate_total(user_total, user_second_card)
puts "#{user_name}, your 1st two cards are a #{user_first_card} and a #{user_second_card} for a TOTAL of #{user_total}."
dealer_second_card = deck.pop
dealer_total = calculate_total(dealer_total, dealer_second_card)
if user_total == 21
puts "BLACKJACK! You WIN #{user_name} :)"
exit
end
if dealer_total == 21
puts "Dealer has BLACKJACK! Sorry #{user_name}, you LOSE :("
exit
end
puts ''
puts "#{user_name}, enter 'h' to Hit or 's' to Stay..."
answer = gets.chomp
while answer == 'h'
new_card = deck.pop
puts "You've been dealt a #{new_card}."
user_total = calculate_total(user_total, new_card)
if user_total <= 21
puts "You now have #{user_total}."
puts "Enter 'h' to Hit or 's' to Stay..."
answer = gets.chomp
elsif user_total > 21
puts "You Bust with #{user_total}! You LOSE #{user_name}!"
break
end
end
if answer == 's'
puts ""
puts "Dealer's other card is a #{dealer_second_card}. So Dealer has a total of #{dealer_total}."
while dealer_total <= 16
new_dealer_card = deck.pop
dealer_total = calculate_total(dealer_total, new_dealer_card)
puts "Dealer hits and is dealt a #{new_dealer_card}. Dealer now has a TOTAL of #{dealer_total}."
puts ""
if dealer_total > 21
puts "Dealer BUST! You WIN #{user_name}!"
elsif dealer_total > 16 && dealer_total <= 21
puts "Dealer has #{dealer_total}."
end
end
end
puts "#{user_name}, you have #{user_total} and Dealer has #{dealer_total}."
if (user_total > dealer_total) && (user_total <= 21)
puts "You WIN!"
elsif (dealer_total > user_total) && (dealer_total <= 21)
puts "You LOSE!"
elsif user_total == dealer_total
puts "PUSH"
end
puts ""
puts "Would you like to play again or nah???"
puts "Enter 'y' if yes or 'n' if no..."
response = gets.chomp
if response == 'y'
begin_game
end
end
begin_game
| true
|
4065eec2bbc4e85c30c40aa1211e56fa51dcb9d0
|
Ruby
|
abillig/rails-activerecord-model-rails-lab-web-0616
|
/app/controllers/movies_list.rb
|
UTF-8
| 849
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'byebug'
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require_relative '../../config/environment.rb'
require_relative 'movie_stats'
require 'openssl'
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
page = Nokogiri::HTML(open("https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture"))
movie_urls=[]
movie_strings=[]
movies=[]
page.css("table.wikitable td i").each do |movie_string|
movie_strings << movie_string.to_s
end
movie_strings.compact.map do |movie_string|
string = movie_string.split("href=")[1]
unless string == nil
movies << string.split("title=").first[2..-3]
end
end
revised = movies.delete_if {|movie| movie.include?("class=")}
academy_awards_hashes = []
revised.each_with_index do |movie, i|
if i < 510 && i > 505
Movie.create(movie_stats(movie))
end
end
| true
|
30586a29f04c4a8b7f231bec1d76e8088c77d022
|
Ruby
|
cdangg/learn_ruby
|
/05_silly_blocks/silly_blocks.rb
|
UTF-8
| 164
| 3.25
| 3
|
[] |
no_license
|
def reverser
yield.split.map { |word| word.reverse}.join(' ')
end
def adder(x=1)
num = yield
num + x
end
def repeater(x=1)
x.times do
yield
end
end
| true
|
0f6961c3f9836078b9f4f8885bba36f32c8ea7ba
|
Ruby
|
danielriley06/badges-and-schedules-v-000
|
/conference_badges.rb
|
UTF-8
| 606
| 3.796875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def badge_maker(name)
return "Hello, my name is #{name}."
end
def batch_badge_creator(attendees)
name_tags = []
attendees.each {|name| name_tags << "Hello, my name is #{name}."}
return name_tags
end
def assign_rooms(attendees)
rooms = 1
assignments = []
while rooms <= 7
attendees.each do |name|
assignments << "Hello, #{name}! You'll be assigned to room #{rooms}!"
rooms += 1
end
end
return assignments
end
def printer(attendees)
batch_badge_creator(attendees).each {|name_tag| puts name_tag}
assign_rooms(attendees).each {|name_tag| puts name_tag}
end
| true
|
fe31393e979d175868404691235d085375e8da1b
|
Ruby
|
rcgutierrez/ruby-exercises
|
/16-ruby-excercise-while-loops.rb
|
UTF-8
| 127
| 3.078125
| 3
|
[] |
no_license
|
# While loops
index = 1
while index <= 5
puts index
index += 1
end
# Make sure you don't make an infinite loop !!!!!
| true
|
710c483a60d9b9dfadceddc16b2839aaffe4a039
|
Ruby
|
esteban-herrera/interview_practice_max_profit
|
/all_test.rb
|
UTF-8
| 405
| 3.125
| 3
|
[] |
no_license
|
require "./MaxProfit.rb"
[1,2,3,4,5,6,7,8].permutation.to_a.each do |p|
answer_brute = MaxProfit.find_max_profit(p)
answer_efficient = MaxProfit.find_max_profit_efficient(p)
if answer_efficient != answer_brute
puts "Failed with array #{p.to_s}, expected:#{answer_brute} - actual:#{answer_efficient}"
end
end
| true
|
1e63a81427b066deb4e875eee24ca45876c03055
|
Ruby
|
smartiqaorg/weather
|
/lib/http.rb
|
UTF-8
| 1,148
| 2.75
| 3
|
[] |
no_license
|
require 'net/http'
class Http
def initialize(host, protocol, headers = {}, auth_cred = nil)
@base_url ="#{protocol}://#{host}"
@headers = headers
@auth_cred = auth_cred
end
def send_request(method, url, params = nil, data = nil)
uri = URI.parse("#{@base_url}#{url}")
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
case method
when 'GET'
uri.query = URI.encode_www_form(params) if params
request = Net::HTTP::Get.new(uri, @headers)
when 'POST'
request = Net::HTTP::Post.new(uri, @headers)
request.body = data.to_json
when 'PUT'
request = Net::HTTP::Put.new(uri, @headers)
request.body = data.to_json
end
request.basic_auth(@auth_cred[:username], @auth_cred[:password]) if @auth_cred
res = http.request(request)
raise "Http request failed. Response code is #{res.code}. Error message is #{res.body || 'empty'}" unless res.class == Net::HTTPOK
handle_result(res.body)
end
end
def handle_result(res)
Common.valid_json?(res) ? JSON.parse(res) : res
end
end
| true
|
4947da0bfa97bd856fb56004ae840af26ef266bf
|
Ruby
|
famished-tiger/Rley
|
/lib/rley/formatter/asciitree.rb
|
UTF-8
| 3,937
| 3.0625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# frozen_string_literal: true
require_relative 'base_formatter'
module Rley # This module is used as a namespace
# Namespace dedicated to parse tree formatters.
module Formatter
# A formatter class that draws parse trees by using characters
class Asciitree < BaseFormatter
# TODO
attr_reader(:curr_path)
# For each node in curr_path, there is a corresponding string value.
# Allowed string values are: 'first', 'last', 'first_and_last', 'other'
attr_reader(:ranks)
# @return [String] The character pattern used for rendering
# a parent - child nesting
attr_reader(:nesting_prefix)
# @return [String] The character pattern used for a blank indentation
attr_reader(:blank_indent)
# @return [String] The character pattern for indentation and nesting
# continuation.
attr_reader(:continuation_indent)
# Constructor.
# @param anIO [IO] The output stream to which the parse tree
# is written.
def initialize(anIO)
super(anIO)
@curr_path = []
@ranks = []
@nesting_prefix = '+-- '
@blank_indent = ' '
@continuation_indent = '| '
end
# Method called by a ParseTreeVisitor to which the formatter subscribed.
# Notification of a visit event: the visitor is about to visit
# the children of a non-terminal node
# @param parent [NonTerminalNode]
# @param _children [Array<ParseTreeNode>] array of children nodes
def before_subnodes(parent, _children)
rank_of(parent)
curr_path << parent
end
# Method called by a ParseTreeVisitor to which the formatter subscribed.
# Notification of a visit event: the visitor is about to visit
# a non-terminal node
# @param aNonTerm [NonTerminalNode]
def before_non_terminal(aNonTerm)
emit(aNonTerm)
end
# Method called by a ParseTreeVisitor to which the formatter subscribed.
# Notification of a visit event: the visitor is about to visit
# a terminal node
# @param aTerm [TerminalNode]
def before_terminal(aTerm)
emit(aTerm, ": '#{aTerm.token.lexeme}'")
end
# Method called by a ParseTreeVisitor to which the formatter subscribed.
# Notification of a visit event: the visitor completed the visit of
# the children of a non-terminal node.
# @param _parent [NonTerminalNode]
# @param _children [Array] array of children nodes
def after_subnodes(_parent, _children)
curr_path.pop
ranks.pop
end
private
# Parent node is last node in current path
# or current path is empty (then aChild is root node)
def rank_of(aChild)
if curr_path.empty?
rank = 'root'
elsif curr_path[-1].subnodes.size == 1
rank = 'first_and_last'
else
parent = curr_path[-1]
siblings = parent.subnodes
siblings_last_index = siblings.size - 1
rank = case siblings.find_index(aChild)
when 0 then 'first'
when siblings_last_index then 'last'
else
'other'
end
end
ranks << rank
end
# 'root', 'first', 'first_and_last', 'last', 'other'
def path_prefix
return '' if ranks.empty?
prefix = +''
@ranks.each_with_index do |rank, i|
next if i.zero?
case rank
when 'first', 'other'
prefix << continuation_indent
when 'last', 'first_and_last', 'root'
prefix << blank_indent
end
end
prefix << nesting_prefix
prefix
end
def emit(aNode, aSuffix = '')
output.puts("#{path_prefix}#{aNode.symbol.name}#{aSuffix}")
end
end # class
end # module
end # module
# End of file
| true
|
6b199c1b0becbc8c9a0bca2557efc8e22e19d717
|
Ruby
|
j-sto/Sneaker_Colors
|
/spec/color_spec.rb
|
UTF-8
| 1,347
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe Color do
describe "initalized" do
it "should initalize the color class with a name of a color" do
test_color = Color.new({:name => 'Solar Red'})
expect(test_color).to be_an_instance_of Color
end
it 'should display attributes when they are called on the class' do
test_color = Color.new({:name => 'Solar Red'})
expect(test_color.name).to eq 'Solar Red'
end
end
describe 'Color.all' do
it 'shoud return all of the saved colors' do
test_color = Color.new({:name => 'Solar Red'})
test_color.save
expect(Color.all).to eq [test_color]
end
end
describe 'save' do
it 'should set the id when the color is saved into the datebase' do
test_color = Color.new({:name => 'Solar Red'})
test_color.save
expect(test_color.id).to be_an_instance_of Fixnum
end
end
describe 'self.list_sneaker_by_color' do
it 'should list all the colors of a selected sneaker' do
test_sneaker = Sneaker.new({:brand => 'Nike', :style => 'Yeezy'})
test_sneaker.save
test_color = Color.new({:name => 'Solar Red'})
test_color.save
test_colorway = Sneaker_Colorway.new({:sneaker_id => test_sneaker.id, :color_id => test_color.id})
test_colorway.save
test_colors = Color.list_sneaker_by_color(test_sneaker.id)
expect(test_colors.first).to eq test_color
end
end
end
| true
|
24423df04ae30926a9506dc78a18857ef4716987
|
Ruby
|
erikbelusic/prime-multiplication-table
|
/lib/multiplication_table.rb
|
UTF-8
| 275
| 3.28125
| 3
|
[] |
no_license
|
class MultiplicationTable
attr_reader :x_axis, :y_axis
def initialize(x_axis, y_axis = nil)
@x_axis = x_axis
@y_axis = y_axis.nil? ? x_axis : y_axis
end
def get_product_at(x_axis_index, y_axis_index)
x_axis[x_axis_index] * y_axis[y_axis_index]
end
end
| true
|
caf2209fe58e51d91370813ddd6d5c41fd4d4531
|
Ruby
|
andrestorresw/ruby
|
/6_io.rb
|
UTF-8
| 383
| 3.890625
| 4
|
[] |
no_license
|
puts "Bienvenido, dame tu nombre por favor"
print "==>"
#Chomp elimina el ultimo caracter de una cadena de texto
nombre = gets.chomp
puts "Hola, #{nombre} Un placer que éstes por aquí"
puts "Calculadora "
puts "Al numero que ingreses se le sumarán 10 puntos"
puts "==>"
numero = gets.chomp.to_i + 10
puts " El resultado final es #{numero}"
=begin
Este es un comentario
=end
| true
|
35d8c969816c054c8c23c9fc33d6b47e42663314
|
Ruby
|
satyajyoti/Ruby_Euler
|
/17.rb
|
UTF-8
| 770
| 3.4375
| 3
|
[] |
no_license
|
def letter_count
num = Hash[(1..20).zip %w(one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty)].merge({
30 =>"thirty",
40 => 'forty',
50 => 'fifty',
60 => 'sixty',
70 => 'seventy',
80 => 'eighty',
90 => 'ninety',
100 => 'hundred',
1000 => 'onethousand',
0 => '' })
size = lambda{|i| (sz = num[i]) && sz.size}
double = ->(z){
size[z] || size[z/10*10] + size[z%10]
}
puts (1..1000).inject(0){ |sum,n| sum +
(size.call(n)||size[n/100] +
if n < 100
0
else
size[100] + if n % 100 == 0 then 0 else 3 end
end +
double[n%100]
)} + 3
end
letter_count
| true
|
44c1576855de1d4090947b832ab1841b68d5396f
|
Ruby
|
saraid/saraid_utils
|
/lib/units/of/length.rb
|
UTF-8
| 917
| 2.609375
| 3
|
[] |
no_license
|
module Units
class Meter < Unit.of(:length)
def to_s; 'm'; end
end
SI.expand_prefixes(Meter)
class Foot < Unit.of(:length)
def to_s; 'ft'; end
def conversions
{ Yard => { method_names: %i( to_yards ),
conversion: proc { |number| number.fdiv 3 } },
Mile => { method_names: %i( to_miles ),
conversion: proc { |number| number.fdiv 5280 } }
}
end
end
class Yard < Unit.of(:length)
def to_s; ' yard'; end
end
class Mile < Unit.of(:length)
def to_s; ' mile'; end
end
module OfLength
extend Monkeypatchable
def meters
Units::Quantity.new(self, Units::Meter.instance)
end
alias meter meters
def kilometers
Units::Quantity.new(self, Units::Kilometer.instance)
end
alias kilometer kilometers
alias km kilometers
refine Numeric do
include OfLength
end
end
end
| true
|
4029c15ddff629be8ce310edc833e31c8adb6b20
|
Ruby
|
ripienaar/mc-plugins
|
/discovery/puppetdb/discovery/puppetdb.rb
|
UTF-8
| 3,528
| 2.515625
| 3
|
[] |
no_license
|
require 'net/http'
require 'net/https'
# Proof of Concept PuppetDB integration for mcollective discovery
# capable of supporting class, fact and identity filters.
#
# Final incorporation into mcollective would depend on the
# http://projects.puppetlabs.com/issues/14763 being closed
#
# There are some hard coded hostnames etc here, so just a POC
module MCollective
class Discovery
class Puppetdb
def self.discover(filter, timeout, limit=0, client=nil)
http = Net::HTTP.new('puppetdb.xx.net', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
found = []
filter.keys.each do |key|
case key
when "identity"
identity_search(filter["identity"], http, found)
when "cf_class"
class_search(filter["cf_class"], http, found)
when "fact"
fact_search(filter["fact"], http, found)
end
end
# filters are combined so we get the intersection of values across
# all matches found using fact, agent and identity filters
found = found.inject(found[0]){|x, y| x & y}
found.flatten.map do |node|
if node =~ /^(.+?)\.\w+\.net/
$1
else
node
end
end
end
def self.fact_search(filter, http, found)
return if filter.empty?
selected_hosts = []
filter.each do |fact|
raise "Can only do == matches using the PuppetDB discovery" unless fact[:operator] == "=="
query = ["and", ["=", ["fact", fact[:fact]], fact[:value]]]
resp, data = http.get("/nodes?query=%s" % URI.escape(query.to_json), {"accept" => "application/json"})
raise "Failed to retrieve nodes from PuppetDB: %s: %s" % [resp.code, resp.message] unless resp.code == "200"
found << JSON.parse(data)
end
end
def self.class_search(filter, http, found)
return if filter.empty?
selected_hosts = []
filter.each do |klass|
klass = klass.split("::").map{|i| i.capitalize}.join("::")
raise "Can not do regular expression matches for classes using the PuppetDB discovery method" if regexy_string(klass).is_a?(Regexp)
query = ["and", ["=", "type", "Class"], ["=", "title", klass]]
resp, data = http.get("/resources?query=%s" % URI.escape(query.to_json), {"accept" => "application/json"})
raise "Failed to retrieve nodes from PuppetDB: %s: %s" % [resp.code, resp.message] unless resp.code == "200"
found << JSON.parse(data).map{|found| found["certname"]}
end
end
def self.identity_search(filter, http, found)
return if filter.empty?
resp, data = http.get("/nodes", {"accept" => "application/json"})
raise "Failed to retrieve nodes from PuppetDB: %s: %s" % [resp.code, resp.message] unless resp.code == "200"
all_hosts = JSON.parse(data)
selected_hosts = []
filter.each do |identity|
identity = regexy_string(identity)
if identity.is_a?(Regexp)
selected_hosts << all_hosts.grep(identity)
else
selected_hosts << identity if all_hosts.include?(identity)
end
end
found << selected_hosts
end
def self.regexy_string(string)
if string.match("^/")
Regexp.new(string.gsub("\/", ""))
else
string
end
end
end
end
end
| true
|
0f9285d48de060d0092313ab3b53d3d5a6c4b32e
|
Ruby
|
emfigo/cluda
|
/spec/distances/chebyshev_spec.rb
|
UTF-8
| 688
| 2.6875
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Cluda::Chebyshev do
let(:valid_point) { { x: 1, y: -3 } }
let(:valid_point2) { { x: -1, y: 3 } }
let(:not_valid_point) { {} }
describe '.distance' do
it 'doest not calculate any distance for a none valid point' do
expect { Cluda::Chebyshev.distance(valid_point, not_valid_point) }.to raise_error(Cluda::InvalidPoint)
end
it 'calculates the distance for specific points' do
distance = [(valid_point[:x] - valid_point2[:x]).abs, (valid_point[:y] - valid_point2[:y]).abs].max
expect(Cluda::Chebyshev.distance(valid_point, valid_point2)).to eq(distance)
end
end
end
| true
|
69a1c9fbf0d4814845a0518716cdbf3e831cc9b2
|
Ruby
|
astro/harvester
|
/chart.rb
|
UTF-8
| 1,304
| 2.890625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require 'dbi'
require 'yaml'
require 'gruff'
config = YAML::load File.new('config.yaml')
timeout = config['settings']['timeout'].to_i
sizelimit = config['settings']['size limit'].to_i
dbi = DBI::connect(config['db']['driver'], config['db']['user'], config['db']['password'])
class StatsPerCollection
attr_reader :days
def initialize
@collections = {}
@days = []
end
def add_one(collection, day)
@days << day unless @days.index(day)
c = @collections[collection] || {}
c[day] = (c[day] || 0) + 1
@collections[collection] = c
end
def each
@collections.each { |n,c|
v = []
@days.each { |d|
v << c[d].to_i
}
yield n, v
}
end
end
c = StatsPerCollection.new
dbi.select_all("select date(items.date) as date,sources.collection from items left join sources on sources.rss=items.rss where date > now() - interval '14 days' and date < now() + interval '1 day' order by date") { |date,collection|
c.add_one(collection, date.day)
}
g = Gruff::Line.new(300)
g.title = "Harvested items per day"
g.x_axis_label = "Days"
g.y_axis_label = "Items"
c.each(&g.method(:data))
labels = {}
c.days.each_with_index do |d,i|
labels[i] = d.to_s
end
g.labels = labels
g.write("#{config['settings']['output']}/chart.jpg")
| true
|
cd0f854467e64d6058de2a3be269eee9f0a539bb
|
Ruby
|
huangkc/phase-0
|
/week-4/errors.rb
|
UTF-8
| 6,244
| 4.34375
| 4
|
[
"MIT"
] |
permissive
|
# Analyze the Errors
# I worked on this challenge [by myself ].
# I spent [1.5] hours on this challenge.
# --- error -------------------------------------------------------
# cartmans_phrase = "Screw you guys " + "I'm going home."
# This error was analyzed in the README file.
# --- error -------------------------------------------------------
# def cartman_hates(thing)
# while true
# puts "What's there to hate about #{thing}?"
#
# end
# This is a tricky error. The line number may throw you off.
# 1. What is the name of the file with the error?
#errors.rb
# 2. What is the line number where the error occurs?
#170
# 3. What is the type of error message?
#syntax
# 4. What additional information does the interpreter provide about this type of error?
#Keyword "end" is missing.
# 5. Where is the error in the code?
#The interpreter did not expect the method to end
# 6. Why did the interpreter give you this error?
#Without the keyword "end" the interpreter expected more input
# --- error -------------------------------------------------------
#south_park
# 1. What is the line number where the error occurs?
#36
# 2. What is the type of error message?
#undefined variable/method.
# 3. What additional information does the interpreter provide about this type of error?
#south_park is undefined.
# 4. Where is the error in the code?
#south_park is not properly defined as a variable or a method
# 5. Why did the interpreter give you this error?
#Interpreter does notknow wehteher south_park is a method or variable
# --- error -------------------------------------------------------
#cartman()
# 1. What is the line number where the error occurs?
#51
# 2. What is the type of error message?
#undefined method.
# 3. What additional information does the interpreter provide about this type of error?
#"cartman" is undefined.
# 4. Where is the error in the code?
#cartman() is not properly defined as a method.
# 5. Why did the interpreter give you this error?
#The interpreter does not know what this object should be.
# --- error -------------------------------------------------------
# def cartmans_phrase
# puts "I'm not fat; I'm big-boned!"
# end
# cartmans_phrase('I hate Kyle')
# 1. What is the line number where the error occurs?
#66
# 2. What is the type of error message?
#Wrong number of arguments.
# 3. What additional information does the interpreter provide about this type of error?
#0 arguments expected but got 1 argument.
# 4. Where is the error in the code?
#The method does not take an argument but one was given when the method was called.
# 5. Why did the interpreter give you this error?
#Either the method should take an argument or the argument should be removed from the method call.
# --- error -------------------------------------------------------
# def cartman_says(offensive_message)
# puts offensive_message
# end
# cartman_says
# 1. What is the line number where the error occurs?
#85
# 2. What is the type of error message?
#Argument error
# 3. What additional information does the interpreter provide about this type of error?
#Expected 1 argument and got 0
# 4. Where is the error in the code?
#The method took 1 argument but the method call gave 0
# 5. Why did the interpreter give you this error?
#Either the method should take no argument or one should be added to the method call.
# --- error -------------------------------------------------------
# def cartmans_lie(lie, name)
# puts "#{lie}, #{name}!"
# end
# cartmans_lie('A meteor the size of the earth is about to hit Wyoming!')
# 1. What is the line number where the error occurs?
#106
# 2. What is the type of error message?
#Argument error.
# 3. What additional information does the interpreter provide about this type of error?
#Wrong number of arguments.
# 4. Where is the error in the code?
#The method takes 2 arguments while the method call gave only 1.
# 5. Why did the interpreter give you this error?
#The interpreter did not get all of the expected input for the method.
# --- error -------------------------------------------------------
#5 * "Respect my authoritay!"
# 1. What is the line number where the error occurs?
#125
# 2. What is the type of error message?
#Type error
# 3. What additional information does the interpreter provide about this type of error?
#String can't be coerced into Fixnum
# 4. Where is the error in the code?
#The multiplication symbol
# 5. Why did the interpreter give you this error?
#The interpreter does not know how convert "Respect my authoritay" to a number
# --- error -------------------------------------------------------
#amount_of_kfc_left = 20/0
# 1. What is the line number where the error occurs?
#140
# 2. What is the type of error message?
#Zero division
# 3. What additional information does the interpreter provide about this type of error?
#Attempt to divide by zero
# 4. Where is the error in the code?
#The division operation
# 5. Why did the interpreter give you this error?
#It is not able to perform the operation
# --- error -------------------------------------------------------
require_relative "cartmans_essay.md"
# 1. What is the line number where the error occurs?
#156
# 2. What is the type of error message?
#Load error
# 3. What additional information does the interpreter provide about this type of error?
#cannot load such file
# 4. Where is the error in the code?
#'require_relative'
# 5. Why did the interpreter give you this error?
#The interpreter could not find "cartmans_essay.md" in the directory.
# --- REFLECTION -------------------------------------------------------
# Write your reflection below as a comment.
# Which error was the most difficult to read?
# "Unexpected end of input"
# # How did you figure out what the issue with the error was?
# I analyzed the error message and used what I know about Ruby to figure out what the issue was.
# # Were you able to determine why each error message happened based on the code?
# Yes except the last one since the syntax appears to be correct.
# When you encounter errors in your future code, what process will you follow to help you debug?
#Go to the line number of the error, analyze the content of the error message, and track down the error.
| true
|
9665d38f2fe0d26b1b7e94bd6e812436567d7a1a
|
Ruby
|
kloomes/rails-longest-word-game
|
/app/controllers/games_controller.rb
|
UTF-8
| 970
| 2.875
| 3
|
[] |
no_license
|
require 'json'
require 'open-uri'
class GamesController < ApplicationController
def new
@selection = []
letters = ("a".."z").to_a
10.times { @selection << letters.sample }
end
def score
@letter_count = {}
params[:letters].split('').each do |letter|
if @letter_count[letter.to_sym].nil?
@letter_count[letter.to_sym] = 1
else
@letter_count[letter.to_sym] += 1
end
end
@word_letter_count = {}
params[:word].split('').each do |letter|
if @word_letter_count[letter.to_sym].nil?
@word_letter_count[letter.to_sym] = 1
else
@word_letter_count[letter.to_sym] += 1
end
end
@valid = true if @word_letter_count.each_key do |key|
@letter_count[key] >= @word_letter_count[key]
end
url = "https://wagon-dictionary.herokuapp.com/#{params[:word]}"
word_object = open(url).read
word = JSON.parse(word_object)
@found = word["found"]
end
end
| true
|
646d7432db746f7e7064a147a39db2eba1bfd752
|
Ruby
|
rothberry/leet
|
/amzn/search_in_rotate_sorted_array.rb
|
UTF-8
| 1,937
| 4.03125
| 4
|
[] |
no_license
|
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer}
# There is an integer array nums sorted in ascending order (with distinct values).
# Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
# Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
# You must write an algorithm with O(log n) runtime complexity.
require "pry"
def search(nums, target)
# with a binary search
left, right = 0, nums.length - 1
# pivot = 0
p "#{nums}, #{target}"
while left <= right
mid = (right - left) / 2
return mid if target == nums[mid]
# # check both sides of mid to see if we are at the pivot point
# sl = nums.slice(mid - 1, 3)
# # if mid - 1 is greater than mid, then mid is the pivot
# # if mid + 1 is less than mid, then mid is the pivot
# check left side of nums sorted
p nums[mid]
p "#{nums[left]}, #{nums[right]}"
# binding.pry
if nums[left] <= nums[mid]
if target > nums[mid] || target < nums[left]
puts "left: left"
left = mid + 1
else
puts "left: right"
right = mid - 1
end
# check right side of sorted
else
if target < nums[mid] || target > nums[right]
puts "right: right"
right = mid - 1
else
puts "right: left"
left = mid + 1
end
end
end
return -1
end
def search1(nums, target)
found = nums.find_index { |x| x == target }
found ? found : -1
end
search([4, 5, 6, 7, 0, 1, 2], 0)
# Output: 4
# search([4, 5, 6, 7, 0, 1, 2], 3)
# # Output: -1
# search([1], 0)
# # Output: -1
| true
|
0e2a27e577ad2de42f01b1149f1b4c1642fdd495
|
Ruby
|
tom-warthog/ultimate_townhall
|
/lib/app/townhalls_follower.rb
|
UTF-8
| 1,561
| 3
| 3
|
[] |
no_license
|
require 'twitter'
require 'dotenv'
require 'pry'
Dotenv.load('.env')
# @info = [{"ville" => "Grenoble", "email" => "[email protected]", "departement" => "Isère"},
# {"ville" => "Meylan", "email" => "[email protected]", "departement" => "Isère"},
# {"ville" => "Echirolles", "email" => "[email protected]", "departement" => "Isère"}]
class Follower
def initialize(info)
@info = info
@client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["TWITTER_API_KEY"]
config.consumer_secret = ENV["TWITTER_API_SECRET_KEY"]
config.access_token = ENV["TWITTER_ACCESS_TOKEN"]
config.access_token_secret = ENV["TWITTER_SECRET_ACCESS_TOKEN"]
end
end
def get_all_cities
json = File.read('..//ultimate_townhall/db/townhall.json') #Update path ...
@cities = []
if json != ""
JSON.parse(json).each do |h|
@cities << h["ville"]
end
end
@cities
end
def find_twitter_handle
@handles = []
@cities.each do |city|
user = @client.user_search(city)[0]
@client.follow(user)
@handles << user.name
end
@handles
end
def add_handles_to_json(arr)
@info.each_with_index do |h, i|
h['twitter'] = @handles[i]
end
File.open("/home/nico/THP/ultimate_townhall/db/townhall.json", "w") do |f|
f.write([])
end
File.open("/home/nico/THP/ultimate_townhall/db/townhall.json","w") do |f|
f.puts JSON.pretty_generate(arr)
end
end
def perform
get_all_cities
find_twitter_handle
add_handles_to_json(@info)
end
end
| true
|
1fc44d572dad7cae432fff98d34ea598999ea26b
|
Ruby
|
Seven-dev7/mini_jeu_poo
|
/app2.rb
|
UTF-8
| 2,966
| 3.359375
| 3
|
[] |
no_license
|
require 'bundler'
Bundler.require
$:.unshift File.expand_path("./../lib", __FILE__)
require 'game'
require 'player'
p "------------------------------------------------"
p "|Bienvenue sur 'ILS VEULENT TOUS MA POO' ! |"
p "|Le but du jeu est d'être le dernier survivant !|"
p "-------------------------------------------------"
#Initialisation du joueur: ensuite, le jeu va demander à l'utilisateur son prénom et créer un HumanPlayer portant ce prénom."
p "Initialisation du joueur"
p "Quel est ton prénom ?"
name = gets.chomp
user = HumanPlayer.new("#{name}")
ennemies = []
p "Voici nos 2 ennemis"
player1 = Player.new("josiane")
p "Ici #{player1.name}"
player2 = Player.new("jose")
[player1, player2].each { |p| ennemies << p }
p "Voila #{player2.name}"
while user.life_points > 0 && (player1.life_points > 0 || player2.life_points > 0 )
user.show_state
p "Que veux tu faire?"
p "a - chercher une meilleure arme"
p "s - chercher à se soigner"
p "attaquer un joueur en vue :"
print "0 - Attaquer "
player1.show_state
print "1 - Attaquer "
player2.show_state
print ">"
input_menu = gets.chomp.to_s
case
when input_menu == 'a'
user.search_weapon
when input_menu == 's'
user.search_health_pack
when input_menu == '0'
user.attacks(player1)
when input_menu == '1'
user.attacks(player2)
else
p "Veuillez taper uniquement les valeurs indiquées"
end
ennemies.each do |ennemy|
if ennemy.life_points > 0
puts "#{ennemy.name} attaque #{user.name}"
ennemy.attacks(user)
end
end
end
p "La partie est fini"
if user.life_points <= 0
p "Tu pus la merde"
else
p "Bravo tu as gagné ! "
end
#Initialisation des ennemis : le jeu va maintenant créer nos deux combattants préférés, "Josiane" et "José".
#Comme nous savons qu'à terme (version 3.0) il y aura plus de 2 ennemis, on va mettre en place une astuce pour manipuler facilement un groupe d'ennemis : le jeu va créer un array enemies qui va contenir les deux objets Player que sont José et Josiane. Tu verras plus tard l'usage qu'on va en faire.
#Le combat : tout comme dans la version 1.0, on peut maintenant lancer le combat ! Tu vas ouvrir une boucle while qui ne doit s'arrêter que si le joueur de l'utilisateur (HumanPlayer) meurt ou si les 2 joueurs "bots" (Player) meurent. Cette condition d'arrêt n'est pas triviale à écrire mais je te propose d'essayer ! Sinon la réponse est disponible plus bas. Laisse la boucle while vide pour le moment, on la codera juste après.
#Fin du jeu : maintenant, si on sort de cette boucle while, c'est que la partie est terminée. Donc juste en dessous du end de la boucle, on va préparer un petit message de fin. Le jeu doit afficher "La partie est finie" et ensuite soit afficher "BRAVO ! TU AS GAGNE !" si le joueur humain est toujours en vie, ou "Loser ! Tu as perdu !" s'il est mort.
| true
|
f95c96b24f86834d21b26f21af9c27328fd3fc73
|
Ruby
|
chhavikirtani2000/rubyx
|
/test/slot_machine/instruction/test_resolve_method.rb
|
UTF-8
| 1,951
| 2.65625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require_relative "helper"
module SlotMachine
class TestResolveMethod < SlotMachineInstructionTest
include Parfait::MethodHelper
def instruction
method = make_method
cache_entry = Parfait::CacheEntry.new(method.frame_type, method)
ResolveMethod.new( "method" , :name , cache_entry )
end
def test_len
assert_equal 19 , all.length , all_str
end
def test_1_load_name
assert_load risc(1) , Symbol , :r1
assert_equal :name , risc(1).constant
end
def test_2_load_cache
assert_load risc(2) , Parfait::CacheEntry , :r2
end
def test_3_get_cache_type
assert_slot_to_reg risc(3) ,:r2 , 1 , :r3
end
def test_4_get_type_methods
assert_slot_to_reg risc(4) ,:r3 , 4 , :r4
end
def test_5_start_label
assert_label risc(5) , "while_start_"
end
def test_6_load_nil
assert_load risc(6) , Parfait::NilClass , :r5
end
def test_7_check_nil
assert_operator risc(7) , :- , :r5 , :r4
end
def test_8_nil_branch
assert_zero risc(8) , "exit_label_"
end
def test_9_get_method_name
assert_slot_to_reg risc(9) ,:r4 , 6 , :r6
end
# Syscall, Label, RegToSlot,] #20
def test_10_check_name
assert_operator risc(10) , :- , :r6 , :r1
end
def test_11_nil_branch
assert_zero risc(11) , "ok_label_"
end
def test_12_get_next_method
assert_slot_to_reg risc(12) ,:r4 , 2 , :r4
end
def test_13_continue_while
assert_branch risc(13) , "while_start_"
end
def test_14_goto_exit
assert_label risc(14) , "exit_label_"
end
def test_15_move_name
assert_transfer( risc(15) , :r1 , :r1)
end
def test_16_die
assert_syscall risc(16) , :died
end
def test_17_label
assert_label risc(17) , "ok_label_"
end
def test_18_load_method
assert_reg_to_slot risc(18) , :r4 , :r2 , 2
end
end
end
| true
|
fe976753f8fa5f2f1409ef1769e12876d2eb4746
|
Ruby
|
newfront/dailyhacking
|
/html5/eventsource/libs/formatter.rb
|
UTF-8
| 1,466
| 3.3125
| 3
|
[] |
no_license
|
require "hashie"
require "json"
require "pp"
# abstract base class Formatter
class Formatter
def format
raise "Abstract method. need to override in child class"
end
end
# Create a Formatter for EventSource
class EventSourceFormatter < Formatter
def format(notification)
# notification is an object of Hashie Type
# {:type=>"user", :content=>"{'content': 'Hello You', 'url': 'http://google.com'}
# event source format
# data: content.chunk\n
# data: content.chunk\n
# data: content.chunk\n
#head = ""
#message = ""
message = "event: #{notification[:event]}\n"
message << "id: #{notification[:id]}\n" unless notification[:id].nil?
message << "retry: #{notification[:retry]}\n" unless notification[:retry].nil?
begin
data = JSON.parse(notification[:data])
message << "data: {\n"
@count = data.size - 1
data.each {|key, value|
message << "data: \"#{key}\": \"#{value}\""
message << "," unless @count <= 0
message << "\n"
@count -= 1
}
message << "data: }\n\n"
rescue
# JSONParseError
message << "data: #{key} - #{val}\n\n"
end
message
end
end
#formatter = EventSourceFormatter.new
# notification
#data = {}
#data[:message] = "Hello User"
#data[:url] = "http://google.com"
#notification = {:event=>"user", :data=> data.to_json, :id=>"23657777", :retry => 10000}
#puts formatter.format(notification)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.