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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dab8a8901b3dbb16f4100460357da47d5d0e49e5
|
Ruby
|
TheEntropics/serben-cash
|
/app/helpers/application_helper.rb
|
UTF-8
| 381
| 2.546875
| 3
|
[] |
no_license
|
module ApplicationHelper
def true_mark
check_box_tag nil, 1, true, disabled: true
end
def false_mark
check_box_tag nil, 0, false, disabled: true
end
def boolean_mark(status)
status ? true_mark : false_mark
end
def format_date(date)
date.strftime("%d/%m/%Y")
end
def format_currency(amount)
number_to_currency amount, unit: '€ '
end
end
| true
|
a437a4205e37c25a08deb3c2e9f97dc7a5e356a0
|
Ruby
|
ginasekhar/ruby-enumerables-hash-practice-green-grocer-lab-online-web-prework
|
/grocer.rb
|
UTF-8
| 2,010
| 3.3125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def consolidate_cart(cart)
consolidated_hash = {}
cart.each do |item_hash|
item_name = item_hash.keys[0]
item_details = item_hash.values[0]
if consolidated_hash.has_key?(item_name)
consolidated_hash[item_name][:count] += 1
else
consolidated_hash[item_name] = {count: 1,
price: item_details[:price],
clearance: item_details[:clearance]
}
end #if
end #do
return consolidated_hash
end
def apply_coupons(cart, coupons)
coupons.each do |each_coupon|
item_name = each_coupon[:item]
item_name_w_coupon = "#{item_name} W/COUPON"
if (cart.has_key?item_name) && (cart[item_name][:count] >= each_coupon[:num])
if cart.has_key?(item_name_w_coupon)
cart[item_name_w_coupon][:count] += each_coupon[:num]
else
cart[item_name_w_coupon] = {clearance: cart[item_name][:clearance],
price: each_coupon[:cost]/each_coupon[:num],
count: each_coupon[:num]}
end #if
cart[item_name][:count] -= each_coupon[:num]
end #if
end #do
cart
end
def apply_clearance(cart)
cart.each do |item, item_attributes|
if item_attributes[:clearance]
item_attributes[:price] = (item_attributes[:price] * 0.8).round(2)
end
end # do
cart
# code here
end
def checkout(cart, coupons)
consolidated_hash = consolidate_cart(cart)
discounted_cart = apply_coupons(consolidated_hash, coupons)
clearanced_cart = apply_clearance(discounted_cart)
total = 0
clearanced_cart.each do |item, item_attributes|
item_total = item_attributes[:count] * item_attributes[:price]
puts " #{item_attributes[:count]} #{item}s at #{item_attributes[:price]} each - #{item_total}"
total += item_total
end #do
if total > 100
total *= 0.9
end
total
end
| true
|
bd9f1e9970871af23a56fe93cc75ac8e69346055
|
Ruby
|
jalena-penaligon/brownfield-of-dreams
|
/spec/models/user_spec.rb
|
UTF-8
| 3,278
| 2.578125
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'validations' do
it {should validate_presence_of(:email)}
it {should validate_presence_of(:first_name)}
it {should validate_presence_of(:password)}
end
describe 'roles' do
it 'can be created as default user' do
user = User.create(email: 'user@email.com', password: 'password', first_name:'Jim', role: 0)
expect(user.role).to eq('default')
expect(user.default?).to be_truthy
end
it 'can be created as an Admin user' do
admin = User.create(email: 'admin@email.com', password: 'admin', first_name:'Bob', role: 1)
expect(admin.role).to eq('admin')
expect(admin.admin?).to be_truthy
end
end
describe 'instance methods' do
describe "friendships?" do
it "determines whether or not user has friendships" do
user = User.create(email: 'user@email.com', password: 'password', first_name:'Jim', role: 0)
expect(user.friendships?).to be false
Friendship.create(user_id: user.id, friend_id: 2, friend_login: "Friend")
expect(user.friendships?).to be true
end
end
describe "friend?" do
end
describe 'confirmation_token' do
it 'updates a users confirm_token' do
user = User.create(email: 'user@email.com', password: 'password', first_name:'Jim', role: 0)
expect(user.confirm_token).to eq(nil)
user.confirmation_token
expect(user.confirm_token).to_not eq(nil)
expect(user.confirm_token).to be_a(String)
end
end
it 'returns tutorials with bookmarked videos' do
user = create(:user)
tutorial= create(:tutorial, title: "I Love Pineapple Pizza")
video = create(:video, title: "The Best Video", tutorial_id: tutorial.id, position: 3)
video_2 = create(:video, title: "The Best Video V2", tutorial_id: tutorial.id, position: 2)
video_3 = create(:video, title: "The Best Video V3", tutorial_id: tutorial.id, position: 1)
user.user_videos.create(video_id: video.id)
user.user_videos.create(video_id: video_3.id)
expect(user.retrieve_bookmarks.first.tutorial_title).to eq(tutorial.title)
expect(user.retrieve_bookmarks.first.tutorial_id).to eq(tutorial.id)
expect(user.retrieve_bookmarks.first.id).to eq(video_3.id)
expect(user.retrieve_bookmarks.last.id).to eq(video.id)
expect(user.retrieve_bookmarks.last.title).to eq(video.title)
end
it 'formats users bookmarks to a hash' do
user = create(:user)
tutorial= create(:tutorial, title: "I Love Pineapple Pizza")
video = create(:video, title: "The Best Video", tutorial_id: tutorial.id, position: 3)
video_2 = create(:video, title: "The Best Video V2", tutorial_id: tutorial.id, position: 2)
video_3 = create(:video, title: "The Best Video V3", tutorial_id: tutorial.id, position: 1)
user.user_videos.create(video_id: video.id)
user.user_videos.create(video_id: video_3.id)
result = {
{
tutorial.id => tutorial.title
} => [
{
video_3.id => video_3.title
},
{
video.id => video.title
}
]
}
expect(user.display_bookmarks).to eq(result)
end
end
end
| true
|
e7756d4f7e6d442b516737b82abbc67efcd0643d
|
Ruby
|
AlwaysBCoding/ruby_tictactoe
|
/lib/square.rb
|
UTF-8
| 585
| 3.40625
| 3
|
[] |
no_license
|
class Square
attr_accessor :x_value, :y_value, :diag_value, :number, :text_value
def initialize(x,y,diag=nil,text_value=nil,number=nil)
@x_value = x
@y_value = y
@diag_value = diag
@text_value = text_value.to_s
@number = number
end
def empty?
return true if text_value.to_s != "X" && text_value.to_s != "O"
end
def change_text_value(val)
@text_value = val
end
def colored_text_value
return text_value.to_s.green if text_value == "X"
return text_value.to_s.red if text_value == "O"
return text_value.to_s.light_yellow
end
end
| true
|
5ddc6c028a84303147ce349142e7644f8c087290
|
Ruby
|
zebogen/climate_tweets
|
/app/controllers/twitterpull.rb
|
UTF-8
| 2,144
| 2.703125
| 3
|
[] |
no_license
|
require 'oauth'
require 'json'
module TwitterPull
def TwitterPull.pull(inp_query, inp_count)
consumer_key = OAuth::Consumer.new(
"wcs1zGACZ8pBMLGUWDJwLvVPt",
"q2OycC0G2cFNBZrkqP5Z2UXClDlcg63BqDEMP9OrRGeYZoCX5v")
access_token = OAuth::Token.new(
"1628440405-T5dufqnbYGMZ8kYOkHMvZaiE6b6lM4vCTDByBUG",
"xCyHQ1bgcgsJ2tKBTPn4NISHQZWB6xJtaRBaqo3W6sdhH")
baseurl = "https://api.twitter.com"
path = "/1.1/search/tweets.json"
query = URI.encode_www_form(
"q" => inp_query,
"count" => 100
)
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri
tweets = nil
tweet_max = inp_count
total_tweets = 0
tweet_block = []
# Set up HTTP.
http = Net::HTTP.new address.host, address.port
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# Issue the request.
request.oauth! http, consumer_key, access_token
http.start
response = http.request request
puts response
while total_tweets < tweet_max and response.code == '200' do
tweet_count = 0
tweets = JSON.parse(response.body)
max_id = tweets["statuses"][0]["id"]
tweets["statuses"].each do |t|
max_id = t["id"] if t["id"] < max_id
tweet_count += 1
# userhash = t["user"]
# tweethash = {
# "id" => t["id"],
# "text" => t["text"],
# "user" => userhash["screen_name"],
# "time" => t["created_at"]
# }
# tweet_block << tweethash
tweet_block << t["text"]
end
total_tweets += tweet_count
query = URI.encode_www_form(
"q" => inp_query,
"count" => 100,
"max_id" => max_id
)
address = URI("#{baseurl}#{path}?#{query}")
request = Net::HTTP::Get.new address.request_uri
request.oauth! http, consumer_key, access_token
response = http.request request
while response.code == '429' do
puts "Too many requests... sleeping for 15 seconds."
sleep 15
request.oauth! http, consumer_key, access_token
response = http.request request
end
end
puts response if response.code != '200'
return tweet_block
end
end
| true
|
82db1e8782d33e803f38ec26a7120f5a1e549d0c
|
Ruby
|
historyforge/historyforge
|
/app/models/role.rb
|
UTF-8
| 848
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
# This used to be an ActiveRecord model from the MapWarper days. It is now a bitmask model to make storage and
# lookup more efficient.
class Role < BitmaskModel
self.data = [
'Administrator',
'Editor',
'Reviewer',
'Photographer',
'Census Taker',
'Builder',
'Person Record Editor'
]
self.descriptions = [
'Administrators can do anything. They are the only ones who can delete anything.',
'Editors can create and edit any census record.',
'Reviewers can review any census record, building, or photograph.',
'Photographers can create and edit any photograph records.',
'Census takers can add new census records and edit the ones they created.',
'Builders can create and edit any building records.',
'Person Record editors can edit person records.'
]
end
| true
|
3251825e48f62ecb263c853c3a3dc0105efbd88a
|
Ruby
|
mikylamoehlenbruck/rb101
|
/lesson_2/rock_paper_scissors.rb
|
UTF-8
| 3,815
| 3.421875
| 3
|
[] |
no_license
|
require 'yaml'
MESSAGES = YAML.load_file('rps_messages.yml')
LANGUAGE = 'en'
VALID_CHOICES = %w(rock paper scissors lizard spock)
ABBREVIATIONS = %w(r p s l $)
WINNING_OPTIONS = {
'rock' => ['scissors', 'lizard'],
'paper' => ['rock', 'spock'],
'scissors' => ['paper' 'lizard'],
'lizard' => ['spock', 'paper'],
'spock' => ['rock', 'scissors']
}
def clear_screen
system("clear") || system("cls")
end
def prompt(message)
puts "=> #{message}"
end
def display_welcome
prompt(MESSAGES['welcome'] + "#{VALID_CHOICES.join(', ')}!")
end
def display_target_points
prompt(MESSAGES['target_points'])
end
def retrieve_player_choice
prompt(MESSAGES['choose_one'])
prompt(MESSAGES['choices'])
answer = ""
loop do
answer = gets.chomp
break if answer.start_with?('r', 'p', 's', 'l', '$')
prompt(MESSAGES['invalid_entry'])
prompt(MESSAGES['please_enter'])
end
answer
end
def win?(first, second)
WINNING_OPTIONS[first].include?(second)
end
def convert_choices(player)
result = case player
when "r" then "rock"
when "p" then "paper"
when "s" then "scissors"
when "l" then "lizard"
when "$" then "spock"
end
result
end
def display_choices(player, computer)
print(MESSAGES['player_choice'] + "#{player}; ")
puts(MESSAGES['computer_choice'] + " #{computer}")
end
def calculate_score(first_player, second_player)
if win?(first_player, second_player)
first_player = 1
else
first_player = 0
end
end
def calculate_winner(first_player, second_player)
if first_player == 1
first_player = 'player'
elsif second_player == 1
second_player = 'computer'
end
end
def display_results(winner)
case winner
when 'player' then prompt(MESSAGES['player_win'])
when 'computer' then prompt(MESSAGES['computer_win'])
else prompt(MESSAGES['tie'])
end
end
def update_score(winner, hash_scores)
case winner
when 'player' then hash_scores[:player_score] += 1
when 'computer' then hash_scores[:computer_score] += 1
end
end
def display_score(hash_scores)
print "You have #{hash_scores[:player_score]} point(s), "
puts "Computer has #{hash_scores[:computer_score]} point(s)"
end
def pause_and_clear
sleep 2.0
clear_screen
end
def game_over?(hash_scores)
hash_scores[:player_score] == 5 || hash_scores[:computer_score] == 5
end
def display_winner(hash_scores)
if hash_scores[:player_score] == 5
prompt(MESSAGES['game_player'] + "#{VALID_CHOICES.join(', ')}!")
else
prompt(MESSAGES['game_computer'] + "#{VALID_CHOICES.join(', ')}!")
end
end
def play_again
prompt(MESSAGES['play_again'])
answer = ''
loop do
answer = gets.chomp.downcase
break if %w(y yes n no).include?(answer)
prompt(MESSAGES['invalid_answer'])
end
answer
end
def reset_scores(hash_scores)
hash_scores[:player_score] = 0
hash_scores[:computer_score] = 0
end
def display_goodbye
prompt(MESSAGES['thank_you'])
end
clear_screen
display_welcome
display_target_points
scores = {
player_score: 0,
computer_score: 0
}
loop do
player_choice = ''
computer_choice = ''
loop do
choice = retrieve_player_choice
computer_choice = VALID_CHOICES.sample
player_choice = convert_choices(choice)
display_choices(player_choice, computer_choice)
player_score = calculate_score(player_choice, computer_choice)
computer_score = calculate_score(computer_choice, player_choice)
winner = calculate_winner(player_score, computer_score)
display_results(winner)
update_score(winner, scores)
display_score(scores)
pause_and_clear
break if game_over?(scores)
end
display_winner(scores)
again = play_again
unless again.start_with?('y')
break
end
reset_scores(scores)
clear_screen
end
display_goodbye
| true
|
be967b155f4c1ba28a431ae64b9b3ade002f3152
|
Ruby
|
BlueVajra/sinatra_test
|
/lib/item_repository.rb
|
UTF-8
| 378
| 3.4375
| 3
|
[] |
no_license
|
class ItemRepository
def initialize
@items = []
end
def add(item_to_add)
@items << item_to_add
end
def items
@items
end
def delete(item_to_delete)
@items.delete(item_to_delete)
end
def edit(old_name, new_name)
@items.each_with_index do |item, index|
if item == old_name
@items[index] = new_name
end
end
end
end
| true
|
6674217de47555dde77f337d9e94beef7195e18e
|
Ruby
|
larouxn/cli-library
|
/library.rb
|
UTF-8
| 5,074
| 3.703125
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
###############################
# Nicholas La Roux #
# April 2015 #
# Command line personal #
# library management utility #
###############################
require 'yaml'
require_relative 'book'
def load_library
storage = File.open('my_library.yaml', 'a+')
if File.size(storage) == 0
@library = []
else
@library = YAML.load(File.read(storage))
end
end
def save_library
File.open('my_library.yaml', 'w+') {|f| f.write(YAML.dump(@library))}
end
def retrieve_book(title, author)
@library.each do |book|
next unless book.title == title && book.author == author
return book
end
return false
end
def add_book_to_library(title, author)
@library << Book.new(title, author) unless retrieve_book(title, author)
puts "Added #{title} by #{author} to your library."
end
def remove_book_from_library(title, author)
if retrieve_book(title, author)
book = retrieve_book(title, author)
@library.delete(book)
puts "Removed #{title} by #{author} from your library."
else
"That book is not in your library."
end
end
def read(title, author)
if retrieve_book(title, author)
book = retrieve_book(title, author)
if book.status == "read"
"Book is already marked as read."
else book.read
puts "#{title} by #{author} has been marked as read."
end
else
"That book is not in your library."
end
end
def place_bookmark(title, author, page_number)
if retrieve_book(title, author)
book = retrieve_book(title, author)
book.place_bookmark(page_number)
puts "Placed bookmark on page #{page_number} in #{title} by #{author}."
else
"That book is not in your library."
end
end
def show(all_or_unread, author = nil)
found_books = false
if @library.size == 0
puts "Your library is empty."
else
@library.each_with_index do |book, index|
if all_or_unread == "unread" && author # show unread by author
if book.status == "unread" && book.author == author
found_books = true and book.to_s
elsif found_books == false && (index + 1) == @library.length
puts "You've already read all of your books by that author."
end
elsif all_or_unread == "unread" # show unread
if book.status == "unread"
found_books = true and book.to_s
elsif found_books == false && (index + 1) == @library.length
puts "You've already read all of your books."
end
elsif author # show all by author
if book.author == author
found_books = true and book.to_s
elsif found_books == false && (index + 1) == @library.length
puts "You do not have any books by that author in your library."
end
else # show all
book.to_s
end
end
end
end
def quit
save_library
puts "Bye!"
exit
end
def help
puts <<-help
Usage: ruby library.rb
Commands:
- add "title" "author" Adds a book to the library with the given title and author. All books are unread by default.
- read "title" Marks a given book as read.
- show all Displays all of the books in the library.
- show unread Display all of the books that are unread.
- show all by "author" Shows all of the books in the library by the given author.
- show unread by "author" Shows the unread books in the library by the given author.
- bookmark "title" "author" page_number Places a bookmark in the specified book at the given page number.
- quit Quits the program.
help
puts "\n"
end
def handle_input()
# Capture input
begin
line = $stdin.gets.chomp
rescue NoMethodError, Interrupt
exit
end
# Decipher input, format it, and send it to methods
case line
when /^help$/
help
when /^add "{1}.*?"{1} "{1}.*?"{1}$/
line = line.scan(/"{1}.*?"{1}/)
line[1] = line[1].tr('"', '')
add_book_to_library(line[0], line[1])
when /^remove "{1}.*?"{1} "{1}.*?"{1}$/
line = line.scan(/"{1}.*?"{1}/)
line[1] = line[1].tr('"', '')
remove_book_from_library(line[0], line[1])
when /^read "{1}.*?"{1} "{1}.*?"{1}$/
line = line.scan(/"{1}.*?"{1}/)
line[1] = line[1].tr('"', '')
read(line[0], line[1])
when /^bookmark "{1}.*?"{1} "{1}.*?"{1} \d+$/
line1 = line.scan(/"{1}.*?"{1}/)
line2 = line.scan(/\d+/)
line1[1] = line1[1].tr('"', '')
place_bookmark(line1[0], line1[1], line2[0])
when /^show (all|unread)\s?(by "{1}.*?"{1})?$/
line = line.scan(/(all|unread)|("{1}.*?"{1})/)
if line[1] == nil # basic
show(line[0][0])
else # with author
line[1][1] = line[1][1].tr('"', '')
show(line[0][0], line[1][1])
end
when /^(quit|exit)$/
quit
when ""
else
puts "Command not recognized, please use 'help' for a list of available commands"
end
end
puts "Welcome to your library!"
load_library
loop do
print "> "
handle_input
end
| true
|
3075c7062ea3df331d4292b526d17f03197d8cc2
|
Ruby
|
the-color-bliu/war_or_peace
|
/test/turn_test.rb
|
UTF-8
| 6,701
| 3.21875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require 'pry'
require './lib/card'
require './lib/deck'
require './lib/player'
require './lib/turn'
class TurnTest < Minitest::Test
def test_it_exists_and_has_attributes
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card3, card4, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_instance_of Turn, turn
assert_equal player1, turn.player1
assert_equal player2, turn.player2
assert_equal [], turn.spoils_of_war
end
def test_type_basic
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card3, card4, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal :basic, turn.type
end
def test_type_war
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card4, card3, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal :war, turn.type
end
def test_type_mutually_assured_destruction
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, '8', 8)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card4, card3, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal :mutually_assured_destruction, turn.type
end
def test_winner
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card3, card4, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal player1, turn.winner
end
def test_pile_cards_basic
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card3, card4, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
turn.pile_cards
assert_equal [card1, card3], turn.spoils_of_war
end
def test_pile_cards_war
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card4, card3, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
turn.pile_cards
assert_equal [card1, card2, card5, card4, card3, card6], turn.spoils_of_war
assert_equal player2, turn.winner
assert_equal [card8], player1.deck.cards
turn.award_spoils(player2)
assert_equal [card8], player1.deck.cards
end
def test_pile_cards_mutually_assured_destruction
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, '8', 8)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card4, card3, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal [], turn.spoils_of_war
assert_equal "No Winner", turn.winner
turn.pile_cards
assert_equal [card8], player1.deck.cards
assert_equal [card7], player2.deck.cards
turn.award_spoils("No Winner")
end
def test_award_spoils
card1 = Card.new(:heart, 'Jack', 11)
card2 = Card.new(:heart, '10', 10)
card3 = Card.new(:heart, '9', 9)
card4 = Card.new(:diamond, 'Jack', 11)
card5 = Card.new(:heart, '8', 8)
card6 = Card.new(:diamond, 'Queen', 12)
card7 = Card.new(:heart, '3', 3)
card8 = Card.new(:diamond, '2', 2)
cards1 = [card1, card2, card5, card8]
cards2 = [card3, card4, card6, card7]
deck1 = Deck.new(cards1)
deck2 = Deck.new(cards2)
player1 = Player.new("Megan", deck1)
player2 = Player.new("Aurora", deck2)
turn = Turn.new(player1, player2)
assert_equal deck1, player1.deck
assert_equal deck2, player2.deck
end
end
| true
|
6809445b23ddcf2d2362c3aa8c58f7860c91b28a
|
Ruby
|
aspc/aspc-website
|
/app/services/engage_events_service.rb
|
UTF-8
| 3,257
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
# app/services/engage_events_service.rb
class EngageEventsService
def initialize()
end
def get_events()
headers = {
"Accept" => "application/json",
"X-Engage-Api-Key" => Rails.application.credentials.engage_api[:production]
}
start_time = Time.now.to_i * 1000 # in milliseconds
end_time = start_time + 30*24*3600*1000 # +30 days
query = {
"startDate" => start_time,
"endDate" => end_time
}
response = HTTParty.get(Rails.application.credentials.engage_api[:url], :headers => headers, :query => query)
engage_events = response["items"] # @events is a list of hashes, each of which is an event
urls = Array.new # keep track of the event url's that are pulled
# save to db on the fly, then let events_controller pull from db
engage_events.each do |event|
# filter out some basic events that are definitely not for the public
filter = ["Sunday Practice", "General Meetings"]
if filter.include? event["eventName"].strip
next
end
urls << event["eventUrl"]
# if event is marked for organisation only, then skip
if event["typeName"] == "Organization Only"
next
end
# if event already exists in database (checking with eventUrl), then skip
if Event.exists?(details_url: event["eventUrl"])
next
end
# if an event starts 12pm PST, the controller expects an input of 12pm UTC (rather than 8pm UTC)
# need to manually offset time
offset = Time.now.in_time_zone("America/Los_Angeles").utc_offset
start_time = Time.at(event["startDateTime"].to_i / 1000) + offset
end_time = Time.at(event["endDateTime"].to_i / 1000) + offset
# remove HTML tags from description
description = ActionView::Base.full_sanitizer.sanitize(event["description"])
@event = Event.new(
:name => event["eventName"],
:location => event["locationName"].presence || "N/A", # return "N/A" if locationName is blank
:description => description,
:host => event["organizationName"],
:details_url => event["eventUrl"],
:start => start_time,
:end => end_time
)
@event.approve!
res = @event.save!
end
# get engage events already in database and check if they still exist on engage
# if not, then delete
# start_ts = Time.at(start_time / 1000)
# end_ts = Time.at(end_time / 1000)
# Event.where("start BETWEEN ? AND ?", start_ts, end_ts).each do |event|
# # check if the event is from engage
# if (event[:details_url].include? "https://claremont.campuslabs.com/engage/event/")
# # check if the event was on the list pulled from engage
# if not (urls.include? event[:details_url])
# puts event
# event.destroy
# end
# end
# end
end
end
| true
|
1c200e1d5373f7a6817506b5890d0ed227ff7b18
|
Ruby
|
MGellman88/Ruby-on-Rails
|
/arrays.rb
|
UTF-8
| 274
| 3.625
| 4
|
[
"MIT"
] |
permissive
|
array1 = ["Rocky", "Colt", "Tum-Tum"]
array2 = ["Larry", "Moe", "Curly"]
array3 = ["Paul", "John", "George", "Ringo"]
x = (array1+array2) - array3
puts x.to_s
puts array1.shuffle.join('-')
array3.delete("John")
puts array3
puts "Length of array3 is #{array3.length}"
| true
|
9584495575a504c35ff06fba8e43d9a91899e081
|
Ruby
|
ramblex/euler
|
/euler-2.rb
|
UTF-8
| 505
| 3.828125
| 4
|
[] |
no_license
|
#
# Each new term in the Fibonacci sequence is generated by adding the previous two
# terms. By starting with 1 and 2, the first 10 terms will be:
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed
# four million, find the sum of the even-valued terms.
#
a = [1,2]
next_num = 0
sum = 2
while next_num < 4000000 do
p next_num
next_num = a[0] + a[1]
sum += next_num if next_num % 2 == 0
a[0] = a[1]
a[1] = next_num
end
p sum
| true
|
a6de7e2c29dc33f52bf7f53a8352bd176a5cf27e
|
Ruby
|
VladislavKadyshev/Rubylabs
|
/lab2/lib/computing.rb
|
UTF-8
| 906
| 3.546875
| 4
|
[] |
no_license
|
require 'csv'
# Comp operations
class Computing
def initialize
name = "#{__dir__}/ruby.csv"
@arr = []
CSV.foreach(name, col_sep: ';') do |a|
@arr << a[1].to_f
end
@arr.shift
end
def comp_max
@arr.max
end
def comp_min
@arr.min.round(2)
end
def comp_average
(@arr.sum / @arr.size).round(2)
end
def comp_dispers
avg = comp_average
iter = @arr.map { |a| (a - avg)**2 }
iter = iter.sum
iter /= @arr.length - 1
iter.round(2)
end
def computing_operation(operation)
abort "Invalid operation number '#{operation}' " unless valid_operation?(operation)
case operation
when '1'
comp_min
when '2'
comp_max
when '3'
comp_average
when '4'
comp_dispers
end
end
def valid_operation?(operation)
%w[1 2 3 4].include? operation
end
end
# obj = Calculate.new
# p obj.calculate
| true
|
a94ff1d82dcd47ea04534c45f9bd567c087e79be
|
Ruby
|
joshmosh/learning-ruby
|
/classes/dog_test.rb
|
UTF-8
| 509
| 3.03125
| 3
|
[] |
no_license
|
require File.join(File.dirname(__FILE__), 'dog')
require 'test/unit'
class DogTest < Test::Unit::TestCase
def test_small_dog_size
small_dog = Dog.new(8)
noise = small_dog.make_noise
assert_equal "Horrific yapping", noise
end
def test_medium_dog_size
medium_dog = Dog.new(24)
noise = medium_dog.make_noise
assert_equal "Bark", noise
end
def test_big_dog_size
big_dog = Dog.new(72)
noise = big_dog.make_noise
assert_equal "Woof woofity woof", noise
end
end
| true
|
b9040e91f57a65a45afdad29caa79664668ca195
|
Ruby
|
anikeef/connect_four
|
/spec/game_spec.rb
|
UTF-8
| 2,192
| 3.140625
| 3
|
[] |
no_license
|
require "./lib/game.rb"
describe Game do
before :each do
$stdout = StringIO.new
end
describe "#initialize" do
it "stores the usernames" do
allow_any_instance_of(Game).to receive(:gets).and_return("Gena", "Tayga")
game = Game.new
players = game.instance_variable_get(:@players)
expect(players[0].name).to eq("Gena")
expect(players[1].name).to eq("Tayga")
end
it "holds the empty grid" do
allow_any_instance_of(Game).to receive(:gets).and_return("Gena", "Tayga")
expect(Game.new.instance_variable_get(:@grid)).to be_a(Grid)
end
end
describe "#play" do
it "outputs the first player's name if he wins" do
allow_any_instance_of(Game).to receive(:gets).and_return(
"Gena", "Tayga", "1", "7", "2", "6", "3", "5", "4"
)
expect { Game.new.play }.to output(/Gena's win!$/).to_stdout
end
it "outputs the second player's name if he wins" do
allow_any_instance_of(Game).to receive(:gets).and_return(
"Gena", "Tayga", "1", "7", "2", "7", "3", "7", "5", "7"
)
expect { Game.new.play }.to output(/Tayga's win!$/).to_stdout
end
it "outputs a draw message" do
allow_any_instance_of(Game).to receive(:gets).and_return(
"Gena", "Tayga",
"1", "2", "1", "2", "1", "2",
"2", "1", "2", "1", "2", "1",
"3", "4", "3", "4", "3", "4",
"4", "3", "4", "3", "4", "3",
"5", "6", "5", "6", "5", "6",
"7", "5", "7", "5", "7", "5",
"6", "7", "6", "7", "6", "7"
)
expect { Game.new.play }.to output(/It's a draw!$/).to_stdout
end
it "works with incorrect inputs" do
allow_any_instance_of(Game).to receive(:gets).and_return(
"Gena", "Tayga", "1", "abc", "7", "2", "23", "b2", "6", "3", "5", "4"
)
expect { Game.new.play }.to output(/Gena's win!$/).to_stdout
end
it "works with full columns" do
allow_any_instance_of(Game).to receive(:gets).and_return(
"Gena", "Tayga", "1", "1", "1", "1", "1", "1", "1", "1", "1",
"2", "7", "3", "7", "4"
)
expect { Game.new.play }.to output(/Gena's win!$/).to_stdout
end
end
end
| true
|
091049dd2e217ecbc05852800f563835d278f77c
|
Ruby
|
volontariat/voluntary_music_metadata_enrichment
|
/dummy/spec/support/deferred_garbage_collector.rb
|
UTF-8
| 1,299
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
# https://makandracards.com/makandra/950-speed-up-rspec-by-deferring-garbage-collection
class DeferredGarbageCollection
DEFERRED_GC_THRESHOLD = (ENV['DEFER_GC'] || 10.0).to_f #used to be 10.0
@@last_gc_run = Time.now
def self.start
return if unsupported_enviroment
GC.disable if DEFERRED_GC_THRESHOLD > 0
end
def self.memory_threshold
@mem = %x(free 2>/dev/null).to_s.split(" ")
return nil if @mem.empty?
@mem[15].to_i / (@mem[7].to_i/100)
end
def self.reconsider
return if unsupported_enviroment
if (percent_used = self.memory_threshold)
running_out_of_memory = percent_used > 90
# just for info, as soon as we got some numbers remove it
swap_percent_used = @mem[19].to_i / (@mem[18].to_i/100) rescue 0
puts "percent memory used #{percent_used} (#{@mem[8]} of #{@mem[7]})"
puts "percent swap used #{swap_percent_used} (#{@mem[19]} of #{@mem[18]})"
else
running_out_of_memory = false
end
if( (DEFERRED_GC_THRESHOLD > 0 && Time.now - @@last_gc_run >= DEFERRED_GC_THRESHOLD) || running_out_of_memory )
GC.enable
GC.start
GC.disable
@@last_gc_run = Time.now
end
end
def self.unsupported_enviroment
ENV['TRAVIS'] # TODO: enable for ruby 1.9.3 or more RAM
end
end
| true
|
7ce219f8638696dcf4858a08f6fb1a489a2c3c3b
|
Ruby
|
lkilk/test_driven_development
|
/library_exercise/spec/library_spec.rb
|
UTF-8
| 1,001
| 3.109375
| 3
|
[] |
no_license
|
require 'library'
describe Library do
describe "#find_book" do
it 'can find a specific book' do
library = Library.new
expect(library.find_book("POODR")).to eq(:title=>"POODR", :author=>"Sandi Metz", :subject=>"OOP")
end
end
describe "#add_book" do
it 'can add a new book' do
library = Library.new
library.add_book(title: "Harry Potter", author: "JK Rowling", subject: "Fiction")
expect(library.list_books).to include(title: "Harry Potter", author: "JK Rowling", subject: "Fiction")
end
end
describe "#remove_book" do
it 'can remove a book' do
library = Library.new
library.remove_book('Eloquent JavaScript')
expect(library.list_books).not_to include('Eloquent JavaScript')
end
end
describe "#all_books_by_subject" do
it 'can list all the books on a specific subject' do
library = Library.new
expect(library.all_books_by_subject("OOP")).to eq [:author=>"Sandi Metz", :subject=>"OOP", :title=>"POODR"]
end
end
end
| true
|
e4d8d0dbf364286eef6c16001af1c65e2d165ebb
|
Ruby
|
andremleblanc/kairosdb-ruby
|
/lib/kairosdb/client/http.rb
|
UTF-8
| 2,644
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
module KairosDB
module HTTP
def post(url, data)
headers = { 'Content-Type' => 'application/json' }
connect_with_retry do |http|
response = do_request http, Net::HTTP::Post.new(url, headers), JSON.generate(data)
if response.is_a? Net::HTTPSuccess
handle_successful_response(response)
else
resolve_error(response)
end
end
end
def delete(url)
connect_with_retry do |http|
response = do_request http, Net::HTTP::Delete.new(url)
if response.is_a? Net::HTTPSuccess
handle_successful_response(response)
elsif response.is_a? Net::HTTPNotFound
false
else
resolve_error(response)
end
end
end
private
def connect_with_retry(&block)
host = config.host
delay = config.initial_delay
retry_count = 0
begin
http = Net::HTTP.new(host, config.port)
http.open_timeout = config.open_timeout
http.read_timeout = config.read_timeout
block.call(http)
rescue Timeout::Error, *KairosDB::NET_HTTP_EXCEPTIONS => e
retry_count += 1
if (config.retry == -1 || retry_count <= config.retry) && !stopped?
log :error, "Failed to contact host #{host}: #{e.inspect} - retrying in #{delay}s."
sleep delay
delay = [config.max_delay, delay * 2].min
retry
else
raise KairosDB::ConnectionError, "Tried #{retry_count - 1} times to reconnect but failed."
end
ensure
http.finish if http.started?
end
end
def do_request(http, req, data = nil)
req.body = data if data
http.request(req)
end
def errors_from_response(parsed_response)
parsed_response.is_a?(Hash) && parsed_response.fetch('errors', nil)
end
def handle_successful_response(response)
parsed_response(response)
end
def parsed_response(response)
response.body ? JSON.parse(response.body) : response
end
def resolve_error(response)
parsed_response = parsed_response(response)
errors = errors_from_response(parsed_response) if parsed_response
raise KairosDB::QueryError, errors if errors
raise KairosDB::Error, response
end
def config
raise NotImplementedError, "This #{self.class} cannot respond to ##{__method__}"
end
def log(level, message)
raise NotImplementedError, "This #{self.class} cannot respond to ##{__method__}"
end
def stopped?
raise NotImplementedError, "This #{self.class} cannot respond to ##{__method__}"
end
end
end
| true
|
d11abcf4d92ff3ff6fa2033e33a048e91386f7b7
|
Ruby
|
ruliana/design-patterns-101
|
/lib/mercearia/cesta.rb
|
UTF-8
| 301
| 3.0625
| 3
|
[] |
no_license
|
class Cesta
def initialize
@produtos = []
end
def adicionar(produto)
@produtos << produto
end
def preco
@produtos.reduce(0.reais) { |acumulado, produto| acumulado + produto.preco }
end
def accept(visitor)
@produtos.each { |produto| produto.accept(visitor) }
end
end
| true
|
f48fd8c18e3b3625ba273e3048010a9691f58323
|
Ruby
|
victorperezcotapos/desafios_Intro_Ruby
|
/mas_cerca_puntos.rb
|
UTF-8
| 701
| 3.34375
| 3
|
[] |
no_license
|
coordenada_x = [ARGV[0].to_f,ARGV[2].to_f,ARGV[4].to_f,ARGV[6].to_f,ARGV[8].to_f]
coordenada_y = [ARGV[1].to_f,ARGV[3].to_f,ARGV[5].to_f,ARGV[7].to_f,ARGV[9].to_f]
distancias = Array.new
distancias[0]= Math.sqrt((coordenada_x[0]-coordenada_x[1])**2+(coordenada_y[0]-coordenada_y[1])**2)
distancias[1]= Math.sqrt((coordenada_x[0]-coordenada_x[2])**2+(coordenada_y[0]-coordenada_y[2])**2)
distancias[2]= Math.sqrt((coordenada_x[0]-coordenada_x[3])**2+(coordenada_y[0]-coordenada_y[3])**2)
distancias[3]= Math.sqrt((coordenada_x[0]-coordenada_x[4])**2+(coordenada_y[0]-coordenada_y[4])**2)
puts "#{coordenada_x[distancias.index(distancias.min)+1]},#{coordenada_y[distancias.index(distancias.min)+1]}"
| true
|
eff5170df1269db119b9abf775305a9b04d25128
|
Ruby
|
MarcusRiemer/sport.db
|
/sportdb-formats/lib/sportdb/formats/season_utils.rb
|
UTF-8
| 3,972
| 3.203125
| 3
|
[
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
# encoding: utf-8
module SeasonHelper ## use Helpers why? why not?
def prev( season )
## todo: add 1964-1965 format too!!!
if season =~ /^(\d{4})-(\d{2})$/ ## season format is 1964-65
fst = $1.to_i - 1
snd = (100 + $2.to_i - 1) % 100 ## note: add 100 to turn 00 => 99
"%4d-%02d" % [fst,snd]
elsif season =~ /^(\d{4})$/
fst = $1.to_i - 1
"%4d" % [fst]
else
puts "*** !!!! wrong season format >>#{season}<<; exit; sorry"
exit 1
end
end # method prev
def key( basename )
if basename =~ /^(\d{4})[\-\/](\d{4})$/ ## e.g. 2011-2012 or 2011/2012 => 2011/12
"%4d/%02d" % [$1.to_i, $2.to_i % 100]
elsif basename =~ /^(\d{4})[\-\/](\d{2})$/ ## e.g. 2011-12 or 2011/12 => 2011/12
"#{$1}/#{$2}"
elsif basename =~ /^(\d{4})$/
$1
else
puts "*** !!!! wrong season format >>#{basename}<<; exit; sorry"
exit 1
end
end # method key
def directory( season, format: nil )
## todo: find better names for formats - why? why not?:
## long | archive | decade(?) => 1980s/1988-89, 2010s/2017-18, ...
## short | std(?) => 1988-89, 2017-18, ...
## convert season name to "standard" season name for directory
## todo/fix: move to parse / validate season (for (re)use)!!!! - why? why not?
if season =~ /^(\d{4})[\-\/](\d{4})$/ ## e.g. 2011-2012 or 2011/2012 => 2011-12
years = [$1.to_i, $2.to_i]
elsif season =~ /^(\d{4})[\-\/](\d{2})$/ ## e.g. 2011-12 or 2011/12 => 2011-12
years = [$1.to_i, $1.to_i+1]
## note: check that season end year is (always) season start year + 1
if ($1.to_i+1) % 100 != $2.to_i
puts "*** !!!! wrong season format >>#{season}<<; season end year MUST (always) equal season start year + 1; exit; sorry"
exit 1
end
elsif season =~ /^(\d{4})$/
years = [$1.to_i]
else
puts "*** !!!! wrong season format >>#{season}<<; exit; sorry"
exit 1
end
if ['l', 'long', 'archive' ].include?( format.to_s ) ## note: allow passing in of symbol to e.g. 'long' or :long
if years.size == 2
"%3d0s/%4d-%02d" % [years[0] / 10, years[0], years[1] % 100] ## e.g. 2000s/2001-02
else ## assume size 1 (single year season)
"%3d0s/%4d" % [years[0] / 10, years[0]]
end
else ## default 'short' format / fallback
if years.size == 2
"%4d-%02d" % [years[0], years[1] % 100] ## e.g. 2001-02
else ## assume size 1 (single year season)
"%4d" % years[0]
end
end
end # method directory
def start_year( season ) ## get start year
## convert season name to "standard" season name for directory
## todo/check: just return year from first for chars - keep it simple - why? why not?
if season =~ /^(\d{4})[\-\/](\d{4})$/ ## e.g. 2011-2010 or 2011/2011 => 2011-10
$1
elsif season =~ /^(\d{4})[\-\/](\d{2})$/
$1
elsif season =~ /^(\d{4})$/
$1
else
puts "*** !!!! wrong season format >>#{season}<<; exit; sorry"
exit 1
end
end
def end_year( season ) ## get end year
## convert season name to "standard" season name for directory
if season =~ /^(\d{4})[\-\/](\d{4})$/ ## e.g. 2011-2010 or 2011/2011 => 2011-10
$2
elsif season =~ /^(\d{4})[\-\/](\d{2})$/
## note: assume second year is always +1
## todo/fix: add assert/check - why? why not?
## eg. 1999-00 => 2000 or 1899-00 => 1900
($1.to_i+1).to_s
elsif season =~ /^(\d{4})$/
$1
else
puts "*** !!!! wrong season format >>#{season}<<; exit; sorry"
exit 1
end
end
end # module SeasonHelper
module SeasonUtils
extend SeasonHelper
## lets you use SeasonHelper as "globals" eg.
## SeasonUtils.prev( season ) etc.
end # SeasonUtils
| true
|
150f575372186996aaa24b4210d57905f1bb7a0b
|
Ruby
|
ssowonny/c11n
|
/lib/c11n/importer/google_drive.rb
|
UTF-8
| 973
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
require 'c11n/external/google_drive_driver'
require 'c11n/table'
module C11n
module Importer
class GoogleDrive
def initialize(options = {})
@driver = C11n::External::GoogleDriveDriver.new(options)
end
def table
@table ||= C11n::Table.new(@driver.table)
end
def import
deserialized = {}
table.to_hash.each do |locale, translations|
deserialized[locale] = translations.inject({}) do |result, key_and_translation|
result.merge key_and_translation.first => deserialize(key_and_translation.last, types[key_and_translation.first])
end
end
deserialized
end
def categories
{}
end
def types
table.types
end
private
def deserialize(value, type = nil)
case type
when C11n::Types::ARRAY
value.split("\n\n")
else
value
end
end
end
end
end
| true
|
2b525a287d4d7a93103680c2a603c1981c77ac5e
|
Ruby
|
nmking22/monster_shop_2008_solo
|
/spec/features/merchant/discounts/edit_spec.rb
|
UTF-8
| 5,660
| 2.546875
| 3
|
[] |
no_license
|
require 'rails_helper'
describe 'As a Merchant Employee, when I visit a discount edit page' do
before :each do
@batarang_emporium = Merchant.create(
name: "Batman's Batarang Emporium",
address: '123 Wayne Dr.',
city: 'Gotham',
state: 'IL',
zip: 80210
)
@batman = User.create!(
name: "Batman",
address: "Some dark cave 11",
city: "Arkham",
state: "CO",
zip: "81301",
email: 'batmansemail@email.com',
password: "password",
role: 1,
merchant: @batarang_emporium
)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@batman)
@ten_rangs = Discount.create!(
name: 'Ten Rangs',
percentage: 5,
threshold: 10,
merchant: @batarang_emporium
)
end
describe 'And I fill out the form and submit' do
it "I am redirected to that discount's show page and can see the changes" do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Eleven Rangs"
fill_in :percentage, with: 6.5
fill_in :threshold, with: 11
click_button "Update Discount"
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}")
expect(page).to have_content("Eleven Rangs")
expect(page).to have_content("Percent Off: 6.5%")
expect(page).to have_content("Minimum Eligible Quantity: 11")
end
end
it 'The form fields are pre-filled with current attributes' do
visit "/merchant/discounts/#{@ten_rangs.id}"
expect(page).to have_content(@ten_rangs.name)
expect(page).to have_content(@ten_rangs.percentage)
expect(page).to have_content(@ten_rangs.threshold)
end
describe 'When I fill out the discounts edit form with a missing name field' do
it 'I am redirected back to discounts edit with a flash message indicating the problem' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: ""
fill_in :percentage, with: 5
fill_in :threshold, with: 20
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('All fields must be filled in.')
end
end
describe 'When I fill out the discounts edit form with a missing percentage field' do
it 'I am redirected back to discounts edit with a flash message indicating the problem' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: ""
fill_in :threshold, with: 20
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('Discount percentage must be filled with an integer or float between 0 and 100.')
end
end
describe 'When I fill out the discounts edit form with a missing threshold field' do
it 'I am redirected back to discounts edit with a flash message indicating the problem' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: 5.5
fill_in :threshold, with: ""
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('Minimum Items for Activation must be filled with an integer zero or greater.')
end
end
describe "When I fill in the discounts edit form with a negative percentage" do
it 'I am redirected to discounts edit with an error indicating an invalid percentage' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: -5
fill_in :threshold, with: 20
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('Discount percentage must be filled with an integer or float between 0 and 100.')
end
end
describe "When I fill in the discounts edit form with a percentage over 100" do
it 'I am redirected to discounts edit with an error indicating an invalid percentage' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: 100.1
fill_in :threshold, with: 20
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('Discount percentage must be filled with an integer or float between 0 and 100.')
end
end
describe "When I fill in the discounts edit form with a negative threshold input" do
it 'I am redirected to discounts edit with an invalid threshold message' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: 20
fill_in :threshold, with: -23
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}/edit")
expect(page).to have_content('Minimum Items for Activation must be filled with an integer zero or greater.')
end
end
describe "When I fill in the discounts edit form with a float threshold input" do
it 'I am redirected to that discounts show with threshold rounded down' do
visit "/merchant/discounts/#{@ten_rangs.id}/edit"
fill_in :name, with: "Nick!"
fill_in :percentage, with: 20
fill_in :threshold, with: 20.92
click_button 'Update Discount'
expect(current_path).to eq("/merchant/discounts/#{@ten_rangs.id}")
expect(page).to have_content('Minimum Eligible Quantity: 20')
end
end
end
| true
|
fbb77f0d272833c9304c4c96d78f2e644e7ae301
|
Ruby
|
jfredrickson/finerworks
|
/lib/finerworks/client.rb
|
UTF-8
| 4,803
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'finerworks/request'
require 'finerworks/response'
require 'finerworks/account'
require 'finerworks/print'
require 'finerworks/gallery'
require 'finerworks/image'
require 'finerworks/order'
require 'finerworks/order_details'
require 'finerworks/cart'
module FinerWorks
# The Client is the primary interface to the FinerWorks Web API.
#
# @attr [String] account_api_key A FinerWorks account API key.
class Client
attr_accessor :account_api_key
def initialize(options = {})
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
yield(self) if block_given?
end
# Provides account profile information.
#
# @return [Account] Account information. Returns the account associated with the client's API key.
def account
result = FinerWorks::Request.get(self, "/Account")
FinerWorks::Account.new(result.json)
end
# Updates account profile information.
#
# @param [Account] account Account information.
# @return [Response] API response.
def update_account(account)
result = FinerWorks::Request.post(self, "/Account", build_post_account_json(account))
end
# Lists prints stored in My Prints Inventory.
#
# @param [Hash] options Filtering options.
# @option options [String] ImageGUID Find prints based on a specific image.
# @option options [String] GalleryGUID Find prints whose images are under a specific gallery.
# @return [Array<Print>] A list of prints.
def prints(options = {})
get(FinerWorks::Print, "/Prints", options)
end
# Lists galleries (aka portfolios) under the current account.
#
# @return [Array<Gallery>] A list of galleries.
def galleries
get(FinerWorks::Gallery, "/Galleries")
end
# Lists images stored in My Images.
#
# @param [Hash] options Filtering/sorting options.
# @option options [String] GalleryGUID Find images that are under a specific gallery.
# @option options [String] Sort ("DESC") Sort images by upload dates. Possible values are "ASC" or "DESC".
# @return [Array<Image>] A list of images.
def images(options = {})
get(FinerWorks::Image, "/Images", options)
end
# Lists orders.
#
# @param [Hash] options Filtering/sorting options.
# @option options [String] OrderDateTime_Start Find orders in the time period starting at the specified date/time. Acceptable formats include "MM/DD/YYYY" or "YYYY-MM-DD".
# @option options [String] OrderDateTime_End Find orders in the time period ending at the specified date/time. Acceptable formats include "MM/DD/YYYY" or "YYYY-MM-DD".
# @option options [String] OrderStatusID Find orders with a specific status.
# @option options [String] OrderID Find a specific order by order ID.
# @option options [String] Sort ("DESC") Sort orders by ID. Possible values are "ASC" or "DESC".
# @return [Array<Order>] A list of orders.
def orders(options = {})
get(FinerWorks::Order, "/Orders", options)
end
# Provides details for a specific order.
#
# @param id [Integer] Order ID number.
# @return [Array<OrderDetails>] Order details for the given order ID.
def order_details(id)
get(FinerWorks::OrderDetails, "/OrderDetails", { "OrderID" => id })
end
# Sets up shopping carts that can be used to submit orders.
#
# @param num_carts [Integer] Number of new carts to create (1-100). Default is 1.
# @return [Array<Cart>] New shopping cart(s).
def order_submission(num_carts = 1)
get(FinerWorks::Cart, "/OrderSubmission", { "NewCart" => num_carts })
end
# Generic GET method to request items of the specified +type+. This always returns an +Array+.
#
# @param type [Class] Type of objects to return.
# @param path [String] API request path.
# @param [Hash] options Parameters to include in the request URI.
# @return [Array<Object>] A list of items.
def get(type, path, options = {})
response = FinerWorks::Request.get(self, path, options)
items = response.json.kind_of?(Array) ? response.json : [response.json]
results = []
items.each do |item|
results << type.new(item)
end
results
end
def build_post_account_json(account)
{
"AccountApiKey" => account_api_key,
"AccountUsername" => account.username,
"AccountUpdate_Info" => {
"AccountEmail" => account.email,
"AccountFirstName" => account.first_name,
"AccountMiddleName" => account.middle_name,
"AccountLastName" => account.last_name,
"AccountPhone" => account.phone,
"AccountBio" => account.bio,
"AccountTitle" => account.title
}
}
end
end
end
| true
|
410f994d0d66c0b31d2c9e482a188dba041a1f8a
|
Ruby
|
ejstraband/Ruby
|
/learnToProgram/chapter8/favorites.rb
|
UTF-8
| 265
| 3.296875
| 3
|
[] |
no_license
|
favorites = []
puts '--------'
puts favorites
puts '--------'
favorites.push 'raindrops on roses'
favorites.push 'whiskey on kittens'
puts favorites[0]
puts favorites.last
puts favorites.length
puts '--------'
puts favorites.pop
puts favorites
puts favorites.length
| true
|
270fef38bd4698547c2307a17092ebe05ab7e379
|
Ruby
|
tkusuki/tasklist-campuscode
|
/tarefa.rb
|
UTF-8
| 477
| 3.140625
| 3
|
[] |
no_license
|
class Tarefa
attr_reader :id, :feita
# attr_reader :descricao
attr_accessor :descricao
def initialize(id, descricao, feita = false)
@id = id
@descricao = descricao
@feita = feita
end
def marcar_feita()
@feita = true
end
def to_s()
string_feita = feita() ? "Sim" : "Não"
"- Tarefa #{ id() } >> #{ descricao() } || Feita: #{ string_feita }"
end
def include?(texto_busca)
descricao.upcase.include? texto_busca.upcase
end
end
| true
|
2d0e6ec32847716c1348d271aa81080719cb0b12
|
Ruby
|
DianaLuciaRinconBl/Small_exercises
|
/easy4/ex_4.rb
|
UTF-8
| 1,368
| 4.65625
| 5
|
[] |
no_license
|
# input
# year (integer)
# output
# true or false
#
# before 1752 leap years were any year divisible by 4
# after 1752 leap years were any year divisible by 4 but
# if also divisible by a 100 then it also needs to be divisible by 400 to be a leap year.
#
# 1. check if the year argument is an integer greater than 1752
# - if it is not find out if it is divisible by 4
# if it is then return true
# if it is not then return false
#
# -if it is then check if it is divisible by 4 and not by 100
# -if it is then return true
# -if it is not then check if year is divisible by 400
# if so return true
# if not retunr false
# - finally return false for everything else
def leap_year?(year)
if year <= 1752
year % 4 == 0
elsif year > 1752
if year % 4 == 0 && year % 100 != 0
true
elsif year % 400 == 0
true
else
false
end
else
false
end
end
puts leap_year?(2016) == true
puts leap_year?(2015) == false
puts leap_year?(2100) == false
puts leap_year?(2400) == true
puts leap_year?(240000) == true
puts leap_year?(240001) == false
puts leap_year?(2000) == true
puts leap_year?(1900) == false
puts leap_year?(1752) == true
puts leap_year?(1700) == true
puts leap_year?(1) == false
puts leap_year?(100) == true
puts leap_year?(400) == true
| true
|
16e08f533b5b1e4225c9dc77fe2128aeb44ce426
|
Ruby
|
bentrevor/ruby_ttt
|
/spec/console_input_spec.rb
|
UTF-8
| 434
| 2.734375
| 3
|
[] |
no_license
|
require 'spec_helper'
require 'console_input'
describe ConsoleInput do
let(:reader) { MockReader.new }
it "reads from stdin" do
reader.inputs = ["1\n", "2\n"]
input = ConsoleInput.new(reader)
input.get_int.should == 1
input.get_int.should == 2
end
it "prompts until it gets an int" do
reader.inputs = ["", "yo\n", "2\n"]
input = ConsoleInput.new(reader)
input.get_int.should == 2
end
end
| true
|
1f1991dd041fd4505c7527ae396391fcf0c8f18c
|
Ruby
|
SesameSeeds/oo-ride-share
|
/lib/driver.rb
|
UTF-8
| 1,013
| 3.125
| 3
|
[] |
no_license
|
require 'csv'
require_relative 'trip'
module RideShare
class Driver
attr_reader :driver_id, :driver_name, :vin
def initialize driver_id, driver_name, vin
@driver_id = driver_id
@driver_name = driver_name
@vin = vin
raise ArgumentError.new("VIN is invalid.") if vin.length != 17
end
def self.all
drivers = []
dcsv = CSV.open("./support/drivers.csv", 'r')
dcsv.each do |driver|
drivers << Driver.new(driver[0].to_i, driver[1], driver[2])
end
return drivers
end
def self.find(driver_id)
drivers = RideShare::Driver.all
drivers.each do |driver|
if driver.driver_id == driver_id
return driver
end
end
end
def average_rating(driver_id)
driver_trips = driver_trips(driver_id)
return (driver_trips.map(&:rating).inject(0, &:+)/driver_trips.length).round(2)
end
def driver_trips(driver_id)
return Trip.all_driver_trips(driver_id)
end
end
end
| true
|
3abd60f17a12a001bafa424c8a0b126aeaaa9a7a
|
Ruby
|
Tafby/oo-relationships-practice-seattle-web-career-012819
|
/app/models/listings.rb
|
UTF-8
| 1,218
| 3.703125
| 4
|
[] |
no_license
|
class Listings
attr_accessor :city, :guests, :trips, :trip_count
@@all = []
def initialize(city)
@city = city
@guests = []
@trips = []
@trip_count = trip_count
@@all << self
end
def self.all
@@all
end
def self.find_all_by_city(city)
self.all.select do |l|
l.city == city
end
end
def self.most_popular
count = 0
name = nil
tally = Hash.new(0)
Trips.all.each do |t|
tally[t.listing] += 1
if tally[t.listing] > count
count = tally[t.listing]
name = t.listing
end
end
name
end
end # end of class
#### Listing
#1- #guests
# - returns an array of all guests who have stayed at a listing
# - #trips
# - returns an array of all trips at a listing
# - #trip_count
# - returns the number of trips that have been taken to that listing
# - .all
# - returns an array of all listings
# - .find_all_by_city(city)
# - takes an argument of a city name (as a string) and returns all the listings for that city
# - .most_popular
# - finds the listing that has had the most trips
| true
|
08a601dea2b1fc78db649e99e0b2d19af6432012
|
Ruby
|
RDJoseDeSouza/nivelamento-aluno
|
/10-exercicio-parte-2.rb
|
UTF-8
| 474
| 3.15625
| 3
|
[] |
no_license
|
# 2) Esse aqui é um desafio. Faça um código para obter esse resultado:
# *
# **
# ***
# ****
# *****
# ******
# *******
# ********
# *********
# **********
vezes = 1
numero = 1
while numero < 11
for espaco_em_branco in (1..9)
print " "
end
for n in (1..vezes)
print "*"
end
puts
numero = numero + 1
vezes = vezes+ 1
end
| true
|
949d28e43157ce6590630a9dd46c710488738f25
|
Ruby
|
peterdk/adventOfCode2015
|
/day21.rb
|
UTF-8
| 4,036
| 3.421875
| 3
|
[] |
no_license
|
class Item
attr_reader :type, :name, :cost, :damage, :armor
def initialize(type, name, cost, damage, armor)
@name = name
@cost = cost
@damage = damage
@armor = armor
@type = type
end
def to_s
"#{@type}: #{@name}\t#{@cost}\t#{@damage}\t#{@armor}"
end
end
class Warrior
attr_accessor :items, :hitpoints
def initialize(hitpoints)
@items = []
@hitpoints = hitpoints
end
def add_item(item)
@items << item
end
def cost
@items.map{|i|i.cost}.inject(:+)
end
def damage
@items.map{|i|i.damage}.inject(:+)
end
def armor
@items.map{|i|i.armor}.inject(:+)
end
def valid
weapons = @items.find_all{|i|i.type=="Weapons"}
armor = @items.find_all{|i|i.type=="Armor"}
rings = @items.find_all{|i|i.type=="Rings"}
return (weapons.size == 1 && (armor.size == 0 || armor.size == 1) && (rings.size >=0 && rings.size <= 2))
end
def clone
w = super
w.items = [ ]
@items.each do |i|
w.items << i
end
w
end
end
class Player
attr_reader :name, :damage, :armor, :cost
attr_accessor :hitpoints
def initialize(name, hitpoints, damage, armor, cost)
@name = name
@hitpoints = hitpoints
@damage = damage
@armor = armor
@cost = cost
end
def deal_damage(enemy)
damage = @damage - enemy.armor
damage = 1 if (damage <= 0)
enemy.hitpoints -= damage
end
def to_s
"#{@name}: hitpoints #{@hitpoints}, damage #{@damage}, armor #{@armor}, cost #{@cost}"
end
end
class Fight
attr_reader :boss, :player
def initialize(boss, player)
@boss = boss
@player = player
end
def winner
while (@boss.hitpoints >= 0 && @player.hitpoints >= 0)
round
end
[@boss, @player].find{|p|p.hitpoints > 0}
end
def round
@player.deal_damage(@boss)
if (@boss.hitpoints >= 0)
@boss.deal_damage(@player)
end
end
end
shop_input = File.new("day21_shop.txt").readlines
@shop = []
type = nil
shop_input.each do |l|
match = l.match(/([a-zA-Z0-9+ ]+)\s+(\d+)\s+(\d+)\s+(\d+)/)
if (match)
all, name, cost, damage, armor = match.to_a
@shop << Item.new(type, name, cost.to_i,damage.to_i,armor.to_i)
else
match = l.match(/(\w+):/)
if (match)
type = match.to_a[1]
end
end
end
def create_combinations(items, min, max)
perms = []
for i in (min..max)
perms << items.combination(i).to_a
end
perms.flatten!(1)
end
def create_warrior_combinations(warriors, items, min, max)
new_warriors= []
new_items = create_combinations(items,min,max)
new_items.each do |ni|
warriors.each do |w|
new_w = w.clone
ni.each do |i|
new_w.add_item(i)
end
new_warriors << new_w
end
end
new_warriors
end
def create_players
weapons = @shop.find_all{|i|i.type == "Weapons"}
armor = @shop.find_all{|i|i.type == "Armor"}
rings = @shop.find_all{|i|i.type == "Rings"}
warriors = [Warrior.new(100)]
warriors = create_warrior_combinations(warriors, weapons, 1, 1)
warriors = create_warrior_combinations(warriors, armor, 0, 1)
warriors = create_warrior_combinations(warriors, rings,0, 2)
players = []
puts "Warriors: #{warriors.size}"
puts "Valid warriors: #{warriors.find_all{|w|w.valid}.size}"
warriors.each do |w|
players << Player.new("player", w.hitpoints, w.damage, w.armor, w.cost)
end
players
end
boss = Player.new("boss", 109, 8, 2, 0)
players = create_players
costs = players.find_all{|p|Fight.new(boss.clone, p).winner == p}.sort_by{|p|p.cost}
puts costs[0]
| true
|
c03ef22ee80a36b8285eac91a365235eba75d926
|
Ruby
|
ajakate/buddy-guy
|
/run.rb
|
UTF-8
| 254
| 3.484375
| 3
|
[] |
no_license
|
module Buddy
CYCLE = ["friend","buddy","pal","guy"]
def self.print
puts "I'm not your #{CYCLE[rand(0..3)]}, #{CYCLE[rand(0..3)]}"
sleep 1
end
end
loop do
begin
Buddy.print
rescue Exception => e
puts "Hey! Stop it!"
end
end
| true
|
769835fa2d5e6d3bd6bb158ec21488e54e2094ff
|
Ruby
|
pepabo-college/1st-pullrequest-question
|
/ryucheru/answer-00.rb
|
UTF-8
| 39
| 2.5625
| 3
|
[] |
no_license
|
str = "stressed"
str.reverse!
puts str
| true
|
0cf228f63007b51f22854280f042d3ebe5a73398
|
Ruby
|
eebbesen/minutes_maid
|
/vendor/cache/ruby/2.5.0/gems/mail-2.7.1/lib/mail/network/delivery_methods/smtp_connection.rb
|
UTF-8
| 2,045
| 3
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'mail/check_delivery_params'
module Mail
# == Sending Email with SMTP
#
# Mail allows you to send emails using an open SMTP connection. This is done by
# passing a created Net::SMTP object. This way we can get better performance to
# our local mail server by reducing the number of connections at any one time.
#
# === Sending via SMTP server on Localhost
#
# To send mail open a connection with Net::Smtp using any options you like
# === Delivering the email
#
# Once you have the settings right, sending the email is done by:
#
# smtp_conn = Net::SMTP.start(settings[:address], settings[:port])
# Mail.defaults do
# delivery_method :smtp_connection, { :connection => smtp_conn }
# end
#
# Mail.deliver do
# to 'mikel@test.lindsaar.net'
# from 'ada@test.lindsaar.net'
# subject 'testing sendmail'
# body 'testing sendmail'
# end
#
# Or by calling deliver on a Mail message
#
# mail = Mail.new do
# to 'mikel@test.lindsaar.net'
# from 'ada@test.lindsaar.net'
# subject 'testing sendmail'
# body 'testing sendmail'
# end
#
# mail.deliver!
class SMTPConnection
attr_accessor :smtp, :settings
def initialize(values)
raise ArgumentError.new('A Net::SMTP object is required for this delivery method') if values[:connection].nil?
self.smtp = values[:connection]
self.settings = values
end
# Send the message via SMTP.
# The from and to attributes are optional. If not set, they are retrieve from the Message.
def deliver!(mail)
smtp_from, smtp_to, message = Mail::CheckDeliveryParams.check(mail)
response = smtp.sendmail(dot_stuff(message), smtp_from, smtp_to)
settings[:return_response] ? response : self
end
private
# This is Net::SMTP's job, but before Ruby 2.x it does not dot-stuff
# an unterminated last line: https://bugs.ruby-lang.org/issues/9627
def dot_stuff(message)
message.gsub(/(\r\n\.)(\r\n|$)/, '\1.\2')
end
end
end
| true
|
4171fdaf948b037e697bb0fa9f260d1cdfcb28d1
|
Ruby
|
instructure/inst-jobs
|
/spec/delayed/message_sending_spec.rb
|
UTF-8
| 3,332
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require "spec_helper"
require "debug_inspector"
RSpec.describe Delayed::MessageSending do
before do
allow(Rails.env).to receive(:test?).and_return(true)
end
before(:all) do
# this has to be a "real" constant
class SpecClass # rubocop:disable RSpec/LeakyConstantDeclaration, Lint/ConstantDefinitionInBlock
def call_private(**enqueue_args)
delay(**enqueue_args).private_method
end
def call_protected(**enqueue_args)
other = self.class.new
other.delay(**enqueue_args).protected_method
end
def call_public(**_kwargs)
42
end
private
def private_method; end
protected
def protected_method; end
end
end
after(:all) do
Object.send(:remove_const, :SpecClass)
end
let(:klass) { SpecClass }
it "allows an object to send a private message to itself" do
expect do
job = klass.new.call_private(ignore_transaction: true)
job.invoke_job
end.not_to raise_error
end
it "allows an object to send a private message to itself synchronouosly" do
expect { klass.new.call_private(synchronous: true) }.not_to raise_error
end
it "warns about directly sending a private message asynchronously" do
expect { klass.new.delay.private_method }.to raise_error(NoMethodError)
end
it "warns about directly sending a private message synchronusly" do
expect { klass.new.delay(synchronous: true).private_method }.to raise_error(NoMethodError)
end
it "does not warn about directly sending a private message in production" do
allow(Rails.env).to receive(:test?).and_return(false)
allow(Rails.env).to receive(:development?).and_return(false)
expect { klass.new.delay.private_method }.not_to raise_error
end
it "does not warn about directly sending a private message synchronously in production" do
allow(Rails.env).to receive(:test?).and_return(false)
allow(Rails.env).to receive(:development?).and_return(false)
expect { klass.new.delay(synchronous: true).private_method }.not_to raise_error
end
it "allows an object to send a protected message to itself" do
job = klass.new.call_protected(ignore_transaction: true)
expect { job.invoke_job }.not_to raise_error
end
it "allows an object to send a protected message to itself synchronouosly" do
expect { klass.new.call_protected(synchronous: true) }.not_to raise_error
end
it "directly calls a public method on an object with kwargs" do
expect(klass.new.delay(synchronous: true).call_public(kwarg: 10)).to eq 42
end
it "warns about directly sending a protected message asynchronously" do
expect { klass.new.delay.protected_method }.to raise_error(NoMethodError)
end
it "warns about directly sending a protected message synchronusly" do
expect { klass.new.delay(synchronous: true).protected_method }.to raise_error(NoMethodError)
end
it "doesn't explode if you can't dump the sender" do
klass = Class.new do
def delay_something
Kernel.delay.sleep(1)
end
def encode_with(_encoder)
raise "yaml encoding failed"
end
end
obj = klass.new
expect { YAML.dump(obj) }.to raise_error("yaml encoding failed")
expect { obj.delay_something }.not_to raise_error
end
end
| true
|
5228dd20c846c2eeaa12f86bd3cb6d0b867d77c0
|
Ruby
|
Geovo/codeeval
|
/moderate/array_absurdity/array_absurdity.rb
|
UTF-8
| 180
| 3.046875
| 3
|
[] |
no_license
|
File.open(ARGV[0]).each_line do |line|
line = line.split(/[\;\,]/).map {|n| n = n.to_i}
size = line.shift
x = 0
line.map {|el| x = el if line.count(el) > 1 }
puts x
end
| true
|
160de41e5a5ca46f3ac91aa2e5d503f6dcc1bce9
|
Ruby
|
aptible/aptible-cli
|
/lib/aptible/cli/formatter/keyed_list.rb
|
UTF-8
| 560
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Aptible
module CLI
module Formatter
class KeyedList < List
# KeyedList is a list of objects with one key that is more important
# than the others. Some renderers may opt to only display this key when
# rendering the list.
attr_reader :key
def initialize(key)
@key = key
super()
end
def value(_)
raise "not supported on #{self.class}"
end
def list
raise "not supported on #{self.class}"
end
end
end
end
end
| true
|
ced689573f575201a04ce088ed6419f26a08fe09
|
Ruby
|
srallen/ruby
|
/tic-tac-toe.rb
|
UTF-8
| 5,009
| 3.8125
| 4
|
[] |
no_license
|
class TicTacToe
def initialize
@cpu = "X"
@player = "O"
@board = { "c1" => " ", "e1" => " ", "c2" => " ",
"e2" => " ", "ct" => " ", "e3" => " ",
"c3" => " ", "e4" => " ", "c4" => " " }
@positions = @board.keys
@board_guide = " c1 | e1 | c2 \n-------------\n e2 | ct | e3 \n-------------\n c3 | e4 | c4"
@winning_combos = [["c1", "e1", "c2"], ["e2", "ct", "e3"], ["c3", "e4", "c4"], ["c1", "e2", "c3"], ["e1", "ct", "e4"], ["c2", "e3", "c4"], ["c3", "ct", "c2"], ["c1", "ct", "c4"]]
instructions
cpu_game_start
end
def print_board
puts ""
puts " #{@board["c1"]} | #{@board["e1"]} | #{@board["c2"]} \n-----------\n #{@board["e2"]} | #{@board["ct"]} | #{@board["e3"]} \n-----------\n #{@board["c3"]} | #{@board["e4"]} | #{@board["c4"]} "
puts ""
end
def cpu_game_start
moves = @positions.reject { |p| p.include?("e") } # Rejecting possible edge start positions. Corner start is strategically best and help prevents forking win by player.
randomize_game_start = moves.sample
@board[randomize_game_start] = @cpu
print_board
end
def instructions
puts "Play Tic-Tac-Toe!"
puts ""
puts "Try to beat the CPU player. CPU plays X and you will play O."
puts 'When it is your turn, input the position you would like to play your "O" token. The board positions are:'
puts ""
puts @board_guide
puts ""
puts 'For your reference, "c" stands for corner, "e" stands for edge, and "ct" stands for center.'
puts 'You can enter "help" when it is your turn to reprint the board positions guide.'
puts 'Also, entering "board" will reprint the current board and entering "end" will end the game.'
puts ""
end
# Logic for player turn.
def player_turn
puts 'Where do you want to place "O"?'
player_input = gets.chomp.downcase
if player_input == "help"
help
elsif player_input == "board"
player_request_board
elsif player_input == "end"
end_game
elsif @positions.include?(player_input)
if @board[player_input] == " "
@board[player_input] = @player
puts "Player moves to #{player_input}."
puts ""
print_board
else
already_played
end
else
invalid_play
end
end
# Various responses to player input
def help
puts @board_guide
player_turn
end
def player_request_board
print_board
player_turn
end
def already_played
puts "You cannot pick a position already in play."
player_turn
end
def invalid_play
puts "Please input a valid board position."
player_turn
end
def end_game
@end_game = true
end
# Counts the tokens in all of the possible winning combinations.
def check_winning_combos(combo, token)
count = 0
combo.each do |item|
if @board[item] == token
count += 1
end
end
count
end
# CPU picks a random move if no other strategically better options are available.
def pick_random_move
randomize = @positions.sample
if @board[randomize] == " "
randomize
else
pick_random_move
end
end
def cpu_turn
moves = {'wins' => [], 'plays' => []}
@winning_combos.each do |combo|
# Select the empty spot to play
if check_winning_combos(combo, @cpu) == 2
moves['wins'].concat combo.select { |c| @board[c] == " " }.first(1)
elsif check_winning_combos(combo, @player) == 2
moves['plays'].concat combo.select { |c| @board[c] == " " }.first(1)
end
end
if !moves['wins'].empty? # Play winning combination if possible.
puts "CPU plays at #{moves['wins'].first}"
@board[moves['wins'].first] = @cpu
elsif !moves['plays'].empty? # Block the player if they have two in a winning combination.
puts "CPU plays at #{moves['plays'].first}"
@board[moves['plays'].first] = @cpu
elsif @board["ct"] == " " # If center position has not been played by CPU, then play it to completely stop any possible player wins by forking.
@board["ct"] = @cpu
else
move = pick_random_move # CPU randomly moves if other strategically better options are not available.
puts "CPU plays at #{move}"
@board[move] = @cpu
end
print_board
end
# Game play order
def play
if @end_game
puts "Goodbye!"
else
player_turn
cpu_turn
cpu_win?
end
end
# Check to see if it is a win by CPU.
def cpu_win?
@winning_combos.each do |combo|
if check_winning_combos(combo, @cpu) == 3
puts "The CPU has beaten you at Tic-Tac-Toe! Game Over!"
return true
end
end
any_moves_left?
end
# Check to see if it is a draw.
def any_moves_left?
unplayed = 0
@positions.each do |p|
if @board[p] == " "
unplayed += 1
end
end
if unplayed == 0
puts "It's a draw!"
else
play
end
end
end
game = TicTacToe.new
game.play
| true
|
391faaa9d5ba7a33090b7d1d287bbe30808469b4
|
Ruby
|
montethinks/Concepts
|
/01_basics/exercise_5.rb
|
UTF-8
| 293
| 3.8125
| 4
|
[] |
no_license
|
#Outputs factorial of the numbers 5, 6, 7, 8.
five_factorial = 5 * 4 * 3 * 2 * 1
six_factorial = 6 * 5 * 4 * 3 * 2 * 1
seven_factorial = 7 * 6 * 5 * 4 * 3 * 2 * 1
eight_factorial = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
puts five_factorial
puts six_factorial
puts seven_factorial
puts eight_factorial
| true
|
cc45c4f37bcdeccf38c12d5d71d5bb1149ae1f48
|
Ruby
|
blsalcido/phase_0_unit_3
|
/week_7/7_gps3.1/our_solution.rb
|
UTF-8
| 1,259
| 4.28125
| 4
|
[] |
no_license
|
# U3.W7: Build an Electronic Grocery List!
# Your full names:
# 1. Bridgette Salcido
# 2. Jen Tutu
# User Stories (As many as you want. Delete the statements you don't need)
# As a user, I want to create a list of products to buy
# As a user, I want to be able to add items to the list
# As a user, I want to be able to cross off items from the list
# As a user, I want to see an updated list
# Pseudocode
#define a class called Grocery List
#Create instance method add, take arguments for item and quantity
#Create instance method cross_off, take argument for item to remove
#Create instance method new_list, return updated list
#
#
# Your fabulous code goes here....
class Item
attr_reader :name
end
class GroceryList
attr_reader :items
def initialize
@items={}
end
def add_item(item, quantity)
@items[item] = quantity
end
def cross_off(item)
@items.delete(item)
end
def display
@items.each { |k,v| puts k; puts v }
raise ArgumentError.new("Your list has no items.") if @items.empty?
end
end
# DRIVER CODE GOES HERE.
shopping_list = GroceryList.new()
shopping_list.add_item("apples", 5)
p shopping_list.items["apples"] == 5
shopping_list.cross_off("apples")
shopping_list.display
| true
|
e01eb8ab5f77baf311fc7e5745b4fb7b3c504410
|
Ruby
|
sethkrasnianski/shenanigans
|
/lib/shenanigans/object/display.rb
|
UTF-8
| 380
| 3.5
| 4
|
[
"MIT"
] |
permissive
|
class Object
# Outputs the object and also returns it.
# Will use <tt>puts</tt> if <tt>new_line</tt> is <tt>true</tt> and
# <tt>print</tt> otherwise.
# "foo".display
# foo
# #=> "foo"
#
# "foo".display(false)
# foo#=> "foo"
def display(new_line = true)
m = new_line ? :puts : :print
self.tap { |o| send(m, o) }
end
alias :d :display
end
| true
|
f3fd94aacf83ca20c0c3afe8d8697e54e4673350
|
Ruby
|
kjhenner/prosody
|
/lib/prosody/poem.rb
|
UTF-8
| 3,650
| 2.890625
| 3
|
[] |
no_license
|
class Poem
def initialize(graph, line_length, scheme)
@line_length = line_length
@scheme = scheme
@rhymes = {}
@line_count = 0
@graph = graph
@starts = get_starts
@path = [init_path]
@meter = '01'
end
def to_s
"#{@line_length}, #{@scheme}"
end
def init_path
{
bigram: first_bigram,
excluded_bigrams: [],
line_end: ''
}
end
def first_bigram
@starts.delete_at(rand(@starts.size))
end
def get_starts
# Find and array of sentence-initial bigrams
@graph.nodes.keys.select{ |k| @graph.nodes[k].can_end_sentence? }
.collect{ |n| @graph.nodes[n].edges }
.flatten
.uniq
end
def print_path
@path.collect{ |p| p[:bigram] + p[:line_end] }.join(' ')
end
def get_rhyme
path_index = (@scheme.index(@scheme[@line_count]) + 1) * @line_length - 1
bigram = @graph.nodes[@path[path_index][:bigram]].bigram rescue nil
return nil unless bigram
type = /^[[:punct:]]$/.match(bigram[1].string) ? bigram[0] : bigram[1]
end
def generate_line(previous_bigram, length, rhyme, meter, starts_sentence, ends_sentence)
line = ''
while meter_with_distance(line)[0].size < length
if line.size = 0
line = first_bigram
end
next_node = @graph.sample_neighbors(bigram, exclude=excluded_bigrams, rhyme=rhyme, final=final, path=print_path, meter=@meter)
end
end
def generate
while @line_count < @scheme.size # while there are fewer lines than specified
if @path.empty?
# The first bigram led to a dead-end
unless @starts.empty?
# There were no valid poems found with the first bigram
# Take a new bigram from the @starts array and try again
@path = [init_path]
else
# There were no more starts in the @starts array to try
puts "Couldn't find a valid poem!"
break
end
end
bigram = @graph.nodes[@path[-1][:bigram]]
excluded_bigrams = @path[-1][:excluded_bigrams]
final = @line_count == @scheme.size() - 1 ? true : false
#final = nil
if (@path.size + 1) % @line_length == 0
# If the next bigram will complete a line
#rhyme = @rhymes[@scheme[@line_count]]
rhyme = get_rhyme
next_node = @graph.sample_neighbors(bigram, exclude=excluded_bigrams, rhyme=rhyme, final=final, path=print_path, meter=@meter)
next_path_element = {
bigram: next_node,
excluded_bigrams: [],
line_end: "\n"
}
else
# If the next bigram won't complete a line
next_node = @graph.sample_neighbors(bigram, exclude=excluded_bigrams, rhyme=nil, final=nil, path=print_path, meter=@meter)
next_path_element = {
bigram: next_node,
excluded_bigrams: [],
line_end: ''
}
end
if next_node
# Mark the next node as already tried for the
# current node. If the path encounters a dead end
# following this node, it won't be picked again next
# time.
if (@path.size + 1) % @line_length == 0
@rhymes[@scheme[@line_count]] ||= @graph.nodes[next_node].bigram[1]
end
@path[-1][:excluded_bigrams] << next_node
@path << next_path_element
else
if (@path.size + 1) % @line_length == 0
@rhymes[@scheme[@line_count]] == nil
end
@path.pop
end
@line_count = @path.collect{ |p| p[:line_end] }
.reject{ |f| f == '' }
.size
puts print_path
end
return print_path
end
end
| true
|
1f3d2b69592bdada4cd0ccc259d74a01b58af971
|
Ruby
|
nanakenashi/moz_api_caller
|
/lib/api.rb
|
UTF-8
| 1,551
| 2.828125
| 3
|
[] |
no_license
|
require 'base64'
require 'bigdecimal'
require 'json'
require 'openssl'
require 'open-uri'
require 'uri'
class Api
ENDPOINT = 'https://lsapi.seomoz.com/linkscape/url-metrics/'
COLS = 32 + # External Equity Links
34359738368 + # Page Authority
68719476736 # Domain Authority
def initialize(params={})
@access_id = params.fetch(:access_id, ENV['MOZ_ACCESS_ID'])
@secret_key = params.fetch(:secret_key, ENV['MOZ_SECRET_KEY'])
@expires = params.fetch(:expires, Time.now.to_i + 300)
end
def get_url_metrics(target_url)
url = get_request_url(target_url)
metrics = request(url)
parse_result(metrics)
end
private
def get_request_url(target_url)
encoded_target = URI.encode(target_url)
signature = get_signature
"#{ENDPOINT}#{encoded_target}?Cols=#{COLS}&AccessID=#{@access_id}&Expires=#{@expires}&Signature=#{signature}"
end
def get_signature
string_to_sign = "#{@access_id}\n#{@expires}"
binary_signature = OpenSSL::HMAC.digest('sha1', @secret_key, string_to_sign)
URI.encode(Base64.encode64(binary_signature))
end
def request(url)
res = open(url)
JSON.parse(res.read)
end
def parse_result(metrics)
mapping = {
'ueid' => 'external_equity_links',
'upa' => 'page_authority',
'pda' => 'domain_authority'
}
metrics.each_with_object({}) do |(key, val), result|
val = BigDecimal(val.to_s).floor(2).to_f if val.instance_of?(Float)
result[mapping[key]] = val
end
end
end
| true
|
049fa82997af7786c77fca2c626033367cb374bf
|
Ruby
|
jencoleman/my-first-repository
|
/array/mutate.rb
|
UTF-8
| 196
| 3.421875
| 3
|
[] |
no_license
|
#testing
def mutate(arr)
arr.pop
end
def not_mutate(arr)
puts arr.select { |i| i > 3 }
end
a = [1, 2, 3, 4, 5, 6]
not_mutate(a)
["b", 1], ["b", 2]
names[names.index('margaret')] = 'jody'
| true
|
86de49fc0961202974ee2fb941cddc099dc6418b
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/bob/3d712df1a56d4e5680c7d97fffef5355.rb
|
UTF-8
| 622
| 3.703125
| 4
|
[] |
no_license
|
class Bob
def hey(message)
if silence?(message)
answer(:silence)
elsif shouting?(message)
answer(:shouting)
elsif asking?(message)
answer(:asking)
else
answer(:talking)
end
end
private
def silence?(message)
message.to_s.strip.empty?
end
def shouting?(message)
message == message.upcase
end
def asking?(message)
message.end_with?('?')
end
def answer(to)
case to
when :silence
'Fine. Be that way!'
when :shouting
'Woah, chill out!'
when :asking
'Sure.'
when :talking
'Whatever.'
end
end
end
| true
|
f989666e775c3f10237ecf817904c65e0fb540b9
|
Ruby
|
andre-schilipack/tostranslate
|
/app/models/translation_file.rb
|
UTF-8
| 649
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
class TranslationFile < ActiveRecord::Base
has_many :translation_lines
attr_accessor :file
after_create :create_translation_lines
def percentage
self.translation_lines.where(translated: true).count.to_f / self.translation_lines.count.to_f * 100
end
private
def create_translation_lines
require 'csv'
rows = CSV.read(self.file.path, { col_sep: "\t" })
rows.each do |row|
translation_line = TranslationLine.new()
translation_line.translation_file_id = self.id
translation_line.translation_code = row[0]
translation_line.description = row[1]
translation_line.save
end
end
end
| true
|
808fe44baf4207ffd969a4615468596a09fb2d60
|
Ruby
|
sdmalek44/algorithm_practice
|
/tests/two_d_array_test.rb
|
UTF-8
| 438
| 3
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/pride'
require './lib/two_d_array.rb'
class TwoDArrayTest < Minitest::Test
def test_it_gets_highest_hourglass
arr = [[-9, -9, -9, 1, 1, 1],
[0, -9, 0, 4, 3, 2],
[-9, -9, -9, 1, 2, 3],
[0, 0, 8, 6, 6, 0],
[0, 0, 0, -2, 0, 0],
[0, 0, 1, 2, 4, 0]]
expected = 28
assert_equal expected, hourglassSum(arr)
end
end
| true
|
3468d6470a7339f5041a2933b4d6aa13bb83cc3e
|
Ruby
|
markdefg/maze-runner
|
/lib/features/steps/request_assertion_steps.rb
|
UTF-8
| 3,614
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'test/unit'
require 'minitest'
require 'open-uri'
require 'json'
require 'cgi'
require_relative '../../maze/wait'
include Test::Unit::Assertions
# @!group Request assertion steps
def assert_received_requests(request_count, list, list_name)
timeout = Maze.config.receive_requests_wait
wait = Maze::Wait.new(timeout: timeout)
received = wait.until { list.size >= request_count }
unless received
raise <<-MESSAGE
Expected #{request_count} #{list_name} but received #{list.size} within the #{timeout}s timeout.
This could indicate that:
- Bugsnag crashed with a fatal error.
- Bugsnag did not make the requests that it should have done.
- The requests were made, but not deemed to be valid (e.g. missing integrity header).
- The requests made were prevented from being received due to a network or other infrastructure issue.
Please check the Maze Runner and device logs to confirm.)
MESSAGE
end
assert_equal(request_count, list.size, "#{list.size} #{list_name} received")
end
#
# Error request assertions
#
# Shortcut to waiting to receive a single request of the given type
#
# @step_input request_type [String] The type of request (error, session, etc)
Then('I wait to receive a(n) {word}') do |request_type|
step "I wait to receive 1 #{request_type}"
end
# Continually checks to see if the required amount of requests have been received.
# Times out according to @see Maze.config.receive_requests_wait.
#
# @step_input request_type [String] The type of request (error, session, etc)
# @step_input request_count [Integer] The amount of requests expected
Then('I wait to receive {int} {word}') do |request_count, request_type|
assert_received_requests request_count, Maze::Server.list_for(request_type), request_type
end
# Assert that the test Server hasn't received any requests - of a specific, or any, type.
#
# @step_input request_type [String] The type of request ('error', 'session', etc), or 'requests' to assert on all
# request types.
Then('I should receive no {word}') do |request_type|
sleep Maze.config.receive_no_requests_wait
if request_type == 'requests'
# Assert that the test Server hasn't received any requests at all.
assert_equal(0, Maze::Server.errors.size, "#{Maze::Server.errors.size} errors received")
assert_equal(0, Maze::Server.sessions.size, "#{Maze::Server.sessions.size} sessions received")
else
list = Maze::Server.list_for(request_type).size
assert_equal(0, list, "#{list.size} #{request_type} received")
end
end
# Moves to the next request
#
# @step_input request_type [String] The type of request (error, session, etc)
Then('I discard the oldest {word}') do |request_type|
raise "No #{request_type} to discard" if Maze::Server.list_for(request_type).current.nil?
Maze::Server.list_for(request_type).next
end
Then('the received errors match:') do |table|
# Checks that each request matches one of the event fields
requests = Maze::Server.errors.remaining
match_count = 0
# iterate through each row in the table. exactly 1 request should match each row.
table.hashes.each do |row|
requests.each do |request|
# Skip if no body.events in this request
next if (!request.key? :body) || (!request[:body].key? 'events')
events = request[:body]['events']
assert_equal(1, events.length, 'Expected exactly one event per request')
match_count += 1 if request_matches_row(events[0], row)
end
end
assert_equal(requests.size, match_count, 'Unexpected number of requests matched the received payloads')
end
| true
|
246e52e5c817c3cfcbf743cad9feed8925cef4f8
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/rna-transcription/2f4b2a9b58014e159fd73eb85b51b6a5.rb
|
UTF-8
| 1,013
| 3.484375
| 3
|
[] |
no_license
|
class Complement
def initialize(params)
@type = :dna if params[:dna]
@type = :rna if params[:rna]
@string = params[@type]
end
def dna?
@type == :dna
end
def rna?
@type == :rna
end
def dna_to_rna_map
{
'G' => 'C',
'C' => 'G',
'T' => 'A',
'A' => 'U'
}
end
def nucleotides(str)
str.split('')
end
def rna_complement_for(nucleotide)
dna_to_rna_map[nucleotide] or raise ArgumentError, "Invalid DNA nucleotide '#{nucleotide}'"
end
def dna_complement_for(nucleotide)
dna_to_rna_map.key nucleotide or raise ArgumentError, "Invalid RNA nucleotide '#{nucleotide}'"
end
def run
hammer = lambda { |nucleotide| rna_complement_for(nucleotide) } if dna?
hammer = lambda { |nucleotide| dna_complement_for(nucleotide) } if rna?
nucleotides(@string).map(&hammer).join
end
def self.of_dna(dna)
Complement.new({ :dna => dna }).run
end
def self.of_rna(rna)
Complement.new({ :rna => rna }).run
end
end
| true
|
34ff9f57561fd2f95e79552afc49a586391382e1
|
Ruby
|
cynthiak/wonton-analytics
|
/app/helpers/expenses_helper.rb
|
UTF-8
| 3,228
| 3.03125
| 3
|
[] |
no_license
|
module ExpensesHelper
# Expenses ##############
def get_expenses_array(expense_type=nil, start_date=nil, end_date=nil)
if start_date == nil
start_date = Expense.all.order("date").first.date
end
if end_date == nil
end_date = Expense.all.order("date").last.date
end
if expense_type
Expense.where(expense_type: expense_type, date: start_date..end_date)
else
Expense.where(date: start_date..end_date)
end
end
def get_expenses(expense_type=nil, start_date=nil, end_date=nil)
if start_date == nil
start_date = Expense.all.order("date").first.date
end
if end_date == nil
end_date = Expense.all.order("date").last.date
end
if expense_type
Expense.where(expense_type: expense_type, date: start_date..end_date).sum(:amount).round(2)
else
Expense.where(date: start_date..end_date).sum(:amount).round(2)
end
end
def get_expenses_by_month(expense_type=nil, month)
start_date = Date.new(month.year, month.month, 1)
end_date = Date.civil(month.year, month.month, -1)
return get_expenses(expense_type, start_date, end_date)
end
def get_expenses_by_year(expense_type=nil, year)
start_date = Date.new(year, 1, 1)
end_date = Date.civil(year, 12, -1)
return get_expenses(expense_type, start_date, end_date)
end
# Average Monthly Expenses ##############
def get_average_monthly_expenses(start_date=nil, end_date=nil)
if start_date == nil
start_date = get_first_sale_date
end
if end_date == nil
end_date = get_last_sale_date
end
(get_expenses(nil, start_date, end_date)/months(nil, start_date, end_date)).round(2)
end
def get_average_monthly_expenses_by_year(year)
start_date = Date.new(year, 1, 1)
end_date = Date.civil(year, 12, -1)
return get_average_monthly_expenses(start_date, end_date)
end
# Average Daily Expenses ##############
def get_average_daily_expenses(start_date=nil, end_date=nil)
if start_date == nil
start_date = get_first_sale_date
end
if end_date == nil
end_date = get_last_sale_date
end
(get_expenses(nil, start_date, end_date)/days(nil, start_date, end_date)).round(2)
end
def get_average_daily_expenses_by_month(month)
start_date = Date.new(month.year, month.month, 1)
end_date = Date.civil(month.year, month.month, -1)
return get_average_daily_expenses(start_date, end_date)
end
def get_average_daily_expenses_by_year(year)
start_date = Date.new(year, 1, 1)
end_date = Date.civil(year, 12, -1)
return get_average_daily_expenses(start_date, end_date)
end
# By Expense Type ##############
def get_expense_types
Expense.order(:expense_type).pluck(:expense_type).uniq
end
def get_expenses_percentage_by_type(expense_type, start_date=nil, end_date=nil)
type = get_expenses(expense_type, start_date, end_date)
total = get_expenses(nil, start_date, end_date)
return ((type/total)*100).round(2)
end
def get_expenses_percentage_by_type_by_year(expense_type, year)
start_date = Date.new(year, 1, 1)
end_date = Date.civil(year, 12, -1)
get_expenses_percentage_by_type(expense_type, start_date, end_date)
end
end
| true
|
4daa644718e8d74b004734b59436d7c808856561
|
Ruby
|
njruby/practice
|
/problems/practice2.rb
|
UTF-8
| 301
| 3.53125
| 4
|
[] |
no_license
|
# Refactor the below methods into a single method
def print_string_class(string)
puts "#{string} is of class #{string.class}"
end
def print_array_class(array)
puts "#{array} is of class #{array.class}"
end
def print_integer_class(integer)
puts "#{integer} is of class #{integer.class}"
end
| true
|
2b831d252ef686fb836eb169664923c3dec17bde
|
Ruby
|
sleepingkingstudios/bronze
|
/lib/bronze/transforms/entities/normalize_transform.rb
|
UTF-8
| 1,680
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'bronze/transform'
require 'bronze/transforms/entities'
module Bronze::Transforms::Entities
# Transform class that maps an entity to a normal representation.
class NormalizeTransform < Bronze::Transform
# @param [Class] entity_class The entity class to normalize.
# @param [Array<Class>] permit An optional array of types to normalize
# as-is, rather than applying a transform. Only default transforms can be
# permitted, i.e. the built-in default transforms for BigDecimal, Date,
# DateTime, Symbol, and Time, or for an attribute with the
# :default_transform flag set to true.
def initialize(entity_class, permit: [])
@entity_class = entity_class
@permitted_types = permit
end
# @return [Class] the entity class to normalize.
attr_reader :entity_class
# @return [Array<Class>] array of types to normalize as-is.
attr_reader :permitted_types
# Returns an entity instance.
#
# @param attributes [Hash] The normal representation of an entity.
#
# @return [Bronze::Entity] the entity instance.
#
# @see [Bronze::Entities::Normalization::denormalize]
def denormalize(attributes)
return nil if attributes.nil?
entity_class.denormalize(attributes)
end
# Returns a normalized representation of the entity.
#
# @param entity [Bronze::Entity] The entity to normalize.
#
# @return [Hash] the normal representation.
#
# @see [Bronze::Entities::Normalization#normalize]
def normalize(entity)
return nil if entity.nil?
entity.normalize(permit: permitted_types)
end
end
end
| true
|
1aebb143795a697014ebb306355637d78ae7dd24
|
Ruby
|
malachispencer/dependency-injection
|
/spec/exercise_4_spec.rb
|
UTF-8
| 1,072
| 3.765625
| 4
|
[] |
no_license
|
=begin
Makers. 05/11/20. Here I wrote a test for the Greeter class, which doesn't use the actual Kernel module.
1) We first created a simple kernel double.
2) We then create an instance of Greeter, where we pass in the kernel double, this double will be @kernel in greeter.
3) Inside the it block, we stub the gets method called in the greet method of the class, and set it to return "Malachi\n".
4) We then set an expectation for the greet method to output the greet message with the return value we set for gets, to
standard output.
4) The chomp method will remove \n from "Malachi\n". But because we use the puts method instead of print, a newline is added
to the end of the greet message.
=end
require 'exercise_4'
describe Greeter do
describe '#greet' do
let(:kernel) { double :kernel }
let(:greeter) { Greeter.new(kernel) }
it 'takes the users name and returns a greet message' do
allow(kernel).to receive(:gets) { "Malachi\n" }
expect { greeter.greet }.to output("What is your name?\nHello, Malachi\n").to_stdout
end
end
end
| true
|
62e239245d855151e90e5e7bd37b8932df432c6c
|
Ruby
|
dhamilt9/sinatra-integrating-models-walkthrough-nyc-web-111918
|
/app.rb
|
UTF-8
| 1,004
| 3.015625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative 'config/environment'
require_relative 'models/text_analyzer.rb'
require 'pry'
class App < Sinatra::Base
get '/' do
erb :index
end
post '/' do
@text_from_user = params[:user_text]
@word_count=@text_from_user.split(" ").count
@vowel_count=0
@consenant_count=0
@letter_hash={}
@text_from_user.split("").each do |letter|
if letter.downcase=='a' || letter.downcase=='e' || letter.downcase=='i' || letter.downcase=='o' || letter.downcase=='u'
@vowel_count+=1
else
if letter!=" "
@consenant_count+=1
end
end
if letter!=" "
if @letter_hash.include?(letter.downcase)
@letter_hash[letter.downcase]+=1
else
@letter_hash[letter.downcase]=1
end
end
end
@most_common_letter=@letter_hash.sort_by{|key, value| value}.reverse[0][0].upcase
@most_common_letter_count=@letter_hash.sort_by{|key, value| value}.reverse[0][1]
erb :results
end
end
| true
|
288edd9f2bb5e0ed0160976c00012cc49813d1b3
|
Ruby
|
sinharahul/solr
|
/ferret/format.rb
|
UTF-8
| 128
| 2.625
| 3
|
[] |
no_license
|
File.open("index.rb").readlines.each do |line|
if line =~ /(\d)+/
line = line.sub(/(\d)+/,"")
puts line
end
end
| true
|
f693490ce382e7f54330f761bc6159a3c4082c50
|
Ruby
|
aphilippartd/zenps-ruby
|
/lib/zenps/client.rb
|
UTF-8
| 1,640
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'net/http'
require 'uri'
require 'json'
module Zenps
# Api client for Zenps
class Client
def initialize
check_configuration
end
def call(options = {})
@options = options
perform_request
expose_response
end
private
attr_reader :options, :response
def check_configuration
raise KeyMissingError if ::Zenps.config[:zenps_key].nil?
end
def perform_request
request = Net::HTTP::Post.new(uri, header)
request.body = body
@response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request request }
end
def expose_response
{
email: get_attribute(:email),
code: response.code.to_i,
body: response.body
}
end
def uri
@uri ||= URI.parse(end_point)
end
def header
@header ||= {
'Content-Type': 'text/json',
'Authorization': ::Zenps.config[:zenps_key]
}
end
def body
{
to: to,
locale: get_attribute(:locale, default: 'en'),
event: get_attribute(:event),
tags: tags
}.compact.to_json
end
def to
{
email: get_attribute(:email),
first_name: get_attribute(:first_name),
last_name: get_attribute(:last_name)
}.compact
end
def get_attribute(attribute, params = {})
options[attribute.to_s] || options[attribute] || params[:default]
end
def tags
get_attribute('tags', default: []).join(', ')
rescue NoMethodError
nil
end
def end_point
'https://api.zenps.io/nps/v1/surveys'
end
end
end
| true
|
80962791b0f5450c0ad4078f477c421a3fdc365f
|
Ruby
|
FeminismIsAwesome/California-Scraper
|
/lib/models/voting_history_scraper.rb
|
UTF-8
| 2,568
| 2.578125
| 3
|
[] |
no_license
|
class VotingHistoryScraper
def self.get_voting_history_for(content)
content = content.force_encoding("ISO-8859-1")
ayes = getAyesFor(content)
noes = getNoesFor(content)
absents = getAbsentsFor(content)
author = getAuthorFor(content)
topic = getTopicFor(content)
date = getDateFor(content)
location = getLocationFor(content)
motion = getMotionFor(content)
VotingSession.new(ayes: ayes, noes: noes, absent: absents,
author: author, topic: topic, date: date, location: location, motion: motion)
end
def self.getMotionFor(content)
motion = content.match(/MOTION:.*/i)[0]
motion["MOTION:".length..motion.length].strip
end
def self.getLocationFor(content)
location = content.match(/LOCATION:.*/)[0]
location["LOCATION:".length..location.length].strip
end
def self.getDateFor(content)
date = content.match(/DATE:.*/)[0]
date = date["DATE:".length..date.length].strip
Date.strptime(date, "%m/%d/%Y")
end
def self.getTopicFor(content)
topic = content.match(/Topic:.*/i)[0]
topic["TOPIC:".length..topic.length].strip
end
def self.getAuthorFor(content)
author = content.match(/Author:.*/i)[0]
author["Author:".length..author.length].strip
end
def self.getNoesFor(content)
if (content.match(/NOES\n\t.*?\*.*ABSENT/m))
noes = content.match(/NOES\n\t.*?\*.*ABSENT/m)[0]
noes = noes["NOES".length..noes.length - " ABSENT".length]
get_names_of_votes_given(noes)
else
noes = content.match(/NOES\n\t.*?\*.*NO VOTE RECORDED/m)[0]
noes = noes["NOES".length..noes.length - " NO VOTE RECORDED".length]
get_names_of_votes_given(noes)
end
end
def self.getAyesFor(content)
ayes = content.match(/AYES\n\t.*?\*.*NOES/m)[0]
ayes = ayes["AYES".length..ayes.length-" NOES".length]
get_names_of_votes_given(ayes)
end
def self.getLines(lines, start, linesFromEnd)
lines.split("\n")[start..lines.length-linesFromEnd].join("\n")
end
def self.getAbsentsFor(content)
if (content.match(/(ABSENT|NO VOTE RECORDED).*/m))
absents = content.match(/(ABSENT|NO VOTE RECORDED).*<br>/m)[0]
absents = absents[0..absents.length-" <br>".length]
absents = getLines(absents,2,1)
get_names_of_votes_given(absents)
end
end
def self.get_names_of_votes_given(namesText)
namesText.split("\n").map { |nameLine|
if (nameLine.match(/[A-z][A-z]*/))
nameLine.split("\t")
else
[]
end
}.select { |name|
!name.nil?
}.reduce(:+)
end
end
| true
|
94f1659eedf63915faeaa753618d1b9f7154f214
|
Ruby
|
StlMaris123/active-jobs
|
/spec/models/article_spec.rb
|
UTF-8
| 2,891
| 2.546875
| 3
|
[] |
no_license
|
require 'rails_helper'
describe Article do
let(:article) { Fabricate(:article) }
[:title, :body].each do |attribute|
it "is not valid without a #{attribute}" do
article.update_attributes(attribute => nil)
expect(subject).to_not be_valid
end
end
context "when it has invalid attributes" do
it "raises an execption when hard saving" do
article.title = nil
expect{article.save!}.to raise_error(ActiveRecord::RecordInvalid)
end
end
it "must have a unique title" do
article.save
second = article.dup
expect(second).to_not be_valid
end
it "returns the title when converted to a string" do
expect(article.to_s).to eq article.title
end
it "responds to comments" do
expect(article).to respond_to(:comments)
end
it "responds to .valid_ids with a set of all current article IDs" do
expect(Article.valid_ids).to eq Article.select(:id).collect{|a| a.id}
end
context ".for_dashboard" do
it "gives the most recent 5 articles" do
6.times do
Fabricate(:article)
end
expected = Article.order('created_at DESC').limit(5).all
articles = Article.for_dashboard
expect(articles.count).to eq(5)
expect(articles).to eq(expected)
end
end
context ".total_word_count" do
it "gives the word count for all articles" do
2.times { Fabricate(:article, :body => "I think that...") }
expect(Article.total_word_count).to eq(6)
end
end
context "#word_count" do
it "gives the total number of words" do
article = Fabricate(:article, :body => "Four score and seven years ago...")
expect(article.word_count).to eq(6)
end
end
context ".most_popular" do
it "returns the article with the most comments" do
articles = (0..5).collect{ Fabricate(:article) }
Comment.destroy_all
target = articles[rand(articles.length)]
Fabricate(:comment, :article => target)
expect(Article.most_popular).to eq target
end
end
context ".search_by_tag_name" do
context "when given no parameter" do
it "should return all the articles" do
articles, tag = Article.search_by_tag_name(nil)
expect(articles).to eq Article.all
end
end
context "when given a tag name" do
context "and the tag exists" do
it "should return the articles associated with that tag and the tag" do
tag = Fabricate(:tag)
tag.articles = [Fabricate(:article), Fabricate(:article)]
expect(Article.search_by_tag_name(tag.name)).to eq [tag.articles, tag]
end
end
context "but the tag does not exist" do
it "should return an empty list of articles and no tag" do
bad_name = Fabricate(:tag).name + "_no_exist"
expect(Article.search_by_tag_name(bad_name)).to eq [[], nil]
end
end
end
end
end
| true
|
232ecc52b4b87b077da8a5078eede155975bc169
|
Ruby
|
SampsonCrowley/assignment_file_ops_sprint
|
/lib/dictionary.rb
|
UTF-8
| 1,061
| 3.109375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require_relative 'dictionary_loader'
require_relative 'dictionary_searcher'
require_relative 'dictionary_ui'
require_relative 'results_saver'
class Dictionary
attr_reader :words, :searcher, :ui, :writer
def initialize(dict = "dictionary.txt")
@words = DictionaryLoader.load(dict)
@searcher = DictionarySearcher.new(words)
@ui = DictionaryUI.new
@writer = ResultsSaver.new
end
def logic_loop
ui.welcome
loop do
ui.instructions
input = ui.listen
break if quit?(input)
output = select_task(input)
save_to_file(output, input) if save?(ui.save_results(output))
end
end
def quit?(input)
return true if input == "q!"
false
end
def select_task(input)
return searcher.starts_with(input[1..-1]) if input[0] == "@"
return searcher.ends_with(input[1..-1]) if input[0] == "$"
searcher.find(input)
end
def save?(input)
input == "y"
end
def save_to_file(results, keyword)
writer.save(results, keyword)
end
end
Dictionary.new.logic_loop
| true
|
8b8e23556d1d1af915b4aa60a4cf511c4d532b12
|
Ruby
|
kenta-s/atcoder
|
/virtual_contest/20200628/caddi2018b_a.rb
|
UTF-8
| 37
| 2.78125
| 3
|
[] |
no_license
|
n = gets.to_i
puts n.to_s.count('2')
| true
|
a35af0110f652f6bef0e8dc633c204f7b3ae68b9
|
Ruby
|
khonowitz/rad_scheduler
|
/app/services/schedule/importer.rb
|
UTF-8
| 760
| 2.546875
| 3
|
[] |
no_license
|
class Schedule::Importer
def perform(spreadsheet_id = "1Ox-aFv-KTMFACh0WRhEnShlSlLL4rcoinN6GhAs_nDA")
@spreadsheet = fetch_spreadsheet(spreadsheet_id)
process_schedule
end
private
def fetch_spreadsheet(spreadsheet_id)
google_drive = GoogleDrive.saved_session(Rails.root.join('google_config.json').to_s)
google_drive.spreadsheet_by_key(spreadsheet_id).worksheet_by_gid(0)
end
def process_schedule
@spreadsheet.rows(1).map do |row|
next unless importable_row?(row)
Employee.create(first_name: row[0], last_name: row[1], pgy: row[2])
end.compact
end
def importable_row?(row)
row[0].present? && row[1].present? && row[2].present?
end
end
| true
|
119056e0fc0a0190ab3d8e3d26a626da195d056d
|
Ruby
|
Kahaan/Daily-Projects
|
/W2D1/chess/board.rb
|
UTF-8
| 2,000
| 3.5
| 4
|
[] |
no_license
|
require 'byebug'
require_relative 'errors'
require_relative 'piece'
require_relative 'display'
class Board
attr_reader :grid
PIECES = {
[0,0] => Rook
}
def initialize
# wboard = Array.new(2) {Array.new(8) {Piece.new(:w)}}
# nboard = Array.new(4) {Array.new(8) {NullPiece.instance}}
# bboard = Array.new(2) {Array.new(8) {Piece.new(:b)}}
@grid = Array.new(8) {Array.new(8)}
end
def populate_grid
@grid.each_with_index do |row,row_idx|
row.each_index do |col_idx|
if row_idx < 2
grid[row_idx][col_idx] = Piece.new(:w,[row_idx,col_idx])
elsif row_idx >= 2 && row_idx < 6
grid[row_idx][col_idx] = NullPiece.instance
elsif row_idx > 5
grid[row_idx][col_idx] = Piece.new(:b,[row_idx,col_idx])
end
end
end
end
def [](pos)
row, col = pos
grid[row][col]
end
def []=(pos, piece)
row, col = pos
grid[row][col] = piece
end
def move_piece(start_pos,end_pos)
unless valid_pos?(start_pos, end_pos)
raise BadMoveError
end
current_piece = self[start_pos]
captured_piece = self[end_pos]
if current_piece.class == NullPiece
raise NoPieceError # no piece at start
elsif captured_piece.color == current_piece.color
raise BadMoveError # friendly fire
elsif captured_piece.color != current_piece.color
# move under this condition only
if captured_piece.class == NullPiece
self[end_pos], self[start_pos] = self[start_pos], self[end_pos]
elsif captured_piece.color != current_piece.color
self[end_pos] = self[start_pos]
self[start_pos] = NullPiece.instance
end
end
end
def valid_pos?(start_pos, end_pos)
if start_pos[0] > 7 || start_pos[1] > 7 || start_pos[0] < 0 || start_pos[1] < 0
return false
elsif end_pos[0] > 7 || end_pos[1] > 7 || end_pos[0] < 0 || end_pos[1] < 0
return false
end
true
end
end
| true
|
9c00701ce2af6305cafa162240dfac7347305b99
|
Ruby
|
binarycleric/berlin_clock
|
/spec/clock_test_cases.rb
|
UTF-8
| 870
| 2.609375
| 3
|
[] |
no_license
|
require "clock"
describe Clock, "#display" do
it "tests display 00:00:00" do
clock = Clock.new
expected = "Y\n" +
"OOOO\n" +
"OOOO\n" +
"OOOOOOOOOOO\n" +
"OOOO"
clock.display('00:00:00').should == expected
end
it "tests display 13:17:01" do
clock = Clock.new
expected = "O\n" +
"RROO\n" +
"RRRO\n" +
"YYROOOOOOOO\n" +
"YYOO"
clock.display('13:17:01').should == expected
end
it "tests display 23:59:59" do
clock = Clock.new
expected = "O\n" +
"RRRR\n" +
"RRRO\n" +
"YYRYYRYYRYY\n" +
"YYYY"
clock.display('23:59:59').should == expected
end
it "tests display 24:00:00" do
clock = Clock.new
expected = "Y\n" +
"RRRR\n" +
"RRRR\n" +
"OOOOOOOOOOO\n" +
"OOOO"
clock.display('24:00:00').should == expected
end
end
| true
|
1b5bbca4e37087797b1b7f6be49f3e4e1b23e7f2
|
Ruby
|
kenta-s/atcoder
|
/virtual_contest/20200628/arc080_b.rb
|
UTF-8
| 1,128
| 2.875
| 3
|
[] |
no_license
|
h, w = gets.split.map(&:to_i)
n = gets.to_i
as = gets.split.map(&:to_i)
table = Array.new(h, Array.new(w))
visited = Array.new(h, Array.new(w))
visited = {}
if w == 1
dir = 'down'
else
dir = 'right'
end
idx = 0
i = 0
j = 0
visited[0] = {}
visited[0][0] = 0
as[idx] -= 1
while (idx != n-1) || as[idx] != 0
visited[i] ||= {}
visited[i+1] ||= {}
idx += 1 if as[idx] == 0
as[idx] -= 1
if dir == 'right'
if j == w - 1
i += 1
dir = 'down'
visited[i][j] = idx
else
j += 1
visited[i][j] = idx
end
elsif dir == 'left'
if j == 0
i += 1
dir = 'down'
visited[i][j] = idx
else
j -= 1
visited[i][j] = idx
end
elsif dir == 'down'
if j == 0 && 0 == w - 1
i += 1
dir = 'down'
visited[i][j] = idx
elsif j == 0
j += 1
dir = 'right'
visited[i][j] = idx
else
j -= 1
dir = 'left'
visited[i][j] = idx
end
end
end
h.times do |i|
tmp = visited[i].dup
tmp = visited[i-1].dup if tmp.nil?
tmp2 = []
w.times do |j|
tmp2 << tmp[j] + 1
end
puts tmp2.join(' ')
end
| true
|
893584d19620e98b03bfc45a80e430aadfde002d
|
Ruby
|
yaauie/PFTT
|
/lib/util/column_manager.rb
|
UTF-8
| 869
| 2.71875
| 3
|
[
"MIT",
"MS-PL"
] |
permissive
|
module Util
module ColumnManager
class Base
# current row number. see #add_row, option hash key :row_number
attr_reader :row_num
def initialize
@row_num = 0
end
def to_s
render
end
def add_row(*cells)
# adds a row of cells
#
# each cell may be a String (the value of the cell) or a Hash of options which include:
#
# :text '' - text to show
# :colspan 1+ - number of columns cell spans. allows a cell to span multiple columns if needed.
# :row_number true|false - replaces :text with an auto-incremented row number
# :center true|false - centers text
#
# Util::ColumnManager::Html also supports
# :bgcolor #000000 - hex color to use as the background color of the cell
#
end
end
end
end
| true
|
07ff3a9bde9dceeadfa8db98e3949a35a894d38d
|
Ruby
|
YujohnNattrass/ruby_challenges
|
/advanced_1/saddle_points.rb
|
UTF-8
| 554
| 3.5
| 4
|
[] |
no_license
|
class Matrix
def initialize(string)
@matrix = string.split("\n").map { |row_string| row_string.split(" ").map(&:to_i) }
end
def rows
@matrix
end
def columns
@matrix.transpose
end
def saddle_points
saddle_points_coordinates = []
@matrix.each_with_index do |row, row_index|
row.each_with_index do |digit, col_index|
if digit >= row.max && digit <= columns[col_index].min
saddle_points_coordinates << [row_index, col_index]
end
end
end
saddle_points_coordinates
end
end
| true
|
6904217275ae427229d5fb846839d35b889b2974
|
Ruby
|
cseiter/Phase3SQLLibrary
|
/lib/querying.rb
|
UTF-8
| 2,213
| 2.96875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def select_books_titles_and_years_in_first_series_order_by_year
"select books.title,books.year from books where books.series_id='1' order by books.year";
end
def select_name_and_motto_of_char_with_longest_motto
"select characters.name,characters.motto from characters order by length(characters.motto) desc limit 1";
end
def select_value_and_count_of_most_prolific_species
"select characters.species,count(characters.species) from characters group by characters.species order by count(characters.species) desc limit 1";
end
def select_name_and_series_subgenres_of_authors
"select authors.name,subgenres.name from authors join series on series.author_id = authors.id join subgenres on series.subgenre_id = subgenres.id";
end
def select_series_title_with_most_human_characters
#just putting this monster here to show how my select statements were evolving to get a return of all the data needed to make the correct result
#select series.title,books.title,character_books.character_id,characters.name,characters.species from series join books on series.id = books.series_id join character_books on books.id = character_books.book_id join characters on character_books.character_id = characters.id;
#select series.title,books.title,character_books.character_id,characters.name,characters.species,count(characters.species) from series join books on series.id = books.series_id join character_books on books.id = character_books.book_id join characters on character_books.character_id = characters.id where characters.species = 'human' group by series.title order by count(characters.species);
"select series.title from series join books on series.id = books.series_id join character_books on books.id = character_books.book_id join characters on character_books.character_id = characters.id where characters.species = 'human' group by series.title order by count(characters.species) desc limit 1";
end
def select_character_names_and_number_of_books_they_are_in
"select characters.name,count(character_books.book_id) from character_books join characters on character_books.character_id = characters.id group by characters.name order by count(character_books.book_id) desc, characters.name";
end
| true
|
3bede1ea13f8c2b7b284ac86d9d616654f00d1ec
|
Ruby
|
dvsocean/rubyStuff
|
/fall_code/puts_count.rb
|
UTF-8
| 310
| 3.15625
| 3
|
[] |
no_license
|
name = 'Boris'
job = 'Engineer is the song that never ends'
life = 'great'
power = 'attorney'
p name, job, life.class, power
multi_line_string = <<DMLS
thjis is the sonf thay never ends, yes it gfors
on an d on my frind
some people started singing it not knowing what it was
DMLS
puts multi_line_string
| true
|
fc8712d68c000ffa92c3eb4b91a00c1f8780ff3d
|
Ruby
|
PierreNicoletti/shipup-challenge
|
/level2/repositories/package_repository.rb
|
UTF-8
| 453
| 3.046875
| 3
|
[] |
no_license
|
require 'json'
require_relative '../models/package'
class PackageRepository
def initialize(input_file_path)
@packages = []
serialized_data = File.read(input_file_path)
JSON.parse(serialized_data)["packages"].each do |package|
@packages << Package.new(id: package["id"], carrier: package["carrier"], shipping_date: package["shipping_date"])
end
end
def all
@packages
end
def find(id)
@packages[id]
end
end
| true
|
57137ff27bd15e868d814a428c65ff4f37074ad1
|
Ruby
|
xuhui-github/rubydailyprogramming
|
/proc/instace_eval.rb
|
UTF-8
| 391
| 3.0625
| 3
|
[] |
no_license
|
class User
end
User.instance_eval do
@Female="Female of User"
def gender
:female
end
def self.Female
@Female
end
def self.setFemale(female)
@Female=female
end
end
puts User.gender
u=User.new
u.instance_eval do
def gender
"female just"
end
end
puts u.gender
puts User.Female
User.setFemale("Changing Female of User")
puts User.Female
puts u.Female
| true
|
f66cebe3bf3fc5b2c0abad9d8f63757dc116d2db
|
Ruby
|
flaviogf/courses
|
/geral/livro_entendendo_algoritmos/binary_search.rb
|
UTF-8
| 567
| 3.828125
| 4
|
[
"MIT"
] |
permissive
|
def main()
values = load()
result = binary_search(values, 9773)
puts result
end
def load()
values = []
IO.foreach("sorted.txt") do |line|
values.push line.to_i
end
return values
end
def binary_search(values, target)
left = 0
right = values.size - 1
while left <= right
mid = (left + right) / 2
if values[mid] == target
return mid
elsif values[mid] < target
left = mid + 1
else
right = mid - 1
end
end
return -1
end
main
| true
|
7e711a52edc0d3ae150f3619e323e99dad617468
|
Ruby
|
danielpselph/enigma
|
/test/shift_test.rb
|
UTF-8
| 1,961
| 3.09375
| 3
|
[] |
no_license
|
require_relative 'test_helper'
require 'date'
require './lib/shift'
class ShiftTest < Minitest::Test
def setup
@shift = Shift.new
end
def test_it_exists
assert_instance_of Shift, @shift
end
def test_it_has_attributes
assert_equal String, @shift.key.class
assert_equal 5, @shift.key.length
assert_equal String, @shift.date.class
assert_equal 6, @shift.date.length
end
def test_keys_are_random
shift1 = Shift.new
shift2 = Shift.new
shift3 = Shift.new
assert_equal false, shift1 == shift2
assert_equal false, shift1 == shift3
assert_equal false, shift2 == shift3
end
def test_keys_can_be_grouped
@shift.stubs(:key => "01234")
expected = ["01", "12", "23", "34"]
assert_equal expected, @shift.key_grouping
end
def test_grouped_keys_can_be_returned_as_integers
@shift.stubs(:key => "01234")
expected = [1, 12, 23, 34]
assert_equal expected, @shift.key_grouping_int
end
def test_current_date_returned_as_default
shift1 = Shift.new
shift2 = Shift.new
shift3 = Shift.new
assert_equal true, shift1.date == shift2.date
assert_equal true, shift1.date == shift3.date
assert_equal true, shift2.date == shift3.date
end
def test_can_return_squared_date
@shift.stubs(:date => "010203")
assert_equal "104101209", @shift.squared_date
end
def test_can_return_offset_date_value
@shift.stubs(:date => "190287")
assert_equal "36209142369", @shift.squared_date
expected = ["2", "3", "6", "9"]
assert_equal expected, @shift.offset_date
end
def test_can_return_offset_date_value_as_integers
@shift.stubs(:date => "190287")
expected = [2, 3, 6, 9]
assert_equal expected, @shift.offset_date_int
end
def test_can_create_key_and_offset_date_hash
@shift.stubs(:key => "35468")
@shift.stubs(:date => "101112")
expected = [41, 59, 50, 72]
assert_equal expected, @shift.shift_key
end
end
| true
|
1f22c0c75a7773bcad192c8e0b9344ffbc9d0e56
|
Ruby
|
joshheath/day1challenges
|
/challenge2.rb
|
UTF-8
| 633
| 4.59375
| 5
|
[] |
no_license
|
hash = { a: 1, b: 2 }
# adding one to each hash value
newhash = {}
hash.each do |key, value|
newhash[key] = hash[key] + 1
end
puts newhash
#zipped values, sorted and turned into a hash
hash2 = { a: 2, b: 5, c: 1 }
hash2values = hash2.values.sort
hash2keys = hash2.keys
print Hash[hash2keys.zip(hash2values)]
#convert to array and sort
print "\n"
print hash2.values.sort
#convert values and keys to a string then zip together in an array reversed
print "\n"
hash3 = { a: 1, b: 2, c: 3 }
hash3values = hash3.values.map { |value| value.to_s}
hash3keys = hash3.keys.map { |value| value.to_s}
print Hash[hash3values.zip(hash3keys)]
| true
|
28bd6d9d02a351cdfac1aa450ac1c6b85e8b86b4
|
Ruby
|
3lsilver/restful_clicktocall
|
/web/run_me.rb
|
UTF-8
| 2,283
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'sinatra' # Get with "gem install sinatra"
require 'restful_adhearsion'
require 'pp'
#Create our Adhearsion object connected to the RESTful API of Adhearsion
Adhearsion = RESTfulAdhearsion.new(:host => "localhost",
:port => 5000,
:user => "jicksta",
:password => "roflcopterz")
# You'll need to change this for your own format.
# Note: this will soon be handled by the Call Routing DSL in Adhearsion.
def format_number(number)
"SIP/#{number}"
end
post "/call" do
options = { :channel => format_number(params[:source]),
:context => "adhearsion",
:priority => "1",
:exten => "1000",
:async => 'true',
:variable => "destination=" + format_number(params[:destination]) }
#Originates a call over the AMI interface
Adhearsion.originate options
"ok".to_json
end
post "/hangup" do
#Get the channel of the active call, then hang it up
channel_of_active_call = Adhearsion.hangup_channel_with_destination params[:call_to_hangup]
"ok".to_json
end
get '/status' do
# The line below will return either {result:"alive"} or {result:"dead"} to the browser
{:result => Adhearsion.call_with_destination(params[:destination])}.to_json
end
get '/' do
#Build our web form that has the JQuery sprinkled in
<<-HTML
<html><head>
<title>Click to Call Demo</title>
<script src="jquery.js" type="text/javascript"></script>
<script src="call.js" type="text/javascript"></script>
<link href="style.css" media="screen" rel="stylesheet" type="text/css" />
</head><body>
<div id="content">
<h1>Click to Call Demo</h1>
<h2>Bridge two people together</h2>
<div id="call-form">
<p><label for="source">Primary party: </label><input type="text" id="source" name="source"/></p>
<p><label for="destination">Second party: </label><input type="text" name="destination" id="destination"/></p>
<p><button onclick="new AhnCall($('#call'), $('#source').val(), $('#destination').val())">Start call</button></p>
</div>
</div>
<div id="call" class="hidden">
<p>Starting...</p>
</div>
</body></html>
HTML
end
| true
|
bd3b0d88242d11bf808c418c01ba5e62c06fdb28
|
Ruby
|
janpadrta/invoicing
|
/app/modules/utilities.rb
|
UTF-8
| 421
| 3
| 3
|
[] |
no_license
|
module Utilities
def self.months_range(klass, column)
date_from = klass.minimum(column).to_date
date_to = klass.maximum(column).to_date
date_range = date_from..date_to
date_range.map { |d| Date.new(d.year, d.month, 1) }.uniq
end
def self.virtual_sum(collection, v_attr) # Totals the virtual attributes of a collection
collection.sum { |collect| collect.method(v_attr).call }.to_f
end
end
| true
|
1e7f9bb910be8ef5c38b92f6614970fb8fb0d162
|
Ruby
|
kagflores/oxford-comma-v-000
|
/lib/oxford_comma.rb
|
UTF-8
| 373
| 3.328125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def oxford_comma(array)
if array.size == 1
comma_free = array.join
return comma_free
elsif array.size == 2
and_join = array.join (" and ")
return and_join
else
last_element = array.pop
comma_join = array.join (", ")
last_element = ", and #{last_element}"
comma_and_join = comma_join << last_element
return comma_and_join
end
end
| true
|
156c30cbb13114117e3c61c0b848d9af1a09bb74
|
Ruby
|
Himuravidal/E6CP1A1
|
/3 ciclos anidados/ejercicio1.rb
|
UTF-8
| 253
| 3.3125
| 3
|
[] |
no_license
|
=begin
Se pide imprimir la secuencia numérica, de la siguiente forma:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
=end
matrix = [1, 2, 3, 4]
(0..4).each do |i|
puts "#{matrix[i]} #{matrix[i] * 2} #{matrix[i] * 3} #{matrix[i] * 4}"
end
| true
|
c9fa5d70537e86788ae0fa35fa66c7a63cf669cc
|
Ruby
|
chastell/talks
|
/src-2011/code/grid-faster.rb
|
UTF-8
| 701
| 3.5625
| 4
|
[] |
no_license
|
require 'inline'
class Integer
def popcount_to_s
to_s(2).count '1'
end
def popcount_bitshift
count = 0
number = self
while number > 0
number &= number - 1
count += 1
end
count
end
inline do |builder|
builder.c '
int popcount_builtin() {
return __builtin_popcountl(NUM2LONG(self));
}
'
builder.c '
long popcount_bitshift_c() {
long number = NUM2LONG(self);
long count = 0;
while (number) {
number &= number - 1;
count++;
}
return count;
}
'
end
end
grid = ARGV.first.to_i
puts (0...2**(2 * grid))
.count { |n| n.popcount_builtin == grid }
| true
|
8c710da8025401459e4e080dd81b2937c33c8958
|
Ruby
|
JanBussieck/simulation-game
|
/app/controllers/simulation_controller.rb
|
UTF-8
| 2,448
| 2.640625
| 3
|
[] |
no_license
|
class SimulationController < ApplicationController
def simulate
update_game_data
remove_sold_resources
update_credit
adjust_market_price
simulate_technical
simulate_disease
simulate_weather
redirect_to root_path
end
def update_game_data
game.period += 1
game.set_current_interest_rate
end
def remove_sold_resources
current_user.crops.map do |crop|
crop.quantity += crop.bought + crop.sold
crop.bought = 0
crop.sold = 0
crop.save!
end
current_user.lifestocks.map do |animal|
animal.quantity += animal.bought + animal.sold
animal.bought = 0
animal.sold = 0
animal.save!
end
end
def update_credit
interest_due = game.credits.reduce(0) do |sum, credit|
credit.duration = credit.duration -1
if credit.duration == 0
credit.destroy!
else
credit.save!
end
sum += credit.accumulated_interest
sum
end
repayment = game.credits.inject(0) do |sum, credit|
repay = (credit.principal / installments)
sum += repay
sum
end
game.cash = game.cash - interest_due
game.save!
Event.financial(nil, "Sie mussten in dieser Saison Zinsen über #{interest_due} Euro und eine Rueckzahlung von #{repayment} bezahlen.")
end
def adjust_market_price
game.prices.each do |price|
price.random_change(0.1)
end
Event.financial(nil, "Es hat signifikante Preisschwankungen am Markt gegeben gegeben. Insbesondere ist Getreide davon betroffen.")
end
def simulate_technical
machines = current_user.machineries.select do |machine| machine.needs_repair? end
unless machines.empty?
place = machines.map(&:to_s).join(", ")
Event.financial(nil, "Leider müssen die folgenden Maschinen repariert werden #{place}")
end
end
def simulate_disease
animals = current_user.lifestocks.reduce(0) do |sum, animal|
sum += animal.number_sick?
sum
end
number = animals.to_i
Event.financial(nil, "Leider sind #{number} deiner Tiere verstorben.")
end
def simulate_weather
if rand(10) < 3
crops = current_user.crops.reduce(0) do |sum, crop|
sum += crop.storm_stricken
sum
end
number = crops.to_i
Event.financial(nil, "Leider sind #{number} deiner Tiere verstorben.")
end
end
def game
Game.current_game
end
#change global price object
end
| true
|
bae28dd0f6ba3b50d8bab52476404d73f3fa7e33
|
Ruby
|
mguymon/obfuscate
|
/lib/obfuscate.rb
|
UTF-8
| 2,505
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with this
# work for additional information regarding copyright ownership. The ASF
# licenses this file to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
require 'obfuscate/version'
require 'obfuscate/crypt'
require 'obfuscate/config'
module Obfuscate
class << self
attr_accessor :config
# Obfuscate text. Depends on Obfuscate.setup to be called first
#
# @param [String] text to be obfuscated
# @param [Hash] options overrides how obfuscation should be handled
# @return [String]
def obfuscate(text, options = {} )
cryptor( options ).obfuscate( text )
end
# Clarify obfuscated text. Depends on Obfuscate.setup to be called first
#
# @param [String] text to be clarified
# @param [Hash] options overrides how clarify should be handled
# @return [String]
def clarify(text, options = {} )
cryptor( options ).clarify( text )
end
# Create instance of Obfuscate::Crypt. Depends on Obfuscate.setup to be called first
#
# @param [Hash] overrides how instance should be created
# @return [Obfuscate::Crypt]
def cryptor(options = {} )
Obfuscate::Crypt.new( @config.apply( options ) )
end
# Setup Obfuscate passing in a hash and/or block
#
# @param [Hash] options of configurations
# @option options [Symbol] :salt A Model specific salt
# @option options [Symbol] :encode Enable Base64 and URL encoding for this Model. Enabled by default.
# @option options [Symbol] :remove_trailing_equal When in :block mode, removes the trailing = from the
# obfuscated text.
# @param [block] blk of configuration, has precedence over options Hash.
# @return [Obfuscate::Config]
def setup(options ={}, &blk)
@config = @config.apply(options, &blk)
end
end
self.config = Obfuscate::Config.new
end
| true
|
91cf6e90f8ee7ff26e6b2815250b4e465bcb76f8
|
Ruby
|
Ahmed13061988/my-each-online-web-pt-120919
|
/my_each.rb
|
UTF-8
| 68
| 2.90625
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def my_each(collection)
my_each(collection) do |i|
puts i
end
| true
|
502685af3a66c74cfcb82bf9ced38c6588ae1512
|
Ruby
|
victoralvesf/ruby-study
|
/capybara/spec/key_spec.rb
|
UTF-8
| 555
| 2.59375
| 3
|
[] |
no_license
|
describe 'Keyboard', :keyboard do
before(:each) do
visit 'https://training-wheels-protocol.herokuapp.com/key_presses'
end
def check_letter(key)
find('#campo-id').send_keys key
expect(page).to have_content 'You entered: ' + key.to_s.upcase
end
it 'enviando teclas' do
keys = %i[tab escape space enter shift control alt]
for key in keys do
check_letter(key)
end
end
it 'enviando letras' do
letters = %w[a s d f g h j k l]
for letter in letters do
check_letter(letter)
end
end
end
| true
|
8e9fe4cc2dc01b43486a50e572c5a4246bd145cd
|
Ruby
|
turingschool-projects/keevah
|
/db/seeds.rb
|
UTF-8
| 3,062
| 2.90625
| 3
|
[] |
no_license
|
class Seed
def call
generate_tenants(200000)
generate_users(30000)
generate_categories(15)
generate_loan_requests(500000)
generate_loans(50000)
end
def generate_users(quantity)
puts "Creating #{quantity} users"
quantity.times do |n|
first_name = Faker::Name.name
username = Faker::Internet.user_name
email = Faker::Internet.safe_email(first_name)
password = "password"
tenant_id = rand(1..@tenant_count)
User.create!(first_name: first_name,
username: username,
email: n.to_s + email,
password: password,
tenant_id: tenant_id
)
end
@user_count = User.count
puts "#{quantity} users created"
end
def generate_tenants(quantity)
puts "Creating #{quantity} tenants"
quantity.times do |n|
name = Faker::Name.name # unique
Tenant.create!(name: n.to_s + name)
end
@tenant_count = Tenant.count
puts "Tenants generated"
end
def generate_categories(quantity)
puts "Creating #{quantity} categories"
quantity.times do |n|
name = Faker::Commerce.department(1, true) + n.to_s
description = Faker::Commerce.product_name
Category.create!(name: name, description: description)
end
@category_count = Category.count
puts "Categories generated"
end
def generate_loan_requests(quantity)
puts "Creating #{quantity} loan requests"
quantity.times do
user_id = rand(1..@user_count)
title = Faker::Commerce.product_name
blurb = Faker::Internet.domain_word
description = Faker::Hacker.say_something_smart
requested_by_date = DateTime.now
payments_begin_date = rand(41..61).days.from_now
payments_end_date = rand(100..182).days.from_now
borrowing_amount = rand(50..1000)
amount_funded = rand(1..49)
loan_request = LoanRequest.create!(user_id: user_id,
title: title,
blurb: blurb,
description: description,
requested_by_date: requested_by_date,
payments_begin_date: payments_begin_date,
payments_end_date: payments_end_date,
borrowing_amount: borrowing_amount,
amount_funded: amount_funded
)
loan_request.categories << Category.find_by(id: rand(1..@category_count))
end
@loan_request_count = LoanRequest.count
puts "LoanRequests generated"
end
def generate_loans(quantity)
puts "Creating #{quantity} loans"
quantity.times do
user_id = rand(1..@user_count)
loan_request_id = rand(1..@loan_request_count)
amount = rand(50..1000)
Loan.create!(user_id: user_id,
loan_request_id: loan_request_id,
amount: amount
)
end
puts "Loans generated"
end
def self.call
new.call
end
end
Seed.call
| true
|
e56eae0b05e5102f8bbcf6c8450278ffab15815d
|
Ruby
|
AcChrome/math_game
|
/question.rb
|
UTF-8
| 328
| 3.859375
| 4
|
[] |
no_license
|
class Question
attr_accessor :num1, :num2, :sum
def initialize()
self.num1 = rand(1..20)
self.num2 = rand(1..20)
self.sum = self.num1 + self.num2
end
def question()
puts "What does #{num1} plus #{num2} equal?\n"
end
def answer(ans)
if ans == sum
true
else false
end
end
end
| true
|
3ceb733cd0fb5c89b2976e9f18e8408a44fb60b8
|
Ruby
|
Angelorup/Kattis
|
/Problems/difficulty_1/symmetric_order.rb
|
UTF-8
| 180
| 3.484375
| 3
|
[] |
no_license
|
def symm
input = gets.to_i
asc_arr = []
desc_arr = []
names_arr = []
for i in (1..input)
names = gets.chomp.to_s
names_arr << names
end
puts names_arr.reverse
end
symm
| true
|
a3d96275f0e2f82ba8940353efb7d98d7d65e7f8
|
Ruby
|
aakim0907/AppAcademy
|
/w2d3/towers_of_hanoi/lib/tower_of_hanoi.rb
|
UTF-8
| 700
| 3.71875
| 4
|
[] |
no_license
|
class Tower
attr_reader :grid
def initialize(grid = [[3,2,1],[],[]])
@grid = grid
end
def move(move_pos)
raise 'invalid argument' unless move_pos.length == 2
start_disc = @grid[move_pos[0]]
end_disc = @grid[move_pos[1]]
if start_disc.last > end_disc.last && !end_disc.empty?
raise 'No! Can\'t move!'
end
disc = start_disc.pop
end_disc << disc
@grid
end
def won?
return false unless @grid[0].empty?
return true if @grid[1].length == 3 || @grid[2].length == 3
end
def play_game
until won?
puts @grid
user_move = gets.split(',').map(&:to_i)
move(user_move)
end
puts @grid
puts 'You won!'
end
end
| true
|
8de2584449ff88b361a106553de329a5dde3eb67
|
Ruby
|
r-gamedev/lita-gamedev-spam
|
/lib/common/messaging/reddit/modmail.rb
|
UTF-8
| 1,747
| 2.84375
| 3
|
[] |
no_license
|
require 'common/messaging/message'
require 'htmlentities'
module Lemtzas
module Common
module Messaging
module Reddit
# Represents a modmail message
class Modmail < Message
attr_accessor :body,
:name,
:id,
:author,
:created_utc,
:subreddit,
:subject,
:distinguished,
:first_message_name
def shortlink
"https://reddit.com/message/messages/#{id}"
end
def shorttext(length = 40, strip_newlines = true)
text = body
text = text.gsub(/\r|\n/, ' ') if strip_newlines
text[0..length]
end
def to_s
"Modmail /r/#{subreddit} /u/#{author} - #{shorttext} - #{shortlink}"
end
# Constructs a modmail from listing data
def self.from_data(data)
modmail = Modmail.new
html_entities = HTMLEntities.new
modmail.uuid = SecureRandom.uuid
modmail.body = html_entities.decode(data.body)
modmail.name = data.name
modmail.id = data.id
modmail.author = data.author
modmail.created_utc = data.created_utc
modmail.subreddit = data.subreddit.downcase
modmail.subject = html_entities.decode(data.subject)
modmail.distinguished = data.distinguished
modmail.first_message_name = data.first_message_name
modmail
end
end # class Modmail
end # module Reddit
end # module Messaging
end # module Common
end # module Lemtzas
| true
|
33c53c11eff143508adf13f11de84e3937d589fe
|
Ruby
|
zeroeth/net_rogo
|
/male_marten.rb
|
UTF-8
| 1,943
| 3.015625
| 3
|
[] |
no_license
|
require File.dirname(__FILE__) + '/marten'
require 'logger'
$log = Logger.new("marten_events.log")
class MaleMarten < Marten
def tick
raise 'spawn me' if spawned?
go
end
def go
actual_distance = 0
forage
die_if_starved
metabolize
self.age += 1
if age > (18 * 365)
$log.info "#{self.id} died of old age"
die
end
end
def stay_probability
(1 - BASE_PATCH_ENTRANCE_PROBABILITY) * (self.energy / MAX_ENERGY)
end
def should_leave?
stay_probability < rand
end
def not_taken_by_other_marten? target
target.marten.nil? || target.marten == self
end
def leave_scent_mark
self.patch.marten = self
self.patch.marten_scent_age = 0
end
# sex-specific sub-routines that feed into move_one_patch function
def move_one_patch
target = patch_ahead 1
# faced patch desirable
# faced patch force move
#
# find desirable neighboring patch
# no desirable, about face
if passable?(target)
if patch_desirable?(target)
walk_forward 1
self.random_walk_suitable_count += 1
elsif should_leave?
walk_forward 1
self.random_walk_unsuitable_count += 1
else
select_forage_patch_and_move
end
else
select_forage_patch_and_move
end
end
def face_random_direction
# different turn methods
# random
turn rand(361).degrees
# correlated +
# turn self.normal_dist 0 self.turn_sd
# correlated -
# turn self.normal_dist 180 self.turn_sd
end
def desirable_patches
#neighborhood_in_radius(1).select{|patch| patch_desirable? patch }
neighborhood.select{|patch| patch_desirable? patch }
end
def patch_desirable?(patch)
not_taken_by_other_marten?(patch) && habitat_suitability_for(patch) == 1
end
def self.can_spawn_on?(patch)
self.passable?(patch) && self.habitat_suitability_for(patch) == 1
end
end
| true
|
8c086f7803345ce0bf5a0c505d258cc425a048f1
|
Ruby
|
jb2718/ls-backend
|
/101/101_3/exercises_m1/q1.rb
|
UTF-8
| 61
| 2.859375
| 3
|
[] |
no_license
|
10.times{ |num| puts "The Flintstones Rock!".rjust(21 + num)}
| true
|
f2e3b018bc6b9019f7d582ef4fec5b33bf4f70f2
|
Ruby
|
8bithero/predict-backend
|
/app/services/prediction_service.rb
|
UTF-8
| 1,624
| 3.09375
| 3
|
[] |
no_license
|
class PredictionService
attr_reader :prediction_term
def initialize(prediction_term=Rails.configuration.x.prediction_word)
@prediction_term = prediction_term
@errors = ErrorHash.new
@value = nil
end
def call(team_string:)
clear!
validate_team_string_format(team_string)
return result unless @errors.empty?
occurances = find_prediction_term_occurences(team_string)
num_string = build_num_string(occurances)
@value = calculate_percentage(num_string)
result
end
private
def clear!
@errors.clear
@value = nil
end
def result
ServiceResultFactory.from_value_and_errors(@value, @errors)
end
def validate_team_string_format(team_string)
# NOTE: This is a crude Regex - Not sutable for production ready
unless team_string =~ /.*\S*\s?[&]\s?\S*.*/
@errors.add(:format, 'Invalid team name format. Example format: "First Name & Second Name"')
end
end
def find_prediction_term_occurences(string)
@prediction_term.upcase.chars.reduce([]) do |occurences, char|
count = string.upcase.count(char)
occurences << count
end
end
def build_num_string(array)
array.reduce('') { |num_str, num| num_str + num.to_s }
end
def calculate_percentage(num_str)
new_array = []
num_str.chars.each_cons(2) do |element, next_element|
new_array << (element.to_i + next_element.to_i)
end
new_num_string = build_num_string(new_array)
return new_num_string if (new_num_string.to_i < 100)
calculate_percentage(new_num_string)
end
end
| true
|
d9a5a92d3c9a27b7cfce9c3f50dfe13a72faa1ca
|
Ruby
|
nodog/povstick-bmp-generator
|
/movie-matrixle.rb
|
UTF-8
| 1,326
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
#
# programming
# nodog
# 2014-03-03
#
# movie-matrixle.rb
# is a generater of a 1D movie (a 2D bmp file) for a 120x1 RGB LED array.
# coding: binary
require "./bmp_writer.rb"
MOVIENAME = "matrixle"
NLEDS = 120
RAMPINLENGTH = 128
RAMPOUTLENGTH = 5048
MAXBRIGHT = 192
NT = 16000
bmp = BMP::Writer.new(NLEDS, NT)
# need an array the length of NT which switches from black (000000)
# to green (00FF00) to black
# make a stripe that I will copy into the final matrix at offsets for each column
stripe = Array.new(NT, "000000")
# make the brightness inramp
0.upto(RAMPINLENGTH) do |j|
bright = MAXBRIGHT * j / (RAMPINLENGTH - 1)
stripe[j] = "00" + sprintf("%02x", bright) + "00"
#p stripe[j]
end
# make the brightness outramp
0.upto(RAMPOUTLENGTH) do |j|
loc = RAMPINLENGTH + j
bright = MAXBRIGHT * (RAMPOUTLENGTH - j) / (RAMPOUTLENGTH - 1)
stripe[loc] = "00" + sprintf("%02x", bright) + "00"
#p stripe[loc]
end
# make one copy of the stripe for each LED, set at a vertical offset
0.upto(NLEDS - 1) do |i|
offset = rand(NT)
0.upto(NT - 1) do |j|
# reversed here b/c time is displayed up from the bottom on the bmp
bmp[i, NT - 1 - j] = stripe[(j + offset) % NT ]
end
end
#bmp[0,0] = "ff0000"
#bmp[1,0] = "00ff00"
#bmp[0,1] = "0000ff"
#bmp[1,1] = "ffffff"
bmp.save_as(MOVIENAME+".bmp")
| true
|
12b901a1cd7f2411e93877b3fdf9d7f7cbe6f4cd
|
Ruby
|
W-Mills/ruby-exercises
|
/Small Problems/Medium/matching_parenthesis.rb
|
UTF-8
| 2,789
| 4.34375
| 4
|
[] |
no_license
|
require 'pry'
# Matching Parentheses?
# Write a method that takes a string as argument, and returns true if all parentheses in the string are properly balanced, false otherwise. To be properly balanced, parentheses must occur in matching '(' and ')' pairs.
# Problem: Write a method that takes a string as an argument and returns true if all parenthesis in the string are properly balanced (matching pairs), false otherwise
# => edge cases: no parenthesis in string?
# => parenthesis in backwards order? i.e. )(
# => an odd number of parenthesis in the string
# Input: a string
# Output: true/false
# Data structure: ## Using an integer as a counter would've been great
# Algorithm:
# => use String#match against input string with lazy pattern matching for ( folloed by )
## original solution:
# def balanced?(string)
# return true unless string.match(/[\(\)]/)
# return false if string.scan(/[\(\)]/).count.odd?
## solving this strictly with regex was unneccesarily difficult.
## getting
# end
DELIMITERS = [['[', ']'], ['(', ')'], ['{', '}']]
def balanced?(string)
counter = 0
count = 0
string = string.gsub(/(?<=\w)'(?=\w)/, '')
DELIMITERS.size.times do
string.chars.each do |char|
count += 1 if char == DELIMITERS[counter][0]
count -= 1 if char == DELIMITERS[counter][1]
break if count < 0
end
counter += 1
end
count.zero? && balanced_quotes?(string)
end
def balanced_quotes?(string)
string.scan(/'/).size.even? && string.scan(/"/).size.even?
end
## from @sawa on Stack overflow:
# non_delimiters = /[^(){}\[\]]*/
# Paired = /\(#{non_delimiters}\)|\{#{non_delimiters}\}|\[#{non_delimiters}\]/
# Delimiter = /[(){}\[\]]/
# def balanced? string
# string = string.dup
# string.gsub!(Paired, "".freeze) while string =~ Paired
# string !~ Delimiter
# end
## LS Solution:
# def balanced?(string)
# parens = 0
# string.each_char do |char|
# parens += 1 if char == '('
# parens -= 1 if char == ')'
# break if parens < 0
# end
# parens.zero?
# end
# Examples:
p balanced?("harvey's friend sam") == true
p balanced_quotes?('"harvey') == false
p balanced_quotes?('"harvey"') == true
p balanced_quotes?('What is" this?') == false
p balanced?('What is" this?') == false
p balanced?('What (is) this?') == true
p balanced?('What is) this?') == false
p balanced?('What (is this?') == false
p balanced?('((What) (is this))?') == true
p balanced?('((What)) (is this))?') == false
p balanced?('Hey!') == true
p balanced?(')Hey!(') == false
p balanced?('What ((is))) up(') == false
p balanced?('What [is] this?') == true
p balanced?('What is] this?') == false
p balanced?('What [is this?') == false
p balanced?('What [[is]]] up[') == false
# Note that balanced pairs must each start with a (, not a ).
| true
|
1c5b2ef570cb7ac74326a6461c50f3fcdcd6ff89
|
Ruby
|
SebastianOsinski/AdventOfCode2016
|
/Day 5/day5.rb
|
UTF-8
| 663
| 3.1875
| 3
|
[] |
no_license
|
require 'digest/md5'
door_id = 'ojvtpuvg'
md5 = Digest::MD5.new
index = 0
password = ''
while password.length < 8
digest = md5.hexdigest(door_id + index.to_s)
password += digest[5] if digest.start_with?('00000')
index += 1
end
puts password
# second part
password = Array.new(8)
known_chars_count = 0
index = 0
while known_chars_count < 8
digest = md5.hexdigest(door_id + index.to_s)
if digest.start_with?('00000') && digest[5] =~ /\d/
position = digest[5].to_i
if position < 8 && password[position].nil?
password[digest[5].to_i] = digest[6]
known_chars_count += 1
end
end
index += 1
end
puts password.join('')
| true
|
38e3ae4211750e4e84ddf69ddd93563dcc7b6d39
|
Ruby
|
substars/trinidad
|
/lib/trinidad/helpers.rb
|
UTF-8
| 2,531
| 2.796875
| 3
|
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Trinidad
module Helpers
# @private
@@silence = nil
# Should we be silent - no warnings will be printed.
def self.silence?; @@silence; end
# Silence ! (... or I kill you)
def self.silence!; @@silence = true; end
# Print a warning (using `Kernel.warn`).
def self.warn(msg)
super unless silence? # Kernel.warn
end
module_function
# @private
@@deprecated = {}
# Print a deprecated message (once - no matter how many times it's called).
def deprecated(msg, prefix = '[DEPRECATED] ')
return nil if @@deprecated[msg]
@@deprecated[msg] = true
Helpers.warn "#{prefix}#{msg}" # Kernel.warn
end
# @private
def deprecate(msg); deprecated(msg) end
# Camelizes the passed (string) parameter.
# @return a new string
def camelize(string)
string = string.to_s.sub(/^[a-z\d]*/) { $&.capitalize }
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
string.gsub!('/', '::')
string
end
# a Hash like `symbolize` helper
def symbolize(hash, deep = true)
new_options = hash.class.new
hash.each do |key, value|
if deep && value.is_a?(Array) # YAML::Omap is an Array
array = new_options[key.to_sym] = value.class.new
value.each do |v|
array << ( hash_like?(v) ? symbolize(v, deep) : v )
end
elsif deep && hash_like?(value)
new_options[key.to_sym] = symbolize(value, deep)
else
new_options[key.to_sym] = value
end
end
new_options
end
# a Hash like `deep_merge` helper
def merge(target, current, deep = true)
return target unless current
target_dup = target.dup
current.keys.each do |key|
target_dup[key] =
if deep && hash_like?(target[key]) && hash_like?(current[key])
merge(target[key], current[key], deep)
else
current[key]
end
end
target_dup
end
def hash_like?(object)
object.is_a?(Hash) || ( object.respond_to?(:keys) && object.respond_to?(:'[]') )
end
def to_url(path)
path = java.net.URLDecoder.decode(path)
if path =~ /^\w*\:/ # might be a valid url: (or C:/windows/yay ... )
return java.net.URL.new("file:/#{path}") if path[1, 1] == ':'
begin
return java.net.URL.new(path)
rescue java.net.MalformedURLException
end
end
java.io.File.new(path).toURL
end
end
end
| true
|
9ba04f853eb177ba016b8a04f99f5930f052e12c
|
Ruby
|
Altovate/OpenTiger
|
/app/services/custom_landing_page/markdown_helper.rb
|
UTF-8
| 2,253
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
module CustomLandingPage
# Limited HTML Markdown Renderer extend the default
# Redcarpet HTML rendered, but it ignores certain Markdown block.
#
# See the list of IGNORED_BLOCKS to see which blocks are ignored.
# The commented blocks in the list are available.
#
class LimitedHTMLMarkdownRenderer < Redcarpet::Render::HTML
IGNORED_BLOCKS = [
'block_code',
'block_quote',
'block_html',
'footnotes',
'footnote_def',
# 'header',
'hrule',
# 'list',
# 'list_item',
# 'paragraph',
'table',
'table_row',
'table_cell',
'autolink',
'codespan',
# 'double_emphasis',
# 'emphasis',
'image',
# 'linebreak',
# 'link',
'raw_html',
# 'triple_emphasis',
# 'strikethrough',
'superscript',
# 'underline',
'highlight',
'quote',
'footnote_ref',
].each do |ignored_block|
define_method ignored_block do |*|
nil
end
end
end
module MarkdownHelper
# Main method to render Markdown
def render_markdown(str)
markdown.render(str || "").html_safe
end
# Memoize the Markdown instance, as instructed in
# the Redcarpet documentation.
#
# Read more: https://github.com/vmg/redcarpet#and-its-like-really-simple-to-use
#
def markdown
@markdown ||= Redcarpet::Markdown.new(
LimitedHTMLMarkdownRenderer,
strikethrough: true,
underline: true,
filter_html: true, # do not allow any user-inputted HTML in the output.
no_images: true, # do not generate any <img> tags.
no_styles: true, # do not generate any <style> tags.
safe_links_only: true # only generate links for protocols which are considered safe.
)
end
# Deprecated
#
# Use Markdown string instead of array
#
# This method was added to maintain backwards compatibility. We
# allowed the contents to be passed as an Array in order to render
# multi paragraph content.
#
def render_markdown_array(arr)
if arr.is_a?(Array)
arr.map { |str| render_markdown(str) }.join().html_safe
else
render_markdown(arr)
end
end
end
end
| true
|
a04aceb40c14af8c251b882ddebf8866df3725c0
|
Ruby
|
p2rdw/viziwiki
|
/lib/viziwiki/mediawiki/parser.rb
|
UTF-8
| 7,586
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
require 'viziwiki/context'
require 'cgi'
class Viziwiki::Mediawiki::Parser
def log
::Viziwiki::log
end
# normalize text (fact to parser)
@@section_elements = %w(h1 h2 h3 h4 h5 h6 h7 h8)
@@end_paragraph_elements = %w(div p li ol ul) + @@section_elements
@@end_sentence_elements = @@end_paragraph_elements + %w(blockquote)
@@vizi_links = %w(a)
@@vizi_elements = @@vizi_links + @@end_sentence_elements
def initialize bot = nil
@bot = bot
# access to the wiki is needed if we want the normalizer
# to create new facts when a fact has been updated (desirable)
reset_context!
init_parse nil, nil, nil
end
def init_parse mediawiki, html, page
# the mediawiki raw text
@mediawiki = ''
# \invariant @mediawiki[0..@mediawiki_until] has been normalized into @normalized
@mediawiki_until = 0
# string where the normalized text is generated
@normalized = ''
# the parsing actually only checks the promising elements
# \invariant doc.css @@vizi_elements[0..@current_node_idx] have been parsed
@current_node_idx = 0
@created_new_sentence = false
@html = html
@mediawiki = mediawiki
@page = page
end
def parsed_vizi_element!
@current_node_idx += 1
end
def reset_context!
# context, which is a kind of evaluator for the vizi elements
# you place operands, and do queries with the object
@context = Viziwiki::Context.new
@fact_update = {}
@new_facts = []
end
def normalized_text
@normalized
end
def context
@context
end
def updated_facts
@fact_update
end
def new_facts
@new_facts
end
# return the text normalized and parse the vizifacts into the context
# WARNING if you want the proper parser and context of a normalized page:
# you need to parse the normalize page! as the offsets are not the same
def parse mediawiki, html, page
log.debug "init parsing: #{mediawiki}"
init_parse mediawiki, html, page
doc = Nokogiri::HTML(@html)
parse_node_r doc
@normalized.concat @mediawiki[@mediawiki_until..-1] # copy the remaining...
true
end
def parse_node_r node
return unless node
log.debug "#{@normalized} ... parsing node #{node}"
parse_node node
node.children.each { |c| parse_node_r c}
end
def parse_node node
return unless node
log.debug "PARSE parse_node #{(vizi_link? node).inspect}: #{node}"
if node.text?
end_sentence if text_end_sentence? node.text
elsif node.element?
name = node.node_name
end_sentence if @@end_sentence_elements.include? name
end_paragraph if @@end_paragraph_elements.include? name
new_section name[1].to_i if @@section_elements.include? name
parse_vizi_link node if vizi_link? node
parsed_vizi_element! if @@vizi_elements.include? name
end
end
def parse_vizi_link element
if @created_new_sentence == false
@created_new_sentence = true
offset, line = place_cursor_to_vizi_link element
@context.new_sentence @page, offset, line
end
log.debug "PARSE parse_vizi_link: #{element}"
fact_node = @context.new_link (vizi_link_title element), element.text
# when we found and edge, we place the cursor in front of it
# this way, when the sentence ends, we can append directly the #fact link
place_cursor_to_vizi_link element if fact_node and fact_node.is_edge?
return fact_node
end
def new_section level
@context.new_section level
end
def end_paragraph
@context.end_paragraph
end
def end_sentence
fact = @context.end_sentence
if fact and (fact.has_edge?)
# do something
if fact.has_name?
log.debug "PARSE end_sentence fact already has a name #{fact.name}"
old_name = fact.name
# we need a bot wiki to query whether the fact has changed or not
if @bot and (not @bot.fact_seq old_name, fact) # compare semantically equal, so ignore name and see all it-s identical or not
fact.force_new_name! @bot
@fact_update[old_name] = fact.name
text = Viziwiki::Fact::to_fancy_mediawiki_link old_name
# if has change update
if @normalized.end_with? text
@normalized = @normalized[0..-(text.size+1)]
log.debug "remove fact link ::: #{@normalized}"
else
raise TypeError, "parsed #-fancy named fact: #{old_name}, but cannot be found before the edge"
end
@normalized.concat fact.fancy_mediawiki_link
log.debug "updated fact into #{fact.fancy_mediawiki_link} ::: #{@normalized}"
end
# if fact hasn-t change, we have already parsed the [[Fact-iwlink|#]]
else
fact.force_new_name! @bot
@new_facts.push fact
@normalized.concat fact.fancy_mediawiki_link
log.debug "new fact #{fact.fancy_mediawiki_link} ::: #{@normalized}"
end
end
# otherwise do not anything
@created_new_sentence = false
fact
end
# get the location of this html element in the @cn_mediawiki string
# WARNING it works only if incrementals calls, i.e. element is the lastest of all the previous get_location <elements> passed as a par
# returns [offset, line]
def place_cursor_to_vizi_link link
text = link.text
page = vizi_link_title link
log.debug "PARSE place_cursor_to_vizi_link #{page} | #{text}"
# get offset of the link
offset = if wikimedia_similar text, page
a = get_offset_wlink page
b = get_offset_wlink_text page, text
[a, b].select { |x| x != nil }.min
else
get_offset_wlink_text page, text
end
if offset == nil
#raise TypeError, "our typing assumptions weren't good at all"
log.debug "PARSE not found link that should be with the page #{@page} follow html: #{@html}"
return [nil, nil]
elsif offset > 0
@normalized.concat @mediawiki[@mediawiki_until..offset - 1]
@mediawiki_until = offset
log.debug "write until offset #{offset} ::: #{@normalized}"
end
[@mediawiki_until, @mediawiki.lines.size]
end
def wikimedia_similar a, b
0 == (a =~ (wikimedia_similar_regexp b))
end
def wikimedia_similar_regexp text
reg_text = text.gsub /[ _]/, '[ _]'
Regexp.new reg_text, Regexp::IGNORECASE
end
def get_offset_wlink link
get_offset_link "#{link}"
end
def get_offset_wlink_text link, text
get_offset_link "#{link}\\|#{text}"
end
def get_offset_link value
get_offset "\\[\\[#{value}\\]\\]"
end
def get_offset text
o = (@mediawiki[@mediawiki_until..-1] =~ (wikimedia_similar_regexp text))
o += @mediawiki_until if o
o
end
def link? node
node and node.node_name == 'a'
end
def vizi_link? element
begin
return false unless link? element
vizi_link_title element
rescue => e
false
end
end
def vizi_link_title element
value = element.attributes['href'].value
if value.start_with? '/w/index.php?'
value = value['/w/index.php?'.size .. -1]
pvalue = CGI::parse value
return nil unless pvalue['section'].empty?
value = pvalue['title'].first
elsif value.start_with? '/w/index.php/'
value = value['/w/index.php?'.size .. -1]
else
raise TypeError, "vizi_link_title unexpected element #{element}"
end
if value and value.size > 0
value
else
nil
end
end
def text_end_sentence?(text)
text =~ /(\.[ \n\t]|\.\ \;|\.$)/
end
end
| true
|
16e9ef11ccc2ad885d13c062944f596062e71ac3
|
Ruby
|
lrotschy/Ruby-Exercises
|
/Basics/easy_4_10.rb
|
UTF-8
| 1,170
| 4.28125
| 4
|
[] |
no_license
|
# easy_4_10.rb
=begin
input: a signed integer (-321, 567)
output: a string version of same with sign ('-321', '+567')
if int > 0 prepend '+'
else
int = int * -1
prepend '-'
=end
DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def integer_to_string(int)
new_num = ''
loop do
remainder, str = int.divmod(10)
new_num.prepend(DIGITS[str])
int = remainder
break if int == 0
end
new_num
end
p integer_to_string(4321) == '4321'
p integer_to_string(0) == '0'
p integer_to_string(5000) == '5000'
=begin
def signed_integer_to_string(int)
new_num = ''
if int > 0
new_num << '+'
elsif int < 0
int = int * -1
new_num << '-'
end
new_num << integer_to_string(int)
end
def signed_integer_to_string(int)
new_num = ''
case int <=> 0
when -1
new_num << '-'
int = -int
when 1
new_num << '+'
end
new_num << integer_to_string(int)
end
=end
def signed_integer_to_string(int)
return '0' if int == 0
int > 0 ? '+' + integer_to_string(int) : '-' + integer_to_string(-int)
end
signed_integer_to_string(4321) == '+4321'
signed_integer_to_string(-123) == '-123'
signed_integer_to_string(0) == '0'
| true
|
8dc847879cf12878ac662064a720041fe0045c6d
|
Ruby
|
undees/yesbut
|
/2008-11-29/quine.rb
|
UTF-8
| 129
| 2.65625
| 3
|
[] |
no_license
|
require 'base64'
class String
def unscramble
Base64.decode64 self
end
end
s = "cmVxdWlyZSAnYmFzZTY0JwoKY2xhc3MgU3RyaW5nCiAgZGVmIHVuc2NyYW1i
bGUKICAgIEJhc2U2NC5kZWNvZGU2NCBzZWxmCiAgZW5kCmVuZAoKcyA9ICIl
cyIKCnB1dHMgcy51bnNjcmFtYmxlLnN1YigiJXMiLCBzKQo=
"
puts s.unscramble.sub("%s", s)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.