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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f6986c8abf5fc40899c0e1b6a5b47140b21d5f9c
|
Ruby
|
cloudfoundry-attic/git_pipeline
|
/app/models/stage.rb
|
UTF-8
| 371
| 2.609375
| 3
|
[] |
no_license
|
class Stage
attr_reader :name, :ci_url, :git_log, :git_submodule_change_log
def initialize(name, ci_url, git_log, git_submodule_change_log)
@name = name
@ci_url = ci_url
@git_log = git_log
@git_submodule_change_log = git_submodule_change_log
end
def has_ci_url?
!!@ci_url
end
def pending_changes?
git_log.git_commits.any?
end
end
| true
|
20c528d7812b2daed5c8a56774b33940f806c4d5
|
Ruby
|
Coderdotnew/intro_web_apps_bs
|
/10_class/03_hash_enumerables/code/01_recipes/spec/recipes_spec.rb
|
UTF-8
| 1,974
| 3.03125
| 3
|
[] |
no_license
|
require_relative './spec_helper'
require_relative '../recipes.rb'
$taco_ingredients = {
:tortilla => "3",
:shredded_chicken => "2 cups",
:salsa => "1 cup",
:shredded_cheddar_cheese => "3 cups"
}
describe '#ingredients' do
it "returns a hash of all 4 ingredients and amounts" do
expect(ingredients($taco_ingredients)).to eq({
:tortilla => "3",
:shredded_chicken => "2 cups",
:salsa => "1 cup",
:shredded_cheddar_cheese => "3 cups"
})
end
end
describe '#amount_of_cheese' do
it 'returns 3 cups' do
expect(amount_of_cheese($taco_ingredients)).to eq("3 cups")
end
end
describe '#ingredients_and_amounts' do
it 'prints all ingredients and amounts' do
expect($stdout).to receive(:puts).with("tortilla 3")
expect($stdout).to receive(:puts).with("shredded_chicken 2 cups")
expect($stdout).to receive(:puts).with("salsa 1 cup")
expect($stdout).to receive(:puts).with("shredded_cheddar_cheese 3 cups")
ingredients_and_amounts($taco_ingredients)
end
end
describe '#ingredients' do
it 'prints all ingredients' do
expect($stdout).to receive(:puts).with("tortilla")
expect($stdout).to receive(:puts).with("shredded_chicken")
expect($stdout).to receive(:puts).with("salsa")
expect($stdout).to receive(:puts).with("shredded_cheddar_cheese")
ingredients($taco_ingredients)
end
end
describe '#amounts' do
it 'prints all amounts' do
expect($stdout).to receive(:puts).with("3")
expect($stdout).to receive(:puts).with("2 cups")
expect($stdout).to receive(:puts).with("1 cup")
expect($stdout).to receive(:puts).with("3 cups")
amounts($taco_ingredients)
end
end
describe '#total_count' do
it 'returns the total number of ingredients and amounts' do
expect(total_count($taco_ingredients)).to eq(8)
end
end
describe '#total_cups' do
it 'returns the total number of ingredients and amounts' do
expect(total_cups($taco_ingredients)).to eq(9)
end
end
| true
|
f8ba568b511c2f7b593327ee87168529325965fe
|
Ruby
|
malachispencer/codewars
|
/ruby/6kyu/christmas-day.rb
|
UTF-8
| 4,411
| 4.5
| 4
|
[] |
no_license
|
=begin
Codewars. 14/05/20. 'Christmas Day'. 6kyu. Here we create a method that tells
us what day christmas on a particular year falls on. Here is the solution I
developed to solve the challenge.
1) We require the date library.
2) We generate an array of the day names using the date library's built-in
constant DAYNAMES and we do the same with the month names using the date
library's built-in constant MONTHNAMES.
3) We store our sting date formats in constants to make our life easier. Our
3 types of string date inputs can be "25 December 2020", "12 25 2020" and
"2020 12 25".
4) We define our method christmas_weekday_ms, which takes the 3 types of string
date inputs and a date object as its potential argument.
5) First we check if the input is a date object using the instance_of?
method, if so, we call the wday method on the date, which returns the
weekday of that date in number form - e.g. Sunday is 0, Monday is 1, Tuesday
2 etc - but we use the result to index the day name array, which then
returns the weekday in word form.
6) If it's not a date object, we check if our string date comes in the form
"2020 12 25" by splitting it into an array and checking if the first
element contains 4 characters, if so, we use the strptime method to turn
our string date into a date object. The strptime method takes two arguments,
the first the string, and the second the format of the string date, so we
use our YMD (Year Month Day) format for this date. Again, we call the wday
method and index DAY with the result.
7) If it's not a YMD string, we check if it's a "12 25 2020" date by checking
if its first element - when it's split - contains 2 characters and that the
string contains no letters, if so, we convert it to a date object, call
wday and index DAY with the result.
8) If it's not any of the previous, it must be a "25 December 2020" date, so
inside an index bracket of DAY, we the string to a date object and call
wday etc.
9) But first, we must convert "December" to 12 so our string formatter can work.
So we split the date, map over it and the element that contains letters, we
convert it into the index position of that element - "December" - in the
MONTH (month names) constant array, using the find_index method. If it
doesn't contain letters, we leave the element the same. Then we join the
array back into a string with its spaces intact.
10) While it was fun making this method, we did a lot of unnecessary work. The
only thing we actually need from the input is the year, because the month
and day are always the same. With that, we can shorten our code to one
line.
=end
require "date"
DAY, MONTH = Date::DAYNAMES, Date::MONTHNAMES
DMY, MDY, YMD = "%d %m %Y", "%m %d %Y", "%Y %m %d"
def christmas_weekday_ms(d)
d.instance_of?(Date) ? DAY[d.wday] :
d.split.first.size == 4 ? DAY[Date.strptime(d, YMD).wday] :
d.split.first.size == 2 && d !~ /[a-z]/ ? DAY[Date.strptime(d, MDY).wday] :
DAY[Date.strptime(d.split.map {|e| e =~ /[a-z]/ ? MONTH.find_index(e) : e}.join(" "), DMY).wday]
end
=begin
Here is a better solution, as we can see, the only thing we need to extract from our string is the year.
1) We create a new date object, which will require a year, a month and a day in
that order, in integer form.
2) Christmas day is always the 25th of December so we can hard code the 12 and
the 25.
3) However, we must extract the year, and we do so by first converting our
input to a string, in case it's a date object, strings will be unaffected
by this. Now our date object will look like this: "2020-12-25".
4) Using the regex, we then slice the year from the date using the regex \d{4,}
which takes any 4 or more digits from our string. We allow 4 or more in
case we want to go beyond the year 9999. This string value however must be
converted to an integer, so we do so.
5) Now we have our date object, we simply call the strftime method, which
formats a date according to which of the many directives we give it. We give
it the "%A" directive, which gives us the full weekday name capitalised.
6) "%^A" = Full weekday name all upper case.
7) "%a" = Abbreviated weekday name capitalised e.g. "Sun".
8) "%^a" = Abbreviated weekday name all upper case e.g. "SUN".
=end
def christmas_weekday(d)
Date.new(d.to_s[/\d{4,}/].to_i, 12, 25).strftime("%A")
end
| true
|
3f34f5ff2d791dd0e998713ce9be295d8af1dde2
|
Ruby
|
hinrik/ircsupport
|
/test/case_test.rb
|
UTF-8
| 1,469
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
# coding: utf-8
require 'test_helper'
include IRCSupport::Case
describe "IRCUpcase" do
it "should put string into IRC uppercase" do
irc_upcase("simple").must_equal "SIMPLE"
irc_upcase("c0mpl^{x}").must_equal "C0MPL~[X]"
irc_upcase("c0mpl~[x]").must_equal "C0MPL~[X]"
irc_upcase("c0mpl~{x}").must_equal "C0MPL~[X]"
irc_upcase("c0mpl|{x}").must_equal "C0MPL\\[X]"
irc_upcase("c0mpl^{x}", :'strict-rfc1459').must_equal "C0MPL^[X]"
irc_upcase("c0mpl^{x}", :ascii).must_equal "C0MPL^{X}"
proc { irc_upcase("c0mpl^{x}", :foobar) }.must_raise ArgumentError
end
end
describe "IRCDowncase" do
it "should put string into IRC lowercase" do
irc_downcase("SIMPLE").must_equal "simple"
irc_downcase("C0MPL~[X]").must_equal "c0mpl^{x}"
irc_downcase("C0MPL^{X}").must_equal "c0mpl^{x}"
irc_downcase("C0MPL^[X]").must_equal "c0mpl^{x}"
irc_downcase("C0MPL\\[X]").must_equal "c0mpl|{x}"
irc_downcase("C0MPL~[x]", :'strict-rfc1459').must_equal "c0mpl~{x}"
irc_downcase("c0mpl^{x}", :ascii).must_equal "c0mpl^{x}"
proc { irc_downcase("c0mpl^{x}", :foobar) }.must_raise ArgumentError
end
end
describe "IRCEql" do
it "should say they are equal in IRC-case" do
irc_eql?('C0MPL~[X]', 'c0mpl^{x}').must_equal true
end
it "should say they are unequal in IRC-case" do
irc_eql?('C0MPL~[X]', 'c0mpl^{x}', :'strict-rfc1459').must_equal false
irc_eql?('C0MPL|[X]', 'c0mpl~{x}').must_equal false
end
end
| true
|
93b66bd398d7c0100c67ac7dbbdc9c56c00ccc69
|
Ruby
|
tnordloh/ltl_packer
|
/best_fit_decreasing_combinations.rb
|
UTF-8
| 1,252
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
#! /usr/bin/env ruby
# frozen_string_literal: true
require 'ltl_packer'
require_relative 'data'
trucks = @trucks.map { |truck| truck = LtlPacker::Truck.new(*truck.to_a) }
shipments = @shipments.map { |shipment| shipment = LtlPacker::Shipment.new(*shipment.to_a) }
loader = LtlPacker::Loader.new(trucks: trucks, shipments: shipments)
def best_fit_decreasing_combinations(loader)
until loader.done?
truck = loader.smallest_truck
shipments = loader.shipments
combinations = shipments.combination(1).to_a + shipments.combination(2).to_a
########
#comment/uncomment the below line, to swap between favoring more even loads with maximum space usage
########
#combinations.sort! { |a, b| [b.size, b.map(&:capacity).sum] <=> [a.size, a.map(&:capacity).sum] }
combinations.sort! { |a, b| [b.map(&:capacity).sum, b.size ] <=> [a.map(&:capacity).sum, a.size] }
#combinations.sort! { |a, b| [b.map(&:capacity).sum, a.size ] <=> [a.map(&:capacity).sum, b.size] }
best_combination = combinations.find { |c| c.map(&:capacity).sum <= truck.capacity }
best_combination.each { |c| loader = loader.load(truck.id, c.id) }
end
loader
end
finished_loader = best_fit_decreasing_combinations(loader)
finished_loader.report
| true
|
d48a1e09b79d93343d97c1f0a7c71df1b289826c
|
Ruby
|
javogel/IH_Coursework
|
/Week_2/Day_4/sinatra_blog/spec/post_spec.rb
|
UTF-8
| 714
| 2.78125
| 3
|
[] |
no_license
|
# spec/post_spec.rb
require_relative("../lib/Post.rb")
RSpec.describe Post do
before(:each) do
@post1 = Post.new("title1", "1", "Hello My name is post 1", "Category0", "author0")
@post2 = Post.new("title2", "2", "Hello My name is post 2", "Category1", "author1")
end
it("#title returns title") do
expect(@post1.title).to eq("title1")
expect(@post2.title).to eq("title2")
end
it("#date returns date") do
expect(@post1.date).to eq("1")
end
it("#text returns text") do
expect(@post1.text).to eq("Hello My name is post 1")
end
it("#text returns text") do
expect(@post1.author).to eq("author0")
end
it("#text returns text") do
expect(@post1.category).to eq("Category0")
end
end
| true
|
8907310caa6a536c70dfbd7804834832495c38fb
|
Ruby
|
jjnewman/DDDT
|
/lib/product.rb
|
UTF-8
| 374
| 3.1875
| 3
|
[] |
no_license
|
class Product
require 'rubygems'
require 'json'
def initialize
json = File.read('products.json')
@items = JSON.parse(json)
end
def all_items
@items[0]
end
def all_item_names
all_items.keys
end
def item_price(item)
all_items[item]["Price"]
end
def item_category(item)
all_items[item]["Category"]
end
def item_stock(item)
all_items[item]["Stock"]
end
end
| true
|
65270c12cf6af95c6cbd7009ddd3c1334f3ee988
|
Ruby
|
tackyunicorn/hello-ruby
|
/methods.rb
|
UTF-8
| 206
| 4.1875
| 4
|
[] |
no_license
|
# Define a method block using def and end
# Pass parameters and give default values
def sayhi(name="no name" , age=-1)
puts ("Hello " + name + ", you are " + age.to_s)
end
puts "Top"
sayhi("Mike" , 73)
| true
|
488321879407a196f8e24a6e20d1ed35fcc39c9c
|
Ruby
|
JPuchalla/backend_module_0_capstone
|
/day_1/ex3.rb
|
UTF-8
| 1,068
| 4.4375
| 4
|
[] |
no_license
|
puts "I will now count my chickens:"
# In hens the line is asking ruby what 25 plus 30 divided by 6 is.
# In roosters line its asking ruby what 100 minus 25 times 3 modulus 4. Modulus meaning Divides left hand operand by right hand operand and returns remainder
puts "Hens #{25.0 + 30.0 / 6.0}"
puts "Roosters #{100.0 - 25.0 * 3.0 % 4.0}"
puts "Now I will count the eggs:"
#This line below is asking ruby to calcute the mathmatidcal equation below.
puts 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
puts "Is it true that 3 + 2 < 5 - 7?"
# The line below is asking ruby is 3 plus 2 less than 5 minus 7.
puts 3.0 + 2.0 < 5.0 - 7.0
puts "What is 3 + 2? #{3.0 + 2.0}"
puts "What is 5 - 7? #{5.0 - 7.0}"
puts "Oh, that's why it's false."
puts "How about some more."
# The three lines below are pretty self explanitory asking is 5 greater than -2.
# Or if 5 is greater or equal to -2.
# Or for the final one if 5 is less or equal to -2.
puts "Is it greater? #{5.0 > -2.0}"
puts "Is it greater or equal? #{5.0 >= -2.0}"
puts "Is it less or equal? #{5.0 <= -2.0}"
| true
|
9c187e20cc273e24ca8e9d88d4deb4a255da3b6e
|
Ruby
|
alexHampton/Ruby
|
/Ruby/rspec_and_tdd/TDD_projects/spec/projects_spec.rb
|
UTF-8
| 5,235
| 3.859375
| 4
|
[] |
no_license
|
require 'rspec'
require 'projects.rb'
describe Array do
subject(:array) { Array.new }
describe '#my_uniq' do
let(:array) { [1,2,3,2,4,5,5] }
it 'takes in an Array and returns a new array' do
expect(array.my_uniq.class).to be(Array)
end
it 'contains every unique item of the original array' do
expect(array.my_uniq).to include(1, 2, 3, 4, 5)
end
it 'has only one of each unique item' do
expect(array.my_uniq).to eq([1,2,3,4,5])
end
end
describe '#two_sum' do
context 'with no matching pairs whose sum equals 0' do
let(:array) { [-2, 0, 1, 3] }
it 'returns an empty array' do
expect(array.two_sum).to eq([])
end
end
context 'with matching pairs whose sum equals 0' do
let(:array) { [-2, -1, 0, 1, 2] }
it 'returns a 2-dimensional array' do
expect(array.two_sum.length).to eq(2)
expect(array.two_sum.flatten.length).to eq(4)
end
it 'returns matching indexes' do
expect(array.two_sum).to eq([ [0, 4], [1, 3] ])
end
it 'is sorted smaller index to bigger index' do
expect([-1, -2, 2, 0, 1].two_sum).to eq([[0, 4], [1, 2]])
end
end
end
describe '#my_transpose' do
subject(:array) {
[
[0,1,2],
[3,4,5],
[6,7,8]
]
}
it 'returns an array' do
expect(array.my_tranpose.class).to eq(Array)
end
it 'has the same length as the original array' do
expect(array.my_tranpose.length).to eq(3)
end
it 'converts rows to columns and vice versa' do
expect(array.my_tranpose).to eq([
[0,3,6],
[1,4,7],
[2,5,8]
])
end
end
describe '#stock_picker' do
let(:array) { [15.46, 21.12, 8.00, 8.23, 17.92, 16.48, 16.54, 17.00, 24.24, 10.17, 14.17] }
let(:mixed_array) { array.reverse }
it 'returns an array of two elements' do
expect(array.stock_picker.length).to eq(2)
end
it 'returns the index representing the days of the stock prices' do
expect(array.stock_picker[0].class).to eq(Integer)
end
it 'returns the index representing the days of the stock prices' do
expect(array.stock_picker[1].class).to eq(Integer)
end
it 'gives the days that would make the biggest profit' do
expect(array.stock_picker).to eq([2,8])
end
it "doesn't take higher prices from previous days" do
expect(mixed_array.stock_picker).to eq([1, 2])
end
end
end
describe TowersOfHanoi do
subject(:game) { TowersOfHanoi.new }
describe '#initialize' do
it 'has array @pieces' do
expect(game.pieces.class).to eq(Array)
end
it 'contains a number representing each pieces in @pieces' do
expect(game.pieces).to eq([3,2,1])
end
it 'initializes the game with a @towers array' do
expect(game.towers.class).to eq(Array)
end
it 'places the pieces in the first tower, in descending order' do
expect(game.towers).to eq([[3,2,1], [], []])
end
end
describe '#move' do
it 'takes in a starting tower and an ending tower as arguments' do
expect { game.move(1, 2)}.not_to raise_error
end
it 'moves the top piece from one tower to the selected tower' do
game.move(1,2)
expect(game.towers).to eq([[3, 2], [1], []])
end
end
describe '#valid_move?' do
it 'takes in a starting tower and and ending tower as arguments' do
expect { game.valid_move?(1, 2) }.not_to raise_error
end
it 'does not allow moving from empty tower' do
expect(game.valid_move?(3, 2)).to eq(false)
end
it 'always allows moving to an empty tower' do
expect(game.valid_move?(1, 2)).to eq(true)
end
it 'does not allow moving onto a smaller disk' do
game.move(1, 2)
expect(game.valid_move?(1, 2)).to eq(false)
end
it 'allows all other moves' do
game.move(1, 2)
game.move(1, 3)
expect(game.valid_move?(2, 3)).to eq(true)
end
end
describe '#won?' do
it 'is not won if any piece is not on tower 3' do
game.move(1, 3)
game.move(1, 2)
game.move(3, 2)
game.move(1, 3)
game.move(2, 1)
game.move(2, 3)
expect(game.won?).to eq(false)
end
it 'is won when all pieces are on tower 3' do
game.move(1, 3)
game.move(1, 2)
game.move(3, 2)
game.move(1, 3)
game.move(2, 1)
game.move(2, 3)
game.move(1, 3)
expect(game.won?).to eq(true)
end
end
end
| true
|
54ce85fdb9530238dd131d84313c7a5a8fc368cd
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/src/1364.rb
|
UTF-8
| 139
| 2.90625
| 3
|
[] |
no_license
|
def compute(first, second)
first.chars
.zip(second.chars)
.reject(&LEFTOVER_CHARS)
.count(&DIFFERENT_PAIRS)
end
end
| true
|
ff00b42dc45db4b20937d05ed98349d211cdcd9c
|
Ruby
|
pofystyy/codewars
|
/6 kyu/create_a_frame.rb
|
UTF-8
| 1,015
| 3.921875
| 4
|
[] |
no_license
|
# https://www.codewars.com/kata/5672f4e3404d0609ec00000a
# Details:
# *************************
# * Create a frame! *
# * __ __ *
# * / \~~~/ \ *
# * ,----( .. ) *
# * / \__ __/ *
# * /| (\ |( *
# * ^ \ /___\ /\ | *
# * |__| |__|-.. *
# *************************
# Given an array of strings and a character to be used as border, output the frame with the content inside.
# Notes:
# Always keep a space between the input string and the left and right borders.
# The biggest string inside the array should always fit in the frame.
# The input array is never empty.
# Example
# frame(['Create', 'a', 'frame'], '+')
# Output:
# ++++++++++
# + Create +
# + a +
# + frame +
# ++++++++++
def frame(text, char)
max = text.map { |i| i.length }.max
frame = char * (max + 4)
text.map do |i|
wh = ' ' * (max - i.length).abs
"#{char} #{i} #{wh}#{char}"
end.unshift(frame).push(frame).join("\n")
end
| true
|
1c8341eb96f54b4ac76b2841f16dbd8789241150
|
Ruby
|
sclinede/ruby-patterns
|
/singleton.rb
|
UTF-8
| 419
| 3.265625
| 3
|
[] |
no_license
|
# Define an unique instance of an object
class HeroFactory
@@instance = nil
def self.instance
@@instance ||= HeroFactory.send(:new)
end
def create_warrior
Warrior.new
end
def create_mage
Mage.new
end
private_class_method :new
end
# Usage
factory = HeroFactory.instance
another_factory = HeroFactory.instance
puts factory == another_factory
# => true
HeroFactory.new
# => Raise Exception
| true
|
1cc6e73d04c5edce2d62d227dbe17a33187e384b
|
Ruby
|
brentvatne/jester
|
/spec/requests/remember_story_spec.rb
|
UTF-8
| 978
| 2.65625
| 3
|
[] |
no_license
|
describe Jester::Request::RememberStory do
include MailTestHelpers
describe "handling" do
let(:invalid_message) { email(:subject => 'some invalid string') }
let(:fishing) { email(:subject => "a funny story 'the time i went fishing from a helicopter'" ) }
subject { Jester::Request::RememberStory }
it "should not handle an incorrect request string" do
subject.handle(invalid_message).should be_nil
end
it "should handle a request string" do
subject.handle(fishing).should be_a(subject)
end
it "should allow quotations between the quotations" do
quotations = email(:subject => "a funny story 'let's try this'")
subject.handle(quotations).should be_a(subject)
end
it "correctly handles the arguments" do
request_object = subject.handle(fishing)
request_object.story.type.should == "funny"
request_object.story.title.should == "the time i went fishing from a helicopter"
end
end
end
| true
|
f93730815becff334401ad02b430ee7c7337870b
|
Ruby
|
nkokkos/ruby-locklizard
|
/lib/locklizard/helper_methods.rb
|
UTF-8
| 1,332
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module HelperMethods
# include LockLizardEndPoints constants as constants to the following methods
include LockLizardEndPoints
#helper methods:
def success?(response = nil)
raise ArgumentError if response.nil?
response.to_str.split("\n").first.gsub(/\n/,'') == SUCCESS
end
def failed?(response = nil)
raise ArgumentError if response.nil?
response.to_str.split("\n").first.gsub(/\n/,'') == FAILED
end
# clean respone
def clean_response(response)
raise "Not Implemented"
end
private
def admin_url
#"?un=" + URI.escape(@admin) + "&pw=" + CGI.escape(@password)
"?key=#{@access_key}"
end
def base_url
@locklizard_base_url
end
# Call final target url after having build the whole final url link.
# This method raises an HTTP::Error exception, therefore
# we need to catch the exception at controller level:
# In controller we need to do this:
# def mycontroller
# begin
# response = call_target_url(url)
# rescue HTTP::Error => e
# "Exception Occurred: #{e}. Message: #{e.message}. Backtrace: \n #{e.backtrace.join("\n")}"
# end
# end
def call_target_url(target)
http = HTTP.timeout(connect: 60, read: 60)
http.get "#{base_url}#{admin_url}#{target}"
end
end
| true
|
278c49e7576282604eeda230c97d26db1155b7e6
|
Ruby
|
zeuslopesqa/RubyCucumberCapybara-trivago_project
|
/features/support/pages/home_page.rb
|
UTF-8
| 1,360
| 2.609375
| 3
|
[] |
no_license
|
require 'securerandom'
class HomePage
include Capybara::DSL
def go
visit ""
end
def click_contact
find('a', text: 'Contact').click
end
def fill_email_newsletter()
#"SecureRandom.alphanumeric(8) + '@mailinator.com'" is afunction to
# generatic an random email and avoid flaky tests
find('.et-email').set SecureRandom.alphanumeric(8) + '@mailinator.com'
end
def fill_invalid_email(invalid_email)
find('input[name=email]').set invalid_email
end
def click_submit_news
find('.submit').click
end
def find_subscribed_success
find('.submitted').text
end
def find_subscribed_error
find('.et-email-error').text
end
def click_menu_top_left
find('.nav-icon').click
end
def click_destination_menu
find('#menu > div > div > div:nth-child(1) > div.menu-expand-header > div > div').click
end
#I made this function only to return the value selected to compare with the page opened in sequence.
def return_first_dest
destination = first('.destination-menu')
result = destination.text
end
def select_1stdestination
destination = first('.destination-menu')
result = destination.text
destination.click
end
end
| true
|
1db37a5d618d12565fc63a9dd2f7f20c68187947
|
Ruby
|
cielavenir/procon
|
/hackerrank/grid-challenge.rb
|
UTF-8
| 130
| 2.921875
| 3
|
[
"0BSD"
] |
permissive
|
#!/usr/bin/ruby
gets.to_i.times{
a=gets.to_i.times.map{gets.chomp.chars.sort}.transpose
puts a.all?{|e|e.sort==e} ? :YES : :NO
}
| true
|
5b06b28420988985e25a7735806889abd7739ddf
|
Ruby
|
Haysonho/programming-exercise
|
/22-missing.rb
|
UTF-8
| 280
| 3.953125
| 4
|
[] |
no_license
|
# 给定一阵列内含数字,请输出 0~9 中不见的数字
def find_missing(arr)
missing_num = []
(0..9).each do |i|
missing_num << i unless arr.include?(i)
end
missing_num
end
answer = find_missing( [2,2,1,5,8,4] )
puts answer.to_s # 应该是 [0,3,6,7,9]
| true
|
fa10fa566adae17e9989c1bff17e5d2e0ea3b87d
|
Ruby
|
Fish-bowl/ruby-golf
|
/hole_2.rb
|
UTF-8
| 716
| 3.578125
| 4
|
[] |
no_license
|
require 'pry'
# def rps
#gets player choice
# choice = gets.chop
#sets comp selection choices
# @cs = random.new
# @cs = %w[r p s].sample
# binding.pry
# to_assoc(1)
# @index = @cs.index(@cs)
# @winning_choice = @index[@index - 1]
# binding.pry
# (choice == @cs) ? (exit) : (choice == @winning_choice) ? (puts "w") : (puts "L")
# if @choice == @cs
# puts "T"
# elsif @choice == @winning_choice
# puts "W"
# else
# puts "L"
# end
# end
# rps
# beat 122
puts "r=0, p=1, s=2"
def rps
o = {?r => 0, ?p => 1, ?s => 2}
c = gets.to_i #42
s = o.values.sample
w = o.values.index(s - 1)
((c == s) ? (exit) : (c == w)) ? (puts ?w) : (puts ?L)
end
#110
rps
| true
|
3416506e481b5994a1a22afe72df6f765aaa2951
|
Ruby
|
brandonbrown4792/furry-finder
|
/app/ui_methods/shelter_menu.rb
|
UTF-8
| 2,031
| 3.609375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def shelter_menu(shelter)
choices = ["View Profile", "Update Shelter Name", "Update Shelter Address", "Add Dog", "Update Dog", "Logout"]
choice = PROMPT.select("Select an option below:", choices)
case choice
when "View Profile"
shelter_view_profile(shelter)
when "Update Shelter Name"
shelter_update_name_menu(shelter)
when "Update Shelter Address"
shelter_update_address_menu(shelter)
when "Add Dog"
shelter_add_dog_menu(shelter)
when "Update Dog"
shelter_select_dog_to_update_menu(shelter)
when "Logout"
logout
end
end
def shelter_view_profile(shelter)
puts ""
puts "Shelter Profile:"
puts "Name: #{shelter.name}"
puts "Address: #{shelter.address}"
puts "Press enter to return to Main Menu"
gets.chomp
end
def shelter_update_name_menu(shelter)
puts ""
puts "Enter the new shelter name"
shelter.update_name(PROMPT.ask("Name:"))
end
def shelter_update_address_menu(shelter)
puts ""
puts "Enter the shelter address"
shelter.update_address(PROMPT.ask("Address:"))
end
def shelter_add_dog_menu(shelter)
name = get_dog_name
age = get_dog_age
breed = get_dog_breed
traits = select_traits
shelter.add_dog(name, age, breed, traits)
end
def shelter_select_dog_to_update_menu(shelter)
dogs = shelter.dogs
puts ""
choice = PROMPT.select("Select which dog you would like to update") do |menu|
dogs.each_with_index do |d, i|
menu.choice "#{d.name} the #{d.breed}", i
end
end
update_dog_shelter_menu(dogs[choice])
end
def update_dog_shelter_menu(dog)
puts ""
choices = ["Name", "Age", "Breed", "Traits", "Back to Main Menu"]
choice = PROMPT.select("What would you like to update?", choices)
case choice
when "Name"
puts "Enter the dog's name"
dog.update_name(get_dog_name)
when "Age"
puts "Enter dog age"
dog.update_age(get_dog_age)
when "Breed"
puts "Select dog breed"
dog.update_breed(get_dog_breed)
when "Traits"
puts "Select dog traits"
dog.update_traits(select_traits)
end
end
| true
|
1d5d9525e7c2f6fb778c5cfa0e5626313a62998f
|
Ruby
|
aniltimt/finna-be-octo-hipster
|
/app/models/app_config.rb
|
UTF-8
| 479
| 2.609375
| 3
|
[] |
no_license
|
class AppConfig < ActiveRecord::Base
class << self
def [](key)
pair = find_by_key(key)
pair.value unless pair.nil?
end
def []=(key, value)
pair = find_by_key(key)
unless pair
pair = new
pair.key, pair.value = key, value
pair.save
else
pair.value = value
pair.save
end
value
end
def to_hash
Hash[ *all.map { |pair| [pair.key, pair.value] }.flatten ]
end
end
end
| true
|
bd7a673c635d1425d0a98ebb212eed962282a322
|
Ruby
|
Encolpius/ruby-building-blocks
|
/stock-picker/stock-picker.rb
|
UTF-8
| 486
| 3.4375
| 3
|
[] |
no_license
|
def stock_picker(days)
buy_sell = []
$sum = 0
def stock(days, sub_days, sum, buy_sell)
temp = sub_days.map { |day| day - sub_days[0]}.max
if temp > $sum
buy_sell[0] = days.index(sub_days.min)
buy_sell[1] = days.index(sub_days.max)
$sum = temp
end
return $sum
end
while days.length > 1
sub_days = days.values_at(days.index(days.min)..-1)
stock(days, sub_days, $sum, buy_sell)
days.delete(days.min)
end
return buy_sell
end
| true
|
96d8fdef352c74d9968f2a2c4db06988e477a775
|
Ruby
|
ddrscott/heart_of_five
|
/lib/heart_of_five/meld.rb
|
UTF-8
| 2,531
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
module HeartOfFive
class Meld
attr_reader :cards, :strength
def initialize(cards)
@cards = cards
end
def two_of_a_kind?
@two_of_a_kind ||= x_of_a_kind?(2)
end
def three_of_a_kind?
@three_of_a_kind ||= x_of_a_kind?(3)
end
def four_of_a_kind?
@four_of_a_kind ||= x_of_a_kind?(4)
end
def sisters?
@sisters ||= pairable? &&
multiple_groups? &&
sequential_groups? &&
same_sized_groups? &&
first_group.size > 1
end
# 1,2,3,4,5,6,7,8,9,10,11,12,13,1
# A 2 3 4 5 6 7 8 9 T J Q K A
def run?
return false unless pairable? && num_groups > 4
@run ||= if sequential_groups? && same_sized_groups? && first_group.size == 1
true
elsif aces?
# funky logic, Aces can be low or high card
# convert one ace to #14
as_ace_high.run?
else
false
end
end
def aces?
@aces ||= cards.detect{|r,s| r == 1}
end
def multiple_groups?
num_groups > 1
end
def num_groups
group_by_rank.size
end
def sequential_groups?
return false unless group_by_rank.any?
(group_by_rank.keys.max - group_by_rank.keys.min) == (num_groups - 1)
end
def first_group
@first_group ||= begin
_, fs = *group_by_rank.first
fs
end
end
def same_sized_groups?
return false unless first_group
# check all groups are the same size
group_by_rank.all?{|g, gs| gs.size == first_group.size}
end
private
def jokers?
@jokers ||= cards.any?{|r,s| s > 4}
end
def pairable?
!jokers?
end
def x_of_a_kind?(x)
cards.size == x && pairable? && cards.group_by{|r,s| r}.all?{|g, gs| gs.size == x}
end
def group_by_rank
@group_by_rank ||= cards.group_by{|r, s| r}
end
# Return a new Meld with a single Ace value changed
# from low to high. Useful for detecting a run with
# and Ace at the end.
#
# Only do this for the first Ace it finds. So a run
# can start and end with an Ace.
#
# This may return a Meld with no material change if
# there's no Ace to upgrade.
def as_ace_high
first = true
ace_high = cards.map do |rank, suit|
if rank == 1 and first
first = false
[14, suit]
else
[rank, suit]
end
end
Meld.new(ace_high)
end
end
end
| true
|
854fdd24a13d36ad68ebbc208d154bcaf6ffd1e9
|
Ruby
|
Payal13/training_assignments
|
/Ashish/day3/new_symbol_test.rb
|
UTF-8
| 396
| 2.75
| 3
|
[] |
no_license
|
class No
attr_reader :No
attr_reader :Not
def initialize
@@Not = 120
@No = 10
end
def self.Not
" This is not method #{:Not.object_id}"
end
def No
print :No.object_id
puts "\n This not variable "+ @@Not.to_s
print " It is from Symbol_Test "
@No
end
end
s = No.new
p No.Not
p s.No
p s.No
p s.No
p No.Not
p " Outside any Class #{:No.object_id}"
| true
|
b4183c37d8dd453820f5b531f7450fc03521cede
|
Ruby
|
frop/Parsoca
|
/app/models/time_bank.rb
|
UTF-8
| 1,853
| 2.625
| 3
|
[] |
no_license
|
class TimeBank < ActiveRecord::Base
belongs_to :user
def self.from_hours(hours)
h,m = hours.split(":")
if h.to_i > 0
h.to_i * 60 + m.to_i
else
h.to_i * 60 - m.to_i
end
end
def self.calculate(user, current_interval)
last_time_bank = user.time_banks.where('date < ?', current_interval.start).order('date DESC').first
last_time_bank_value = (last_time_bank.nil?) ? (user.basic.time_bank || 0) : last_time_bank.value
date = current_interval.start.to_date.to_formatted_s(:db)
current_time_bank = user.time_banks.find(:first, :conditions => ["DATE(date) = ?", current_interval.start.to_date])
if current_time_bank.nil? #abrindo banco para hoje
new_time_bank = user.time_banks.new
new_time_bank.date = current_interval.start
new_time_bank.value = last_time_bank_value - user.basic.daily_hours # desconta a jornada do banco se foi o primeiro intervalo do dia
else #editando banco
new_time_bank = current_time_bank
end
puts new_time_bank.value
new_time_bank.value += current_interval.amount unless current_interval.amount.nil?
puts new_time_bank.value
puts "--"
new_time_bank.save
end
# TODO REFACTOR!!!
def self.recalculate(user, interval)
date = interval.start.to_date
user.time_banks.find(:all, :conditions => ['DATE(date) >= ?', date]).each { |t| t.destroy } # deleta todos pra frente pra recalcular
user.intervals.find(:all, :order => 'start ASC', :conditions => ['DATE(start) >= ?', date]).each { |i|
self.calculate(user, i)
}
# user.time_banks.find(:all, :conditions => ['DATE(date) >= ?', date]).each { |t|
# if user.intervals.find(:all, :conditions => ['DATE(start) > ?', t.date.to_date]).count > 0
# t.value -= amount
# t.save
# else
# t.destroy
# end
# }
end
end
| true
|
00480bad9cd64078d26a53e367e8c6feae1b94a4
|
Ruby
|
rmwerner18/ruby-enumerables-hash-practice-emoticon-translator-lab-nyc01-seng-ft-071320
|
/lib/translator.rb
|
UTF-8
| 914
| 3.21875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'yaml'
require 'pry'
def load_library(file)
emoticons = YAML.load_file(file)
keys = emoticons.keys
count = 0
while count < keys.length do
emoticons[keys[count]] = {english: emoticons[keys[count]][0], japanese: emoticons[keys[count]][1]}
count += 1
end
emoticons
end
def get_japanese_emoticon(file, emoticon)
emoticons = load_library(file)
keys = emoticons.keys
count = 0
while count < keys.length do
if emoticons[keys[count]][:english] == emoticon
return emoticons[keys[count]][:japanese]
end
count += 1
end
return "Sorry, that emoticon was not found"
end
def get_english_meaning(file, emoticon)
emoticons = load_library(file)
keys = emoticons.keys
count = 0
while count < keys.length do
if emoticons[keys[count]][:japanese] == emoticon
return keys[count]
end
count += 1
end
return "Sorry, that emoticon was not found"
end
| true
|
2906926a9f9cf1014b2b7ea2d286981bce96c7a3
|
Ruby
|
jsuabur/libro-de-actividades
|
/actividades/prog/files/ruby/empezando/lib/02.clases/clases02.rb
|
UTF-8
| 364
| 3.984375
| 4
|
[
"CC0-1.0",
"CC-BY-SA-3.0"
] |
permissive
|
#!/usr/bin/ruby
puts "[#{$0}] Antes de definir la clase animal"
class Animal
puts " [Clase Animal] Estamos dentro"
attr_accessor :nombre
def info
puts "Hola soy Animal: "+@nombre
end
puts " [Clase Animal] Saliendo de dentro de la clase animal"
end
puts "[#{$0}] Después de definir la clase animal\n\n"
a = Animal.new
a.nombre = "Gato"
a.info
| true
|
4df9d50a34482284b50e701954461689b86e60bf
|
Ruby
|
codeforamerica/data-portal-info-collector
|
/data_portal_info_collector/csv_to_json.rb
|
UTF-8
| 792
| 2.59375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'csv'
require 'json'
places_array = []
state_hash = {}
CSV.foreach("lib/states.csv", { :col_sep => "\t" }) do |row|
state_hash[row[2]] = row[8] if row[8] != "Name"
end
CSV.foreach("lib/counties.csv", { :col_sep => "\t" }) do |row|
county_fips = "#{row[2]}#{row[4]}"
places_array << "#{row[8]}, #{state_hash[row[2]]} (#{county_fips})" if row[8] != "Name"
end
CSV.foreach("lib/places.csv", { :col_sep => "\t" }) do |row|
place_fips = "#{row[2]}#{row[3]}"
places_array <<"#{row[8]}, #{state_hash[row[2]]} (#{place_fips})" if row[8] != "Name"
end
CSV.foreach("lib/states.csv", { :col_sep => "\t" }) do |row|
places_array << "#{row[8]} (#{row[2]})" if row[8] != "Name"
end
File.open("static/places.js", "w") { |f| f.write(places_array.to_json
) }
| true
|
7d89ad2d5c532d1923f4ce411071c767b0538905
|
Ruby
|
dkelly205/ruby_animal_shelter_project2
|
/db/seeds.rb
|
UTF-8
| 1,166
| 2.625
| 3
|
[] |
no_license
|
require_relative('../models/animal.rb')
require_relative('../models/customer.rb')
require_relative('../models/adoption.rb')
Customer.delete_all
Animal.delete_all
customer1 = Customer.new({
'name' => 'John Smith',
'address' => '10 Crow Road, Glasgow, G10 6PP',
'phone_number' => '01411111111'
})
customer1.save
animal1 = Animal.new({
'name' => 'Alfie',
'type' => 'dog',
'breed' => 'shitzu',
'admission_date' => '08-Jan-2018',
'adoptable' => true,
'image' => 'shitzu.jpeg',
'incare' => false
})
animal1.save
animal2 = Animal.new({
'name' => 'Whizz',
'type' => 'dog',
'breed' => 'whippet',
'admission_date' => '08-Jan-2018',
'adoptable' => true,
'image' => 'whippet.jpeg',
'incare' => false
})
animal2.save
animal3 = Animal.new({
'name' => 'Rocky',
'type' => 'dog',
'breed' => 'rottweiller',
'admission_date' => '08-Jan-2018',
'adoptable' => true,
'image' => 'rottweiler.jpeg',
'incare' => true
})
animal3.save
adoption1 = Adoption.new({
'animal_id' => animal1.id,
'customer_id' => customer1.id
})
adoption1.save
| true
|
71f60e2014cd24f1beb9abde8d8add37c488b8e1
|
Ruby
|
SRBusiness/grocery-store
|
/specs/online_order_spec.rb
|
UTF-8
| 4,935
| 2.59375
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/reporters'
require 'minitest/skip_dsl'
require 'minitest/pride'
require 'pry'
require_relative '../lib/online_order'
require_relative '../lib/customer'
describe "OnlineOrder" do
before do
@online_order_one = Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25,"complete")
@online_order_two = Grocery::OnlineOrder.new(2,{}, 26,"pending")
@customer_first = Grocery::Customer.new(25, "leonard.rogahn@hagenes.org", {address1: "71596 Eden Route" , city: "Connellymouth" , state: "LA", zip_code: "98872-9105" })
@online_orders = Grocery::OnlineOrder.all
end
describe "#initialize" do
it "Is a kind of Order" do
@online_order_one.must_be_kind_of Grocery::Order
end
it "Can access Customer object" do
@online_order_one.customer_id.must_equal @customer_first.customer_id
end
it "Can access the online order status, Order ID, products, and customer id" do
@online_order_one.must_respond_to :status
@online_order_one.must_respond_to :id
@online_order_one.must_respond_to :customer_id
@online_order_one.must_respond_to :products
end
it "Default status for and order is pending" do
order_with_no_status = Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25)
order_with_no_status.status.must_equal :pending
end
end # End of describe "#initialize"
describe "#total" do
it "Adds a shipping fee" do
@online_order_one.total.must_equal 180.68
end
it "Doesn't add a shipping fee if there are no products" do
@online_order_two.total.must_equal 0
end
end #end of describe "total"
describe "#add_product" do
it "Does not permit action for processing, shipped or completed statuses" do
proc{Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25,"processing").add_product("Macadamia Nut",79.19)}.must_raise ArgumentError
proc{Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25,"shipped").add_product("Macadamia Nut",79.19)}.must_raise ArgumentError
proc{Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25,"complete").add_product("Macadamia Nut",79.19)}.must_raise ArgumentError
end
it "Permits action for pending and paid satuses" do
#@online_order_two status = pending, has no product so products. length = 0, when we add a product length should equal 1
@online_order_two.add_product("Macadamia Nut",79.19)
after = @online_order_two.products.length
after.must_equal 1
after = Grocery::OnlineOrder.new(1,{"Lobster" =>17.18, "Annatto seed" => 58.38, "Camomile" =>83.21}, 25,"paid")
after.add_product("Macadamia Nut",79.19)
after.products.length.must_equal 4
end
end # end of describe "#add_product"
describe "OnlineOrder.all" do
it "Everything in the array is an Order" do
@online_orders.each do |order|
order.must_be_kind_of Grocery::OnlineOrder
end
end
it "OnlineOrder.all returns an array" do
@online_orders.must_be_kind_of Array
end
it "The number of online orders is correct (100)" do
@online_orders.length.must_equal 100
end
#The wording on this prompt and the next is vauge. I'm not sure this test is targeted at extracting/working with the approptiate information
it "The customer is present - Raises and error if the customer ID doesn't exist" do
@online_orders.each do |order|
order.customer_id.wont_be_empty
end
end
it "The status is present - all users have a status AKA default parameter value works" do
@online_orders.each do |order|
order.status.wont_be_empty
end
end
end
describe "OnlineOrder.find(ID)" do
it "Can find the first order from the CSV" do
Grocery::OnlineOrder.find(1).must_be_same_as @online_orders.first
end
it "Can find the last order from the CSV" do
Grocery::OnlineOrder.find(100).must_be_same_as @online_orders.last
end
it "Raises an error for an order that doesn't exist" do
proc{Grocery::OnlineOrder.find(107)}.must_raise ArgumentError
end
end #end of "OnlineOrder.find(id)"
describe "OnlineOrder.find_by_customer" do
it "Returns an array of online orders for a specific customer ID" do
Grocery::OnlineOrder.find_by_customer(29).must_be_kind_of Array
end
it "Can access all the orders for a customer" do
customer_orders_array = Grocery::OnlineOrder.find_by_customer(5)
customer_orders_array.length.must_equal 1
end
it "Raises an error for an customer id that doesn't exist" do
proc{Grocery::OnlineOrder.find_by_customer(1009)}.must_raise ArgumentError
end
end #end of "OnlineOrder.find_by_customer"
end #end of "OnlineOrder"
| true
|
d2822f22b388d5e05f5a039c9a0692768e3301e7
|
Ruby
|
IsaacHardy/blackjack_with_ruby
|
/lib/card.rb
|
UTF-8
| 601
| 3.921875
| 4
|
[] |
no_license
|
require_relative "game"
class Card
RANKS = [:A, 2, 3, 4, 5, 6, 7, 8, 9, 10, :J, :Q, :K]
SUITS = [:clubs, :diamonds, :hearts, :spades]
attr_reader :rank, :suit, :value
def initialize(rank, suit)
@rank = rank
@suit = suit
@value = card_value
end
def greater_than?(other)
RANKS.index(self.rank) > RANKS.index(other.rank)
end
def ==(other)
self.rank == other.rank && self.suit == other.suit
end
def card_value
if @rank == :A
return 11
elsif @rank == :J || @rank == :Q || @rank == :K
return 10
else
return @rank
end
end
end
| true
|
88525cbdbaf83adb54033370c296956a1b9422bc
|
Ruby
|
Jwan622/ruby_turing_lesssons
|
/module_1_lessons/REPL/repl_lesson.rb
|
UTF-8
| 1,040
| 3.421875
| 3
|
[] |
no_license
|
# def repl(instream, outstream)
# loop do
# #read
#
# #print prompt
# outstream.print "> " #print to whatever local variable outstream is pointing at
#
# # read
# input = instream.gets
#
# #eval
# result = eval(input)
#
# #print
# outstream.puts(result.inspect)
#
# #loop
# end
# end
# repl($stdin, $stdout)
#
# def get_next_line
# line1 = gets
# line2 = $stdin.gets
# puts "FIRST LINE IS: #{line1}"
# puts "SECOND LINE IS: #{line2}"
# end
# require 'pry'
# binding.pry
#
# def get_next_line_from(stream)
# line = stream.gets
# puts "LINE IS: #{line}"
# end
# require 'pry'
# binding.pry
#
# def upcase_the_input
# input = gets
# input.upcase
# end
# require "pry"
# binding.pry
#
# def upcase_the_input(stream)
# input = stream.gets
# input.upcase
# end
# require "pry"
# binding.pry
def repl(input_stream, output_stream)
loop do
output_stream.print "> "
input = input_stream.gets()
result = binding.eval(input)
output_stream.puts(result)
end
end
| true
|
fb2b16ae8ffcc306761f94de47cea20938d64e00
|
Ruby
|
nahi/examples
|
/jjug-indy-2012/2_benchmark/6_math.rb
|
UTF-8
| 117
| 2.734375
| 3
|
[] |
no_license
|
require 'benchmark'
a = 44
6.times do
puts Benchmark.measure {
10000000.times do
a - 2
end
}
end
| true
|
ec6c80e22b3c9302eb6eb8c012f09dc309f53eaa
|
Ruby
|
keisuke0831/furima-31145
|
/spec/models/purchase_customer_spec.rb
|
UTF-8
| 2,968
| 2.53125
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe PurchaseCustomer, type: :model do
before do
@purchase_customer = FactoryBot.build(:purchase_customer)
end
describe '購入情報の保存' do
context '購入情報の保存ができる場合' do
it 'すべての値が正しく入力されていれば保存できること' do
expect(@purchase_customer).to be_valid
end
it '建物の名前は空でも保存できること' do
@purchase_customer.building_name = nil
expect(@purchase_customer).to be_valid
end
end
context '購入情報の保存ができない場合' do
it '郵便番号が空だと保存できないこと' do
@purchase_customer.postal_code = ''
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("Postal code can't be blank")
end
it '郵便番号がハイフンを含む必要があること' do
@purchase_customer.postal_code = 1_234_567
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include('Postal code is invalid. Include hyphen(-)')
end
it '都道府県の情報を選択していないと保存できないこと' do
@purchase_customer.prefecture_id = ''
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("Prefecture can't be blank")
end
it '都道府県の情報のidが1では保存出来ないこと' do
@purchase_customer.prefecture_id = 1
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include('Prefecture must be other than 1')
end
it '市区町村が空だと保存できないこと' do
@purchase_customer.city = ''
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("City can't be blank")
end
it '番地が空だと保存できないこと' do
@purchase_customer.address = ''
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("Address can't be blank")
end
it '電話番号が空だと保存できないこと' do
@purchase_customer.phone_number = ''
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("Phone number can't be blank")
end
it '電話番号が11桁以内の半角数字(ハイフンなし)でないと保存できないこと' do
@purchase_customer.phone_number = 111_111_111_111
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include('Phone number is invalid')
end
it 'tokenが空では登録できないこと' do
@purchase_customer.token = nil
@purchase_customer.valid?
expect(@purchase_customer.errors.full_messages).to include("Token can't be blank")
end
end
end
end
| true
|
88212d486c585cba6721c480d9c6de55455b4407
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/bob/f366fcea584544ef8ec021ad0e46775d.rb
|
UTF-8
| 1,429
| 3.984375
| 4
|
[] |
no_license
|
# Thanks for your nitpicks tennety. I've addressed each in comments below.
class Bob
def hey(comment)
# I had actually considered using Enumerable#detect at first, but I was put off by having to make Response#responds?
# a class method. However, I hadn't considered the ifnone parameter you can pass to #detect, and upon introspection
# I realized this helps mitigate the fact that order matters in the Array in the previous version. Thank you!
reply = [Responses::Silence, Responses::Shout, Responses::Question].detect(lambda { Responses::Default }) do |response|
# I'm casting the comment to a string here instead of the nil check in the Response, good call.
response.responds?(comment.to_s)
end
reply.new.text
end
end
class Responses
class Default
def self.responds?(comment)
true
end
def text
"Whatever."
end
end
class Question
def self.responds?(comment)
# I don't know why I didn't know about this method - maybe I did but just forgot. Either way, thank you so much!
comment.end_with?("?")
end
def text
"Sure."
end
end
class Shout
def self.responds?(comment)
comment == comment.upcase
end
def text
"Woah, chill out!"
end
end
class Silence
def self.responds?(comment)
comment.strip.empty?
end
def text
"Fine. Be that way!"
end
end
end
| true
|
f4ff05d3efa69e12d6417917d3add29c5acc2305
|
Ruby
|
melriffe/AdventOfCode2020
|
/spec/day-12/rain_risk_spec.rb
|
UTF-8
| 895
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require './lib/day_12'
RSpec.describe 'Day 12: Rain Risk' do
let(:test_data) do
[
'F10',
'N3',
'F7',
'R90',
'F11'
]
end
let(:fixture) { File.join fixtures_path, 'day_12.data' }
let(:fixture_data) { [] }
before do
File.readlines(fixture).each do |line|
fixture_data << line.chomp
end
end
context 'Examples' do
let(:model) { Day12.new test_data }
it 'finds the Manhattan distance' do
expect(model.exercise1).to eq 25
end
it 'finds the Manhattan distance' do
expect(model.exercise2).to eq 286
end
end
context 'Exercises' do
let(:model) { Day12.new fixture_data }
it 'finds the Manhattan distance' do
expect(model.exercise1).to eq 562
end
it 'finds the Manhattan distance' do
expect(model.exercise2).to eq 101860
end
end
end
| true
|
413edeee94bbfbde04d02a3362d2d63a46d91528
|
Ruby
|
KevinDTran/my-first-hash-001-prework-web
|
/my_first_hash.rb
|
UTF-8
| 803
| 2.96875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def my_hash
my_hash = {"key" => "value"}
# use the literal constructor to set the variable, my_hash, equal to a hash with key/value pairs of your choice.
end
def shipping_manifest
shipping_manifest = Hash.new(0)
shipping_manifest["whale bone corsets"] = 5
shipping_manifest["porcelain vases"] = 2
shipping_manifest["oil paintings"] = 3
return shipping_manifest
end
def retrieval
shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3}
x = shipping_manifest["oil paintings"]
return x
end
def adding
shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3}
shipping_manifest ['pearl necklace'] = 1
return shipping_manifest
#your code here
#remember to return the shipping_manifest hash
end
| true
|
a202f41e10cddfb543ca558b40e3a7bb5fac1cda
|
Ruby
|
arthur-littm/cookbook
|
/lib/controller.rb
|
UTF-8
| 703
| 3.0625
| 3
|
[] |
no_license
|
require_relative 'view'
require_relative 'recipe'
class Controller
def initialize(cookbook)
@cookbook = cookbook
@view = View.new
end
# user actions that your app has
def create
# ask for a recipe name
name = @view.ask_for('name')
# ask for a recipe description
description = @view.ask_for('description')
# create an instance of `Recipe`
recipe = Recipe.new(name, description)
# sending the recipe to the cookbook
@cookbook.add_recipe(recipe)
end
def destroy
list
index = @view.ask_for('index').to_i - 1
@cookbook.remove_recipe(index)
end
def list
recipes = @cookbook.all
@view.display_recipes(recipes)
end
end
| true
|
66e640b0c998df58d7abce5c72a8da163957df98
|
Ruby
|
cpb/scad4r
|
/lib/scad4r/notification.rb
|
UTF-8
| 1,103
| 2.578125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Scad4r
class Notification
class << self
def parse(result)
if error = result.fetch(:error, false)
Array(new(error: error))
else
timings = if real = result.fetch(:real,nil)
new(success: real)
else
nil
end
Array(result.fetch(:warnings,nil)).map do |warning|
new(warning: warning)
end + Array(result.fetch(:echos,nil)).map do |echo|
new(echo: echo)
end + Array(timings)
end
end
end
attr_reader :message
def initialize(attributes={})
@type, @message = attributes.to_a.pop
end
def image
case @type
when :error
:error
when :warning
:error
when :echo, :success
:success
end
end
def title
"openscad #{@type.to_s.upcase}"
end
def priority
case @type
when :error
2
when :warning
1
when :echo
1
when :success
-1
end
end
end
end
| true
|
fcf37b203921c486dafc00f3cf711fff19928feb
|
Ruby
|
hamadanoor9/sample-doordash
|
/customer.rb
|
UTF-8
| 165
| 2.828125
| 3
|
[] |
no_license
|
require_relative "address"
class Customer
attr_reader :name, :address
def initialize(name, address)
@name= name
@address= address
end
end
| true
|
badf2fdc3a8dc0c0c74c9f300928d7012ba710df
|
Ruby
|
amcolling/reunion
|
/test/activity_test.rb
|
UTF-8
| 1,463
| 3.484375
| 3
|
[] |
no_license
|
require 'minitest'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/activity'
class ActivityTest < Minitest::Test
def test_it_exists
activity = Activity.new("hiking")
assert_instance_of Activity, activity
end
def test_activity_type
activity = Activity.new("hiking")
assert_equal ["hiking"], activity.type
end
def test_add_participants
activity = Activity.new("hiking")
activity.add_participant("Angi", 5)
activity.add_participant("Claire", 10)
activity.add_participant("Richard", 6)
activity.add_participant("Seth", 10)
expected = { "Angi" => 5, "Claire" => 10, "Richard" => 6, "Seth" => 10}
assert_equal expected, activity.participants
end
def test_activity_cost
activity = Activity.new("hiking")
activity.add_cost("hiking", 20)
assert_equal 20, activity.cost
end
def test_split_cost
activity = Activity.new("hiking")
assert_equal 5, activity.split_cost
end
end
# Iteration 2: Activity Calculations
#
# Add to the Activity class so that it supports the following functionality. Note, it is assumed that the cost of each activity is split evenly between all participants.
#
# You can split the cost of an activity
# You can evaluate out how much each person is owed/owes
# If a participant paid less than their fair share they owe a positive amount.
# If a participant paid more than their fair share they owe a negative amount (meaning they are owed money).
| true
|
cac041faded18e76e9037da063fdc5a805d28e51
|
Ruby
|
hackjackychan/les3_exos
|
/escalier2.rb
|
UTF-8
| 283
| 3.0625
| 3
|
[] |
no_license
|
if (ARGV.length != 1)
puts "#{File.basename(__FILE__)} requires one argument: #{File.basename(__FILE__)} number_of_steps"
exit
end
marche_nb = ARGV[0].to_i
i = 0
while (i < marche_nb)
print ' ' * (marche_nb - i - 1)
print "#" * (i + 1)
print "\n"
i += 1
end
| true
|
4a513df9c207f9198666d47877d9690456dcd7ea
|
Ruby
|
geronimo/spoj
|
/MIXTURES/matrix_chain.rb
|
UTF-8
| 1,162
| 3.390625
| 3
|
[] |
no_license
|
class Matrix
attr_accessor :columns, :rows
def initialize(rows, columns)
self.columns = columns
self.rows = rows
end
end
class Multiplicator
attr_accessor :chain, :costs, :p
def initialize(chain)
self.chain = chain
self.costs = []
(0...chain.size).each do |i|
self.costs[i] = []
self.costs[i][i] = 0
end
self.p = []
(0...chain.size).each do |i|
self.p[i] = self.chain[i].rows
end
self.p[chain.size] = chain[chain.size - 1].columns
end
def optimal_multiplication
n = p.size - 1
(2..n).each do |l|
(0..n - l).each do |i|
j = i + l - 1
self.costs[i][j] = 1 << 32
(i...j).each do |k|
tmp = self.costs[i][k] + self.costs[k+1][j] + (self.p[i] * self.p[k+1] * self.p[j+1])
if tmp < self.costs[i][j]
self.costs[i][j] = tmp
end
end
end
end
return self.costs[0][chain.size - 1]
end
end
test_case = [Matrix.new(30, 35), Matrix.new(35, 15), Matrix.new(15, 5), Matrix.new(5, 10), Matrix.new(10, 20), Matrix.new(20, 25)]
m = Multiplicator.new(test_case)
ap m.optimal_multiplication
ap m.costs
| true
|
f5524365739b5fbe8a6a41ea9cb9fd3c5e951129
|
Ruby
|
johnle192/exercises
|
/server.rb
|
UTF-8
| 1,503
| 3.34375
| 3
|
[] |
no_license
|
# This is my attempt at building a naive
# HTTP server to understand what HTTP is
require 'socket' # Get sockets from stdlib
class ParseHTTPRequest
def parse_request(request_line, headers)
parse_request_line(request_line)
parsed_request = {
'method' => @verb,
'path' => @path,
'version' => @version,
'headers' => parse_headers(headers)
}
end
private
def parse_request_line(request_line)
request_line.gsub!("\r\n",'')
@verb, @path, @version = request_line.split(' ')
end
def parse_headers(headers)
array_headers = headers.map do |header|
header.chomp!
header.split(': ')
end
Hash[array_headers]
end
end
class BuildHTTPResponse
def build(request)
body = "<div style='color: red'> #{request['path']} </div>"
content_length = body.bytesize
status_line = "#{request['version']} 200 OK\r\n"
headers = [
"Content-Type: text/html\r\n",
"Content-Length: #{content_length}\r\n",
"Connection: close\r\n",
"\r\n"
]
return [status_line, headers, body].flatten
end
end
server = TCPServer.open(2000)
loop {
client = server.accept
headers = []
request_line = client.gets
while (request_header = client.gets).chomp != ""
headers << request_header
end
parsed_request = ParseHTTPRequest.new.parse_request(request_line, headers)
response = BuildHTTPResponse.new.build(parsed_request)
client.puts response
client.puts
client.close
}
| true
|
d33b6ed32534d61d797509970bcb89ec3472e26d
|
Ruby
|
davidvgus/backup_alert
|
/backup_checker.rb
|
UTF-8
| 9,240
| 2.921875
| 3
|
[] |
no_license
|
#backup_checker.rb
require 'inifile'
require 'logger'
LOG = Logger.new( 'backupalert.log', 'monthly' )
class BackupFile
attr_accessor :name, :size, :ftype
def initialize(filename, size, ftype)
@name = filename
@size = size
@ftype = ftype
end
def to_s
@name
end
end
class BackupSet
attr_accessor :complete, :files, :size, :creation_date
def initialize(backup_set, backup_dir, minsize)
@set_number = backup_set
@backup_dir = backup_dir
@files = []
@creation_date = 0
@complete = false
@min_size = minsize
@size = 0
@ftypes = {"K" => false, "R" => false}
end
def add_file(filename, size, ftype)
case ftype
when "K"
@ftypes[ftype] = true
when "R"
@ftypes[ftype] = true
else
end
@files << BackupFile.new(filename, size, ftype)
@size += size
@creation_date = File.mtime(File.absolute_path(File.join(@backup_dir, filename))).to_i if ftype == "K"
@creation_date = File.mtime(File.absolute_path(File.join(@backup_dir, filename))).to_i if ftype == "R"
end
def describe_set_state(testing = false)
if is_complete? && hours_old < 24
if testing
"Backup Set 666 Has Problems : The backup is older than 24 hours."
else
"Backup Set #{@set_number} is complete"
end
else
description = "Backup Set #{@set_number} Has Problems : "
unless @ftypes["R"]
description << "No backup resource file. "
end
unless @ftypes["K"]
description << "No initial backup data file. "
end
unless min_size_reached?
description << "Minimum file size not reached. "
end
unless hours_old < 24
description << "The backup is older than 24 hours."
end
description
end
end
def is_complete?
# A set is complete if it has at least one:
#*.4BK
#*.4BR
#and is of the minimum kilobyte size
complete = true
unless @ftypes["K"]
complete = false
end
unless @ftypes["R"]
complete = false
end
unless min_size_reached?
complete = false
end
#@complete = @ftypes["K"] && @ftypes["R"] && min_size_reached? ? true : false
@complete = complete
end
def min_size_reached?
@size >= @min_size ? true : false
end
def hours_old
date = Time.at(@creation_date)
elapsed_time = (Time.now - date).to_i / (60 * 60)
end
def info(files_column_width, size_column_width)
list_of_names = []
@files.each {|f| list_of_names << "#{f.name}" }
#"666, test_file.txt, test_file2.txt, C, 100"
status = is_complete? ? 'Complete' : 'Incomplete'
date = Time.at(@creation_date)
#elapsed_time = (Time.now - date).to_i / (60 * 60)
elapsed_time = hours_old
size = (@size/(1024 * 1024)).to_s + "MB"
size = "<1MB" if size == "0MB"
"\nSet:%s Files: % -#{files_column_width }s \n\t Status: % -10s \n\t Size: % -#{size_column_width}s\n\t Date: %s\n Age in Hours: %s\n" %
[@set_number, list_of_names.join(', '), status, size, date, elapsed_time]
end
end
class BackupSetCatalog
attr_accessor :catalog
def initialize(backup_dir = 'sample', min_size)
@catalog = create_catalog(backup_dir, min_size)
end
def create_catalog(backup_dir, min_size)
backup_sets = {}
unless File.directory?(backup_dir)
#email_config = File.join(Dir.home, "authinfo.txt")
email_config = IniFile.new('backup_checker.ini').to_h['global']['email_config_file']
report = "The Backup Directory (#{File.absolute_path(backup_dir)}) Does not exist."
puts report
mailer = EmailAlerter.new()
mailer.send_report(email_config, report)
exit()
end
Dir.entries(backup_dir).each do |file|
/(?<set_number>\d{3})(-\d)?\.4B(?<backup_file_type>[RSK])$/ =~ file
if $~
#puts "%s %d" % [$~[:backup_file_type], $~[:set_number]]
set_number = $~[:set_number]
file_size = File.size(File.join(backup_dir, file))
file_type = $~[:backup_file_type]
if backup_sets.has_key?(set_number)
backup_sets[set_number].add_file(file, file_size, file_type)
else
backup_sets[set_number] = BackupSet.new(set_number, backup_dir, min_size)
backup_sets[set_number].add_file(file, file_size, file_type)
end
end
end
backup_sets
end
def list_set_names
@catalog.keys
end
def get_ordered_set_keys
inverse_hash = @catalog.inject({}) { |h, (k, v)| h[v.creation_date] = k; h }.reject {|k,v| k == 0}
inverse_hash.values
end
def get_last_set
inverse_hash = @catalog.inject({}) { |h, (k, v)| h[v.creation_date] = k; h }.reject {|k,v| k == 0}
inverse_hash[inverse_hash.keys.sort.last]
end
def last_backup_complete?
#Change this if statement so that you do something useful if there is no catalog
@catalog[get_last_set].is_complete? if @catalog
end
def time_since_last_backup(test_time = nil)
if test_time == nil
#test_time not used except in a testing.
Time.now.to_i - @catalog[get_last_set].creation_date
else
#test_time used when testing.
test_time - @catalog[get_last_set].creation_date
end
end
def hours_since_last_complete_backup(test_time = nil)
#test_time used for testing
time_since_last_backup(test_time) / (60 * 60)
end
def empty?
@catalog.empty?
end
def describe_last_set_state
@catalog[get_last_set].describe_set_state
end
def last_set_age_in_hours
@catalog[get_last_set].hours_old
end
end
class BackupChecker
#load parameters from ini file
require 'inifile'
require 'date'
attr_reader :ini_contents, :current_time, :set_manager, :backup_dir, :alert_message
def initialize(current_time = nil)
LOG.level = Logger::INFO
@ini_contents = IniFile.new('backup_alert.ini').to_h['global']
LOG.debug "ini_contents = " << @ini_contents.to_s
@server_name = @ini_contents['server_name']
@email_address = @ini_contents['email_address']
@alert_message = @ini_contents['alert_message'].gsub!('[server_name]', @server_name)
@alert_message = @alert_message.gsub!("email_address", @email_address)
@files_column_width = @ini_contents['files_column_width'].to_i
@size_column_width = @ini_contents['size_column_width'].to_i
@current_time = current_time || Time.now
@one_day = 24 * 60 * 60
@alert_message = @ini_contents['alert_message']
@working_directory = Dir.new(".")
@log_file_full_path = File.join(Dir.new("."), @ini_contents['log_file_name'])
@minimum_size_in_k = @ini_contents['min_size'].to_i
@backup_dir = @ini_contents['backup_directory']
@set_manager = BackupSetCatalog.new(@backup_dir, @minimum_size_in_k)
end
def alert?(test_time = nil)
if test_time
!@set_manager.last_backup_complete? || @set_manager.hours_since_last_complete_backup(test_time) > 24
else
!@set_manager.last_backup_complete? || @set_manager.hours_since_last_complete_backup > 24
end
end
def backup_dir_exists?
File.directory?(@backup_dir)
end
def complete?
@set_manager.last_backup_complete?
end
def report
report_string = ""
# set first line to describe_set_state
report_string = @alert_message
report_string << @set_manager.describe_last_set_state << "\n"
report_string << "Age of set in hours: " << @set_manager.last_set_age_in_hours.to_s << "\n"
report_string << "\n LIST OF KNOWN BACKUP SETS \n"
@set_manager.get_ordered_set_keys.each do |key|
report_string << @set_manager.catalog[key].info(@files_column_width, @size_column_width)
LOG.info @set_manager.catalog[key].info(@files_column_width, @size_column_width)
end
report_string
end
end
#class Gmailer
# require 'tlsmail'
# require 'time'
# require 'parseconfig'
#
#
# def send_report(email_config, message)
# email_config = ParseConfig.new(email_config).params
# from = email_config['from_address']
# to = email_config['to_address']
# p = email_config['p']
# content = <<EOF
#From: #{from}
#To: #{to}
#subject: Backup Alert
#Date: #{Time.now.rfc2822}
#
# #{message}
#EOF
# print 'content', content
#
# Net::SMTP.enable_tls(OpenSSL::SSL::VERIFY_NONE)
# Net::SMTP.start('smtp.gmail.com', 587, 'gmail.com', from, p, :login) do |smtp|
# smtp.send_message(content, from, to)
# end
# end
#end
class EmailAlerter
require 'net/smtp'
require 'time'
require 'parseconfig'
def send_report(email_config, report)
email_config = ParseConfig.new(email_config).params
from = email_config['from_address']
to = email_config['to_address']
server = email_config['server']
message = <<MESSAGE_END
From: Site of Care Backup_Checker <#{from}>
To: IT<#{to}>
Subject: SoC Backup Needs Attention
Date: #{Time.now.rfc2822}
MESSAGE_END
message << report
Net::SMTP.start(server) do |smtp|
smtp.send_message message, from,
to
end
#Net::SMTP.start('mail.your-domain.com',
# 25,
# 'localhost',
# 'username', 'password' :plain)
end
end
| true
|
2ea9d93c49f06f44bbe93554f287240e0aacb086
|
Ruby
|
yusukeyasuo/github-issues-rails
|
/lib/github.rb
|
UTF-8
| 406
| 2.71875
| 3
|
[] |
no_license
|
require 'net/http'
require 'json'
class Github
def self.get_issues(repo_url, page = 1, per_page = 5)
res_csv = ''
res = Net::HTTP.get(URI.parse("#{repo_url}?page=#{page}&per_page=#{per_page}"))
issues = JSON.parse(res)
issues.each do |i|
res_csv += "#{i['title'].slice(0, 30)},#{i['body'].slice(0, 50).gsub(/(\r\n?|\n)/," ")},#{i['comments_url']}\n"
end
res_csv
end
end
| true
|
63e72339ee50348fdb83acef92f8052898b52dda
|
Ruby
|
MateoKommit/RubyOnRailsCourse
|
/Section12/160.lengthempty.rb
|
UTF-8
| 244
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
shopping_list = {
banana: 5,
oranges: 10,
carrots: 3,
crackers: 15
}
vegan_shopping_list = {}
p(shopping_list.length)
p(vegan_shopping_list.length)
p(shopping_list.empty?)
p(vegan_shopping_list.empty?)
| true
|
bf913fa21bae5b3b7b0abfc86e18060a1763081f
|
Ruby
|
emmiehayes/dtc-admin
|
/app/respositories/donation_repository.rb
|
UTF-8
| 198
| 2.6875
| 3
|
[] |
no_license
|
class DonationRepository
def initialize(raw_payments)
@raw_payments = raw_payments
end
def run
@raw_payments.each do |payment|
DonationCreator.new(payment)
end
end
end
| true
|
1dd0f503cacc4e5abbcf4a9b7679831170f35097
|
Ruby
|
bysxiang/ruby-learn
|
/class/test7.rb
|
UTF-8
| 603
| 3.609375
| 4
|
[] |
no_license
|
# 单例模式-残缺版
class Abc
class << self
private
def new
super
puts "进入new"
end
end
def self.instance
new
end
def initialize()
puts "进入init"
end
end
# 对于一个类来说,new是类方法,initialize是实例方法
# 默认情况下Abc.new调用Abc.new方法,它默认会调用initialize
#
# 实现单例方法,private :new,只对之前的new有效,对于后边代码定义的:new是无效的,
# ruby是解释性的语言,只对之前的内容有效
#a = Abc.new
a1 = Abc.instance
| true
|
4da391068ce23ff57fc384c02d7544e226e21c5f
|
Ruby
|
sigovpaul/1000_issues
|
/begin/begin_06.rb
|
UTF-8
| 580
| 3.140625
| 3
|
[] |
no_license
|
puts "Введите длину ребер параллелепипеда"
puts "Введите первую сторону"
first_side = gets.chomp.to_f
puts "Введите вторую сторону"
second_side = gets.chomp.to_f
puts "Введите третью сторону"
third_side = gets.chomp.to_f
volume = first_side * second_side * third_side
square = 2 * ( first_side * second_side + second_side * third_side + first_side * third_side )
puts "Объем куба равен #{volume}"
puts "Площадь поверхности куба равна #{square}"
| true
|
6ec783ac540df828a6ba9b92985879dd97884fa7
|
Ruby
|
shanyi/Ruby-exercises
|
/Chap5.rb
|
UTF-8
| 560
| 3.8125
| 4
|
[] |
no_license
|
puts 'Hallo there, and what\'s your first name?'
fname = gets.chomp
puts 'What\'s your middle name?'
mname = gets.chomp
puts 'How about your last name?'
lname = gets.chomp
puts 'Your name is ' + fname + ' ' + mname + ' ' + lname + '? what a lovely name!'
puts 'Pleased to meet you, ' + fname + ' ' + mname + ' ' + lname + '. :)'
puts ''
puts 'What\'s your favorite number?'
number = gets.chomp.to_i
nnumber = number+1
puts 'How amazing! my favorite number is ' + nnumber.to_s + '.'
puts 'I think ' + nnumber.to_s + ' is a bigger and better favorite number. :)'
| true
|
5ed7e2c6ba9ee90fa9a52b93bdcc95ed4a7052a2
|
Ruby
|
copiousfreetime/flat_kit
|
/lib/flat_kit/command/merge.rb
|
UTF-8
| 3,039
| 3.078125
| 3
|
[
"MIT"
] |
permissive
|
require 'csv'
module FlatKit
class Command
class Merge < ::FlatKit::Command
def self.name
"merge"
end
def self.description
"Merge sorted files together that have the same structure."
end
def self.parser
::Optimist::Parser.new do
banner "#{Merge.description}"
banner ""
banner <<~BANNER
Given a set of input files that have the same structure, and are already
sorted by a set of keys. The Merge command will merge all those files
into a single output file.
The --key parameter is required, and it must be a comma separated list
of field nams on the input on which to use as the sort key for the merge
process.
There must also be at least 2 input files. Merging only 1 file into an
output file is the same as the 'cat' command.
The flatfile type(s) will be automatically determined by the file name.
If the output is not a file, but to stdout then the output type will
be the same as the first input file, or it can be specified as a commandline
switch.
The merge will do a single pass through the input to generate the
output.
BANNER
banner <<~USAGE
Usage:
fk merge --key surname,given_name file1.csv file2.csv > all.csv
fk merge --key surname,given_name --output-format json file1.csv file2.csv > all.json
fk merge --key field1,field2 --output-format json input*.csv | gzip -c > all.json.gz
fk merge --key field12 file*.json.gz -o all.json.gz
USAGE
banner <<~OPTIONS
Options:
OPTIONS
opt :output, "Send the output to the given path instead of standard out.", default: "<stdout>"
opt :input_format, "Input format, csv or json", default: "auto", short: :none
opt :output_format, "Output format, csv or json", default: "auto", short: :none
opt :key, "The comma separted list of field(s) to use for sorting the input", required: true, type: :string
end
end
attr_reader :compare_keys
def parse
parser = self.class.parser
::Optimist::with_standard_exception_handling(parser) do
begin
@opts = parser.parse(argv)
@compare_keys = CSV.parse_line(opts[:key])
paths = parser.leftovers
raise ::Optimist::CommandlineError, "At least 2 input files are required" if paths.size < 2
@merge = ::FlatKit::Merge.new(inputs: paths, input_fallback: opts[:input_format],
compare_fields: @compare_keys,
output: opts[:output], output_fallback: opts[:output_format])
rescue ::FlatKit::Error => e
raise ::Optimist::CommandlineError, e.message
end
end
end
def call
@merge.call
end
end
end
end
| true
|
5c07bcfe2a388aef32acf1ee8d9c123b018f70de
|
Ruby
|
pawn-stars/chess-app
|
/app/models/rook.rb
|
UTF-8
| 520
| 2.734375
| 3
|
[] |
no_license
|
class Rook < Piece
def move_legal?(to_row, to_col)
col == to_col || row == to_row
end
def king_rook_path_clear?(king_col)
return false if move_obstructed?(row, king_col)
true
end
def update_rook_for_castle
new_rook_col = col.zero? ? 3 : 5
update_attributes(row: row, col: new_rook_col)
end
def path_to_king
king = game.pieces.where.not(is_black: is_black).where(type: 'King').first
return nil unless valid_move?(king.row, king.col)
get_path(king.row, king.col)
end
end
| true
|
85681328321081a875f0ca8a1b90ece452a3c74f
|
Ruby
|
sonataFarm/algorithms
|
/week-7/lecture/bfs.rb
|
UTF-8
| 705
| 3.296875
| 3
|
[] |
no_license
|
class Paths
def initialize(g, s)
@g = g
@s = s
bfs
end
def has_path_to?(v)
!!@distance[v]
end
def path_to(v)
return nil if !has_path_to?(v)
path = []
x = v
while x != @s do
path.unshift(x)
x = @edge_to[x]
end
path.unshift(@s)
path
end
def distance(v)
@distance[v]
end
private
def bfs
@edge_to = Array.new(@g.v)
@distance = Array.new(@g.v)
queue = [@s]
@distance[@s] = 0
while queue.any?
v = queue.pop
@g.adj(v).each do |a|
if !@distance[a]
@distance[a] = @distance[v] + 1
@edge_to[a] = v
queue.unshift(a)
end
end
end
end
end
| true
|
d43b28bffdb1053e868a7eae67e95c864d1bed6a
|
Ruby
|
bartelink/ErikSchierboom.github.io
|
/_import/movies/moviecollection.rb
|
UTF-8
| 435
| 3.078125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'nokogiri'
require './movie'
class MovieCollection
include Enumerable
attr :movies
def initialize(collectionXml)
@movies = Nokogiri::XML(collectionXml)
.xpath("//Collection/DVD")
.select {|movieXml| movieXml.at_xpath('BoxSet/Parent').content.empty? }
.collect {|movieXml| Movie.new(movieXml)}
.sort_by {|movie| [movie.title.to_s, movie.year.to_s]}
end
def each(&block)
@movies.each(&block)
end
end
| true
|
fc89ef441f606f384ee6b269ca96e36646887e6d
|
Ruby
|
chatwoot/chatwoot
|
/app/drops/user_drop.rb
|
UTF-8
| 437
| 2.90625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class UserDrop < BaseDrop
def name
@obj.try(:name).try(:split).try(:map, &:capitalize).try(:join, ' ')
end
def available_name
@obj.try(:available_name)
end
def first_name
@obj.try(:name).try(:split).try(:first).try(:capitalize) if @obj.try(:name).try(:split).try(:size) > 1
end
def last_name
@obj.try(:name).try(:split).try(:last).try(:capitalize) if @obj.try(:name).try(:split).try(:size) > 1
end
end
| true
|
e46a30445de199f3909b16727510f9234bc1d0a2
|
Ruby
|
ronaldcnunez/801eb65b65dff5b10f7bade646311dc8
|
/Task-1/api_endpoints.rb
|
UTF-8
| 1,017
| 3.1875
| 3
|
[] |
no_license
|
require 'rest-client'
require 'json'
require 'yaml'
def users_api_call(id)
user_id = id.to_i
if user_id != 0
query_specific_user(user_id)
else
query_all_data
end
end
def query_specific_user(user_id)
api_info = RestClient.get("https://reqres.in/api/users/#{user_id}")
user_data = JSON.parse(api_info).to_yaml()
File.open("users.yml", 'w') { |file| file.write(user_data) }
puts File.read("users.yml")
end
def query_all_data
api_info = RestClient.get("https://reqres.in/api/users/")
user_data = JSON.parse(api_info)
total = JSON.parse(api_info)["total"]
(1..total).each do |n|
api_info = RestClient.get("https://reqres.in/api/users/#{n}")
user_data = JSON.parse(api_info).to_yaml()
File.open("users.yml", 'w') { |file| file.write(user_data) }
puts File.read("users.yml")
end
end
def welcome
puts "Hello! Please enter an id or leave blank"
end
def get_id
gets.chomp
end
def run_program
welcome
id = get_id
users_api_call(id)
end
run_program
| true
|
ec9473acab47af281d3412fb749c572327e0ffc3
|
Ruby
|
sljuka/bizflow
|
/lib/bizflow/monkey_patch.rb
|
UTF-8
| 212
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
unless "foo_bar".respond_to? :camelcase_notation
class String
def camelcase_notation
return self if self !~ /_/ && self =~ /[A-Z]+.*/
split('_').map{|e| e.capitalize}.join
end
end
end
| true
|
5a2d2a6960a9fb6a88ea218cd0176298bacf76a8
|
Ruby
|
ChanceMims/ruby-oo-object-relationships-collaborating-objects-lab-austin-web-120919
|
/lib/mp3_importer.rb
|
UTF-8
| 450
| 3.203125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class MP3Importer
attr_reader :path
def initialize(path)
@path = path
end
def files
#binding.pry
get_file_from_path
end
def import
#binding.pry
files.each{|filename|Song.new_by_filename(filename)}
end
def get_file_from_path
Dir.entries(@path).select{|file| !File.directory? file} #Returns true if the named file is a directory
#binding.pry
end
end
| true
|
90d367b6765394cbbe73578e9050e5c8f024909d
|
Ruby
|
plainpicture/attachments
|
/lib/attachments/fake_driver.rb
|
UTF-8
| 1,648
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
module Attachments
class FakeMultipartUpload
include MonitorMixin
def initialize(name, bucket, options, &block)
super()
@name = name
@bucket = bucket
block.call(self) if block_given?
end
def upload_part(data)
synchronize do
@data ||= ""
@data << data
end
true
end
def data
synchronize do
@data
end
end
def abort_upload; end
def complete_upload; end
end
class FakeDriver
class ItemNotFound < StandardError; end
def list(bucket, prefix: nil)
return enum_for(:list, bucket, prefix: prefix) unless block_given?
objects(bucket).each do |key, _|
yield key if prefix.nil? || key.start_with?(prefix)
end
end
def store(name, data_or_io, bucket, options = {})
objects(bucket)[name] = data_or_io.respond_to?(:read) ? data_or_io.read : data_or_io
end
def store_multipart(name, bucket, options = {}, &block)
objects(bucket)[name] = FakeMultipartUpload.new(name, bucket, options, &block).data
end
def exists?(name, bucket)
objects(bucket).key?(name)
end
def delete(name, bucket)
objects(bucket).delete(name)
end
def value(name, bucket)
raise(ItemNotFound) unless objects(bucket).key?(name)
objects(bucket)[name]
end
def temp_url(name, bucket, options = {})
"https://example.com/#{bucket}/#{name}?signature=signature&expires=expires"
end
def flush
@objects = {}
end
private
def objects(bucket)
@objects ||= {}
@objects[bucket] ||= {}
end
end
end
| true
|
82ed9cc6864cd965f092260d74916089882e5e28
|
Ruby
|
abellotti/insights-api-common-rails
|
/lib/insights/api/common/filter.rb
|
UTF-8
| 11,007
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
module Insights
module API
module Common
class Filter
INTEGER_COMPARISON_KEYWORDS = ["eq", "not_eq", "gt", "gte", "lt", "lte", "nil", "not_nil"].freeze
STRING_COMPARISON_KEYWORDS = ["contains", "contains_i", "eq", "not_eq", "eq_i", "not_eq_i", "starts_with", "starts_with_i", "ends_with", "ends_with_i", "nil", "not_nil"].freeze
ALL_COMPARISON_KEYWORDS = (INTEGER_COMPARISON_KEYWORDS + STRING_COMPARISON_KEYWORDS).uniq.freeze
attr_reader :apply, :arel_table, :api_doc_definition, :extra_filterable_attributes, :model
# Instantiates a new Filter object
#
# == Parameters:
# model::
# An AR model that acts as the base collection to be filtered
# raw_filter::
# The filter from the request query string
# api_doc_definition::
# The documented object definition from the OpenAPI doc
# extra_filterable_attributes::
# Attributes that can be used for filtering but are not documented in the OpenAPI doc. Something like `{"undocumented_column" => {"type" => "string"}}`
#
# == Returns:
# A new Filter object, call #apply to get the filtered set of results.
#
def initialize(model, raw_filter, api_doc_definition, extra_filterable_attributes = {})
@raw_filter = raw_filter
@api_doc_definition = api_doc_definition
@arel_table = model.arel_table
@extra_filterable_attributes = extra_filterable_attributes
@model = model
end
def query
@query ||= filter_associations.present? ? model.left_outer_joins(filter_associations) : model
end
attr_writer :query
def apply
return query if @raw_filter.blank?
self.class.compact_filter(@raw_filter).each do |k, v|
next unless (attribute = attribute_for_key(k))
if attribute["type"] == "string"
type = determine_string_attribute_type(attribute)
send(type, k, v)
else
errors << "unsupported attribute type for: #{k}"
end
end
raise(Insights::API::Common::Filter::Error, errors.join(", ")) unless errors.blank?
query
end
# Compact filters to support association filtering
#
# Input: {"source_type"=>{"name"=>{"eq"=>"rhev"}}}
# Output: {"source_type.name"=>{"eq"=>"rhev"}}
#
# Input: {"source_type"=>{"name"=>{"eq"=>["openstack", "openshift"]}}}
# Output: {"source_type.name"=>{"eq"=>["openstack", "openshift"]}}
#
def self.compact_filter(filter)
result = {}
return result if filter.blank?
return filter unless filter.kind_of?(Hash) || filter.kind_of?(ActionController::Parameters)
filter = Hash(filter.permit!) if filter.kind_of?(ActionController::Parameters)
filter.each do |ak, av|
if av.kind_of?(Hash)
av.each do |atk, atv|
if !ALL_COMPARISON_KEYWORDS.include?(atk)
result["#{ak}.#{atk}"] = atv
else
result[ak] = av
end
end
else
result[ak] = av
end
end
result
end
def self.association_attribute_properties(api_doc_definitions, raw_filter)
return {} if raw_filter.blank?
association_attributes = compact_filter(raw_filter).keys.select { |key| key.include?('.') }.compact.uniq
return {} if association_attributes.blank?
association_attributes.each_with_object({}) do |key, hash|
association, attr = key.split('.')
hash[key] = api_doc_definitions[association.singularize.classify].properties[attr.to_s]
end
end
private
delegate(:arel_attribute, :to => :model)
class Error < ArgumentError; end
def key_model_attribute(key)
if key.include?('.')
association, attr = key.split('.')
[association.classify.constantize, attr]
else
[model, key]
end
end
def model_arel_attribute(key)
key_model, attr = key_model_attribute(key)
key_model.arel_attribute(attr)
end
def model_arel_table(key)
key_model, attr = key_model_attribute(key)
key_model.arel_table
end
def filter_associations
return nil if @raw_filter.blank?
@filter_associations ||= begin
self.class.compact_filter(@raw_filter).keys.collect do |key|
next unless key.include?('.')
key.split('.').first.to_sym
end.compact.uniq
end
end
def attribute_for_key(key)
attribute = api_doc_definition.properties[key.to_s]
attribute ||= extra_filterable_attributes[key.to_s]
return attribute if attribute
errors << "found unpermitted parameter: #{key}"
nil
end
def determine_string_attribute_type(attribute)
return :timestamp if attribute["format"] == "date-time"
return :integer if attribute["pattern"] == /^\d+$/
:string
end
def errors
@errors ||= []
end
def string(k, val)
if val.kind_of?(Hash)
val.each do |comparator, value|
add_filter(comparator, STRING_COMPARISON_KEYWORDS, k, value)
end
else
add_filter("eq", STRING_COMPARISON_KEYWORDS, k, val)
end
end
def add_filter(requested_comparator, allowed_comparators, key, value)
return unless attribute = attribute_for_key(key)
type = determine_string_attribute_type(attribute)
if requested_comparator.in?(["nil", "not_nil"])
send("comparator_#{requested_comparator}", key, value)
elsif requested_comparator.in?(allowed_comparators)
value = parse_datetime(value) if type == :datetime
return if value.nil?
send("comparator_#{requested_comparator}", key, value)
else
errors << "unsupported #{type} comparator: #{requested_comparator}"
end
end
def self.build_filtered_scope(scope, api_version, klass_name, filter)
return scope unless filter
openapi_doc = ::Insights::API::Common::OpenApi::Docs.instance[api_version]
openapi_schema_name, = ::Insights::API::Common::GraphQL::Generator.openapi_schema(openapi_doc, klass_name)
action_parameters = ActionController::Parameters.new(filter)
definitions = openapi_doc.definitions
association_attribute_properties = association_attribute_properties(definitions, action_parameters)
new(scope, action_parameters, definitions[openapi_schema_name], association_attribute_properties).apply
end
def timestamp(k, val)
if val.kind_of?(Hash)
val.each do |comparator, value|
add_filter(comparator, INTEGER_COMPARISON_KEYWORDS, k, value)
end
else
add_filter("eq", INTEGER_COMPARISON_KEYWORDS, k, val)
end
end
def parse_datetime(value)
return value.collect { |i| parse_datetime(i, ) } if value.kind_of?(Array)
DateTime.parse(value)
rescue ArgumentError
errors << "invalid timestamp: #{value}"
return nil
end
def integer(k, val)
if val.kind_of?(Hash)
val.each do |comparator, value|
add_filter(comparator, INTEGER_COMPARISON_KEYWORDS, k, value)
end
else
add_filter("eq", INTEGER_COMPARISON_KEYWORDS, k, val)
end
end
def arel_lower(key)
Arel::Nodes::NamedFunction.new("LOWER", [model_arel_attribute(key)])
end
def comparator_contains(key, value)
return value.each { |v| comparator_contains(key, v) } if value.kind_of?(Array)
self.query = query.where(model_arel_attribute(key).matches("%#{query.sanitize_sql_like(value)}%", nil, true))
end
def comparator_contains_i(key, value)
return value.each { |v| comparator_contains_i(key, v) } if value.kind_of?(Array)
self.query = query.where(model_arel_table(key).grouping(arel_lower(key).matches("%#{query.sanitize_sql_like(value.downcase)}%", nil, true)))
end
def comparator_starts_with(key, value)
self.query = query.where(model_arel_attribute(key).matches("#{query.sanitize_sql_like(value)}%", nil, true))
end
def comparator_starts_with_i(key, value)
self.query = query.where(model_arel_table(key).grouping(arel_lower(key).matches("#{query.sanitize_sql_like(value.downcase)}%", nil, true)))
end
def comparator_ends_with(key, value)
self.query = query.where(model_arel_attribute(key).matches("%#{query.sanitize_sql_like(value)}", nil, true))
end
def comparator_ends_with_i(key, value)
self.query = query.where(model_arel_table(key).grouping(arel_lower(key).matches("%#{query.sanitize_sql_like(value.downcase)}", nil, true)))
end
def comparator_eq(key, value)
self.query = query.where(model_arel_attribute(key).eq_any(Array(value)))
end
def comparator_not_eq(key, value)
self.query = query.where.not(model_arel_attribute(key).eq_any(Array(value)))
end
def comparator_not_eq_i(key, value)
values = Array(value).map { |v| query.sanitize_sql_like(v.downcase) }
self.query = query.where.not(model_arel_table(key).grouping(arel_lower(key).matches_any(values)))
end
def comparator_eq_i(key, value)
values = Array(value).map { |v| query.sanitize_sql_like(v.downcase) }
self.query = query.where(model_arel_table(key).grouping(arel_lower(key).matches_any(values)))
end
def comparator_gt(key, value)
self.query = query.where(model_arel_attribute(key).gt(value))
end
def comparator_gte(key, value)
self.query = query.where(model_arel_attribute(key).gteq(value))
end
def comparator_lt(key, value)
self.query = query.where(model_arel_attribute(key).lt(value))
end
def comparator_lte(key, value)
self.query = query.where(model_arel_attribute(key).lteq(value))
end
def comparator_nil(key, _value = nil)
self.query = query.where(model_arel_attribute(key).eq(nil))
end
def comparator_not_nil(key, _value = nil)
self.query = query.where.not(model_arel_attribute(key).eq(nil))
end
end
end
end
end
| true
|
eaafda7c82d1bf46cbfee980d29759349913d209
|
Ruby
|
Sephi-Chan/map_data_extractor
|
/lib/map_data_extractor/paths_extractor.rb
|
UTF-8
| 1,872
| 3.078125
| 3
|
[] |
no_license
|
class MapDataExtractor::PathsExtractor
def initialize(image, nodes)
@image = image
@view = image.view(0, 0, image.columns, image.rows)
@nodes = nodes
end
def paths
# Find path's starting points from each node.
start_points = Hash.new { |k, v| k[v] = [] }
@nodes.each do |node|
node[:points].each do |point|
x, y = point
pixel = @view[y][x]
start_points[node] << point if pixel.opacity == 0
end
end
# Follow the path for each starting point found.
paths = []
start_points.each do |node, start_points|
start_points.each do |starting_point|
x, y = starting_point
color = @image.pixel_color(*starting_point)
color_code = MapDataExtractor::color_code(@view[y][x])
steps = [ starting_point ]
begin
point = point_with_colour_around(color, steps[-1], steps[-2])
steps << point if point
end while point
arrival_node = node_for_point(steps[-1], @nodes)
paths << { from: node, to: arrival_node, points: steps, color: color_code }
end
end
paths
end
private
# Return the first point with the given color around given coordinates.
def point_with_colour_around(color, origin_point, point_to_ignore = nil)
x, y = origin_point
[
[ x - 1, y - 1 ],
[ x, y - 1 ],
[ x + 1, y - 1 ],
[ x - 1, y ],
[ x + 1, y ],
[ x - 1, y + 1 ],
[ x, y + 1 ],
[ x + 1, y + 1 ]
].each do |point|
return point if point != point_to_ignore && @image.pixel_color(*point) == color
end
nil
end
def node_for_point(searched_point, nodes)
nodes.find do |node|
node[:points].any? do |point|
point[0] == searched_point[0] && point[1] == searched_point[1]
end
end
end
end
| true
|
8e83bc4c262e35bb5c0667cff23faa018dd5d6d6
|
Ruby
|
gildesmarais/dotfiles
|
/irbrc
|
UTF-8
| 1,003
| 2.703125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'rubygems'
##
# Improve pasting speed on macos.
#
# source: https://github.com/ruby/irb/issues/43#issuecomment-572981408
IRB.conf[:USE_MULTILINE] = false
##
# monkey-patch (restricted to irb session) Class
class Class
##
# Show only this class class methods
def class_methods
(methods - Class.instance_methods - Object.methods).sort
end
##
# Show instance and class methods
def defined_methods
{ instance: new.local_methods, class: class_methods }
end
end
##
# monkey-patch (restricted to irb session) Object
class Object
##
# returns local methods (defined on this object)
def local_methods(obj = self)
(obj.methods - obj.class.superclass.instance_methods).sort
end
##
# copies input to clipboard (mac os only)
def pbcopy(input)
str = input.to_s
IO.popen('pbcopy', 'w') { |f| f << str }
str
end
##
# pastes from the clipboard (macos only)
def pbpaste
`pbpaste`
end
end
| true
|
433ce3c0beedd90d4f77222c72d9b8e29df9a3d1
|
Ruby
|
KaitlynMcPartland/health-insurance-helper
|
/app/models/user.rb
|
UTF-8
| 410
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
class User < ActiveRecord::Base
include BCrypt
def password
@password ||= Password.new(password_hash)
end
def password=(new_password)
@password = Password.create(new_password)
self.password_hash = @password
end
def self.authenticate(user_info)
user = User.find_by(username: user_info[:username])
if user && user.password == user_info[:password]
return user
else
return nil
end
end
end
| true
|
dcf73dcf307638ac5fc6694e932ccc1516de9a83
|
Ruby
|
dlaststark/machine-learning-projects
|
/Programming Language Detection/Experiment-2/Dataset/Train/Ruby/100-doors-1.rb
|
UTF-8
| 188
| 2.671875
| 3
|
[] |
no_license
|
doors = Array.new(101,0)
print "Open doors "
(1..100).step(){ |i|
(i..100).step(i) { |d|
doors[d] = doors[d]^= 1
if i == d and doors[d] == 1 then
print "#{i} "
end
}
}
| true
|
b2aeaff6a954b418ea573bd9d998bad2df894bfb
|
Ruby
|
catprice444/anagram-detector-online-web-sp-000
|
/lib/anagram.rb
|
UTF-8
| 1,039
| 4.5
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# Your class, `Anagram` should take a word on initialization, and instances should
# respond to a `match` method that takes an array of possible anagrams. It should
# return all matches in an array. If no matches exist, it should return an empty
# array.
class Anagram
attr_accessor :word
def initialize(word)
@word = word
end
# take in an array
# returns an empty array if you matches
# iterate over the array of words using the ".select" method
# compare the new array of words to the :word method
# have to determine if they are composed of the same letters
# use the ".split" method to seperate out the words in the array
# use the "==" to compare the words/ arrays
# can use the ".sort" method to compare the words/arrays
# what I have to do is take in an array of words and compare them (.select)
# then I have to compare the two words but when I compare then I have to (.split) and (.sort)
def match(array)
array.select do |word|
(@word.split("").sort) == (word.split("").sort)
end
end
end
| true
|
1a8b6e2d2585e583ef575da6c98a0f17f876c2e9
|
Ruby
|
Cysioland/phpunit-docker
|
/Rakefile
|
UTF-8
| 2,409
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
require 'rake'
require './scripts/Settings'
require './scripts/Console'
require './scripts/Version'
require './scripts/Template'
# External args
VERSION = ENV['version'] || ''
# Version's tasks
namespace :version do
desc "Add new version"
task :add do
Console::display_box('Add new version')
if Version::check_version_syntax?(VERSION)
unless Version::check_version_exists?(VERSION)
Version::create_version(VERSION)
Console::display_done("Create new version: #{VERSION}")
Settings::add_version(VERSION)
Console::display_done("Update settings")
Template::create_template('Dockerfile', VERSION, {"version": VERSION})
Console::display_done("Add new version")
Template::create_template('Dockerfile', 'master')
Console::display_done("Update master")
Template::create_template('Makefile')
Console::display_done("Update make")
Template::create_template('README.md')
Console::display_done("Update documentation")
else
Console::display_error("This version '#{VERSION}' already exists.")
Console::display_info("Use another version than: " + Version::list_versions)
end
else
Console::display_error("Bad version: #{VERSION}")
Console::display_info("Please use a good version. (Eg: 1.0.0)")
end
end
desc "Remove version"
task :remove do
Console::display_box('Remove version')
if Version::check_version_syntax?(VERSION)
if Version::check_version_exists?(VERSION)
Version::remove_version(VERSION)
Console::display_done("Remove version: #{VERSION}")
Settings::remove_version(VERSION)
Console::display_done("Update settings")
Template::create_template('Dockerfile', 'master')
Console::display_done("Update master")
Template::create_template('Makefile')
Console::display_done("Update make")
Template::create_template('README.md')
Console::display_done("Update documentation")
else
Console::display_error("This version '#{VERSION}' does not exists.")
Console::display_info("Use a version in: " + Version::list_versions)
end
else
Console::display_error("Bad version: #{VERSION}")
Console::display_info("Please use a good version. (Eg: 1.0.0)")
end
end
end
# Default task
task :default => 'version:add'
| true
|
8d1605948541e1a69465f2995dc842e38f3ca2a6
|
Ruby
|
miriamhit02/afternoon_zoo_2105
|
/spec/zoo_spec.rb
|
UTF-8
| 1,341
| 3.046875
| 3
|
[] |
no_license
|
require './lib/animal'
require './lib/zoo'
RSpec.describe Zoo do
it 'exists' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo).to be_a(Zoo)
end
it 'has a street' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.street).to eq("2300 Southern Blvd")
end
it 'has a name' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.name).to eq("Bronx Zoo")
end
it 'has a state' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.city).to eq("Bronx")
end
it 'has a state' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.state).to eq("NY")
end
it 'has a state' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.zip_code).to eq("10460")
end
it 'has an address' do
zoo = Zoo.new("Bronx Zoo", "2300 Southern Blvd", "Bronx", "NY", "10460")
expect(zoo.address).to eq("2300 Southern Blvd Bronx, NY 10460")
end
it 'can add an animal' do
animal_new = Animal.new("Polar Bear", 100, 15)
expect(zoo.add_animals).to eq(["Polar Bear", 100, 15])
end
xit 'has an animal count' do
end
end
| true
|
45714249fe34b4bbb16e87eddd7a9d7bbf5c51c3
|
Ruby
|
vano468/apple-warranty-scraper
|
/example.rb
|
UTF-8
| 372
| 2.671875
| 3
|
[] |
no_license
|
require_relative 'lib/apple_warranty_scraper'
def print_phone_info(info)
result = "serial: #{info.serial}"
result += ", warranty: #{info.warranty}"
result += ", expiration date: #{info.expiration}" if info.warranty == :active
puts result
end
print_phone_info AppleWarrantyScraper.new '013896000639712'
print_phone_info AppleWarrantyScraper.new '013977000323877'
| true
|
8ca8d76defa6f3e31305b7823d95dc60409a3974
|
Ruby
|
tonidas/versi
|
/lib/versi/generate_command/interactors/extract_release_type_from_commit_message.rb
|
UTF-8
| 1,852
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require "rescue_interactor"
class Versi < Clamp::Command
class GenerateCommand < Clamp::Command
class Interactors
class ExtractReleaseTypeFromCommitMessage
include RescueInteractor
MERGE_COMMIT_REGEXES = [MERGE_COMMIT_REGEX_BITBUCKET = /.*Merge\sbranch\s\'(.*)\'.*/,
MERGE_COMMIT_REGEX_GITHUB = /.*Merge.*from\s([^\s]*).*/,
MERGE_COMMIT_REGEX_GIT = /.*Merged\s([^\s]*)\sinto\s([^\s]*).*/]
before :setup
def call
source_branch = extract_source_branch
return if !source_branch
context.release_type = extract_release_type_from_merge_source_branch(source_branch)
end
private
def setup
raise(ArgumentError, "Missing commit_message argument") if !context.commit_message
end
def extract_source_branch
MERGE_COMMIT_REGEXES.each do |regex|
match_data = context.commit_message.match(regex)
return match_data[1] if match_data && match_data[1]
end
# The nil here is to ensure that the nil value will be returned if
# the commit_message doesn't match any regex
nil
end
def extract_release_type_from_merge_source_branch(source_branch)
if source_branch.start_with?("hotfix/")
if source_branch =~ /feature/i
Versi::Util::SemanticReleaseTypes::MINOR
else
Versi::Util::SemanticReleaseTypes::PATCH
end
elsif source_branch.start_with?("release/")
Versi::Util::SemanticReleaseTypes::MINOR
elsif source_branch.start_with?("major-release/")
Versi::Util::SemanticReleaseTypes::MAJOR
end
end
end
end
end
end
| true
|
b2eef2ec2060b4eceef9db1a18aea3979fc822dc
|
Ruby
|
Keemtaker/duckrev
|
/lib/tasks/football_teams.rake
|
UTF-8
| 923
| 2.515625
| 3
|
[] |
no_license
|
require 'httparty'
base_uri = ENV['BASE_URI']
sports_token_key = ENV['SPORTS_TOKEN_KEY']
sports_token_value = ENV['SPORTS_TOKEN_VALUE']
desc "This task retrieves teams api data"
task :football_teams_data => :environment do
competition_ids = ["2002", "2014", "2015", "2019", "2021"]
competition_ids.each do | competition_id |
response = HTTParty.get("#{base_uri}/competitions/#{competition_id}/teams", :headers => { "#{sports_token_key}" => "#{sports_token_value}"}).parsed_response
response["teams"].each do | team |
puts "creating football team #{team["shortName"]}"
puts "-----------"
FootballTeam.create(name: team["name"], team_api_id: team["id"], short_name: team["shortName"], team_country: team["area"]["name"])
puts "-----------"
puts "created"
end
end
puts "updating Monaco to France"
FootballTeam.find_by(team_api_id: 548).update(team_country: "France")
end
| true
|
9eb88ba100ba9ff45003789d7532481cda2e4f0d
|
Ruby
|
skitale-design/viselitsa
|
/lib/printer.rb
|
UTF-8
| 539
| 3.171875
| 3
|
[] |
no_license
|
class Printer
IMAGE_PATH = 'image'
def initialize(game)
@game = game
end
def print_info
@game.word_array.each do |letter|
if @game.good_letters.include?(letter)
print " #{letter} "
else
print " _ "
end
end
end
def print_image
begin
File.readlines("#{IMAGE_PATH}/#{@game.errors}.txt", '\n').map {|x| puts x}
rescue Errno::ENOENT => e
abort "\n\nОшибка! Не найден файл #{"#{IMAGE_PATH}/#{@game.errors}.txt"} : #{e.message}"
end
end
end
| true
|
344f63a7c67316e4ac1ef012bce71d776d6adb7e
|
Ruby
|
RianaFerreira/wdi_sydney_2_hw
|
/w01/d05/nick/Shelter/main.rb
|
UTF-8
| 5,016
| 3.828125
| 4
|
[] |
no_license
|
require 'pry'
require_relative 'shelter'
require_relative 'client'
require_relative 'animal'
$shelter = Shelter.new
def get_input
menu_selection = 0
while menu_selection != 7
print "What would you like to do?\n
(1) Add client
(2) Add animal
(3) Adopt animal
(4) Put animal up for adoption
(5) Display all HappiTails animals
(6) Display all HappiTails clients
(7) Close program\n
Your selection > "
menu_selection = gets.chomp.to_i
process_request(menu_selection)
end
end
def process_request(menu_selection)
case menu_selection
when 1
create_client
when 2
create_animal
when 3
adopt_animal
when 4
up_for_adoption
display_animal
display_client
when 5
display_animal
when 6
display_client
when 7
puts "Have a HappiTail day :)"
return
else
puts "Please pick an option 1 to 7."
get_input
end
end
def create_client
#prompt them for the client information
puts "Enter client information"
print "Name:\t\t\t"
name = gets.chomp
print "Age:\t\t\t"
age = gets.chomp.to_i
print "Number of children:\t"
num_children = gets.chomp.to_i
print "Number of pets:\t\t"
num_pets = gets.chomp.to_i
#create instance of client
new_client = Client.new
#setup client
new_client.name = name
new_client.age = age
new_client.num_children = num_children
new_client.num_pets = num_pets
#link the new client to the shelter
$shelter.clients[new_client.name] = new_client
puts "Client #{new_client.name} successfully added."
return new_client
end
def create_animal
#prompt them for the animal information
puts "Enter animal information"
print "Name:\t\t"
name = gets.chomp
print "Age:\t\t"
age = gets.chomp.to_i
print "Gender:\t\t"
gender = gets.chomp
print "Species:\t"
species = gets.chomp
#create instance of animal
new_animal = Animal.new
#setup animal
new_animal.name = name
new_animal.age = age
new_animal.gender = gender
new_animal.species = species
#assign multiple toys to the animal
print "Toys:\t\t"
done = false
while !done
toy = gets.chomp
new_animal.toys << toy
print "Do you want to add another toy? (Y/N): "
response = gets.chomp.downcase
if response == "n"
done = true
else
print "Toy description > "
end
end
#link the new animal to the shelter
$shelter.animals[new_animal.name] = new_animal
puts "Animal #{new_animal.name} successfully added."
return new_animal
end
def display_animal
#display all animals linked to a shelter
if $shelter.animals.empty?
puts "HappiTails has no animals available for adoption!"
else
$shelter.animals.each {|key,value| puts value}
end
end
def display_client
#display all clients linked to a shelter
$shelter.clients.each{|animal,value| puts value}
end
def adopt_animal
#show animals available for adoption
puts "Animals that can be adopted"
display_animal
#prompt user to select an animal for adoption
print "Enter name of animal that is being adopted: "
chosen_animal = gets.chomp
#find chosen animal in the hash of animals linked to the shelter
chosen_animal = $shelter.animals[chosen_animal]
#show clients who can adopt a pet
puts "Clients who are able to adopt #{chosen_animal.name}"
display_client
#prompt user to select a client who is adopting a pet
print "Enter name of client or 'Add' to create a new client for the adoption: "
chosen_client = gets.chomp
#if the client doesn't exist, redirect user to the create_client method and return the new client object
if chosen_client == "Add"
chosen_client = create_client
else
#find chosen client in the hash of clients linked to the shelter
chosen_client = $shelter.clients[chosen_client]
end
#animal should have a link to a client
chosen_animal.owner = chosen_client.name
#animal should be assigned to a client
chosen_client.animals[chosen_animal.name] = chosen_animal
#remove shelter association
$shelter.animals.delete(chosen_animal.name)
puts "#{chosen_animal.name} has found a loving home with #{chosen_client.name} :)"
end
def up_for_adoption
#no need to capture the person who is giving up the animal as a client
#create the animal that the shelter is taking in
new_animal = create_animal
new_animal.owner = "HappiTails"
#link the animal to the shelter
$shelter.animals[new_animal.name] = new_animal
puts "Welcome to HappiTails #{new_animal.name} we'll find you a loving home soon!"
end
get_input
| true
|
b35c1733e6152b9eba6662cff04c17460619d460
|
Ruby
|
afinapd/learn-selenium-ruby
|
/variable.rb
|
UTF-8
| 668
| 3.71875
| 4
|
[] |
no_license
|
# local variable start with small letter or _
class LocalVariable
def setData
_a = 100
puts _a
end
def getData
puts a
end
end
# Instance variable start with @
class InstanceVariable
def sum(a, b)
@c = a + b
end
def display
puts @c
end
end
# class variable start with @@
class ClassVariable
def sum(a, b)
@@c = a + b
end
def display
puts @@c
end
end
# class variable start with $
# global variable outside class
$firstname = 'afina'
# global variable inside class
class GlobalVariable
$middlename = 'putri'
def sum(a, b)
$lastname = 'dayanti'
@@c = a + b
end
def display
puts @@c
end
end
| true
|
032def304ab144cd094513ea92afb1932b77bcc3
|
Ruby
|
jrubio12/ejemplosRuby
|
/general/funciones_01.rb
|
UTF-8
| 88
| 3.09375
| 3
|
[] |
no_license
|
def say_hello(name)
puts "Hola #{name}"
end
say_hello("Jesus Rubio")
say_hello "Hernandez"
| true
|
ae5cf50c3dc70380a567d381a7a934ad4d0850cd
|
Ruby
|
reneedv/class_mngmt_December4_6
|
/features/step_definitions/assignments_steps.rb
|
UTF-8
| 623
| 2.578125
| 3
|
[] |
no_license
|
Given(/^I am on the home page$/) do
visit '/'
end
Then(/^I should see "(.*?)"$/) do |arg1|
page.should have_content arg1
end
When(/^I (follow|press) "(.*?)"$/) do |click_type, arg1|
click_link_or_button arg1
end
When(/^I fill in "(.*?)" with "(.*?)"$/) do |arg1, arg2|
fill_in arg1, with: arg2
end
Then(/^I [sS]hould be on the home page$/) do
current_path.should eq '/'
end
Given(/^I have an "(.*?)" with a "(.*?)" of "(.*?)"$/) do |thing, attr_key, attr_value|
thing.constantize.create attr_key.to_s => attr_value
#Assignment.create(title: arg1)
end
When(/^I check "(.*?)"$/) do |arg1|
check arg1
end
| true
|
6074a7d3b54c4509617030e521ca1b9a9b275fcf
|
Ruby
|
NicciSheets/tdd_methods
|
/test_array_tdd_methods.rb
|
UTF-8
| 403
| 2.515625
| 3
|
[] |
no_license
|
require "minitest/autorun"
require_relative "array_tdd_methods.rb"
class TestArrayTddMethods < Minitest::Test
def test_assert_that_using_reject_method_returns_false_values
assert_equal([3, 4, 5, 6], reject_method([1, 2, 3, 4, 5, 6]))
end
def test_assert_that_returns_same_without_using_method
assert_equal([3, 4, 5, 6], reject_without_method([1, 2, 3, 4, 5, 6]))
end
end
| true
|
c9a09dfedebd9c7786a81359c4c4583615293845
|
Ruby
|
DHBW-KA/ruby_on_rails
|
/1_Ruby/uebungen/ü6.rb
|
UTF-8
| 149
| 2.90625
| 3
|
[] |
no_license
|
class Foo
def self.bar
puts 'class method'
end
def baz
puts 'instance method'
end
end
# Wie wird welche Methode aufgerufen. Warum?
| true
|
7824f9b4788387abf5c425e48d7cdf4f0b755167
|
Ruby
|
bingo8670/programming-exercise
|
/47-directions-reduction.rb
|
UTF-8
| 469
| 3.4375
| 3
|
[] |
no_license
|
# 方向计算,去除相邻的相反方向
OPPOSITE = {
"NORTH" => "SOUTH",
"SOUTH" => "NORTH",
"EAST" => "WEST",
"WEST" => "EAST"
}
def dirReduc(arr)
stack = []
arr.each do |dir|
OPPOSITE[dir] == stack.last ? stack.pop : stack.push(dir)
end
stack
end
a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
p dirReduc(a) # => ["WEST"])
u=["NORTH", "WEST", "SOUTH", "EAST"]
p dirReduc(u) # => ["NORTH", "WEST", "SOUTH", "EAST"])
| true
|
580e6e328e89d6670958e8056db2ae3689dba6bc
|
Ruby
|
malnakli/Ruby_on_Rails_Tutorial
|
/sample_app/app/models/user.rb
|
UTF-8
| 3,617
| 2.890625
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
# dependent: :destroy arranges for the dependent microposts to be destroyed when the user itself is destroyed
has_many :microposts , dependent: :destroy
# Since destroying a user should also destroy that user’s relationships,
# we’ve gone ahead and added dependent: :destroy to the association
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
# To make a followed_users array of users, it would be possible to pull out
# an array of followed_id attributes and then find the user for each one
# Rails uses has_many through to make this procedure more convenient.
#
# source parameter which explicitly tells Rails that the source of
# the followed_users array is the set of followed ids.
has_many :followed_users, through: :relationships, source: :followed
# we actually have to include the class name for this association
# because otherwise Rails would look for a ReverseRelationship class, which doesn’t exist.
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy
# we could actually omit the :source key in this case
# in the case of a :followers attribute, Rails will singularize “followers” and
# automatically look for the foreign key follower_id in this case
has_many :followers, through: :reverse_relationships, source: :follower
# validation Users
before_create :create_remember_token
before_save { self.email = email.downcase }
#callback to force Rails to downcase the email attribute before saving the user to the database
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
#The expression above does have one weakness, though: it allows invalid addresses such as foo@bar..com
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: {case_sensitive: false }
has_secure_password # for more info https://github.com/rails/rails/blob/master/activemodel/lib/active_model/secure_password.rb
validates :password, length: { minimum: 6 }
# users methods
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end
def feed
# This is preliminary. See "Following users" for the full implementation.
#The question mark
# ensures that id is properly escaped before being included in the underlying SQL query, thereby avoiding
# a serious security hole called SQL injection. The id attribute here is just an integer
# (i.e., self.id, the unique ID of the user), so there is no danger in this case,
# but always escaping variables injected into SQL statements is a good habit to cultivate.
# Micropost.where("user_id = ?", self.id) # is equal to "self.microposts"
Micropost.from_users_followed_by(self)
end
def following?(other_user)
# find_by return boolean
self.relationships.find_by(followed_id: other_user.id)
end
def follow!(other_user)
self.relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by(followed_id: other_user.id).destroy
end
private
def create_remember_token
# Create the token.
self.remember_token = User.digest(User.new_remember_token)
end
end
| true
|
31945490f2be94022473e42becf4aa7e18b08523
|
Ruby
|
graemenelson/hv-app
|
/app/presenters/dashboard_presenter.rb
|
UTF-8
| 1,593
| 2.8125
| 3
|
[] |
no_license
|
class DashboardPresenter
class Year
attr_reader :label,
:months
def initialize(label)
@label = label
@months = []
end
def push(customer, report)
@months.push(Month.new(customer,report))
end
end
class Month
attr_reader :customer,
:report
def initialize(customer, report)
@customer = customer
@report = report
end
def label
report.month.strftime("%m %B")
end
def media_count
report.count
end
def template
# NOTE: might need to handle current month
# currently, all months are completed months
return "no_media" unless media_count > 0
return "download" if downloadable?
return "building" if building?
return "order"
end
private
def downloadable?
report.build_pdf_finished_at && report.build_pdf_finished_at <= Time.zone.now
end
def building?
report.purchased_at && report.purchased_at <= Time.zone.now
end
end
attr_reader :customer
def initialize(customer)
@customer = customer
end
def years
@years ||= build_years
end
private
def build_years
customer.reports.inject([]) do |years, report|
year = create_or_find_year(years, report)
year.push(customer, report)
years
end
end
def create_or_find_year(years, report)
report_year = report.month.year
if years.last && years.last.label == report_year
years.last
else
year = Year.new(report_year)
years.push(year)
year
end
end
end
| true
|
3c13e6a83ae5ebf973ee9b87f7c7c5e96ace034a
|
Ruby
|
piepieninja/PiePieNinja.zshrc
|
/scripts/itunes.rb
|
UTF-8
| 764
| 2.78125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# coding: utf-8
##
# Author: Caleb Adams
# Contact: CalebAshmoreAdams@gmail.com
# Website: CalebDevelops.com
##
require 'colorize'
# ੦ᐅᖱ•‣∮ ⌘ ⏸ ⏹ ⏯ ⏲ ☞ ⚡ ✖ ♬
#cmd = "osascript -e 'tell application \"iTunes\" to if player state is playing then \"♬ \" & name of current track & \" - \" & artist of current track'"
cmd = "osascript -e 'tell application \"iTunes\" to if player state is playing then \"♬ \" & name of current track & \" - \" & artist of current track'"
input = `#{cmd}`
output = ""
# see colors
#puts String.colors
if input.to_s == ''
output << "[".white
output << "♬ ".magenta
output << "]".white
else
output << "[".white
output << input.gsub("\n","").magenta
output << "]".white
end
puts output
| true
|
2d7d42043f6f9d37d4dd6e13e5366453392a6180
|
Ruby
|
okasten/OO-mini-project-dumbo-web-100818
|
/app/models/Recipe.rb
|
UTF-8
| 937
| 3.109375
| 3
|
[] |
no_license
|
class Recipe
@@all = []
attr_reader :name
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def recipe_cards
RecipeCard.all.select do |card|
card.recipe == self
end
end
def self.most_popular
most = @@all.sort_by do |recipe|
recipe.recipe_cards.count
end
most[-1]
end
def users
recipe_cards.map do |card|
card.user
end
end
def recipe_ingredients
RecipeIngredient.all.select do |ri|
ri.recipe == self
end
end
def ingredients
recipe_ingredients.map do |ri|
ri.ingredient
end
end
def allergens
allergy = Allergen.all.select do |allergen|
ingredients.include?(allergen.ingredient)
end
allergy.map do |allergy|
allergy.ingredient
end
end
def add_ingredients(ingredients)
ingredients.each do |ing|
RecipeIngredient.new(self, ing)
end
end
end
| true
|
bfc69b12edbbd5be89c890cdac5238a0cbd753df
|
Ruby
|
stevenjackson/advent-of-code
|
/2016/3/day3_test.rb
|
UTF-8
| 999
| 3.421875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
class Day3Test < Minitest::Test
def test_is_triangle
input = "3 4 5"
assert triangle? input
end
def test_not_triangle
input = "12 1 2"
assert_equal(false, triangle?(input))
end
def test_pt1
full_input = File.read('input')
count = full_input.split("\n").select { |line| triangle?(line.strip) }.count
assert_equal 1050, count
end
def test_pt2
ordered_input = build_input
count = 0
ordered_input.each_slice(3) do |trinput|
count += 1 if triangle?(trinput.join(" "))
end
assert_equal 1921, count
end
def build_input
full_input = File.read('input')
lines = full_input.split("\n").map(&:strip)
inputs = lines.map(&:split)
ordered_input =
inputs.map(&:first) +
inputs.map { |parts| parts[1] } +
inputs.map(&:last)
end
def count_triangles(input)
end
def triangle?(input)
sides = input.split.map(&:to_i).sort
sides[0] + sides[1] > sides[2]
end
end
| true
|
624561e96a1e538271deb2fad6fa5b6341ac07d6
|
Ruby
|
xmisao/syobocal
|
/test/sub_titles/test_parser.rb
|
UTF-8
| 1,654
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
require "minitest/autorun"
require "syobocal"
module Syobocal
module SubTitles
class TestParser < MiniTest::Test
def test_parse
sub_titles = <<SUB_TITLES
*01*hoge
*02*hoge*piyo
03
*04*
**
SUB_TITLES
expected = [
SubTitle.new("01", "hoge"),
SubTitle.new("02", "hoge*piyo"),
SubTitle.new("04", ""),
SubTitle.new("", ""),
]
actual = Parser.new(sub_titles).parse
assert_equal actual, expected
end
def test_parse_sample
sample = ::JSON.parse(File.read(File.expand_path("../../samples/2077.json", __FILE__)))
sample_sub_titles = sample["sub_titles"]
expected = [
SubTitle.new("01", "夢の中で会った、ような・・・・・"),
SubTitle.new("02", "それはとっても嬉しいなって"),
SubTitle.new("03", "もう何も恐くない"),
SubTitle.new("04", "奇跡も、魔法も、あるんだよ"),
SubTitle.new("05", "後悔なんて、あるわけない"),
SubTitle.new("06", "こんなの絶対おかしいよ"),
SubTitle.new("07", "本当の気持ちと向き合えますか?"),
SubTitle.new("08", "あたしって、ほんとバカ"),
SubTitle.new("09", "そんなの、あたしが許さない"),
SubTitle.new("10", "もう誰にも頼らない"),
SubTitle.new("11", "最後に残った道しるべ"),
SubTitle.new("12", "わたしの、最高の友達"),
]
actual = Parser.new(sample_sub_titles).parse
assert_equal actual, expected
end
end
end
end
| true
|
d42d3058523fcd7afff8f78b13c4079b18f712e8
|
Ruby
|
pierrenav13/w4d5
|
/two_sums.rb
|
UTF-8
| 1,274
| 3.90625
| 4
|
[] |
no_license
|
def bad_two_sum?(arr, target_sum)
arr.each_with_index do |num1, idx1|
arr.each_with_index do |num2, idx2|
next if idx1 == idx2
return true if num1 + num2 == target_sum
end
end
false
end
arr = [0, 1, 5, 7]
# p bad_two_sum?(arr, 6) # => should be true
# p bad_two_sum?(arr, 10) # => should be false
def bsearch(arr, target)
mid = arr.length/2
case arr[mid] <=> target
when -1
result = bsearch(arr.drop(mid+1), target)
result ? result + mid + 1 : nil
when 0
return mid
when 1
return bsearch(arr.take(mid), target)
end
end
def okay_two_sum?(arr, target_sum)
sorted_arr = arr.sort
sorted_arr.each_with_index do |num, idx|
diff = target_sum - num
match = bsearch(sorted_arr[(idx+1)..-1], diff)
return true unless match.nil?
end
false
end
# p okay_two_sum?(arr, 6) # => should be true
# p okay_two_sum?(arr, 10) # => should be false
def two_sum?(arr, target_sum)
hash = {}
arr.each do |num|
diff = target_sum - num
return true if hash[diff]
hash[num] = true
end
false
end
p two_sum?(arr, 6) # => should be true
p two_sum?(arr, 10) # => should be false
| true
|
7ec29448e2962a66c34f86d2ead60254a00f02f3
|
Ruby
|
Samkiroko/Algorithms-and-Data-structures
|
/tower_of_hanoi2.rb
|
UTF-8
| 2,078
| 4.28125
| 4
|
[] |
no_license
|
# frozen_string_literal: true
# Challenge
# Create a program that solves the tower of Hanoi. You will be given one number as input - the number of disks on Peg 1.
# Create a method that prints a string with the correct steps to solve the puzzle.
# Output Format
# Print the peg to move from, an arrow "->", and the peg to move to. For example, to move from peg 1 to peg 3, print:
# 1->3.
# Print a string with all the steps, each step on its own line.
# Examples
# hanoi_steps(2)
# # => 1->2
# # 1->3
# # 2->3
# hanoi_steps(3)
# # => 1->3
# # 1->2
# # 3->2
# # 1->3
# # 2->1
# # 2->3
# # 1->3
# hanoi_steps(4)
# # => 1->2
# # 1->3
# # 2->3
# # 1->2
# # 3->1
# # 3->2
# # 1->2
# # 1->3
# # 2->3
# # 2->1
# # 3->1
# # 2->3
# # 1->2
# # 1->3
# # 2->3
def hanoi_steps(number_of_discs)
# your code here
step(number_of_discs, 1, 2, 3)
end
def step(number_of_discs, starting, intermediate, goal)
if number_of_discs == 1
puts move(starting, goal)
else
step(number_of_discs - 1, starting, goal, intermediate)
puts move(starting, goal)
step(number_of_discs - 1, intermediate, starting, goal)
end
end
def move(starting, goal)
"#{starting}->#{goal}"
end
hanoi_steps(2)
# => 1->2
# 1->3
# 2->3
hanoi_steps(3)
# => 1->3
# 1->2
# 3->2
# 1->3
# 2->1
# 2->3
# 1->3
hanoi_steps(4)
# => 1->2
# 1->3
# 2->3
# 1->2
# 3->1
# 3->2
# 1->2
# 1->3
# 2->3
# 2->1
# 3->1
# 2->3
# 1->2
# 1->3
# 2->3
# anothor solution
def hanoi_steps(number_of_discs)
move_discs(number_of_discs, 1, 2, 3)
end
def move_discs(n, a, b, c)
if n.positive?
move_discs(n - 1, a, c, b)
puts "#{a}->#{c}"
move_discs(n - 1, b, a, c)
end
end
hanoi_steps(2)
# => 1->2
# 1->3
# 2->3
hanoi_steps(3)
# => 1->3
# 1->2
# 3->2
# 1->3
# 2->1
# 2->3
# 1->3
hanoi_steps(4)
# => 1->2
# 1->3
# 2->3
# 1->2
# 3->1
# 3->2
# 1->2
# 1->3
# 2->3
# 2->1
# 3->1
# 2->3
# 1->2
# 1->3
# 2->3
| true
|
25d687add2a749b7844c637496a1dcc7a534fc01
|
Ruby
|
bstiber/launch_school_exercises
|
/loops1/loops2-2.rb/8.rb
|
UTF-8
| 428
| 4.34375
| 4
|
[] |
no_license
|
# Given the array of several numbers below, use an until loop to print each number.
puts "NON destructive version"
numbers = [7, 9, 13, 25, 18]
index = 0
until index == numbers.size
p numbers[index]
index += 1
end
puts '-' * 35 #-------------------------------------------
puts "destructive version"
numbers = [7, 9, 13, 25, 18]
new_array = []
until numbers.size == 0
new_array << numbers.shift
end
puts new_array
| true
|
a3233968140c07c64b9bbb1f863652ee9875b6e2
|
Ruby
|
jasonZYJ/ruby_python_useful_scripts
|
/ruby/zip_writer.rb
|
UTF-8
| 1,091
| 2.625
| 3
|
[] |
no_license
|
require 'zip'
module Purchasing
class ZipWriter
attr_accessor :input_dir, :output_file
def initialize(input_dir, output_file)
self.input_dir = input_dir
self.output_file = output_file
end
def write
entries = Dir.entries(input_dir) #TODO need to replace with sa file path
entries.delete(".")
entries.delete("..")
zip = Zip::File.open(output_file, Zip::File::CREATE)
write_entries(entries, "", zip)
zip.close
end
def write_entries(entries, path, io)
entries.each { |e|
zip_file_path = path == "" ? e : File.join(path, e)
disk_file_path = File.join(input_dir, zip_file_path)
puts "Zipping " + disk_file_path #TODO Debug
if File.directory?(disk_file_path)
io.mkdir(zip_file_path)
subdir =Dir.entries(disk_file_path); subdir.delete("."); subdir.delete("..")
write_entries(subdir, zip_file_path, io)
else
io.get_ouDtput_stream(zip_file_path) { |f| f.puts(File.open(disk_file_path, "rb").read) }
end
}
end
end
end
| true
|
9507cec8ed641480fefaa2b0187643eb847c8ea9
|
Ruby
|
thebravoman/software_engineering_2014
|
/vhodno_nivo/Veselina_Kolova_11B_8/Veselina_Kolova_16.rb
|
UTF-8
| 202
| 3.375
| 3
|
[] |
no_license
|
require 'mathn'
x = gets.to_i
while x < 0 || x > 10 do x = gets.to_i end
arr = Array.new(10)
z = 2
(0..x).each do
if Prime.prime?(z) && z % 10 == x then
puts z
arr < z
end
z++
end
puts arr
| true
|
76ce99429193f1b4a6f0f71f52ac1e47306b6ef1
|
Ruby
|
torianne02/advent-of-code
|
/2020/day-05/solution.rb
|
UTF-8
| 419
| 3.4375
| 3
|
[] |
no_license
|
def get_seats
File.read("2020/day-05/input.txt").split("\n")
end
def get_seat_ids(seats)
seats.map {|seat| seat.tr("BFRL", "1010").to_i(2) }
end
# part 1
def find_highest_seat_id(seat_ids)
seat_ids.max
end
# part 2
def find_my_seat(seat_ids)
my_seat = (seat_ids.min...seat_ids.max).to_a - seat_ids
my_seat.first
end
seat_ids = get_seat_ids(get_seats)
find_highest_seat_id(seat_ids)
find_my_seat(seat_ids)
| true
|
1d7a125d1fdc845fa11dd9ff1e10f7afeed1c80b
|
Ruby
|
livelink/morandi-rb
|
/lib/morandi/image_ops.rb
|
UTF-8
| 7,679
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'pango'
require 'colorscore'
module Morandi
class ImageOp
class << self
def new_from_hash(hash)
op = allocate
hash.each_pair do |key, val|
op.instance_variable_set("@#{key}", val) if op.respond_to?(key.intern)
end
op
end
end
def initialize; end
def priority
100
end
end
class Crop < ImageOp
attr_accessor :area
def initialize(area = nil)
super()
@area = area
end
def constrain(val, min, max)
if val < min
min
elsif val > max
max
else
val
end
end
def call(_image, pixbuf)
if @area && !@area.width.zero? && !@area.height.zero?
# NB: Cheap - fast & shares memory
Gdk::Pixbuf.new(pixbuf, @area.x, @area.y,
@area.width, @area.height)
else
pixbuf
end
end
end
class Rotate < ImageOp
attr_accessor :angle
def initialize(angle = 0)
super()
@angle = angle
end
def call(_image, pixbuf)
if @angle.zero?
pixbuf
else
case @angle
when 0, 90, 180, 270
PixbufUtils.rotate(pixbuf, @angle)
else
raise 'Not a valid angle'
end
end
end
end
class Straighten < ImageOp
attr_accessor :angle
def initialize(angle = 0)
super()
@angle = angle
end
def call(_image, pixbuf)
if @angle.zero?
pixbuf
else
surface = Cairo::ImageSurface.new(:rgb24, pixbuf.width, pixbuf.height)
rotation_value_rad = @angle * (Math::PI / 180)
ratio = pixbuf.width.to_f / pixbuf.height
rh = pixbuf.height / ((ratio * Math.sin(rotation_value_rad.abs)) + Math.cos(rotation_value_rad.abs))
scale = pixbuf.height / rh.to_f.abs
a_ratio = pixbuf.height.to_f / pixbuf.width
a_rh = pixbuf.width / ((a_ratio * Math.sin(rotation_value_rad.abs)) + Math.cos(rotation_value_rad.abs))
a_scale = pixbuf.width / a_rh.to_f.abs
scale = a_scale if a_scale > scale
cr = Cairo::Context.new(surface)
cr.translate(pixbuf.width / 2.0, pixbuf.height / 2.0)
cr.rotate(rotation_value_rad)
cr.scale(scale, scale)
cr.translate(pixbuf.width / -2.0, pixbuf.height / - 2.0)
cr.set_source_pixbuf(pixbuf)
cr.rectangle(0, 0, pixbuf.width, pixbuf.height)
cr.paint(1.0)
final_pb = surface.to_pixbuf
cr.destroy
surface.destroy
final_pb
end
end
end
class ImageCaption < ImageOp
attr_accessor :text
def font
@font || "Open Sans Condensed Light #{([@pixbuf.width, @pixbuf.height].max / 80.0).to_i}"
end
def position
@position ||
(@pixbuf ? ([[@pixbuf.width, @pixbuf.height].max / 20] * 2) : [100, 100])
end
def call(_image, pixbuf)
@pixbuf = pixbuf
surface = Cairo::ImageSurface.new(:rgb24, pixbuf.width, pixbuf.height)
cr = Cairo::Context.new(surface)
cr.save do
cr.set_source_pixbuf(pixbuf)
cr.paint(1.0)
cr.translate(*position)
layout = cr.create_pango_layout
layout.set_text(text)
layout.font_description = Pango::FontDescription.new(font)
layout.set_width((pixbuf.width - position[0] - 100) * Pango::SCALE)
layout.context_changed
ink, = layout.pixel_extents
cr.set_source_rgba(0, 0, 0, 0.3)
cr.rectangle(-25, -25, ink.width + 50, ink.height + 50)
cr.fill
cr.set_source_rgb(1, 1, 1)
cr.show_pango_layout(layout)
end
final_pb = surface.to_pixbuf
cr.destroy
surface.destroy
final_pb
end
end
class ImageBorder < ImageOp
attr_accessor :style, :colour, :crop, :size, :print_size, :shrink, :border_size
def initialize(style = 'none', colour = 'white')
super()
@style = style
@colour = colour
end
def call(_image, pixbuf)
return pixbuf unless %w[square retro].include? @style
surface = Cairo::ImageSurface.new(:rgb24, pixbuf.width, pixbuf.height)
cr = Cairo::Context.new(surface)
img_width = pixbuf.width
img_height = pixbuf.height
cr.save do
if @crop && ((@crop[0]).negative? || (@crop[1]).negative?)
img_width = size[0]
img_height = size[1]
cr.translate(- @crop[0], - @crop[1])
end
cr.save do
cr.set_operator :source
cr.set_source_rgb 1, 1, 1
cr.paint
cr.rectangle(0, 0, img_width, img_height)
case colour
when 'dominant'
pixbuf.scale_max(400).save(fn = "/tmp/hist-#{$PROCESS_ID}.#{Time.now.to_i}", 'jpeg')
hgram = Colorscore::Histogram.new(fn)
begin
File.unlink(fn)
rescue StandardError
nil
end
col = hgram.scores.first[1]
cr.set_source_rgb col.red / 256.0, col.green / 256.0, col.blue / 256.0
when 'retro'
cr.set_source_rgb 1, 1, 0.8
when 'black'
cr.set_source_rgb 0, 0, 0
else
cr.set_source_rgb 1, 1, 1
end
cr.fill
end
end
border_scale = [img_width, img_height].max.to_f / print_size.max.to_i
size = @border_size
size *= border_scale
x = size
y = size
# This biggest impact will be on the smallest side, so to avoid white
# edges between photo and border scale by the longest changed side.
longest_side = [pixbuf.width, pixbuf.height].max.to_f
# Should be less than 1
pb_scale = (longest_side - (size * 2)) / longest_side
if @crop && ((@crop[0]).negative? || (@crop[1]).negative?)
x -= @crop[0]
y -= @crop[1]
end
case style
when 'retro'
# WARNING: CairoUtils class is not available in this gem!
CairoUtils.rounded_rectangle(cr, x, y,
img_width + x - (size * 2), img_height + y - (size * 2), size)
when 'square'
cr.rectangle(x, y, img_width - (size * 2), img_height - (size * 2))
end
cr.clip
if @shrink
cr.translate(size, size)
cr.scale(pb_scale, pb_scale)
end
cr.set_source_pixbuf(pixbuf)
cr.rectangle(0, 0, pixbuf.width, pixbuf.height)
cr.paint(1.0)
final_pb = surface.to_pixbuf
cr.destroy
surface.destroy
final_pb
end
end
class Gamma < ImageOp
attr_reader :gamma
def initialize(gamma = 1.0)
super()
@gamma = gamma
end
def call(_image, pixbuf)
if (@gamma - 1.0).abs < Float::EPSILON
pixbuf
else
PixbufUtils.gamma(pixbuf, @gamma)
end
end
def priority
90
end
end
class Colourify < ImageOp
attr_reader :op
def initialize(operation, alpha = 255)
super()
@operation = operation
@alpha = alpha
end
def alpha
@alpha || 255
end
def sepia(pixbuf)
PixbufUtils.tint(pixbuf, 25, 5, -25, alpha)
end
def bluetone(pixbuf)
PixbufUtils.tint(pixbuf, -10, 5, 25, alpha)
end
def null(pixbuf)
pixbuf
end
alias full null # WebKiosk
alias colour null # WebKiosk
def greyscale(pixbuf)
PixbufUtils.tint(pixbuf, 0, 0, 0, alpha)
end
alias bw greyscale # WebKiosk
def call(_image, pixbuf)
if @operation && respond_to?(@operation)
__send__(@operation, pixbuf)
else
pixbuf # Default is nothing
end
end
end
end
| true
|
5b41bf39cea523b75deedb5c4735ed4a2533d501
|
Ruby
|
programmurr/chess
|
/spec/move_checks_spec.rb
|
UTF-8
| 10,616
| 2.828125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require_relative '../lib/move_checks'
describe MoveChecks do
before do
@board = Board.new
@board.set_cell_coordinates
@board.place_pawns
@board.place_royalty
end
context '#promote_pawn?' do
it 'returns true if there is a white Pawn present on board row 0' do
@board.grid[0][0].value = Pawn.new('White')
player = double
expect(MoveChecks.new(player, @board).promote_pawn?).to eq true
end
it 'returns false if there is not white Pawn present on board row 0' do
player = double
expect(MoveChecks.new(player, @board).promote_pawn?).to eq false
end
it 'returns true if there is a black Pawn present on board row 7' do
@board.grid[7][0].value = Pawn.new('Black')
player = double
expect(MoveChecks.new(player, @board).promote_pawn?).to eq true
end
it 'returns false if there is not black Pawn present on board row 7' do
player = double
expect(MoveChecks.new(player, @board).promote_pawn?).to eq false
end
end
context '#castle?' do
it 'returns false if the spaces between the a1 rook and the king are occupied' do
@board.grid[7][2].value = nil
@board.grid[7][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns true if the spaces between the a1 rook and the king are unoccupied and it is the first move of the rook and the king' do
@board.grid[7][1].value = nil
@board.grid[7][2].value = nil
@board.grid[7][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq true
end
it 'returns false if the spaces between the a1 rook and the king are unoccupied and it is not the first move of the rook' do
@board.grid[7][0].value.number_of_moves = 2
@board.grid[7][1].value = nil
@board.grid[7][2].value = nil
@board.grid[7][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the a1 rook and the king are unoccupied and it is not the first move of the king' do
@board.grid[7][4].value.number_of_moves = 2
@board.grid[7][1].value = nil
@board.grid[7][2].value = nil
@board.grid[7][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the a1 rook and the king are unoccupied and it is not the first move of the king and not the first move of the rook' do
@board.grid[7][4].value.number_of_moves = 1
@board.grid[7][0].value.number_of_moves = 1
@board.grid[7][1].value = nil
@board.grid[7][2].value = nil
@board.grid[7][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h1 rook and the king are occupied' do
player = double('Player', move: 'castlea1', color: 'White')
check_cells = nil
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns true if the spaces between the h1 rook and the king are unoccupied and it is the first move of the rook and the king' do
@board.grid[7][5].value = nil
@board.grid[7][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq true
end
it 'returns false if the spaces between the h1 rook and the king are unoccupied and it is not the first move of the rook' do
@board.grid[7][7].value.number_of_moves = 2
@board.grid[7][5].value = nil
@board.grid[7][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h1 rook and the king are unoccupied and it is not the first move of the king' do
@board.grid[7][4].value.number_of_moves = 2
@board.grid[7][5].value = nil
@board.grid[7][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h1 rook and the king are unoccupied and it is not the first move of the king and not the first move of the rook' do
@board.grid[7][4].value.number_of_moves = 2
@board.grid[7][7].value.number_of_moves = 2
@board.grid[7][5].value = nil
@board.grid[7][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh1', color: 'White')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h8 rook and the king are occupied' do
player = double('Player', move: 'castleh8', color: 'Black')
check_cells = nil
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns true if the spaces between the h8 rook and the king are unoccupied and it is the first move of the rook and the king' do
@board.grid[0][5].value = nil
@board.grid[0][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq true
end
it 'returns false if the spaces between the h8 rook and the king are unoccupied and it is not the first move of the rook' do
@board.grid[0][7].value.number_of_moves = 2
@board.grid[0][5].value = nil
@board.grid[0][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h8 rook and the king are unoccupied and it is not the first move of the king' do
@board.grid[0][4].value.number_of_moves = 1
@board.grid[0][5].value = nil
@board.grid[0][6].value = nil
check_cells = nil
player = double('Player', move: 'castleh8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the h8 rook and the king are unoccupied and it is not the first move of the king and not the first move of the rook' do
@board.grid[0][4].value.number_of_moves = 3
@board.grid[0][7].value.number_of_moves = 1
@board.grid[0][5].value = nil
@board.grid[0][6].value = nil
player = double('Player', move: 'castleh8', color: 'Black')
check_cells = nil
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the a8 rook and the king are occupied' do
@board.grid[0][2].value = nil
@board.grid[0][3].value = nil
player = double('Player', move: 'castlea8', color: 'Black')
check_cells = nil
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns true if the spaces between the a8 rook and the king are unoccupied and it is the first move of the rook and the king' do
@board.grid[0][1].value = nil
@board.grid[0][2].value = nil
@board.grid[0][3].value = nil
player = double('Player', move: 'castlea8', color: 'Black')
check_cells = nil
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq true
end
it 'returns false if the spaces between the a8 rook and the king are unoccupied and it is not the first move of the rook' do
@board.grid[0][0].value.number_of_moves = 2
@board.grid[0][1].value = nil
@board.grid[0][2].value = nil
@board.grid[0][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the a8 rook and the king are unoccupied and it is not the first move of the king' do
@board.grid[0][4].value.number_of_moves = 21
@board.grid[0][1].value = nil
@board.grid[0][2].value = nil
@board.grid[0][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
it 'returns false if the spaces between the a8 rook and the king are unoccupied and it is not the first move of the king and not the first move of the rook' do
@board.grid[0][4].value.number_of_moves = 2
@board.grid[0][0].value.number_of_moves = 21
@board.grid[0][1].value = nil
@board.grid[0][2].value = nil
@board.grid[0][3].value = nil
check_cells = nil
player = double('Player', move: 'castlea8', color: 'Black')
expect(MoveChecks.new(player, @board).castle?(check_cells)).to eq false
end
end
context '#cell_contains_piece?' do
it 'returns true if the cell contains a piece to be moved' do
player = double('Player', move: %w[h2 h3])
expect(MoveChecks.new(player, @board).start_cell_contains_piece?).to eq true
end
it 'returns false if the cell does not contain a piece to be moved' do
player = double('Player', move: %w[h3 h5])
expect(MoveChecks.new(player, @board).start_cell_contains_piece?).to eq false
end
end
context '#matching_piece_class?' do
it "returns 'true' if the player piece class matches the superclass of the piece to be moved" do
player = double('Player', move: %w[a2 a4], color: 'White')
expect(MoveChecks.new(player, @board).matching_piece_class?).to eq true
end
it "returns 'false' if the player piece class does not match the superclass of the piece to be moved" do
player = double('Player', move: %w[a2 a4], color: 'Black')
expect(MoveChecks.new(player, @board).matching_piece_class?).to eq false
end
end
end
| true
|
8e0ebe0ffab95e25e5f92618cb302370653b8556
|
Ruby
|
rodikno/Automation_course
|
/helpers/redmine_user.rb
|
UTF-8
| 663
| 2.734375
| 3
|
[] |
no_license
|
require 'selenium-webdriver'
require 'faker'
class RedmineUser
attr_reader :first_name, :last_name, :full_name, :login, :email
attr_accessor :password, :id
def initialize(opts={})
@first_name = opts[:first_name] || Faker::Name.first_name
@last_name = opts[:last_name] || Faker::Name.last_name
@login = opts[:login] || Faker::Internet.user_name("#{@first_name} #{@last_name}", %w(. _ -)) + rand(1000).to_s
@password = opts[:password] || Faker::Internet.password
@email = opts[:email] || Faker::Internet.safe_email(@login)
@id = opts[:id] || nil
@full_name = @first_name + ' ' + @last_name
end
end
| true
|
b20689e7e52021725ce923301ade54228b5f1966
|
Ruby
|
manutazo/radar_module
|
/spec/attack_mode_spec.rb
|
UTF-8
| 815
| 2.5625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe AttackMode do
describe 'building' do
context 'insufficient params' do
it 'returns an error' do
expect { AttackMode.new }.to raise_error(KeyError)
end
end
context 'sufficient params' do
it 'returns an error' do
expect(AttackMode.new(mode: 'closest-first')).to be_a AttackMode
end
end
end
describe 'validity' do
AttackMode::MODES.each do |mode|
context "building an AttackMode of mode #{mode}" do
it 'is valid' do
expect(AttackMode.new(mode: mode).valid?).to eq true
end
end
end
context 'building an AttackMode of non permitted mode' do
it 'is invalid' do
expect(AttackMode.new(mode: 'Predator', damage: 30).valid?).to eq false
end
end
end
end
| true
|
ec2fda8949950fc7047dbed36c622b18b14a6354
|
Ruby
|
bdphilly/chess
|
/pieces/stepping_piece.rb
|
UTF-8
| 835
| 3.15625
| 3
|
[] |
no_license
|
require_relative "./piece.rb"
class SteppingPiece < Piece
attr_accessor :deltas, :display, :color
def initialize(pos, board, color)
super(pos, board, color)
@deltas = []
end
def moves
[].tap do |valid_moves|
self.deltas.each do |each_delta|
current_position = self.position
1.times do
current_position = (current_position.first + each_delta.first), (current_position.last + each_delta.last)
break unless valid?(current_position)
valid_moves << current_position
end
end
end
end
def valid?(pos)
if ((0..7).cover?(pos.first) &&
(0..7).cover?(pos.last)) &&
((board[pos.first][pos.last].class == Board::EmptyTile) ||
(board[pos.first][pos.last].color != self.color))
return true
end
false
end
end
| true
|
c86737caf5aa3070ad7d47e62e51ab2d4c71cc65
|
Ruby
|
jlieb10/MazeSolver
|
/maze_solver.rb
|
UTF-8
| 3,845
| 3.609375
| 4
|
[] |
no_license
|
class MazeSolver
attr_reader :maze, :traveled_path, :visited_nodes, :node_queue
def initialize(maze)
@maze = maze # ASCII Maze Input to Class Var
@maze_array=[] # @maze variable parsed into an array of rows
@start=[] # coordinates of start of maze indicated by "→"
@end=[] # coordinates of end of maze indicated by "@"
@traveled_path = []
@visited_nodes = []
@node_queue = []
@nodes=[]
@levels=[]
end
def maze_array
@maze_array = @maze.split("\n").map do |maze_row|
maze_row.strip.split(//)
end
end
def startend
@maze_array.each do |maze_row|
if maze_row.index("→")
@start = [maze_row.index("→"), @maze_array.index(maze_row)]
@visited_nodes << @start
@node_queue << @start
@levels[0] = [@start]
elsif maze_row.index("@")
@end = [maze_row.index("@"), @maze_array.index(maze_row)]
@nodes << @end
end
end
end
def possible_nodes
y = 0
x = 0
while y < @maze_array.length
while x <@maze_array[y].length
@nodes << [x, y] if @maze_array[y][x] == " "
x += 1
end
y += 1
x = 0
end
end
def breadth
counter = 1
until @node_queue.include?(@end)
new_node_queue = []
@node_queue.each do |current_node|
x, y = current_node
if @nodes.include?([x+1, y]) &&
!@visited_nodes.include?([x+1, y])
new_node_queue << [x+1, y]
@visited_nodes << [x+1, y]
end
if @nodes.include?([x-1, y]) &&
!@visited_nodes.include?([x-1, y])
new_node_queue << [x-1, y]
@visited_nodes << [x-1, y]
end
if @nodes.include?([x, y+1]) &&
!@visited_nodes.include?([x, y+1])
new_node_queue << [x, y+1]
@visited_nodes << [x, y+1]
end
if @nodes.include?([x, y-1]) &&
!@visited_nodes.include?([x, y-1])
new_node_queue << [x, y-1]
@visited_nodes << [x, y-1]
end
end
@levels[counter]=new_node_queue
@node_queue = new_node_queue
counter += 1
end
end
def solve
maze_array
startend
possible_nodes
breadth
@traveled_path << @start << @end
counter = 1
while counter <= @levels.length-2
if @levels[counter].length == 1
@traveled_path << @levels[counter][0]
counter+=1
else
@levels[counter].map do |coord|
x, y = coord
if (@levels[counter+1].include?([x+1, y]) ||
@levels[counter+1].include?([x-1, y]) ||
@levels[counter+1].include?([x, y+1]) ||
@levels[counter+1].include?([x, y-1])) &&
(@levels[counter-1].include?([x+1, y]) ||
@levels[counter-1].include?([x-1, y]) ||
@levels[counter-1].include?([x, y+1]) ||
@levels[counter-1].include?([x, y-1]))
@traveled_path << coord
counter+=1
else
@levels[counter].delete(coord)
end
end
end
end
solution_path
end
def solution_path
@traveled_path
end
def display_solution_path
solve
solved_array = @maze_array
@traveled_path.each do |coord|
x, y = coord
solved_array[y][x] = "." if solved_array[y][x] == " "
end
solved_array = solved_array.map do |row|
row.join
end.join("\n")
puts solved_array
end
end
maze =
"
######################
# # #
# ## ### ######## ## #
→ # # # #
### # ### ## ### ## #
# # # #
# ########## ######
# # # @
# ### ########## #####
# # #
######################"
ms = MazeSolver.new(maze)
ms.display_solution_path
| true
|
6f42885e656df7d73c8f50178e53ed19352d4231
|
Ruby
|
wallezhang/aliyun-odps-ruby-sdk
|
/lib/odps/models/instance.rb
|
UTF-8
| 4,696
| 2.515625
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] |
permissive
|
=begin
Copyright 2015 ZhangZhaoyuan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'odps/xml_serializer'
require 'rexml/document'
require 'odps/models/tasks'
require 'odps/models/stage'
require 'json'
module AliODPS
class Instance < XMLSerializer
attr_accessor :name, :owner, :status, :start_time, :end_time, :tasks, :priority, :comment, :location, :detail,
:progress, :json_summary, :summary
def initialize
@root_node = 'Instance'
node_register [String, nil, "/#{@root_node}/Name", '@name'],
[String, nil, "/#{@root_node}/Owner", '@owner'],
[String, nil, "/#{@root_node}/Status", '@status'],
[String, nil, "/#{@root_node}/StartTime", '@start_time'],
[Array, Hash, "/#{@root_node}/EndTime", '@end_time']
end
##
# Get the instance tasks
# [path] /projects/test_project/instances/instancename?taskstatus
# [method] GET
# [return] task object array
def get_tasks
res = ODPS.conn.get "projects/#{ODPS.current_project}/instances/#{self.name}?taskstatus"
tasks = []
REXML::XPath.each(REXML::Document.new(res.body), '/Instance/Tasks/Task') do |element|
case element.attribute('Type').value
when 'SQL'
tasks << SQLTask.new.deserialize(element)
when 'SQLPlan'
tasks << SQLPlanTask.new.deserialize(element)
else
AliODPS::LOGGER.warn "Unknown task type: #{element.attribute('Type').value}"
end
end
tasks
end
##
# Refresh instance status
# [path] /projects/test_project/instances/instancename
# [method] GET
# [return] refresh result: +true+ or +false+
def refresh_status
res = ODPS.conn.get "projects/#{ODPS.current_project}/instances/#{self.name}"
self.deserialize res.body
res.status == 200
end
##
# Get a instance detail
# [path] /projects/projectname/instances/instancename?instancedetail&taskname=taskname
# [method] GET
# [return] detail hash object. e.g. detail['JsonSummary']
def get_detail(task_name)
res = ODPS.conn.get "projects/#{ODPS.current_project}/instances/#{self.name}?instancedetail&taskname=#{task_name}"
if res.status == 200
obj = JSON.parse(res.body)
if obj.has_key? 'Instance'
self.detail = obj['Instance']
end
end
self.detail
end
##
# Get a instance task execute progress
# [path] /projects/projectname/instances/instancename?instanceprogress&taskname=taskname
# [method] GET
# [return] progress array. e.g. [+Stage+ Object...]
def get_progress(task_name)
res = ODPS.conn.get "projects/#{ODPS.current_project}/instances/#{self.name}?instanceprogress&taskname=#{task_name}"
progress = []
REXML::XPath.each(REXML::Document.new(res.body), '/Progress/Stage') do |element|
stage = Stage.new.deserialize(element)
stage.id = element.attribute['ID'].value
progress << stage
end
self.progress = progress
progress
end
##
# Get a instance task summary
# [path] /projects/projectname/instances/instancename?instancesummary&taskname=taskname
# [method] GET
# [return] a hash object. obj['Summary'],obj['JsonSummary']
def get_summary(task_name)
res = ODPS.conn.get "projects/#{ODPS.current_project}/instances/#{self.name}?instancesummary&taskname=#{task_name}"
obj = JSON.parse res.body
if obj.has_key? 'Instance'
self.json_summary = obj['Instance']['JsonSummary']
self.summary = obj['Instance']['Summary']
end
obj['Instance']
end
##
# Terminate a instance
# [path] /projects/test_project/instances/instancname
# [method] PUT
# [return] terminate result. +true+ or +false+
def terminate
res = ODPS.conn.put do |req|
req.url "projects/#{ODPS.current_project}/instances/#{self.name}"
req.headers['Content-Type'] = 'application/xml'
req.body = self.serialize [String, nil, 'Status', 'Terminated']
end
self.location = res['Location']
res.status == 200
end
end
end
| true
|
26163afd6d943f317378546c93bd10de2bde63f6
|
Ruby
|
traciechang/algorithm-problems
|
/verifying_an_alien_dictionary.rb
|
UTF-8
| 1,746
| 4.0625
| 4
|
[] |
no_license
|
# leet
# In an alien language, surprisingly they also use english lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters.
# Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographicaly in this alien language.
require 'pry'
def is_alien_sorted(words, order)
# output = true
words.each_with_index do |word, idx|
current_idx = 0
# current_word_pos = order[word[current_idx]]
# next_word_pos = order[words[idx+1][current_idx]]
# return false if current_word_pos > next_word_pos
# if current_word_pos == next_word_pos
# current_idx += 1
# end
unless idx == words.length - 1
# binding.pry
temp = compare_letters(words, order, word, idx, current_idx)
binding.pry
# return false
end
end
true
end
def compare_letters(words, order, word, idx, current_idx)
# break if words[idx+1].nil?
# binding.pry
current_word_pos = order.index(word[current_idx])
next_word_pos = order.index(words[idx+1][current_idx])
# binding.pry
if next_word_pos.nil? || current_word_pos > next_word_pos
return false
end
if current_word_pos == next_word_pos
current_idx += 1
compare_letters(words, order, word, idx, current_idx) unless idx == word.length - 1
end
true
end
puts is_alien_sorted(["hello","leetcode"], "hlabcdefgijkmnopqrstuvwxyz")
# puts is_alien_sorted(["word","world","row"], "worldabcefghijkmnpqstuvxyz")
# puts is_alien_sorted(["apple","app"], "abcdefghijklmnopqrstuvwxyz")
| true
|
cff7b48bdeef88b421edbdf17e371f21b7a2b775
|
Ruby
|
p8952/nginx-puma-sinatra
|
/app.rb
|
UTF-8
| 154
| 2.515625
| 3
|
[] |
no_license
|
require 'sinatra/base'
class App < Sinatra::Base
get '/' do
"<p>This is <i>dynamic</i> content served via puma: #{rand(36**6).to_s(36)}"
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.