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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
00d7a9741e2cf47befc0986efa47af89747d5882 | Ruby | willemmanuel/innisfree | /app/controllers/houses_controller.rb | UTF-8 | 2,922 | 2.625 | 3 | [
"MIT"
] | permissive | class HousesController < ApplicationController
before_action :set_house, only: [:show, :edit, :update, :destroy]
before_action :check_admin, except: [:index, :show, :edit, :update]
before_action :check_privileges, only: [:edit, :update]
before_action :set_most_recent, ony: [:new]
# GET /houses
# GET /houses.json
def index
houses = House.all.map
houses = houses.sort_by{|u| [u.name]}
@houses = houses
respond_to do |format|
format.html
format.csv { render text: @houses.to_csv }
end
end
# Displays an individual house page
def show
end
# Gets a new house to be filled in
def new
@house = House.new
end
# Opens a house for changes
def edit
end
# Adds the new house to the database, relating success or error to the user
def create
@house = House.new(house_params)
respond_to do |format|
if @house.save
format.html { redirect_to new_house_path, notice: 'House (' + @house.name + ') was successfully created.' }
format.json { render :show, status: :created, location: @house }
else
format.html { render :new }
format.json { render json: @house.errors, status: :unprocessable_entity }
end
end
end
# Changes a house based on edits, relating success or error back to the user
def update
respond_to do |format|
if @house.update(house_params)
format.html { redirect_to @house, notice: 'House (' + @house.name + ') was successfully updated.' }
format.json { render :show, status: :ok, location: @house }
else
format.html { render :edit }
format.json { render json: @house.errors, status: :unprocessable_entity }
end
end
end
# Deletes a house from the database, notifying the user as to what was deleted
def destroy
@house.destroy
respond_to do |format|
format.html { redirect_to houses_url, notice: 'House (' + @house.name + ') was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Check to see if the user is an admin or if they are in a house that gives them access
def check_privileges
redirect_to houses_path, alert: "You do not have admin privileges." unless current_user.admin || current_user.house == @house
end
# Check to see if the user is an admin
def check_admin
redirect_to houses_path, alert: "You do not have admin privileges." unless current_user.admin
end
# Use callbacks to share common setup or constraints between actions
def set_house
@house = House.find(params[:id])
end
#Finds the most recently created house (for use in navigation)
def set_most_recent
@recent = House.order("created_at").last
end
# Never trust parameters from the scary internet, only allow the white list through
def house_params
params.require(:house).permit(:name, :phone)
end
end
| true |
0783a61848adae47c6a793a389d3861cd979a0d2 | Ruby | vincentpaca/whosthis | /whosthis.rb | UTF-8 | 4,353 | 2.71875 | 3 | [] | no_license | require 'nokogiri'
require 'open-uri'
require 'uri'
require 'whois'
require 'anemone'
class WhosThis
@@filtered_mails = ['domaindiscreet', 'domainsbyproxy', 'whois', 'domains']
@@regex = Regexp.new(/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/)
def initialize
#get inputs
puts "Input the tags to search for separated in spaces : "
@tags = gets.chomp
puts "How many results would you like? Give a number : "
@pages = gets.chomp
puts "Use a proxy? (Y/N) : "
@use_proxy = gets.chomp
#init whois
@whois = Whois::Client.new
end
def start
puts "Starting"
parse("http://www.google.com/search?num=#{@pages}&q=#{@tags.gsub(' ', '+')}")
puts "Done"
end
def parse(url)
result = ""
if @use_proxy.downcase.include?("y")
puts "Selecting a working proxy server, this will take a while :)"
proxy = find_working_proxy
begin
puts "Searching Google for '#{@tags}'"
result = Nokogiri::HTML(open(url, :proxy => "http://#{proxy[:host]}:#{proxy[:port]}"))
rescue
puts "The server timed out, retrying..."
retry
end
else
puts "Searching Google for '#{@tags}'"
result = Nokogiri::HTML(open(url, "User-Agent" => 'Mozilla/5.0'))
end
sites = []
File.open("output.txt", 'w') do |f|
result.css('h3 a').each do |link|
begin
host = URI.parse(link['href'].clean).host
#somtimes, a website gets two spots on the list. greedy bastards.
break if sites.include?(host)
sites << host
who = @whois.query(host.gsub('www.', '')).to_s
puts "Checking WhoIs for #{host}"
emails = who.scan(@@regex).uniq
#remove emails which we think are 'host-generated' emails
emails.delete_if { |email| @@filtered_mails.each { |f| email.include?(f) } }
emails.each { |email| f.puts "WhoIs: #{email} - #{host}" }
#if can't find anything from WhoIs, dig into their contact/about pages
if emails.empty?
begin
Anemone.crawl("http://#{host}", :proxy_host => proxy[:host], :proxy_port => proxy[:port]) do |website|
checked_urls = []
website.on_pages_like(/(about|info|contact)/) do |page|
#skip this url if we've been here before
break if checked_urls.include?(page.url)
puts "Checking #{page.url}..."
checked_urls << page.url
emails = "#{page.doc.at('body')}".scan(@@regex).uniq
emails.each { |email| f.puts "Contact page: #{email} - #{page.url}" } unless emails.nil?
#NOBODY HAS 5 CONTACT US PAGES. NOBODY.
break if checked_urls.count > 5
end
end
rescue Timeout::Error
puts "The server timed out, retrying..."
retry
end
end
rescue
nil
end
end
end
end
def find_working_proxy
get_proxies.each do |proxy|
print "Testing #{proxy[:host]}:#{proxy[:port]}..."
begin
result = Nokogiri::HTML(open("http://google.com/search?num=1&q=test", :proxy => "http://#{proxy[:host]}:#{proxy[:port]}"))
puts "Working!"
return proxy
rescue
puts "Failed!"
end
end
end
def get_proxies
uri = URI.parse("http://hidemyass.com/proxy-list/search-226094")
dom = Nokogiri::HTML(open(uri))
@proxies ||= dom.xpath('//table[@id="listtable"]/tr').collect do |node|
if node.at_xpath('td[5]/div').at_xpath('div').to_s.include?("fast") || node.at_xpath('td[6]/div').at_xpath('div').to_s.include?("fast") || node.at_xpath('td[8]').to_s.include?("High")
{ port: node.at_xpath('td[3]').content.strip,
host: node.at_xpath('td[2]/span').xpath('text() | *[not(contains(@style, "display:none"))]').map(&:content).compact.join.to_s }
end
end
end
end
class String
def clean
str = self.gsub('/url?q=', '')
end
end
a = WhosThis.new
begin
a.start
rescue Exception =>e
File.open("err.txt", 'w') do |f|
f.puts e.inspect
f.puts e.backtrace
end
end
| true |
d657d71c0722c6e6395a21b65a2de96e15f4f5bb | Ruby | andyprickett/launch-school | /exercises/101-109-small-problems/easy-1/07_stringy_strings.rb | UTF-8 | 439 | 3.78125 | 4 | [] | no_license | def stringy(n, first=1)
string = []
while n > 0
if n.odd?
string.unshift(first)
else
string.unshift((first - 1).abs)
end
n -= 1
end
# OR
# n.times do |i|
# s = i.even? ? 1 : 0
# string << s
# end
string.join
end
puts stringy(6) == '101010'
puts stringy(9) == '101010101'
puts stringy(4) == '1010'
puts stringy(7) == '1010101'
puts stringy(7, 0) == '0101010'
puts stringy(4, 0) == '0101'
| true |
9b897987ead561126944f4398fbd9d88eaa4fd66 | Ruby | daelynj/poker_hands | /lib/poker_hands/hand_rankings/find_straight.rb | UTF-8 | 758 | 3.109375 | 3 | [
"MIT"
] | permissive | require 'poker_hands/hand_rankings/hand_entities/straight'
module PokerHands
class FindStraight
def call(hand)
sorted_hand = hand.sort_by { |card| card.rank }
if sorted_hand[-1].rank == 14 && sorted_hand[-2].rank == 5
wheel = sorted_hand.clone
wheel.pop
high_card = wheel.last
if wheel.each_cons(2).all? { |card, next_card| next_card.rank == card.rank + 1 }
return Entities::Straight.new(cards: hand, high_card: high_card)
end
end
if !sorted_hand.each_cons(2).all? { |card, next_card| next_card.rank == card.rank + 1 }
return nil
end
high_card = sorted_hand.last
Entities::Straight.new(cards: hand, high_card: high_card)
end
end
end
| true |
98c2529485e8eac177452e5aea20aa7ee35255ba | Ruby | lucasdonuts/hangman | /lib/hangman.rb | UTF-8 | 3,523 | 3.90625 | 4 | [] | no_license | require_relative 'word.rb'
require_relative 'noose.rb'
def get_dictionary
file = File.open("dictionary.txt")
dictionary = file.read.split("\r\n")
dictionary = dictionary.delete_if { |word| word.length > 12 || word.length < 5 }
end
class Hangman
attr_accessor :word, :chances, :letters_guessed
def initialize(dictionary)
puts "Welcome to Hangman."
dictionary = dictionary
@chances = 6
@noose = Noose.new
@word = Word.new(dictionary)
@letters_guessed = []
check_save
turn
end
def check_save
if File.exist? "saves/save_file"
answer = nil
data = nil
loop do
puts "Would you like to load a save file? (y/n): "
answer = gets.chomp
puts ""
break if answer == "y" || answer == "n"
puts "Invalid answer."
end
if answer == "y"
File.open("saves/save_file") do |i|
data = Marshal.load(i)
end
self.word = data.word
self.letters_guessed = data.letters_guessed
self.chances = data.chances
puts "Save file loaded."
else
false
end
@noose.display_noose(@chances)
@word.display_blanks
else
false
end
end
def save_game?
print "Save game and quit?(y/n): "
answer = gets.chomp
if answer == "y"
true
elsif answer == "n"
false
else
puts "Invalid answer."
save_game?
end
end
def save_game
Dir.mkdir("saves") unless Dir.exists?("saves")
File.open("saves/save_file", "w+") do |info|
Marshal.dump(self, info)
end
exit
end
def turn
puts "\n"
puts "Type \"save\" at any time to save and quit."
@letters_guessed.sort!
puts @letters_guessed.nil? ? "Letters guessed: None" : "Letters guessed: #{@letters_guessed.join(" ")}"
@guess = get_guess
check_guess
puts "\n\n"
end
def get_guess
print "Guess a letter: "
guess = gets.chomp.downcase
if guess == "save"
save_game
else
guess
end
end
def check_guess
if @letters_guessed.include?(@guess)
puts "You already tried that one!"
@noose.display_noose(@chances)
@word.display_blanks
turn
elsif (@word.letter_in_word?(@guess))
@letters_guessed.push(@guess)
@noose.display_noose(@chances)
@word.update_blanks(@guess)
if @word.word_complete?
@word.display_blanks
display_message("victory")
if play_again?
Hangman.new(@dictionary)
else
exit
end
else
display_message("correct")
@word.display_blanks
turn
end
else
@letters_guessed.push(@guess)
@chances -= 1
@noose.display_noose(@chances)
if @chances == 0
display_message("game over")
if play_again?
Hangman.new(@dictionary)
else
exit
end
else
display_message("incorrect")
@word.display_blanks
turn
end
end
end
def play_again?
puts "Would you like to play again? (y/n)"
answer = gets.chomp
answer == "y" ? true : false
end
def display_message(message)
case message
when "victory" then puts "Congratulations! You win!\n"
when "correct" then puts "Correct!\n"
when "game over" then puts "Sorry! You lose. The word was #{@word.word}\n"
when "incorrect" then puts "Nope, sorry. #{@chances} remaining.\n"
end
end
end
game = Hangman.new(get_dictionary) | true |
c1a12e62e44b526db203529a2b638a2d24f1d44c | Ruby | zlang19/sortingAlgorithms | /selectionSort.rb | UTF-8 | 297 | 3.265625 | 3 | [] | no_license | def selection_sort(arr = Array.new)
(0..arr.length - 2).each do |i|
lowestIndex = i
(i + 1..arr.length - 1).each do |other|
if arr[lowestIndex] > arr[other]
lowestIndex = other
end
end
arr[i], arr[lowestIndex] = arr[lowestIndex], arr[i]
end
return arr
end | true |
3258728b1da58acf2aaa3718020aa5748db48c7f | Ruby | Tantarium/AmazonAutomationTests | /features/AmazonAutomationTest/step-definitions/shopping_cart_steps.rb | UTF-8 | 7,220 | 2.53125 | 3 | [] | no_license | require 'page-object'
require 'watir'
require_relative '../workflows/navigation'
require_relative '../workflows/searching'
require_relative '../workflows/shopping_cart'
include Navigation
include Searching
include ShoppingCart
And(/^I navigate to a specific item$/) do
@amazon.goto_watership_down
end
When(/^I click the button to add the item to my shopping cart$/) do
@browser.span(id: 'nav-cart-count').wait_until_present
@items_in_cart_before_add = @browser.span(id: 'nav-cart-count').text
@amazon.add_to_cart
end
Then(/^The item is successfully added to my shopping cart$/) do
@browser.span(id: 'nav-cart-count').wait_until_present
@items_in_cart_after_add = @browser.span(id: 'nav-cart-count').text
expect(@items_in_cart_before_add.to_i + 1).to eq(@items_in_cart_after_add.to_i)
end
And(/^I have items in my shopping cart$/) do
@amazon.goto_watership_down
@product_title_1 = @browser.span(id: 'productTitle').text
@amazon.add_to_cart
@amazon.goto_devops_handbook
@product_title_2 = @browser.span(id: 'productTitle').text
@amazon.add_to_cart
@amazon.goto_clean_code
@product_title_3 = @browser.span(id: 'productTitle').text
@amazon.add_to_cart
@amazon.goto_phoenix_project
@product_title_4 = @browser.span(id: 'productTitle').text
@amazon.add_to_cart
@amazon.goto_sword_of_shannara
@product_title_5 = @browser.span(id: 'productTitle').text
basic_text = @browser.div(id: 'detail-bullets').text
isbn_10_line = basic_text.split("\n")[5]
expect(isbn_10_line).to include('ISBN-10:')
@isbn_10 = isbn_10_line.split(":")[-1].strip
@amazon.add_to_cart
end
When(/^I click the button to view my shopping cart$/) do
@browser.span(id: 'nav-cart-count').click
end
Then(/^I should see a list of all the items in my shopping cart$/) do
text_from_page_element = @browser.div(class: 'sc-cart-header').text
expect(text_from_page_element).to eq("Shopping Cart")
browser_text = @browser.div(class: 'sc-list-body').text
expect(browser_text).to include(@product_title_1)
expect(browser_text).to include(@product_title_2)
expect(browser_text).to include(@product_title_3)
expect(browser_text).to include(@product_title_4)
expect(browser_text).to include(@product_title_5)
end
And(/^I have an item in my shopping cart$/) do
@amazon.goto_watership_down
@product_title_1 = @browser.span(id: 'productTitle').text
@amazon.add_to_cart
end
And(/^I navigate to view my shopping cart$/) do
@browser.span(id: 'nav-cart-count').click
end
When(/^I change the quantity of an item in my cart$/) do
@cart_count_before_qty_change = @browser.span(id: 'nav-cart-count').text
@initial_value = @browser.select_list(name: 'quantity').text
@selected_value = '2'
@browser.select_list(name: 'quantity').select(@selected_value)
end
Then(/^The quantity of that item changes to the value I selected$/) do
new_value = @browser.select_list(name: 'quantity').text
expect(new_value).not_to eq(@initial_value)
expect(new_value).to eq(@selected_value)
end
When(/^I click to remove the item from my shopping cart$/) do
@list_text_single = @browser.div(class: 'sc-list-body').text
@browser.input(value: 'Delete').click
end
Then(/^The item it removed from my shopping cart$/) do
while @list_text_single == @browser.div(class: 'sc-list-body').text do
sleep(1)
end
expected_text_removal_portion = ' was removed from Shopping Cart.'
updated_list_text = @browser.div(class: 'sc-list-body').text
expect(updated_list_text).to eq(@product_title_1 + expected_text_removal_portion)
end
And(/^My shopping cart is empty$/) do
expected_text = 'Your Shopping Cart is empty.'
updated_cart_text = @browser.div(id: 'sc-active-cart').text
expect(updated_cart_text).to include(expected_text)
end
And(/^The number of items in my shopping cart is zero$/) do
@items_in_cart_after_deletion = @browser.span(id: 'nav-cart-count').text
expect(@items_in_cart_after_deletion.to_i).to eq(0)
end
When(/^I click to delete a specific item from my shopping cart$/) do
@subtotal_before_delete = @browser.form(id: 'gutterCartViewForm').text.split("$")[1].split("\n")[0]
@list_text_multiple_del = @browser.div(class: 'sc-list-body').text
@items_in_cart_before_deletion = @browser.span(id: 'nav-cart-count').text
@browser.div('data-asin': @isbn_10).input(value: 'Delete').click
end
Then(/^The selected item is successfully removed$/) do
while @list_text_multiple_del == @browser.div(class: 'sc-list-body').text do
sleep(1)
end
expected_text_removal_portion = ' was removed from Shopping Cart.'
updated_list_text = @browser.div(class: 'sc-list-body').text
expected_text = @product_title_5 + expected_text_removal_portion
expect(updated_list_text).to include(expected_text)
end
And(/^The item no longer appears in my shopping cart$/) do
@browser.refresh
updated_list = @browser.div(class: 'sc-list-body').text
expect(updated_list).to_not include(@product_title_5)
end
And(/^My shopping cart shows the updated number of items after deleting$/) do
items_after_deletion = @browser.span(id: 'nav-cart-count').text
expect(items_after_deletion.to_i).to eq(@items_in_cart_before_deletion.to_i - 1)
end
And(/^The subtotal for my shopping cost successfully updates after deleting$/) do
subtotal_after_delete = @browser.form(id: 'gutterCartViewForm').text.split("$")[1].split("\n")[0]
expect(@subtotal_before_delete.to_f).to be > subtotal_after_delete.to_f
end
And(/^My shopping cart shows an updated count of items due to the quantity change$/) do
while @cart_count_before_qty_change == @browser.span(id: 'nav-cart-count').text do
sleep(1)
end
updated_cart_count = @browser.span(id: 'nav-cart-count').text
expect(updated_cart_count).to eq(@selected_value)
end
When(/^I click to save a specific item for later$/) do
@subtotal_before_saving = @browser.form(id: 'gutterCartViewForm').text.split("$")[1].split("\n")[0]
@list_text_multiple_save = @browser.div(class: 'sc-list-body').text
@items_in_cart_before_save = @browser.span(id: 'nav-cart-count').text
@browser.div('data-asin': @isbn_10).input(value: 'Save for later').click
end
Then(/^The selected item is successfully saved for later$/) do
while @list_text_multiple_save == @browser.div(class: 'sc-list-body').text do
sleep(1)
end
expected_text_save_portion = ' has been moved to Save for Later.'
updated_list_text = @browser.div(class: 'sc-list-body').text
expected_text = @product_title_5 + expected_text_save_portion
expect(updated_list_text).to include(expected_text)
end
And(/^The selected item appears in the saved for later list$/) do
save_list_text = @browser.form(id: 'savedCartViewForm').text
expect(save_list_text).to include(@product_title_5)
end
And(/^My shopping cart shows the updated number of items after saving$/) do
items_after_saving = @browser.span(id: 'nav-cart-count').text
expect(items_after_saving.to_i).to eq(@items_in_cart_before_save.to_i - 1)
end
And(/^The subtotal for the shopping cart successfully updates after saving$/) do
subtotal_after_saving = @browser.form(id: 'gutterCartViewForm').text.split("$")[1].split("\n")[0]
expect(@subtotal_before_saving.to_f).to be > subtotal_after_saving.to_f
end
| true |
b654b4999835733a5a06eba53174328269465365 | Ruby | Hektve87/upcoming-events | /lib/upcoming/country.rb | UTF-8 | 629 | 2.53125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | module Upcoming
class Country
include Upcoming::Defaults
# +country_id+ (Required)
# The country_id number of the country to look within. Country ID's are referred to within other API methods, such as metro.getStateList and state.getInfo. To run getInfo on multiple countries, simply pass an array or a comma-separated list of country_id numbers.
#
def self.info(country_id)
country_id = country_id.join(',') if country_id.is_a?(Array)
Mash.new(self.get('/', :query => {:method => 'country.getInfo', :country_id => country_id}.merge(Upcoming.default_options))).rsp.country
end
end
end | true |
feba3e2c2bb5a9f77d19d3a21329b60525910c5b | Ruby | sridhar61/Tasks | /task69.rb | UTF-8 | 379 | 3.578125 | 4 | [] | no_license | class Constant
PI=3.14
@@r=2
class << Constant
def area
puts"The area is :#{PI*@@r*@@r}"
end
end
def perimeter
puts"The perimeter is: #{2*PI*@@r}"
end
end
class Secondclass
@@r=2
@@a=0.5
def semic
puts"The area of the semicircle: #{@@a*Constant::PI*@@r*@@r}"
end
end
obj=Constant.new
obj2=Secondclass.new
Constant.area
obj.perimeter
obj2.semic
| true |
151def6d24069dc44e32271642bf1e334c31a6e8 | Ruby | jhartwell/ironruby | /Tests/Experiments/Misc/Locals.rb | UTF-8 | 109 | 3.109375 | 3 | [] | no_license | def foo()
b = 123
puts "before eval"
eval("a = b;puts a,b")
puts "after eval"
puts a
end
foo | true |
dbc8a47816d1a2255d4ea9fe3fa962d46eb5b47b | Ruby | Dfletcher1234/dice | /rolls_sorted.rb | UTF-8 | 188 | 2.859375 | 3 | [] | no_license | # number = Random.rand(6)
results = []
10.times { results << Random.rand(1..6) + 1
}
results.sort!
results.each{|result| puts "The result of your roll is #{result}"}
| true |
c6dac3a5f8bd76809aeccb5fc1ee7c14010c8768 | Ruby | Freygarr/disgaea-2-save-editor | /app/models/base_data/plain_string.rb | UTF-8 | 417 | 2.765625 | 3 | [
"MIT"
] | permissive | #renaming because Ruby is fucking retarded about figuring out what constants we actually want
class BaseData::PlainString < BaseData::Base
def self.struct_size; 1; end
def disassemble(file_data)
self.value = raw_from_file(file_data)
end
#TODO: Limit string lengths when re-assigned
def self.clean_value(string)
end_pos = string.index("\000") || string.size
string[0...end_pos]
end
end | true |
a3c044d0ff065ca0aa01b892b342bbed9ec0316a | Ruby | makotoyokei/at_coder | /arc113/c_string_invasion.rb | UTF-8 | 250 | 3.015625 | 3 | [] | no_license | arr = gets.chomp!.split('')
result = 0
l = arr.length
(l-2).downto(1) do |i|
next if !(arr[i-1] == arr[i] && arr[i-1] != arr[i+1])
result += l - i - 1 - arr[i+1...l].count(arr[i-1])
arr[i+1...l] = Array.new(l-i-1){arr[i-1]}
end
puts result | true |
6108b40cd09fed5ab3cfbfb446b7888f7230dda5 | Ruby | dividead/ru8y | /project_euler/21.rb | UTF-8 | 205 | 3.28125 | 3 | [] | no_license | def factors(x)
(1...x).select {|n| (x % n).zero?}.reduce(:+)
end
a=[]
(2..10000).each do |i|
x = factors(i)
a<< i unless a.include?(i) if i==factors(x) and i!=x
end
p a.reduce(:+)
| true |
e4fc01b239b0abc403b74ff0dd44f5b49536a6bc | Ruby | bellesamways/ruby-exercises | /animal.rb | UTF-8 | 470 | 3.890625 | 4 | [] | no_license | class Animal
def pular
puts 'toim toim toim'
end
def dormir
puts 'zzzzz'
end
end
class Cachorro < Animal
def latir
puts 'auau'
end
end
cachorro = Cachorro.new
cachorro.pular
cachorro.dormir
cachorro.latir
# Cachorro é um objeto que possui todos os comportamentos existentes na classe animal
# (pular e respirar), então ele herda esta classe.
# Sendo assim, é possível executar os métodos pular e respirar através de um objeto Cachorro.
| true |
f7b3dbf3efa6c20b4d379578ea1915418972d809 | Ruby | fazer06/micro-shop | /app/models/customer.rb | UTF-8 | 1,471 | 2.71875 | 3 | [] | no_license | # == Schema Information
#
# Table name: customers
#
# id :integer not null, primary key
# first_name :string
# last_name :string
# username :string
# password :string
# email_address :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Customer < ActiveRecord::Base
# The parent
# This side (the customers table) is the parent, and it has one child object
has_one :detail, dependent: :destroy
has_many :orders, dependent: :destroy
has_many :subscriptions
has_many :magazines, through: :subscriptions
# From the outside we shouldn’t know the Detail object exists at all.
# To do that we use Rails’ delegate method:
# Ruby’s splat (*)operator breaks apart an array into a list of parameters
delegate *Detail::ATTR_METHODS, to: :detail
# Create an attached Detail object whenever a Customer object is initialized
# we do that with after_initialize which is an Active Record callback
after_initialize do
self.build_detail if detail.nil?
end
# Now when we call Customer.new it will automatically build a Detail and
# associate them in memory. Once the Customer is saved it will get an
# ID from the database and that ID will be stored in the customer_id field
# of the Detail. We only want to build a Detail object if we don’t already
# have one, so we add the if detail.nil? condition to avoid replacing an
# existing Detail object.
end
| true |
467a22e42249c697d8d567cf20c95eb5acb6e3bf | Ruby | MikeSilvis/espn-scraper | /lib/espn_scraper/schedule/team.rb | UTF-8 | 3,705 | 2.65625 | 3 | [] | no_license | module ESPN::Schedule
class Team
attr_accessor :league, :name
def initialize(league, name)
self.league = league
self.name = name
end
def self.find(league, team)
new(league, team).get_with_cache
end
def get_with_cache
ESPN::Cache.fetch("by_team_#{league}_#{name}", expires_in: 1.day) do
get
end
end
def get
data = {}
data[:league] = self.league
data[:team_name] = self.name
data[:games] = schedule(markup.css('tr'))
if league == 'mlb'
data[:games] = schedule(second_markup.css('tr'))
end
return data
end
def schedule(rows)
headings = markup.css('.stathead').map(&:content)
current_heading = -1
rows.map do |row|
starting_index = league == 'nfl' ? 1 : 0
next if row.attributes['class'].value == 'colhead'
if row.attributes['class'].value == 'stathead'
current_heading = current_heading + 1
end
tds = row.xpath('td')
next if tds.count == 1
next if row.content.match(/BYE WEEK/)
next if tds[starting_index + 2].content.match(/Postponed|Canceled/i)
has_hall_of_fame = false
current_week = 0
{}.tap do |game_info|
time_string = "#{tds[starting_index + 2].content.match(/^\d*:\d\d (PM|AM)/)} EST"
time = (Time.parse(time_string) rescue nil) if !time_string.match(/^[WL]/)
is_over = !time && !tds[starting_index + 2].content.match(/TBD|TBA|Half/)
date = Date.parse("#{tds[starting_index].content} #{Date.today.year}")
game_info[:over] = is_over
game_info[:date] = if !is_over && Date.today > date
date + 1.year
else
date
end
date = game_info[:date]
game_info[:date] = if is_over && Date.today < date
date - 1.year
else
date
end
game_info[:opponent] = ESPN.parse_data_name_from(tds[starting_index + 1])
game_info[:opponent_name] = tds[(starting_index.to_i + 1)].at_css('.team-name').content.to_s.gsub(/#\d*/, '').strip
game_info[:is_away] = !!tds[(starting_index.to_i + 1)].content.match(/^@/)
game_info[:week] = tds[0].content.to_i if %w[ncf nfl].include?(league)
game_info[:heading] = headings[current_heading]
if league == 'ncf'
game_info[:week] = current_week + 1
current_week = current_week + 1
end
if game_info[:week] == 'HOF'
game_info[:week] = 1
has_hall_of_fame = true
end
if has_hall_of_fame && tds[0].content != 'HOF'
game_info[:week] = game_info[:week].to_i + 1
end
if is_over
game_info[:result] = tds[starting_index + 2].at_css('.score').content.strip
game_info[:win] = tds[starting_index + 2].at_css('.game-status').content == 'W' rescue nil
else
game_info[:time] = DateTime.parse("#{game_info[:date].to_s} #{time_string}").utc
end
end
end.compact.sort_by do |game|
game[:date]
end
end
private
def by
%w[ncf ncb].include?(league) ? 'id' : 'name'
end
def markup
@markup ||= ESPN.get "#{league}/team/schedule/_/#{by}/#{name}/year/#{Date.today.year}"
end
def second_markup
@second_half ||= ESPN.get "#{league}/team/schedule/_/#{by}/#{name}/year/#{Date.today.year}/half/2"
end
end
end
| true |
6f3412ab6898f0fb9c0f5e7a06464803949634ad | Ruby | johnmarindotco/ruby-codewars | /finddigit.rb | UTF-8 | 580 | 3.640625 | 4 | [] | no_license |
def find_digit(num, nth)
if (nth <= 0)
return -1
elsif (nth > num.abs.to_s.length)
return 0
else
num = num.abs
place = nth - 1
arr = num.to_s.split('').map(&:to_i).reverse
return arr[place]
end
end
# Complete the function that takes two numbers as input, num and nth and return the nth digit of num (counting from right to left).
# Note: If num is negative, ignore its sign and treat it as a positive value
# If nth is not positive, return -1
# Keep in mind that 42 = 00042. This means that findDigit(42, 5) would return 0
# User: Goncalerta | true |
4b21d074958365ca267b4cef293a90d289a598f6 | Ruby | lpenzey/battle_ship | /lib/validation.rb | UTF-8 | 642 | 3.640625 | 4 | [] | no_license | class Validation
def valid_first_move?(board, x, y)
open_space?(board, x, y)
end
def valid_second_move?(board, x, y, ship)
open_space?(board, x, y) && has_neighbor?(board, x, y, ship)
end
private
def open_space?(board, x, y)
board[x][y] == 0
end
def has_neighbor?(board, x, y, ship)
neighbors = [
board[x - 1][y - 1] == ship,
board[x - 1][y] == ship,
board[x - 1][x + 1] == ship,
board[x][y - 1] == ship,
board[x][y + 1] == ship,
board[x + 1][y - 1] == ship,
board[x + 1][y] == ship,
board[x + 1][y + 1] == ship
]
neighbors.include?(true)
end
end
| true |
8c5881946cc837dc83201c8c51e944d0e39a5118 | Ruby | hassanshamim/chess | /lib/pawn.rb | UTF-8 | 626 | 3.015625 | 3 | [] | no_license | require_relative 'game_piece.rb'
class Pawn < GamePiece
def piece_initial
'P'
end
def valid_attack_coords
new_rank = ( color == :white ? rank + 1 : rank - 1 )
coords = [ [file-1, new_rank], [file+1, new_rank] ]
coords.select do |file, rank|
(0..7).include?(file) and (0..7).include?(rank)
end
end
def valid_move_coords
new_rank = ( color == :white ? rank + 1 : rank - 1 )
coords = [[file, new_rank]]
coords.select do |file, rank|
(0..7).include?(file) and (0..7).include?(rank)
end
end
def path_to(coordinate) #move to template?
[[]]
end
end
| true |
3e38dcedb94fccf727b88655771f63b076b796cf | Ruby | kiote/Pythagoras | /bin/run_pyth | UTF-8 | 395 | 2.75 | 3 | [] | no_license | #!/usr/bin/env ruby
$LOAD_PATH << File.expand_path('../../lib', __FILE__)
require 'pyth'
require 'thor'
class RunPyth < Thor
default_task :birthday
desc :birthday, 'Draw pyth square'
def birthday
b = ask "your birhtday (dd.mm.yyyy):"
say 'Your square:', :green
res = Pyth.birthday(b)
p res
p Pyth.description(res)
end
end
RunPyth.start
| true |
1bb5b3f3315f1faac5794dfe8bcdbf73dafb1d57 | Ruby | Nucc/lucie | /lucie-lib/lib/lucie/command_line_slicer.rb | UTF-8 | 1,781 | 3.453125 | 3 | [
"MIT"
] | permissive | module Lucie
module Core
# Command Line Slicer can split the input string to words.
#
class CommandLineSlicer
# Initializes a CommandLineSlicer object with the input.
#
# @param line [String] The input that need to be sliced
def initialize(line)
@line = line.split("")
@parts = []
@neutral_status = false
@quotation_open = false
@scanned = ""
end
# Returns the words of the input in an array.
#
def to_a
each_char do |char|
if boundary? char
save_chunk
elsif in_quoatation? char
toggle_quotation_state
elsif neutral? char
neutral :on
else
neutral :off
append char
end
end
save_chunk
end
private
def append(char)
@scanned += char
end
def each_char(&blk)
while @line.size > 0
yield(@line.shift)
end
end
def toggle_quotation_state
@quotation_open = !@quotation_open
end
def save_chunk
@parts << @scanned if @scanned != ""
@scanned = ""
@parts
end
def neutral(sym)
@neutral_status = (sym == :on)
end
private
def neutral_chars
["\\"]
end
def boundary_chars
[" "]
end
def quotation_chars
["\"", "'"]
end
def boundary?(char)
boundary_chars.include?(char) && !@neutral_status && !@quotation_open
end
def in_quoatation?(char)
quotation_chars.include?(char) && !@neutral_status
end
def neutral?(char)
neutral_chars.include?(char) && !@neutral_status
end
end
end
end | true |
225e0290db6e91b94a57b4348c1bb35ed9a52d84 | Ruby | hasandeveloper/Programms-and-Data-structures | /School/Round-robin-optimized-code-medium-problems-practice/practice-1/Array1/max_consecutive_1.rb | UTF-8 | 666 | 3.4375 | 3 | [] | no_license | # Given a binary array, find the index of 0 to be flipped to get max nor of consecutive 1' only single 0 flip is allowed
# i/p:- [0,1,1,1,0,1,0,1,0,1,0,1]
def max_con_1(array)
s = -1
zero_count = 0
array.push(0)
n=0
array.each_with_index do |v,e|
if v == 0
zero_count += 1
end
if zero_count == 2
p e-s-1
(n..array.length - 1).to_a.each do |i|
if array[i] == 0
s=i
n=i+1
break
end
end
zero_count -= 1
end
end
end
max_con_1([0,1,1,1,0,1,0,1,0,1,0,1])
| true |
c5623a1664f4bc687db4c95cad724215afccecc4 | Ruby | tbreitenfeldt/utopia-agent-microservice | /travelers.rb | UTF-8 | 3,078 | 2.65625 | 3 | [] | no_license | require 'jwt'
require 'json'
require 'mysql2'
require 'sequel'
begin
$DB = Sequel.connect(
:adapter => 'mysql2',
:host => ENV["DB_HOST"],
:port => ENV["DB_PORT"],
:database => ENV["DB_NAME"],
:user => ENV["DB_USER"],
:password => ENV["DB_PASSWORD"])
class Travelers < Sequel::Model($DB[:traveler]); end
rescue
@error_message="#{$!}"
return {
statusCode: 400,
headers: {
'Content-Type': 'application/json',
},
body: @error_message.to_json
}
end
# Handler function returned to the Lambda runtime environment
def lambda_handler(event:, context:)
# Uncomment for token authorization
begin
hmac_secret = ENV["JWT_SECRET"]
token = event['headers']['Authorization']
token.slice! "Bearer "
token_data = JWT.decode(token, hmac_secret, true, { algorithm: 'HS256' })[0]
if !token_data.key?('role') || token_data['role'] != 'AGENT'
raise 'Authorization token invalid'
end
rescue
@error_message="#{$!}"
return {
statusCode: 403,
headers: {
'Content-Type': 'application/json',
},
body: @error_message.to_json
}
end
# Query processing
data = Array.new
case event["httpMethod"]
when "GET"
traveler_id = event['pathParameters']['id']
Travelers.where(id: traveler_id).each{ |t| data.push(t.values) }
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: data.to_json
}
when "POST"
body = JSON.parse(event['body'])
$DB.transaction do
traveler = Travelers. new(
first_name: body['first_name'],
last_name: body['last_name'],
dob: body['dob'],
phone: body['phone'],
email: body['email'],
street: body['street'],
city: body['city'],
state: body['state'],
postal_code: body['postal_code'],
country: body['country'])
traveler.save
traveler = Travelers.where(id: traveler.id).first.values
data.push(traveler)
end
return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: data.to_json
}
when "PUT"
body = JSON.parse(event['body'])
$DB.transaction do
Travelers.where(id: body['id']).update(
first_name: body['first_name'],
last_name: body['last_name'],
dob: body['dob'],
phone: body['phone'],
email: body['email'],
street: body['street'],
city: body['city'],
state: body['state'],
postal_code: body['postal_code'],
country: body['country'])
traveler = Travelers.where(id: body['id']).first.values
data.push(traveler)
end
return {
statusCode: 201,
headers: { 'Content-Type': 'application/json' },
body: data.to_json
}
end
end
| true |
5b9d1426558accac52e9a52bd501c2288a1183ac | Ruby | JayTeeSF/cmd_notes | /security/patch_servers.rb | UTF-8 | 1,632 | 2.625 | 3 | [] | no_license | #!/usr/bin/env ruby
class ServerControl
SERVERS = [ ... ] # FIXME
USER = '...' # FIXME
PATCHED = 'not vulnerable'
def patched?(server)
PATCHED == remote_execute('wget https://dl.dropboxusercontent.com/u/6867373/CVE-2015-0235.c && gcc CVE-2015-0235.c -o CVE-2015-0235 && ./CVE-2015-0235', server).chomp
end
def remote_execute(command, machine_name='some_server')
command = %Q(time ssh #{USER}@#{machine_name} #{command})
execute(command, machine_name, _force=true)
end
def cleanup_patch_verifier(server)
remote_execute('rm CVE-2015-0235 CVE-2015-0235.c', server)
end
def execute(command, machine_name='some_server', force=false)
if force
result = %x{#{command}}
puts "\n#{machine_name}:#{command}\n\t=> #{result}"
else
puts "command: #{command}"
end
end
def patch
SERVERS.each do |server|
warn "server: #{server}"
unless patched?(server)
warn "patching..."
command = %Q(time ssh #{USER}@#{server} 'yes Y | sudo -S aptitude update')
execute(command, server)
command = %Q(time ssh #{USER}@#{server} 'yes N | sudo -S aptitude safe-update')
execute(command, server)
end
unless patched?(server)
cleanup_patch_verifier(server)
fail('unable to patch this server')
end
cleanup_patch_verifier(server)
warn "done"
return # debug
end
end
def help
warn "#{$PROGRAM_NAME} help|patch"
end
end
if __FILE__ == $0
server_control = ServerControl.new
case ARGV.first
when /patch/i
server_control.patch
else
server_control.help
end
end
| true |
0a8936bfa4ea4b2acf94cd5ed61d279382304d36 | Ruby | derric-d/todo_list.rb | /listPlay.rb | UTF-8 | 2,181 | 3.640625 | 4 | [] | no_license | movies = {
Memento: 3,
Primer: 4,
Ishtar: 1
}
puts "What would you like to do?"
puts "-- Type 'add' to add a movie."
puts "-- Type 'update' to update a movie."
puts "-- Type 'display' to display all movies."
puts "-- Type 'delete' to delete a movie."
choice = gets.chomp.downcase
case choice
when 'add'
puts "What movie do you want to add?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "What's the rating? (Type a number 0 to 4.)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been added with a rating of #{rating}."
else
puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
end
when 'update'
puts "What movie do you want to update?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "Movie not found!"
else
puts "What's the new rating? (Type a number 0 to 4.)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been updated with new rating of #{rating}."
end
when 'display'
movies.each do |movie, rating|
puts "#{movie}: #{rating}"
end
when 'delete'
puts "What movie do you want to delete?"
title = gets.chomp
if movies[title.to_sym].nil?
puts "Movie not found!"
else
movies.delete(title.to_sym)
puts "#{title} has been removed."
end
else
puts "Sorry, I didn't understand you."
end
puts "What would you like to do?"
puts "-- Type 'create' to create a list"
puts "-- Type 'add' to add a task"
puts "-- Type 'update' to update a task"
puts "-- Type 'read' to read a specific task"
puts "-- Type 'display' to display all tasks"
puts "-- Type 'delete' to delete a task"
my_list = List.new
puts "you've created a new list"
my_list.add( Task.new('Make Breakfast'))
my_list.add( Task.new('wash after Breakfast'))
my_list.add( Task.new('pack lunch'))
my_list.add( Task.new('Get gas'))
puts "You have added a task to the Todo List"
if my_list.show.join.include?('#<')
print [
'Are you sure you are handling your task object correctly for showing',
"as a string?\n"
]
end
puts 'Your task list:'
puts my_list.show | true |
185fad9b57805645ab79872205733f9850ead35b | Ruby | alex6851/badges-and-schedules-online-web-sp-000 | /conference_badges.rb | UTF-8 | 564 | 3.875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def badge_maker(name)
"Hello, my name is #{name}."
end
def batch_badge_creator(list_of_names)
badges = []
list_of_names.each {|name| badges << "Hello, my name is #{name}."}
badges
end
def assign_rooms(list_of_names)
assignments = []
list_of_names.each_with_index {|name, room| assignments << "Hello, #{name}! You'll be assigned to room #{room + 1}!" }
assignments
end
def printer(list_of_names)
batch_badge_creator(list_of_names).each {|badge| puts badge }
assign_rooms(list_of_names).each {|room_assignments| puts room_assignments}
end
| true |
ae73d85869c4e091e5a01185961a3f2f8473c770 | Ruby | emadb/playground | /ruby/palindrome.rb | UTF-8 | 269 | 3.671875 | 4 | [] | no_license | #!/usr/bin/ruby
def run
input = STDIN.gets
i = 0
j = input.length-2
match = true
while match and i < j
match = input[i] == input[j]
i = i+1
j = j-1
end
result = match ? "Y": "N"
puts result
end
STDIN.gets.to_i.times { run } | true |
4433cdc6ddea0e4bc3721c56b61ac6f406c4aa95 | Ruby | pasha-bolokhov-cs/Udemy | /Ruby/times.rb | UTF-8 | 201 | 3.59375 | 4 | [] | no_license | #!/usr/bin/ruby
# a number of times
5.times do
print ("Hey there!\n")
end
puts()
1.upto(8) do |k|
print (" k = " + k.to_s() + "\n")
end
puts()
0.step(40,4) { | k | puts( "k = " + k.to_s() ) }
| true |
7397346506b0e485b34c7141ae7470c407fe7b65 | Ruby | yamadaj2/object_orientated_game | /lib/object_orientated_game/characters/character.rb | UTF-8 | 3,630 | 3.421875 | 3 | [] | no_license | require_relative '../modules/trash_talk'
require_relative '../modules/attack_list'
require_relative '../modules/attack_remarks'
class Character
include AttackList
include TrashTalk
include AttackRemarks
attr_accessor :name, :health_points
attr_reader :attack_points
def initialize(name, health_points, attack_points)
@name = name
@health_points = health_points
@attack_points = attack_points
end
def show_full_stats
divider = '-' * 40
stats_display = <<~END
#{divider}
Name: #{@name}
Type: #{@type}
Health Points: #{@health_points}
Attack Points: #{@attack_points}
#{divider}
END
stats_display
end
def show_player_selection
"You chose #{self.name} the #{self.type}"
end
def show_challenge_line
"#{self.name} the #{self.type} has appeared and is challenging you to a fight to the death!"
end
def show_character_intro
"#{self.name} looks at you dead in the eye and says:\n#{character_trash_talk}"
end
def character_trash_talk
r = Random.new
trash_talk_lines = TrashTalk::Lines
trash_talk_lines[r.rand(trash_talk_lines.length)]
end
#todo test (stdout)
def select_attack
attack_choice_number = 0
while attack_choice_number < 1 || attack_choice_number > self.attack_list_length
puts "Choose your attack by entering a number between 1 and #{self.attack_list_length}"
self.show_attack_list
attack_choice_number = gets.chomp.to_i
if attack_choice_number > 0 && attack_choice_number <= self.attack_list_length
system 'clear'
return attack_choice_number
else
puts "You've entered an invalid option. Please select from the list"
end
end
end
def generate_random_attack_number
r = Random.new
r.rand(self.attack_list_length)
end
def show_attack_description(attack_number_choice)
attack_list = self.get_attack_list
"#{self.name} #{attack_list[attack_list.keys[attack_number_choice - 1]][:description]}"
end
def get_attack_list
character_type = self.class.to_s
case character_type
when Ninja.to_s
attack_list = AttackList::NINJA_ATTACK_LIST
when Samurai.to_s
attack_list = AttackList::SAMURAI_ATTACK_LIST
when Demon.to_s
attack_list = AttackList::DEMON_ATTACK_LIST
end
attack_list
end
def is_alive?
self.health_points > 0 ? true : false
end
def calculate_damage(attack_number_choice)
damage = self.get_attack_damage(attack_number_choice) * self.attack_points
damage
end
def deduct_health(damage_amount)
self.health_points -= damage_amount
end
def damaged_received_remark
remark = AttackRemarks::AccurateAttackRemarks.new
remark.random_attack_remark(self)
end
#todo test (stdout)
def show_damage_scene(damage_amount)
sleep 1
puts show_target_is_hit(self)
sleep 1
puts show_damage_amount(damage_amount)
sleep 1
end
def show_target_is_hit(target)
"#{target.name} is hit!"
end
def show_damage_amount(damage_amount)
"Damage inflicted: #{damage_amount}"
end
def show_attack_miss_scene(target)
"#{self.name} attacks and misses #{target.name}!!"
end
def missed_attack_remark
remark = AttackRemarks::MissRemarks.new
#todo this self is ugly. Re-factor
remark.random_miss_remark(self)
end
#todo test (stdout)
def show_victory_scene(loser)
star_divider = '*' * 20
puts star_divider + " #{self.name} has killed #{loser.name} " + star_divider
sleep 1
puts star_divider + " #{self.name} is the Victor!! " + star_divider
end
end | true |
e96578e2a1f5074e1e4ff8cd464ef87b6744892f | Ruby | richwblake/school-domain-onl01-seng-pt-110319 | /lib/school.rb | UTF-8 | 437 | 3.390625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class School
attr_accessor :roster
def initialize( school )
@school = school
@roster = {}
end
def add_student( student_name, student_grade )
if roster[student_grade] == nil
roster[student_grade] = [student_name]
else
roster[student_grade].push( student_name)
end
end
def grade( grade )
roster[grade]
end
def sort
roster.each { |grade, name_list| name_list.sort! }
end
end
| true |
0dfe866e203c16f5eac9c8922645898f7083372a | Ruby | davidSoutarson/tuto_ruby | /tuto-pour-coder/tp_amis_avec.rb | UTF-8 | 482 | 3.65625 | 4 | [] | no_license | class Utilisateur
attr_accessor :prenom, :amis
def est_amis_avec?(prenom)
puts"On vas tester si amis avec "+prenom
amis.each do |ami|
puts "on test sur " + ami.prenom
return true if ami.prenom == prenom
end
return false
end
end
alice = Utilisateur.new
alice.prenom = "Alice"
bob = Utilisateur.new
bob.prenom = "Bob"
jane = Utilisateur.new
jane.prenom = "Jane"
alice.amis = [jane, bob]
puts alice.est_amis_avec?("Bob")
puts alice.amis.size
| true |
b04e8b776be4e4c1cc5c15838e3d540b660183be | Ruby | tra38/example_api_library | /lib/customer_profile.rb | UTF-8 | 1,116 | 3.03125 | 3 | [] | no_license | require 'net/http'
require 'json'
require_relative 'http_request'
class CustomerProfile
attr_reader :age, :income, :zipcode, :propensity, :ranking
def initialize(age:, income:, zipcode:)
@age = age
@income = income
@zipcode = zipcode
json = acquire_json
if json
@propensity = json["propensity"]
@ranking = json["ranking"]
end
end
def get_request_uri
URI("https://not_real.com/customer_scoring?income=#{income}&zipcode=#{zipcode}&age=#{age}")
end
def acquire_json
http_request = HttpRequest.get_request(get_request_uri)
code = http_request[:code]
if request_successful?(code)
JSON.parse(http_request[:response])
elsif client_error?(code)
message = JSON.parse(http_request[:response])["message"]
raise "The server rejects the request. HTTP Response Code: #{code}. Message: #{message}"
else
raise "The API server is currently down. HTTP Response Code: #{code}."
end
end
private
def request_successful?(code)
code.between?(200, 399)
end
def client_error?(code)
code.between?(400,499)
end
end | true |
908b508709cbb76ba85779532716245a701f5af2 | Ruby | jcasts/sunshine | /lib/commands/run.rb | UTF-8 | 3,681 | 2.96875 | 3 | [
"MIT"
] | permissive | module Sunshine
##
# Run one or more sunshine scripts.
#
# Usage: sunshine run [options] [run_file] ...
#
# Arguments:
# run_file Load a script or app path. Defaults to ./Sunshine
#
# Options:
# -l, --level LEVEL Set trace level. Defaults to info.
# -e, --env DEPLOY_ENV Sets the deploy env. Defaults to development.
# -a, --auto Non-interactive - automate or fail.
# --no-trace Don't trace any output.
class RunCommand < DefaultCommand
##
# Takes an array and a hash, runs the command and returns:
# true: success
# false: failed
# exitcode:
# code == 0: success
# code != 0: failed
# and optionally an accompanying message.
def self.exec run_files, config
run_files.each do |run_file|
run_file = run_file_from run_file
with_load_path File.dirname(run_file) do
puts "Running #{run_file}"
get_file_data run_file
require run_file
end
end
return true
end
##
# Tries to infer what run file to used based on a given path:
# run_file_from "path/to/some/dir"
# #=> "path/to/some/dir/Sunshine"
# run_file_from nil
# #=> "Sunshine"
# run_file_from "path/to/run_script.rb"
# #=> "path/to/run_script.rb"
def self.run_file_from run_file
run_file = File.join(run_file, "Sunshine") if
run_file && File.directory?(run_file)
run_file ||= "Sunshine"
File.expand_path run_file
end
##
# Adds a directory to the ruby load path and runs the passed block.
# Useful for scripts to be able to reference their own dirs.
def self.with_load_path path
path = File.expand_path path
# TODO: Find a better way to make file path accessible to App objects.
Sunshine.send :remove_const, "PATH" if defined?(Sunshine::PATH)
Sunshine.const_set "PATH", path
added = unless $:.include? path
$: << path && true
end
yield
Sunshine.send :remove_const, "PATH"
$:.delete path if added
end
##
# Returns file data in a run file as a File IO object.
def self.get_file_data run_file
# TODO: Find a better way to make file data accessible to App objects.
Sunshine.send :remove_const, "DATA" if defined?(Sunshine::DATA)
data_marker = "__END__\n"
line = nil
Sunshine.const_set("DATA", File.open(run_file, 'r'))
until line == data_marker || Sunshine::DATA.eof?
line = Sunshine::DATA.gets
end
end
##
# Parses the argv passed to the command
def self.parse_args argv
options = {'trace' => true}
opts = opt_parser(options) do |opt|
opt.banner = <<-EOF
Usage: #{opt.program_name} run [options] [run_file] ...
Arguments:
run_file Load a script or app path. Defaults to ./Sunshine
EOF
opt.separator nil
opt.separator "Options:"
opt.on('-l', '--level LEVEL',
'Set trace level. Defaults to info.') do |value|
options['level'] = value
end
opt.on('-e', '--env DEPLOY_ENV',
'Sets the deploy env. Defaults to development.') do |value|
options['deploy_env'] = value
end
opt.on('-a', '--auto',
'Non-interactive - automate or fail.') do
options['auto'] = true
end
opt.on('--no-trace',
"Don't trace any output.") do
options['trace'] = false
end
end
opts.parse! argv
options
end
end
end
| true |
f2aeab1156a4bc79949a4049c9228a27ea947b7c | Ruby | IF977/SchoolClue | /spec/comparador_spec.rb | UTF-8 | 747 | 2.703125 | 3 | [] | no_license | require "rails_helper"
describe "#comparestring" do
obj = KeeperController.new
it "should be defined" do
expect {obj.send(:comparestring,"escola do seu joão", "escola municipal do seu joão")}.to_not raise_error
end
it "returns true when one of the parameters has all its words inside the other" do
obj.send(:comparestring,"escola municipal engenheiro josé adalberto","escola josé adalberto").should be true
end
it "returns false when none of the parameters has its words inside the other" do
obj.send(:comparestring,"escola municipal epamenondas","escola municipal casa").should be false
end
it "should reject numbers" do
expect {obj.send(:comparestring,1,23)}.to raise_error("Não é permitido números")
end
end
| true |
0fe0cde792ff847f032073eb9225d17815d343fe | Ruby | Sruthisarav/My-computer-science-journey | /The Odin Project/Ruby Programming/Testing Ruby Code/Enumerables/spec/enumerables_spec.rb | UTF-8 | 3,337 | 3.75 | 4 | [] | no_license | require './lib/enumerables.rb'
describe Enumerable do
describe "#my_all?" do
it "returns true if array is empty" do
expect([].my_all?{|num| num > 0}).to eql(true)
end
it "returns false if even one elemnt doesn't meet condition" do
expect([1, 5, -1].my_all? {|num| num < 0}).to eql(false)
end
it "returns true when all elements meet condition" do
expect([1, 2, 4, 5].my_all? {|num| num > 0}).to eql(true)
end
it "works with string arrays too" do
expect(["hello", "as", "now"].my_all? {|str| str.length > 0}).to eql(true)
end
end
describe '#my_any?' do
it "returns true if array is empty" do
expect([].my_any?{|num| num > 0}).to eql(true)
end
it "returns true if at least one element meets condition" do
expect([1, 4, 5].my_any? {|num| num >= 5}).to eql(true)
end
it "returns false is all elements do not meet condition" do
expect(['a', 'b', 'c'].my_any? {|char| char == 'd'}).to eql(false)
end
it "returns true if all elements meet condition" do
expect([1, 2, 4, 5].my_any? {|num| num > 0}).to eql(true)
end
end
describe '#my_none?' do
it "returns true if array is empty" do
expect([].my_none? {|num| num > 0}).to eql(true)
end
it "returns true if all elements do not meet condition" do
expect([1, 3, 5].my_none? {|num| num < 0}).to eql(true)
end
it "returns false if even one element meets condition" do
expect([1, 5, 6].my_none? {|num| num > 5}). to eql(false)
end
it "returns false if all elements meet condition" do
expect([1, 2, 4, 5].my_none? {|num| num > 0}).to eql(false)
end
end
describe "#my_count" do
it "returns 0 if array is empty" do
expect([].my_count {|num| num > 0}).to eql(0)
end
it "returns 0 if all elements fail to meet condition" do
expect([1, 3, 5].count {|num| num < 0}).to eql(0)
end
it "returns 1 if one elements meets conidtion" do
['a', 'b', 'c'].count {|char| char == 'b'}
end
it "returns count if more than one element meets condition" do
expect([1, 5, 7, 9].my_count {|num| num >= 6}).to eql(2)
end
end
describe "#my_map" do
it "returns an empty array when given an empty array" do
expect([].my_map).to eql([])
end
it "my_map works when given a proc" do
expect([1, 2, 3, 4].my_map(Proc.new {|num| num*2})).to eql([2, 4, 6, 8])
end
it "my_map works when a block is given instead of a proc" do
expect([1, 3, 5].my_map {|ele| ele*2}).to eql([2, 6, 10])
end
end
describe "#my_inject" do
it "returns nil when array is empty" do
expect([].my_inject).to eql(nil)
end
it "returns the result of the blk given when there's no accumulator" do
expect([1, 2, 3, 4].my_inject {|sum, num| sum*num}).to eql(24)
end
it "returns the result when there's an accumulator given" do
expect([1, 2, 3].my_inject(0){|result, num| result-num}).to eql(-6)
end
end
end | true |
8f53aa51d6685274cf38e8272149ef2ff574d6a6 | Ruby | aconstandinou/ls-exercises | /101_109_small_problems/easy_1/sum_of_digits.rb | UTF-8 | 402 | 3.671875 | 4 | [] | no_license | def sum(num)
last_index = num.to_s.length # tells us how many values to sum
sum = 0
num_string = num.to_s
(0..last_index).each do |idx|
sum += num_string[idx].to_i
end
sum
end
puts sum(23) == 5
puts sum(496) == 19
puts sum(123_456_789) == 45
# LS answer
def sum(number)
number.to_s.chars.map(&:to_i).reduce(:+)
end
puts sum(23) == 5
puts sum(496) == 19
puts sum(123_456_789) == 45
| true |
07b810c573f0116d34a721f19b8595d5064831c6 | Ruby | tim0414/ruby_practice | /range_test.rb | UTF-8 | 1,011 | 4.125 | 4 | [] | no_license | class Discrete_Point
attr_accessor :x, :y
#include Comparable
def initialize(x,y)
@x, @y = x, y
end
=begin
def succ
Discrete_Point.new(@x+2, @y+2)
end
=end
def <=> (obj)
return 1 if (self.x > obj.x) && (self.y > obj.y)
return 0 if (self.x == obj.x) && (self.y == obj.y)
return -1 if (self.x < obj.x) && (self.y < obj.y)
end
=begin
def to_s
"(#{@x}, #{@y})"
end
=end
end
p1 = Discrete_Point.new(1,1)
p2 = Discrete_Point.new(9,9)
p3 = Discrete_Point.new(2,2)
puts (p1..p2).class
puts (p1..p2).cover?(p3) # => true
#puts (p1..p2).each
#puts (p1..p2).include?(p3) # => can't iterate from Discrete_Point (TypeError)
#puts p1>p3
class A
attr_accessor :x, :y
include Enumerable
def initialize(x, y)
@x, @y = x, y
end
def each
yield @x
yield @y
end
end
a1 = A.new(10,2)
a2=a1.map {|x| x*x}
print a2
for value in A.new(10,2)
puts value
end
5.times do |x|
print x
end | true |
1534f661ea638844d3c0015d096d5584e440bc08 | Ruby | joshjeong/phase_0_unit_2 | /week_5/9_gps2.1/my_solution.rb | UTF-8 | 4,181 | 3.53125 | 4 | [] | no_license | # U2.W5: The Bakery Challenge (GPS 2.1)
# Your Names
# 1) Lienha Carleton
# 2) Josh Jeong
# This is the file you should end up editing.
def bakery_num(num_of_people, fav_food)
my_list = {"pie" => [8,0], "cake" => [6,0], "cookie" => [1,0]}
raise ArgumentError.new("You can't make that food") unless my_list.has_key?(fav_food)
my_list[fav_food][1] = num_of_people / my_list[fav_food][0]
num_of_people = num_of_people % my_list[fav_food][0]
if num_of_people == 0
"You need to make #{my_list[fav_food][1]} #{fav_food}(s)."
else
my_list.select {|key, value| key != fav_food}.each { |key, value|
value[1] = num_of_people / value[0]
num_of_people = num_of_people % value[0]
}
"You need to make #{my_list["pie"][1]} pie(s), #{my_list["cake"][1]} cake(s), and #{my_list["cookie"][1]} cookie(s)."
end
end
# def bakery_num(num_of_people, fav_food)
# my_list = {"pie" => 8, "cake" => 6, "cookie" => 1}
# raise ArgumentError.new("You can't make that food") unless my_list.has_key?(fav_food)
# if num_of_people % my_list[fav_food] == 0
# num_of_food = num_of_people / my_list[fav_food]
# "You need to make #{num_of_food} #{fav_food}(s)."
# else
# while num_of_people > 0
# new_list = Hash.new
# my_list.each { |key, value|
# new_list[key] = num_of_people / value
# num_of_people %= value }
# end
# "You need to make #{new_list['pie']} pie(s), #{new_list['cake']} cake(s), and #{new_list['cookie']} cookie(s)."
# end
# end
# def bakery_num(num_of_people, fav_food)
# my_list = {"pie" => 8, "cake" => 6, "cookie" => 1}
# pie_qty = 0
# cake_qty = 0
# cookie_qty = 0
# raise ArgumentError.new("You can't make that food") unless my_list.has_key?(fav_food)
# fav_food_qty = my_list[fav_food]
# if num_of_people % fav_food_qty == 0
# num_of_food = num_of_people / fav_food_qty
# return "You need to make #{num_of_food} #{fav_food}(s)."
# else
# case fav_food
# when "pie"
# pie_qty = num_of_people/ my_list["pie"]
# num_of_people = num_of_people % my_list["pie"]
# cake_qty = num_of_people / my_list["cake"]
# num_of_people = num_of_people % my_list["cake"]
# cookie_qty = num_of_people
# when "cake"
# cake_qty= num_of_people / my_list["cake"]
# num_of_people = num_of_people % my_list["cake"]
# cookie_qty = num_of_people
# else
# cookie_qty= num_of_people
# end
# while num_of_people > 0
# if num_of_people / my_list["pie"] > 0
# pie_qty = num_of_people / my_list["pie"]
# num_of_people = num_of_people % my_list["pie"]
# elsif num_of_people / my_list["cake"] > 0
# cake_qty = num_of_people / my_list["cake"]
# num_of_people = num_of_people % my_list["cake"]
# else
# cookie_qty = num_of_people
# num_of_people = 0
# end
# end
# return "You need to make #{pie_qty} pie(s), #{cake_qty} cake(s), and #{cookie_qty} cookie(s)."
# end
# end
#-----------------------------------------------------------------------------------------------------
#DRIVER CODE-- DO NOT MODIFY ANYTHING BELOW THIS LINE (except in the section at the bottom)
# These are the tests to ensure it's working.
# These should all print true if the method is working properly.
p bakery_num(24, "cake") == "You need to make 4 cake(s)."
p bakery_num(41, "pie") == "You need to make 5 pie(s), 0 cake(s), and 1 cookie(s)."
p bakery_num(24, "cookie") == "You need to make 24 cookie(s)."
p bakery_num(4, "pie") == "You need to make 0 pie(s), 0 cake(s), and 4 cookie(s)."
p bakery_num(130, "pie") == "You need to make 16 pie(s), 0 cake(s), and 2 cookie(s)."
# p bakery_num(3, "apples") this will raise an ArgumentError
# # You SHOULD change this driver code. Why? Because it doesn't make sense.
p bakery_num(41, "cake") == "You need to make 0 pie(s), 6 cake(s), and 5 cookie(s)." # WHAAAAAT? I thought I said I wanted cake!
| true |
1c4e1ce40a4ce07f0535fb862ea2270d59c151bd | Ruby | bbatsov/opalrb.org | /source/javascripts/try_opal.rb | UTF-8 | 1,970 | 2.71875 | 3 | [
"MIT"
] | permissive | require 'opal'
require 'opal-parser'
require 'opal-jquery'
DEFAULT_TRY_CODE = <<-RUBY
class User
attr_accessor :name
def initialize(name)
@name = name
end
def admin?
@name == 'Admin'
end
end
user = User.new('Bob')
puts user
puts user.admin?
RUBY
class TryOpal
class Editor
def initialize(dom_id, options)
@native = `CodeMirror(document.getElementById(dom_id), #{options.to_n})`
end
def value=(str)
`#@native.setValue(str)`
end
def value
`#@native.getValue()`
end
end
def self.instance
@instance ||= self.new
end
def initialize
@flush = []
@output = Editor.new :output, lineNumbers: false, mode: 'text', readOnly: true
@viewer = Editor.new :viewer, lineNumbers: true, mode: 'javascript', readOnly: true, theme: 'tomorrow-night-eighties'
@editor = Editor.new :editor, lineNumbers: true, mode: 'ruby', tabMode: 'shift', theme: 'tomorrow-night-eighties', extraKeys: {
'Cmd-Enter' => -> { run_code }
}
@link = Element.find('#link_code')
Element.find('#run_code').on(:click) { run_code }
hash = `decodeURIComponent(location.hash || location.search)`
if hash =~ /^[#?]code:/
@editor.value = hash[6..-1]
else
@editor.value = DEFAULT_TRY_CODE.strip
end
end
def run_code
@flush = []
@output.value = ''
@link[:href] = "?code:#{`encodeURIComponent(#{@editor.value})`}"
begin
code = Opal.compile(@editor.value, :source_map_enabled => false)
@viewer.value = code
eval_code code
rescue => err
log_error err
end
end
def eval_code(js_code)
`eval(js_code)`
end
def log_error(err)
puts "#{err}\n#{`err.stack`}"
end
def print_to_output(str)
@flush << str
@output.value = @flush.join('')
end
end
Document.ready? do
$stdout.write_proc = $stderr.write_proc = proc do |str|
TryOpal.instance.print_to_output(str)
end
TryOpal.instance.run_code
end
| true |
1e09b61b14df80dc53de20e62bd27b22174ce0f1 | Ruby | amitkgupta/adventofcode.com | /2017/day15/part2.rb | UTF-8 | 435 | 2.75 | 3 | [] | no_license | a, b = ENV["TEST"] == "true" ? [65, 8921] : [722, 354]
judge_a = []
judge_b = []
num_comparisons = 0
num_matches = 0
until num_comparisons == 5_000_000
a = (a * 16807) % 2147483647
b = (b * 48271) % 2147483647
judge_a << a if a % 4 == 0
judge_b << b if b % 8 == 0
unless judge_a.empty? || judge_b.empty?
num_comparisons += 1
num_matches += 1 if (judge_a.shift % 65536) == (judge_b.shift % 65536)
end
end
puts num_matches
| true |
96543327b898caaf29056f54f4e5f33154be04da | Ruby | AndreasHolmback/190815_livecode | /acronymize/spec/acronymize_spec.rb | UTF-8 | 765 | 3 | 3 | [] | no_license | require_relative "../acronymize"
describe "#acronymize" do
it "returns an empty string when passed an empty string" do
actual = acronymize("")
expected = ""
# passes if `actual == expected`
expect(actual).to eq(expected)
end
it 'returns "FAQ" when passed "frequently asked questions"' do
actual = acronymize("frequently asked questions")
expected = 'FAQ'
expect(actual).to eq(expected)
end
it 'returns "AFK" when passed "AWAY FROM KEYBOARD"' do
actual = acronymize("AWAY FROM KEYBOARD")
expected = 'AFK'
expect(actual).to eq(expected)
end
it 'returns "WFH" when passed "working from home"' do
actual = acronymize("working from home")
expected = 'WFH'
expect(actual).to eq(expected)
end
end
| true |
e0833dbfc2ba4c488d2b71bae2f7dc13bf6acd66 | Ruby | vishank1997/ruby-practice | /numberguessing.rb | UTF-8 | 519 | 3.78125 | 4 | [] | no_license | #ruby
puts "welcome to whats my number?"
puts "what is your name?"
ch=gets.to_s.chomp
print "hello"+ ch + "how are you"
number = rand(10..20)
print number
print "ok i have selected my number guess what it is"
select=gets.to_i
guess=1
until select==number
if select<number
print "your number is smaller\n try once more"
select=gets.to_i
guess=guess+1
elsif select>number
print "your no. is larger\n try once more"
select=gets.to_i
guess=guess+1
end
end
puts "no. of guess ="+guess.to_s
| true |
802df1e7d565a763b067285d4625bf779d85afe7 | Ruby | dantebronto/consensus | /lib/tasks/setup.rake | UTF-8 | 818 | 2.875 | 3 | [
"MIT"
] | permissive | namespace :setup do
desc "create the admin user"
task :admin => :environment do
admin = User.first(:conditions => {:permission_level => -1})
if admin
puts "Admin user already exists"
else
puts "This user has the ability to create all other users in the system"
login = ask("what should the admin's login be? ")
password = ask("what should the admin's password be? ")
admin = User.create({
:login => login,
:password => password,
:password_confirmation => password,
:permission_level => -1
})
if admin
puts "Created admin user. login: #{login}, pasword: #{password}"
else
puts "Error encountered while creating admin"
end
end
end
end
def ask message
print message
STDIN.gets.chomp
end | true |
8e057bd2f94e5984e9b0ce8f63109b7460e29328 | Ruby | m-oka-system/demo_app | /sample11.rb | UTF-8 | 447 | 3.8125 | 4 | [] | no_license | class Player
attr_accessor :name, :health_point, :attack
def initialize
@name = "主人公"
@health_point = 10
@attack = 3
end
def dead(is_dead)
if is_dead
@name + "は戦闘不能になりました"
else
@name + "は元気です"
end
end
end
p = Player.new
puts p.dead(false)
puts p.dead(true)
p.name = "ヒロイン"
puts p.dead(true)
puts p.health_point
puts p.attack
| true |
d4b3a90486dbdb0d7940b4a777e101d7bbf67871 | Ruby | mlevine1708/oo-tic-tac-toe-online-web-sp-000 | /lib/tic_tac_toe.rb | UTF-8 | 1,579 | 3.78125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class TicTacToe
attr_accessor :board
def initialize
@board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
end
end
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,4,8],
[2,4,6],
[0,3,6],
[1,4,7],
[2,5,8]
]
def play
while !over?
turn
end
if won?
puts "Congratulations #{winner}!"
elsif draw?
puts "Cats Game!"
end
end
def display_board
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts '-----------'
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts '-----------'
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def valid_move?
index.between?(0, 8) && !position_taken?(input.to_i-1)
end
def won?
WIN_COMBINATIONS.detect do |combo|
board[combo[0]] == board[combo[1]] &&
board[combo[1]] == board[combo[2]] &&
position_taken?(board, combo[0])
end
end
def full?
board.all? { |token| token == 'X' || token == 'O' }
end
def draw?
!won?(board) && full?(board)
end
def over?
won? || draw?
end
def input_to_index(user_input)
user_input.to_i - 1
end
def turn
display_board
puts 'Please enter 1-9:'
user_input = gets.strip
if !valid_move?(input)
turn
end
move(input, current_player)
display_board
end
def position_taken?
board[index] == 'X' || board[index] == 'O'
end
def current_player
turn_count(board).even? ? 'X' : 'O'
end
def turn_count
board.count { |token| token == 'X' || token == 'O' }
end
def move(location, token)
@board[location.to_i-1] = token
end
def winner
if winning_combo = won?(board)
board[winning_combo.first]
end
end
end
| true |
56e23e900f7015c64a989d7104836b15a944055a | Ruby | oknashar/Problem-Solving | /CodeFights Challenges/stringsCrossover.rb | UTF-8 | 339 | 2.71875 | 3 | [] | no_license | #link: https://app.codesignal.com/challenge/hbQgkZtYLXHpg7nKR
def stringsCrossover(a, r)
c = 0
for i in 0..a.size-1
for j in i+1..a.size-1
ok = true
for k in 0..r.size-1
ok &&= r[k] == a[i][k] || r[k] == a[j][k]
end
c += 1 if ok
end
end
c
end
| true |
b62e3f7de4c3346f083084e09d58034458bc0ca5 | Ruby | lebrancconvas/Ruby-Lab | /range.rb | UTF-8 | 233 | 3.1875 | 3 | [] | no_license | #(<num1>..<num2>) is mean from range num1 to num2 (include)
include_array = (1..10).to_a
puts include_array
puts ""
#(<num1>...<num2>) is mean from range num1 to num2 - 1 (exclude)
exclude_array = (1...10).to_a
puts exclude_array
| true |
e7c356218b9410e84369f7561613e30511b1d018 | Ruby | wachr/Project-Euler-Programs | /euler-prob-004.rb | UTF-8 | 788 | 3.796875 | 4 | [] | no_license | #! euler-prob-004.rb
# euler-prob-04.rb
# author: Ray Wach
# date: 2014-10-02
# info: Program to solve Project Euler problem 4 in Ruby.
def palindrome?(arg)
if (arg.to_s.reverse == arg.to_s)
true
else
false
end
end
num_digits = ARGV[0].to_i
if (ARGV[0].nil?)
puts "Usage: #{$0} <num_digits>"
exit(1)
end
ceiling = ('9' * num_digits).to_i
floor = ('1' + '0' * (num_digits - 1)).to_i
puts "Searching for the largest palindrome product in [#{floor},#{ceiling}]."
left = right = ceiling
max_pal = 0
max_pal = left * right if (palindrome?(left * right))
until (left < floor) do
if (max_pal < left * right) && (palindrome?(left * right))
max_pal = left * right
end
right -= 1
if (right < floor)
left -= 1
right = ceiling
end
end
puts "#{max_pal}"
| true |
adb5dfa50e8d7f370db9b0b4a1dc52a456f1f7de | Ruby | fantasygame/watcher | /app/models/tv.rb | UTF-8 | 1,365 | 2.53125 | 3 | [] | no_license | class Tv < Resource
attr_reader :seasons_summary
def self.find(id)
loop do
begin
return build Tmdb::TV.detail(id)
rescue => e
raise e unless e.message =~ /over the allowed limit/
end
end
end
def seasons(sort: :asc)
seasons_since(0, nil, sort: sort)
end
def seasons_since(season_number, limit = nil, sort: :asc)
season_numbers_since = season_numbers.reject { |number| number < season_number }
season_numbers_since = season_numbers_since[0..(limit - 1)] if limit.present?
seasons = season_numbers_since.map { |number| Season.find(id, number) }
seasons.sort_by! { |e| - e.season_number } if sort == :desc
seasons
end
def episodes
episodes = []
seasons.each do |season|
episodes += season.episodes
end
episodes
end
def year
return unless first_air_date.present?
first_date = first_air_date[0..3]
last_date = last_air_date[0..3]
first_date != last_date ? "(#{first_date} - #{last_date})" : "(#{first_date})"
end
def last_season
Season.find(id, seasons_summary.last["season_number"])
end
def last_episode
last_season.episodes.last
end
def season_numbers
seasons_summary.map { |season_summary| season_summary["season_number"] }
end
def seasons=(seasons_summary)
@seasons_summary = seasons_summary
end
end
| true |
e338dd604960b14a02e07dd3a9285b575c76902e | Ruby | alphagov/optic14n | /lib/uri/bluri.rb | UTF-8 | 3,622 | 2.6875 | 3 | [
"MIT"
] | permissive | module URI
##
# A URI class with a bit extra for canonicalising query strings
#
class BLURI < URI::HTTP
PATH_ESCAPE_MAPPINGS = {
"[" => "%5b",
"]" => "%5d",
"," => "%2c",
'"' => "%22",
"'" => "%27",
"|" => "%7c",
"!" => "%21",
"£" => "%c2%a3",
}.freeze
PATH_UNESCAPE_MAPPINGS = {
"%7e" => "~",
"%21" => "!",
}.freeze
REQUIRE_REGEX_ESCAPE = [".", "|", "(", ")", "[", "]", "{", "}", "+", " ^", "$", "*", "?"] & PATH_ESCAPE_MAPPINGS.keys
extend Forwardable
def_delegators :@uri, :scheme, :path, :host, :host=, :query, :fragment, :to_s
def initialize(uri_str) # rubocop:disable Lint/MissingSuper - This class seems a reimplementation rather than an ancestor
@uri = ::Addressable::URI.parse(uri_str)
raise URI::InvalidURIError, "'#{uri_str}' not a valid URI" unless valid_uri?
end
def valid_uri?
return unless @uri
%w[http https mailto].include?(@uri.scheme)
end
def query_hash
@query_hash ||= CGI.parse(query || "").tap do |query_hash|
# By default, CGI::parse produces lots of arrays. Usually they have a single element
# in them. That's correct but not terribly usable. Fix it here.
query_hash.each_pair { |k, v| query_hash[k] = v[0] if v.length == 1 }
query_hash.extend QueryHash
end
end
def query_hash=(value)
@query_hash = value
@uri.query = @query_hash.to_s == "" ? nil : @query_hash.to_s
end
def query=(query_str)
@query_hash = nil
@uri.query = query_str == "" ? nil : query_str
end
def self.parse(uri_str)
# Deal with known URI spec breaks - leading/trailing spaces and unencoded entities
if uri_str.is_a? String
uri_str = uri_str.strip.downcase.gsub(" ", "%20")
uri_str.gsub!("&", "%26") if uri_str =~ /^mailto:.*&.*/
end
BLURI.new(uri_str)
end
def has_query?
%w[http https].include?(@uri.scheme) && query
end
def canonicalize!(options = {})
@uri.scheme = "http" if @uri.scheme == "https"
@uri.path = @uri.path.sub(/\/*$/, "") if @uri.path =~ /^*\/$/
@uri.path.gsub!(BLURI.path_escape_char_regex, PATH_ESCAPE_MAPPINGS)
@uri.path.gsub!(BLURI.path_unescape_code_regex, PATH_UNESCAPE_MAPPINGS)
canonicalize_query!(options)
@uri.fragment = nil
self
end
def canonicalize_query!(options)
allow_all = (options[:allow_query] == :all)
allowed_keys = [options[:allow_query]].flatten.compact.map(&:to_s) unless allow_all
query_hash.keep_if do |k, _|
allow_all || allowed_keys.include?(k.to_s)
end
self.query_hash = QueryHash[query_hash.sort_by { |k, _| k }]
end
##
# Generate a regex which matches all characters in PATH_ESCAPE_MAPPINGS
def self.path_escape_char_regex
@path_escape_char_regex ||= begin
escaped_characters_for_regex = PATH_ESCAPE_MAPPINGS.keys.map do |char|
REQUIRE_REGEX_ESCAPE.include?(char) ? "\\#{char}" : char
end
Regexp.new("[#{escaped_characters_for_regex.join}]")
end
end
##
# Generate a regex which matches all escape sequences in PATH_UNESCAPE_MAPPINGS
def self.path_unescape_code_regex
@path_unescape_code_regex ||= Regexp.new(
PATH_UNESCAPE_MAPPINGS.keys.map { |code| "(?:#{code})" }.join("|"),
)
end
end
end
module Kernel
# rubocop:disable Naming/MethodName
def BLURI(uri_str)
::URI::BLURI.parse(uri_str)
end
# rubocop:enable Naming/MethodName
module_function :BLURI
end
| true |
a0dfb8060846826e9ce5081fce748c5a5a52dc3c | Ruby | hacaravan/boris-bikes-2 | /lib/docking_station.rb | UTF-8 | 564 | 3.234375 | 3 | [] | no_license | class DockingStation
attr_reader :bikes, :capacity, :broken_bikes
DEFAULT_CAPACITY = 20
def initialize(capacity = DEFAULT_CAPACITY)
@bikes = []
@broken_bikes = []
@capacity = capacity
end
def release_bike
raise "Sorry, no bikes" if empty?
bike = bikes[-1]
bikes.delete(bike)
bike
end
def dock(bike)
raise "Sorry, station full" if full?
broken_bikes << bike if bike.working? == false
bikes << bike
end
private
def empty?
bikes.length == 0
end
def full?
bikes.length == capacity
end
end
| true |
0bc37880c71d038e0109200a875cab0bf2b2c771 | Ruby | chrisgit/yeoman-generator-sinatra-rack | /generators/app/templates/app/models/product.rb | UTF-8 | 186 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Product
attr_reader :productid, :description, :cost
def initialize(args = {})
args.each do |k,v|
instance_variable_set("@#{k}", v) unless v.nil?
end
end
end
| true |
6606b75e062183c5c1b67ff4067abdb8f5b51f47 | Ruby | CodingMBA/ls_101_lesson_6 | /twenty_one.rb | UTF-8 | 5,316 | 3.84375 | 4 | [] | no_license | SUITS = ['H', 'D', 'C', 'S']
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
GAME = 31
DEALER_STAYS = GAME - 4
def prompt(message)
puts "=> #{message}"
end
def initialize_deck
VALUES.product(SUITS).shuffle
end
def total(cards)
# cards = [['H', '3'], ['S', 'Q'], ... ]
values = cards.map { |card| card[0] }
sum = 0
values.each do |value|
if value == "A"
sum += (GAME - 10)
elsif value.to_i == 0 # J, Q, K
sum += 10
else
sum += value.to_i
end
end
# correct for Aces
values.select { |value| value == "A" }.count.times do
sum -= 10 if sum > GAME
end
sum
end
def busted?(cards)
total(cards) > GAME
end
def detect_result(dealer_hand, player_hand)
player_total = total(player_hand)
dealer_total = total(dealer_hand)
if player_total > GAME
:player_busted
elsif dealer_total > GAME
:dealer_busted
elsif player_total > dealer_total
:player
elsif dealer_total > player_total
:dealer
else
:tie
end
end
def display_result(dealer_hand, player_hand)
result = detect_result(dealer_hand, player_hand)
case result
when :player_busted
prompt "You busted. Dealer wins this round."
when :dealer_busted
prompt "Dealer busted. You win this round!"
when :player
prompt "You win this round!"
when :dealer
prompt "Dealer wins this round"
when :tie
prompt "This round is a tie."
end
end
def round_end_summary(dealer_hand, dealer_total, player_hand, player_total)
puts "\n=============="
prompt "Dealer has #{dealer_hand}, for a total of: #{dealer_total}"
prompt "Player has #{player_hand}, for a total of: #{player_total}"
puts "==============\n\n"
sleep 2
display_result(dealer_hand, player_hand)
end
def match_status(dealer_hand, dealer_score, player_hand, player_score)
winner = detect_result(dealer_hand, player_hand)
if winner == :dealer or winner == :player_busted
dealer_score += 1
elsif winner == :player or winner == :dealer_busted
player_score += 1
end
prompt "Dealer has #{dealer_score} wins."
prompt "Player has #{player_score} wins."
return dealer_score, player_score
end
def match_won?(dealer_score, player_score)
if dealer_score >= 5
prompt "=> Dealer wins the match. <==<=="
return true
elsif player_score >= 5
prompt "=> Player wins the match! <==<=="
return true
else
false
end
end
def play_again?
puts "-------------------------"
prompt "Press 'y' to play again or 'n' to quit."
answer = gets.chomp
answer.downcase.start_with?('y')
end
loop do # match loop
dealer_score = 0
player_score = 0
puts "Let's Play #{GAME.to_s}!!"
loop do # round loop
sleep 1
system 'clear'
deck = initialize_deck
player_hand = []
dealer_hand = []
player_total = 0
dealer_total = 0
# initial deal
2.times do
player_hand << deck.pop
dealer_hand << deck.pop
end
player_total = total(player_hand)
dealer_total = total(dealer_hand)
prompt "Dealer has #{dealer_hand[0]} and ? \n\n"
sleep 1
prompt "Your cards are #{player_hand[0]} and #{player_hand[1]}."
prompt "You have #{player_total} \n\n"
sleep 1
# player turn
loop do
player_choice = nil
loop do
prompt "Press 'h' to hit or 's' to stay."
player_choice = gets.chomp.downcase
break if ['h', 's'].include?(player_choice)
prompt "You must enter 'h' or 's'."
end
if player_choice == 'h'
player_hand << deck.pop
# prompt "You received another card."
prompt "Your cards are now: #{player_hand}"
player_total = total(player_hand)
prompt "Your total is now: #{player_total}"
end
break if player_choice == 's' || busted?(player_hand)
end
if busted?(player_hand)
round_end_summary(dealer_hand, dealer_total, player_hand, player_total)
sleep 2
dealer_score, player_score = match_status(dealer_hand, dealer_score, player_hand, player_score)
sleep 1
match_won?(dealer_score, player_score) ? break : next
else
prompt "You stayed at #{player_total}.\n\n"
end
sleep 1
# dealer turn
prompt "Dealer's turn..."
sleep 1
prompt "Dealer's cards are #{dealer_hand}."
prompt "Dealer has #{dealer_total}."
sleep 2
loop do
break if total(dealer_hand) >= DEALER_STAYS
prompt "Dealer hits."
dealer_hand << deck.pop
dealer_total = total(dealer_hand)
prompt "Dealers cards are now: #{dealer_hand}"
sleep 2
end
if busted?(dealer_hand)
round_end_summary(dealer_hand, dealer_total, player_hand, player_total)
sleep 2
dealer_score, player_score = match_status(dealer_hand, dealer_score, player_hand, player_score)
sleep 1
match_won?(dealer_score, player_score) ? break : next
else
prompt "Dealer stays at #{dealer_total}"
end
round_end_summary(dealer_hand, dealer_total, player_hand, player_total)
sleep 2
dealer_score, player_score = match_status(dealer_hand, dealer_score, player_hand, player_score)
sleep 1
break if match_won?(dealer_score, player_score)
end
break unless play_again?
end
prompt "Thank you for playing! Good bye!"
| true |
319cdcc4d4590ea6e077e9618b0784dce30eb1b7 | Ruby | rockdisco/coderbyte | /SecondGreatLow.rb | UTF-8 | 159 | 2.96875 | 3 | [] | no_license | def SecondGreatLow(arr)
arr = arr.sort.uniq
return "#{arr[0]} #{arr[0]}" if arr.length == 1
return "#{arr[1]} #{arr[-2]}"
end
SecondGreatLow(STDIN.gets)
| true |
5c97b581a927b6f313f3e8cde480c15e8816d8d6 | Ruby | averimj/backend_prework | /day_7/10_little_monkeys_test.rb | UTF-8 | 938 | 2.96875 | 3 | [] | no_license | require "minitest/autorun"
require "minitest/pride"
require "./10_little_monkeys"
class LittleMonkeysTest < Minitest::Test
def test_it_exist
little_monkeys = LittleMonkeys.new
assert_instance_of LittleMonkeys, little_monkeys
end
def test_count_down
little_monkeys = LittleMonkeys.new
expected = "3 little monkeys jumping the on the bed,
One fell off and bumped his head,
Mama called the doctor and the doctor said,
No more monkeys jumping on the bed!
2 little monkeys jumping the on the bed,
One fell off and bumped his head,
Mama called the doctor and the doctor said,
No more monkeys jumping on the bed!
1 little monkeys jumping the on the bed,
One fell off and bumped his head,
Mama called the doctor and the doctor said,
No more monkeys jumping on the bed!
Get those monkeys right to bed!"
assert_equal expected, little_monkeys.count_down(3)
end
end
| true |
1a1b05279bbf40aa365beda320d3fd495fe1f78e | Ruby | marcinwal/wealth | /app/models/user.rb | UTF-8 | 1,188 | 2.609375 | 3 | [] | no_license | require 'bcrypt'
class User
include DataMapper::Resource
has n, :peeps ,:through => Resource
has n, :comments ,:through => Resource
property :id, Serial
property :name, String
property :username, String, :unique => true, :message => "User name is already taken"
property :email, String, :unique => true, :message => "Email is already registered"
property :password_digest, Text
property :password_token, Text
property :password_token_timestamp, DateTime
attr_reader :password
attr_accessor :password_confirmation
validates_confirmation_of :password
def password=(password)
@password = password
self.password_digest = BCrypt::Password.create(password)
end
def self.authenticate_email(email, password)
user = first(:email => email)
if user && BCrypt::Password.new(user.password_digest) == password
user
else
nil
end
end
def self.authenticate_username(username, password)
user = first(:username => username)
if user && BCrypt::Password.new(user.password_digest) == password
user
else
nil
end
end
def self.generate_token
(1..64).map{('A'..'Z').to_a.sample}.join
end
end | true |
976ccf3ef7dd0a8863a24dde058efd6034ed4710 | Ruby | Dancalif/Learning-Ruby | /TA/HW_23/script_23_01.rb | UTF-8 | 667 | 3.25 | 3 | [] | no_license | # Convertion
BEGIN{
name = "Denis Umanets"
description = "Convertion without slice, using delete, reverse, chop"
puts "#################################### "
puts "Author \s\s\s\s\s : " + name
puts "Date \s\s\s\s\s\s\s\s: " + Time.now.to_s[0 .. 18]
puts ""
puts "Ruby version : " + RUBY_VERSION
puts "Script \s\s\s\s\s\s: " + __FILE__.chop.chop.chop
puts "Description \s: " + description
puts "#################################### "
puts ""
}
monthly_payment = "$1,654.55"
yearly_payment = monthly_payment.delete(',').reverse.chop.reverse.to_f * 12
puts "Yearly payment is: #{yearly_payment} dollars" | true |
3e28dbf71fbb3663dc9b5c0d0a669a956cce481c | Ruby | dangalipo/Toyrobotv2 | /lib/direction.rb | UTF-8 | 259 | 3.015625 | 3 | [] | no_license | # frozen_string_literal: true
class Direction
attr_reader :name, :move_x, :move_y
def initialize(name:, move_x:, move_y:)
self.name = name
self.move_x = move_x
self.move_y = move_y
end
private
attr_writer :name, :move_x, :move_y
end
| true |
89d6dc6b95d1796578149887adbc2190a20a04a6 | Ruby | krlenell/rails-demo-app | /tutorials/samples/ex13.rb | UTF-8 | 224 | 3.453125 | 3 | [] | no_license | first, second, third = ARGV
puts "first variable is #{first}"
puts "first second is #{second}"
puts "first third is #{third}"
puts "what is your birthday? "
birthday = $stdin.gets.chomp
puts "your birthday is #{birthday}"
| true |
9a3d7eb0ee0a209d8f80fa6eeb9b16eac2ac238f | Ruby | duxdamian/Pedro_le_scrappeur_fou | /lib/dark_trader.rb | UTF-8 | 1,537 | 2.875 | 3 | [] | no_license | require 'pry'
require 'dotenv'
require 'rubygems'
require 'nokogiri'
require 'open-uri'
# def open_website(url)
# page = Nokogiri::HTML(open(url))
# page.class # => Nokogiri::HTML::Document
# end
def open_website(url)
page = Nokogiri::HTML(open(url))
# page.class # => Nokogiri::HTML::Document
page
end
def coinmarketcap_name
currency_name_array = []
page_html = "https://coinmarketcap.com/all/views/all/"
coinmarketcap_page = Nokogiri::HTML(open(page_html))
return currency_name_array = coinmarketcap_page.xpath("//tr/td/a[contains(@class, 'currency-name-container')]/text()").map {|x| x.to_s }
end
def coinmarketcap_price (price)
currency_price_array = []
for n in 0...price.length
page_html = "https://coinmarketcap.com/all/views/all/"
coinmarketcap_page_price = Nokogiri::HTML(open(page_html))
begin
currency_price_array << coinmarketcap_page_price.xpath("//tbody/tr/td[@class='cmc-table__cell cmc-table__cell--sortable cmc-table__cell--right cmc-table__cell--sort-by__price']").to_s
currency_price_array << " "
end
end
return currency_price_array
end
puts currency_result = Hash[coinmarketcap_name.zip(coinmarketcap_price(coinmarketcap_name))]
# Victor
# crypto_name = site.xpath("//*[@class = 'cmc-tablecell cmc-tablecell--sortable cmc-tablecell--left cmc-tablecell--sort-by__symbol']/div")
# Billy
#nokogiri_xpath_coin_name = page_html.xpath("//tbody/tr/td[@class='cmc-table__cell cmc-table__cell--sortable cmc-table__cell--right cmc-table__cell--sort-by__price']")
| true |
0128f43504c6bad4039ff4a7a83e14e44dc671a9 | Ruby | GBH/letmein | /test/letmein_test.rb | UTF-8 | 7,268 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'test/unit'
require 'rails'
require 'letmein'
require 'sqlite3'
$stdout_orig = $stdout
$stdout = StringIO.new
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
ActiveRecord::Base.logger = Logger.new($stdout)
class User < ActiveRecord::Base ; end
class Admin < ActiveRecord::Base ; end
class OpenSession < LetMeIn::Session
# @model, @attribute = 'User', 'email'
def authenticate
super
end
end
class ClosedSession < LetMeIn::Session
# @model, @attribute = 'User', 'email'
def authenticate
super
errors.add :base, "You shall not pass #{user.email}"
end
end
class CustomAdminSession < LetMeIn::Session
@model = 'Admin'
# ...
end
class LetMeInTest < Test::Unit::TestCase
def setup
ActiveRecord::Base.logger
ActiveRecord::Schema.define(:version => 1) do
create_table :users do |t|
t.column :email, :string
t.column :password_hash, :string
t.column :password_salt, :string
end
create_table :admins do |t|
t.column :username, :string
t.column :pass_hash, :string
t.column :pass_salt, :string
end
end
init_default_configuration
end
def init_default_configuration
remove_session_classes
LetMeIn.configure do |c|
c.models = ['User']
c.attributes = ['email']
c.passwords = ['password_hash']
c.salts = ['password_salt']
end
LetMeIn.initialize
end
def init_custom_configuration
remove_session_classes
LetMeIn.configure do |c|
c.models = ['User', 'Admin']
c.attributes = ['email', 'username']
c.passwords = ['password_hash', 'pass_hash']
c.salts = ['password_salt', 'pass_salt']
end
LetMeIn.initialize
end
def remove_session_classes
Object.send(:remove_const, :UserSession) rescue nil
Object.send(:remove_const, :AdminSession) rescue nil
end
def teardown
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.drop_table(table)
end
remove_session_classes
end
# -- Tests ----------------------------------------------------------------
def test_default_configuration_initialization
assert_equal ['User'], LetMeIn.config.models
assert_equal ['email'], LetMeIn.config.attributes
assert_equal ['password_hash'], LetMeIn.config.passwords
assert_equal ['password_salt'], LetMeIn.config.salts
end
def test_custom_configuration_initialization
LetMeIn.configure do |c|
c.model = 'Account'
c.attribute = 'username'
c.password = 'encrypted_pass'
c.salt = 'salt'
end
assert_equal ['Account'], LetMeIn.config.models
assert_equal ['username'], LetMeIn.config.attributes
assert_equal ['encrypted_pass'], LetMeIn.config.passwords
assert_equal ['salt'], LetMeIn.config.salts
end
def test_model_integration
assert User.new.respond_to?(:password)
user = User.create!(:email => 'test@test.test', :password => 'pass')
assert_match /^.{60}$/, user.password_hash
assert_match /^.{29}$/, user.password_salt
end
def test_model_integration_custom
init_custom_configuration
assert Admin.new.respond_to?(:password)
user = Admin.create!(:username => 'test', :password => 'pass')
assert_match /^.{60}$/, user.pass_hash
assert_match /^.{29}$/, user.pass_salt
end
def test_session_initialization
assert defined?(UserSession)
session = UserSession.new(:email => 'test@test.test', :password => 'pass')
assert_equal 'test@test.test', session.login
assert_equal 'test@test.test', session.email
assert_equal 'pass', session.password
session.email = 'new_user@test.test'
assert_equal 'new_user@test.test', session.login
assert_equal 'new_user@test.test', session.email
assert_equal nil, session.object
assert_equal nil, session.user
end
def test_session_initialization_secondary
init_custom_configuration
assert defined?(AdminSession)
session = AdminSession.new(:username => 'admin', :password => 'test_pass')
assert_equal 'admin', session.login
assert_equal 'admin', session.username
assert_equal 'test_pass', session.password
session.username = 'new_admin'
assert_equal 'new_admin', session.login
assert_equal 'new_admin', session.username
assert_equal nil, session.object
assert_equal nil, session.admin
end
def test_session_authentication
user = User.create!(:email => 'test@test.test', :password => 'pass')
session = UserSession.create(:email => user.email, :password => 'pass')
assert session.errors.blank?
assert_equal user, session.object
assert_equal user, session.user
end
def test_session_authentication_custom
init_custom_configuration
admin = Admin.create!(:username => 'admin', :password => 'pass')
session = AdminSession.create(:username => admin.username, :password => 'pass')
assert session.errors.blank?
assert_equal admin, session.object
assert_equal admin, session.admin
end
def test_session_authentication_failure
user = User.create!(:email => 'test@test.test', :password => 'pass')
session = UserSession.create(:email => user.email, :password => 'bad_pass')
assert session.errors.present?
assert_equal 'Failed to authenticate', session.errors[:base].first
assert_equal nil, session.object
assert_equal nil, session.user
end
def test_session_authentication_exception
user = User.create!(:email => 'test@test.test', :password => 'pass')
session = UserSession.new(:email => user.email, :password => 'bad_pass')
begin
session.save!
rescue LetMeIn::Error => e
assert_equal 'Failed to authenticate', e.to_s
end
assert_equal nil, session.object
end
def test_session_authentication_on_blank_object
user = User.create!(:email => 'test@test.test')
session = UserSession.new(:email => 'test@test.test', :password => 'pass')
begin
session.save!
rescue LetMeIn::Error => e
assert_equal 'Failed to authenticate', e.to_s
end
assert_equal nil, session.object
end
def test_custom_open_session
user = User.create!(:email => 'test@test.test', :password => 'pass')
session = OpenSession.new(:email => 'test@test.test', :password => 'bad_pass')
assert session.invalid?
assert_equal 'Failed to authenticate', session.errors[:base].first
session = OpenSession.new(:email => 'test@test.test', :password => 'pass')
assert session.valid?
assert_equal user, session.user
end
def test_custom_closed_session
user = User.create!(:email => 'test@test.test', :password => 'pass')
session = ClosedSession.new(:email => 'test@test.test', :password => 'pass')
assert session.invalid?
assert_equal 'You shall not pass test@test.test', session.errors[:base].first
end
def test_custom_admin_session
init_custom_configuration
admin = Admin.create!(:username => 'admin', :password => 'pass')
session = CustomAdminSession.new(:username => 'admin', :password => 'pass')
assert session.valid?
assert_equal admin, session.admin
end
end | true |
3db507e9213b41b1fc59d15b347568e5c382ecc9 | Ruby | ykpythemind/github-deploy-hook | /hook.rb | UTF-8 | 1,832 | 2.5625 | 3 | [
"MIT"
] | permissive |
require "sinatra"
SCRIPT_FILE = (ENV["SCRIPT_FILE"] || "test.sh").freeze
SCRIPT_DIR = 'scripts'.freeze
if ENV["SCRIPT_PATH"]
SCRIPT_PATH = ENV["SCRIPT_PATH"]
else
SCRIPT_PATH = File.expand_path("../#{SCRIPT_DIR}/#{SCRIPT_FILE}", __FILE__)
end
abort "SCRIPT_FILE not found" unless File.exist? SCRIPT_PATH
LOG_PATH = ENV["LOG_PATH"]
SECRET = ENV["SECRET"]
post '/' do
if request.env["HTTP_X_GITHUB_EVENT"] != "push"
halt 200, "Event is not push"
end
request.body.rewind
payload = request.body.read
verify_signature payload
hash = JSON.parse payload
if hash["ref"] != "refs/heads/master"
halt 200, "Not master branch"
end
if skip_script?(hash)
halt 200, "Skipped."
end
spawn "#{SCRIPT_PATH}"
body "script executed"
end
get '/' do
body "alive"
end
get '/log' do
if !LOG_PATH || !File.exist?(LOG_PATH)
halt 404, "Not found log file"
end
# tail したいので手抜き
lines = `tail -n 100 #{LOG_PATH}`.chomp.split("\n")
body html(
["<h1>tailing log</h1><ul>",
*lines.map { |line| "<li>#{line}</li>" },
"</ul>"].join)
end
def skip_script?(payload)
commits = payload["commits"]
return false if commits.empty?
commits.any? do |commit|
commit["message"].include? "[ci skip]"
end
end
def html(body)
"""
<!DOCTYPE html>
<html lang=\"en\">
<head>
<meta charset=\"UTF-8\">
<title></title>
</head>
<body>
#{body}
</body>
</html>
"""
end
def verify_signature(payload_body)
# https://developer.github.com/webhooks/securing/#validating-payloads-from-github
return unless SECRET
signature = 'sha1=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha1'), SECRET, payload_body)
return halt 500, "Signatures didn't match!" unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE'])
end
| true |
4d6dba0636f2aab965e314ce1f74c17e8fa90ba2 | Ruby | alproddev/portable_light | /vendor/plugins/table_helper/test/unit/header_test.rb | UTF-8 | 7,023 | 2.6875 | 3 | [
"MIT"
] | permissive | require File.expand_path(File.dirname(__FILE__) + '/../test_helper')
class HeaderByDefaultTest < Test::Unit::TestCase
def setup
@table = TableHelper::CollectionTable.new([])
@header = TableHelper::Header.new(@table)
end
def test_should_hide_when_empty
assert @header.hide_when_empty
end
def test_should_have_no_columns
expected = {}
assert_equal expected, @header.columns
end
def test_should_have_no_column_names
assert_equal [], @header.column_names
end
def test_should_be_empty
assert @header.empty?
end
def test_should_have_a_row
assert_not_nil @header.row
end
def test_should_have_a_table
assert_equal @table, @header.table
end
end
class HeaderWithColumnDetectionTest < Test::Unit::TestCase
class Post
def self.column_names
['title', 'author_name']
end
end
def test_should_have_columns_if_class_has_column_names
table = TableHelper::CollectionTable.new([], Post)
header = TableHelper::Header.new(table)
assert_equal ['title', 'author_name'], header.column_names
end
def test_should_not_have_columns_if_class_has_no_column_names
table = TableHelper::CollectionTable.new([], Array)
header = TableHelper::Header.new(table)
assert header.columns.empty?
end
end
class HeaderWithAutomaticColumnsTest < Test::Unit::TestCase
class Post
def self.column_names
['title', 'author_name']
end
end
def setup
table = TableHelper::CollectionTable.new([Post.new], Post)
@header = TableHelper::Header.new(table)
end
def test_should_use_titleized_name_for_content
assert_equal 'Title', @header.columns['title'].content
assert_equal 'Author Name', @header.columns['author_name'].content
end
def test_should_namespace_html_classes
assert_equal 'post-title', @header.columns['title'][:class]
assert_equal 'post-author_name', @header.columns['author_name'][:class]
end
def test_should_not_be_empty
assert !@header.empty?
end
def test_should_build_html
expected = <<-end_str
<thead>
<tr>
<th class="post-title" scope="col">Title</th>
<th class="post-author_name" scope="col">Author Name</th>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
def test_should_clear_existing_columns_when_first_column_is_created
cell = @header.column :created_on
assert_raise(NoMethodError) {@header.builder.title}
assert_raise(NoMethodError) {@header.builder.author_name}
expected = {'created_on' => cell}
assert_equal expected, @header.columns
end
end
class HeaderWithCustomColumnsTest < Test::Unit::TestCase
def setup
table = TableHelper::CollectionTable.new([])
@header = TableHelper::Header.new(table)
@title = @header.column :title
end
def test_should_set_scope
assert_equal 'col', @title[:scope]
end
def test_should_use_name_for_default_content
assert_equal 'Title', @title.content
end
def test_should_allow_content_to_be_customized
title = @header.column :title, 'The Title'
assert_equal 'The Title', title.content
end
def test_should_allow_html_options_to_be_customized
title = @header.column :title, :class => 'pretty'
assert_equal 'pretty title', title[:class]
end
def test_should_not_be_empty
assert !@header.empty?
end
end
class HeaderWithMultipleColumnsTest < Test::Unit::TestCase
def setup
table = TableHelper::CollectionTable.new([])
@header = TableHelper::Header.new(table)
@title, @author_name = @header.column :title, :author_name, :class => 'pretty'
end
def test_should_use_default_content_for_each
assert_equal 'Title', @title.content
assert_equal 'Author Name', @author_name.content
end
def test_should_share_html_options
assert_equal 'pretty title', @title[:class]
end
end
class HeaderWithEmptyCollectionTest < Test::Unit::TestCase
def setup
table = TableHelper::CollectionTable.new([])
@header = TableHelper::Header.new(table)
end
def test_should_not_display_if_hide_when_empty
@header.hide_when_empty = true
expected = <<-end_str
<thead style="display: none;">
<tr>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
def test_should_display_if_not_hide_when_empty
@header.hide_when_empty = false
expected = <<-end_str
<thead>
<tr>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
end
class HeaderWithCollectionTest < Test::Unit::TestCase
def setup
table = TableHelper::CollectionTable.new([Object.new])
@header = TableHelper::Header.new(table)
@header.column :title, :author_name
end
def test_should_display_if_hide_when_empty
@header.hide_when_empty = true
expected = <<-end_str
<thead>
<tr>
<th class="object-title" scope="col">Title</th>
<th class="object-author_name" scope="col">Author Name</th>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
def test_should_display_if_not_hide_when_empty
@header.hide_when_empty = false
expected = <<-end_str
<thead>
<tr>
<th class="object-title" scope="col">Title</th>
<th class="object-author_name" scope="col">Author Name</th>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
end
class HeaderWithCustomHtmlOptionsTest < Test::Unit::TestCase
def setup
table = TableHelper::CollectionTable.new([Object.new])
@header = TableHelper::Header.new(table)
@header.column :title
end
def test_should_include_html_options
@header[:class] = 'pretty'
expected = <<-end_str
<thead class="pretty">
<tr>
<th class="object-title" scope="col">Title</th>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
def test_should_include_html_options_for_header_row
@header.row[:class] = 'pretty'
expected = <<-end_str
<thead>
<tr class="pretty">
<th class="object-title" scope="col">Title</th>
</tr>
</thead>
end_str
assert_html_equal expected, @header.html
end
end
class HeaderWithModelsTest < ActiveRecord::TestCase
def setup
Person.create(:first_name => 'John', :last_name => 'Smith')
end
def test_should_include_all_columns_if_not_selecting_columns
table = TableHelper::CollectionTable.new(Person.all)
@header = TableHelper::Header.new(table)
assert_equal %w(first_name id last_name), @header.column_names.sort
end
def test_should_only_include_selected_columns_if_specified_in_query
table = TableHelper::CollectionTable.new(Person.all(:select => 'first_name'))
@header = TableHelper::Header.new(table)
assert_equal %w(first_name), @header.column_names.sort
end
end
| true |
1f3abed04fec9717b56111cf67d26eea3d0e1afc | Ruby | tundal45/project_euler | /2_fib_even_sum.rb | UTF-8 | 748 | 4.0625 | 4 | [] | no_license | # Project Euler
# Problem # 2
#
# Description: 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, ...
# Find the sum of all the even-valued terms in the sequence which
# do not exceed four million.
#
# URL: http://projecteuler.net/index.php?section=problems&id=2
def fib(i,j)
i + j
end
max = 40_00_000
seq = [1, 2]
sum = 0
seq << fib(seq[-2],seq [-1]) while (seq[-2] < max && seq [-1] < max)
seq.reject { |item| item % 2 != 0 }.each { |evens| sum += evens}
puts "The sum of all even-valued terms in the sequence which do not exceed #{max} is #{sum}"
| true |
57552cce87c84b8bb07df725d56931f421265795 | Ruby | instructure/ims-lti | /spec/ims/lti/models/parameter_spec.rb | UTF-8 | 4,406 | 2.53125 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
module IMS::LTI::Models
describe Parameter do
describe '#fixed?' do
it 'returns true if the value is fixed' do
subject.fixed = 'my_fixed_value'
expect(subject.fixed?).to eq true
end
it 'returns false if the value is variable' do
subject.variable = 'my_variable'
expect(subject.fixed?).to eq false
end
end
describe '#self.process_params' do
it 'replaces variable params' do
param = described_class.new(name: 'param1', variable: 'my.variable.value')
p = described_class.process_params(param, {'my.variable.value' => 123})
expect(p['param1']).to eq 123
end
it "doesn't replace fixed params" do
param = described_class.new(name: 'param1', fixed: 'my fixed value')
p = described_class.process_params(param, {'my.variable.value' => 123})
expect(p['param1']).to eq 'my fixed value'
end
it 'handles fixed and variable params' do
params = [described_class.new(name: 'param1', fixed: 'my fixed value'),
described_class.new(name: 'param2', variable: 'my.variable.value')]
p = described_class.process_params(params, {'my.variable.value' => 123})
expect(p['param1']).to eq 'my fixed value'
expect(p['param2']).to eq 123
end
it 'handles lambdas for variables' do
param = described_class.new(name: 'param1', variable: 'my.variable.value')
p = described_class.process_params(param, {'my.variable.value' => -> { 123 }})
expect(p['param1']).to eq 123
end
it 'handles procs for variables' do
param = described_class.new(name: 'param1', variable: 'my.variable.value')
p = described_class.process_params(param, {'my.variable.value' => Proc.new { 123 } } )
expect(p['param1']).to eq 123
end
it 'returns the variable with a $ prepended if it ca not be expanded' do
param = described_class.new(name: 'param1', variable: 'my.variable.value')
p = described_class.process_params(param, {})
expect(p['param1']).to eq '$my.variable.value'
end
end
describe '#==' do
it 'is equal when both are fixed and the names and fixed values are the same' do
subject.name = 'my_name'
subject.fixed = 'my_fixed_value'
param = described_class.new(name: subject.name, fixed: subject.fixed)
expect(subject).to eq param
end
it 'is equal when both are variable and the names and variable values are the same' do
subject.name = 'my_name'
subject.variable = 'my_variable_value'
param = described_class.new(name: subject.name, variable: subject.variable)
expect(subject).to eq param
end
it 'is not equal when one is fixed and the other variable' do
subject.name = 'my_name'
subject.variable = 'my_variable_value'
param = described_class.new(name: subject.name, fixed: 'my_fixed_value')
expect(subject).to_not eq param
end
it 'is not equal when both are fixed, the names are the same, and fixed values are different' do
subject.name = 'my_name'
subject.fixed = 'my_fixed_value'
param = described_class.new(name: subject.name, fixed: 'my_other_fixed_value')
expect(subject).to_not eq param
end
it 'is not equal when both are fixed, the names are different, and fixed values are the same' do
subject.name = 'my_name'
subject.fixed = 'my_fixed_value'
param = described_class.new(name: 'my_other_name', fixed: subject.fixed)
expect(subject).to_not eq param
end
it 'is not equal when both are variable, the names are the same, and variable values are different' do
subject.name = 'my_name'
subject.variable = 'my_variable_value'
param = described_class.new(name: subject.name, fixed: 'my_other_variable_value')
expect(subject).to_not eq param
end
it 'is not equal when both are variable, the names are different, and variable values are the same' do
subject.name = 'my_name'
subject.variable = 'my_varaible_value'
param = described_class.new(name: 'my_other_name', fixed: subject.variable)
expect(subject).to_not eq param
end
end
end
end | true |
42427b422692c777ab64f8550344cb891e4b9fad | Ruby | Koda-thp/RPG_Game | /lib/game.rb | UTF-8 | 5,636 | 3.78125 | 4 | [] | no_license | #SPECIFICATIONS Class game.rb
#Voici ce que tu dois faire dans la classe Game (80 % du travail consiste à rapatrier
#du code depuis app_2.rb) :
#Crée la classe Game qui aura 2 attr_accessor : un @human_player de type HumanPlayer
#et un array @enemies qui contiendra des Player.
# ¿WHY?
# Cette Classe doit gerer les menu du jeu, ainsi que les processus de combat
class Game
attr_accessor :human_player, :enemies_in_sight, :players_left
#Un objet Game s'initialise ainsi : my_game = Game.new("Wolverine"). Il crée automatiquement 4 Player qu'il met dans @enemies et un HumanPlayer portant (dans cet exemple) le nom "Wolverine".
def initialize (name,nb)
@players_left = nb
@human_player = HumanPlayer.new(name)
@enemies_in_sight = []
5.times do |n|
@enemies_in_sight << Player.new("Enemy #{n}")
end
@players_left
end
#Cette méthode permet d'éliminer un adversaire tué.
def kill_player(player)
@enemies_in_sight.reject! {|k| k.name == player.name}
@players_left-=1
end
#Écris une méthode is_still_ongoing? qui retourne true si le jeu est toujours en cours et false
#sinon. Le jeu continue tant que le @human_player a encore des points de vie et qu'il reste des
#Player à combattre dans l’array @enemies.
def is_still_ongoing?
return false if @human_player.life_points <= 0
return false if ((@enemies_in_sight.select {|enemy| enemy.life_points > 0}.size == 0) && @players_left==0)
return true
end
#Écris une méthode show_players qui va afficher 1) l'état du joueur humain et 2) le nombre de
#joueurs "bots" restant
def show_players
puts "#{@human_player.name} has #{@human_player.life_points} HP and a lvl #{@human_player.weapon_level} weapon"
puts "There is still #{@enemies_in_sight.size} remaining enemies in sight and #{@players_left} over all"
end
#Écris une méthode menu qui va afficher le menu de choix (juste l'afficher, pas plus). On a les
#mêmes choix que dans la version 2.0 à la seule différence qu'il y a plus de 2 ennemis à combattre
#et que si un ennemi est mort, on ne doit plus proposer de l'attaquer.
def menu
puts "What to do ?"
puts "a - Find a better weapon ?"
puts "s - Find a health pack ?"
puts "Attack a player in sight :"
for n in 0..@enemies_in_sight.size-1 do
if(@enemies_in_sight[n].life_points >0) then
puts "#{n} - #{@enemies_in_sight[n].name} who has #{@enemies_in_sight[n].life_points} HP left"
end
end
end
#Écris une méthode menu_choice qui prend en entrée un string. Cette méthode va permettre de faire
#réagir le jeu en fonction du choix, dans le menu, de l'utilisateur. Par exemple, si l'entrée est
#{}"a", le @human_player doit aller chercher une arme. Si l'entrée est "0", on le fait attaquer
#l'ennemi présenté au choix "0", etc. Pense à faire appel, dans cette méthode, à la méthode kill_player
#si jamais un Player est tué par le joueur humain !
def menu_choice (str)
case str
when "a"
@human_player.search_weapon
when "s"
@human_player.search_health_pack
else
if (str.to_i.between?(0,@enemies_in_sight.size-1)) then
@human_player.attacks(@enemies_in_sight[str.to_i])
if @enemies_in_sight[str.to_i].life_points <=0 then
kill_player(@enemies_in_sight[str.to_i])
end
end
end
end
#Écris une méthode enemies_attack qui va faire riposter tous les ennemis vivants. Ils vont attaquer à
#tour de rôle le joueur humain.
def enemies_attack
puts "#{@human_player.name} is under attack !!"
@enemies_in_sight.each {|enemy| enemy.attacks(@human_player) if is_still_ongoing?}
end
#Écris une méthode end qui va effectuer l'affichage de fin de jeu. Tu sais, la partie "le jeu est fini"
#puis "Bravo..." ou "Loser..."
def game_end
puts "The game is over"
if(@human_player.life_points > 0) && (@enemies_in_sight.size == 0)
puts "Congratulation, you Won !!!"
else
puts "You were defeated in battle, what a looser !"
end
end
#Crée une méthode new_players_in_sight qui va avoir pour rôle de rajouter des ennemis en vue.
#Voici les règles de fonctionnement de cette méthode :
#Si tous les joueurs du jeu sont déjà "en vue", on ne doit pas en rajouter. Dans ce cas, cela
#signifie que le nombre d'objets Player dans @enemies_in_sight est égal à l'integer @players_left.
#Affiche alors un message d'info du type "Tous les joueurs sont déjà en vue".
#La méthode va lancer un dé à 6 faces et va réagir en fonction de ce résultat aléatoire :
#Si le dé vaut 1, aucun nouveau joueur adverse n'arrive (afficher un message informant l'utilisateur).
#Si le dé vaut entre 2 et 4 inclus, un nouvel adversaire arrive en vue. Il faut alors créer un Player
#avec un nom aléatoire du genre "joueur_1234" ou "joueur_6938" (ou ce que tu veux) et injecter ce Player
#dans le array @enemies_in_sight . Affiche un message informant l'utilisateur de ce qui se passe.
#Si le dé vaut 5 ou 6, cette fois c'est 2 nouveaux adversaires qui arrivent en vue. De même qu'au-dessus,
#il faut les créer et les rajouter au jeu. Rajoute toujours un message informant l'utilisateur.
def new_players_in_sight
if @players_left == @enemies_in_sight.size
puts "All enemies are already in sight"
else
nb_enemy = rand(1..6)
if(nb_enemy < 3)
puts "No new enemy appear this round"
elsif nb_enemy < 5
puts "A new enemy appear !!"
@enemies_in_sight << Player.new("Enemy #{enemies_in_sight.size}")
else
puts "Two new enemies appear"
2.times do |n|
@enemies_in_sight << Player.new("Enemy #{enemies_in_sight.size+n}")
end
end
end
end
end
| true |
1b98983a9920a0c17b7935dd294bd77c763350ff | Ruby | nstory/boston_public_records | /lib/tocsv.rb | UTF-8 | 617 | 2.703125 | 3 | [
"MIT"
] | permissive | require "csv"
require "logger"
require "pry"
require_relative "./page.rb"
$logger = Logger.new(STDERR)
def to_text(file)
`pdftotext -layout "#{file}" -`
end
def tocsv(filename, field_count, row_regexp)
text = to_text(filename)
pages = Page.from_text(text)
pages.each do |page|
rows = page.extract(field_count, row_regexp)
$logger.warn "no rows found on page #{page.page_num}" if rows.empty?
rows.each { |r| puts r.to_csv }
end
end
filename = ARGV.fetch(0)
field_count = ENV.fetch('FIELD_COUNT').to_i
row_regexp = Regexp.new(ENV.fetch('ROW_REGEXP'))
tocsv(filename, field_count, row_regexp)
| true |
b024971f7f4cd30e082e3571c02cb608de6d2d2b | Ruby | HouseTrip/guignol | /lib/guignol/commands/base.rb | UTF-8 | 1,677 | 2.59375 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | require 'thor'
require 'pathname'
require 'parallel'
require 'guignol'
require 'guignol/configuration'
require 'guignol/models/instance'
require 'core_ext/array/collect_key'
module Guignol::Commands
class Base
def initialize(patterns, options = {})
@configs = select_configs(patterns)
@options = options
end
# Run the block for each server in +configs+ (in parallel).
def run
before_run(@configs, @options) or return
results = {}
Parallel.each(@configs, parallel_options) do |name,config|
instance = Guignol::Models::Instance.new(name, config)
results[name] = run_on_server(instance, @options)
end
after_run(results, @options)
end
protected
# Override in subclasses
def before_run(configs, options) ; true ; end
# Override in subclasses
def after_run(data, options) ; true ; end
def shell
Guignol::Shell.shared_shell
end
def synchronize
(@mutex ||= Mutex.new).synchronize do
yield
end
end
private
def parallel_options
if RUBY_VERSION =~ /1\.9\.3/
# 1.9.3 has bugs with Excon / SSL connections
# work in 1.8.7, 1.9.2, fixed in 2.0.0+
{ :in_threads => 0 }
else
{ :in_threads => @configs.size }
end
end
# Put all the servers matching one of the +names+ in +configs+.
def select_configs(patterns)
patterns = patterns.map { |pattern|
pattern.kind_of?(String) ? Regexp.new(pattern) : pattern
}
Guignol.configuration.delete_if { |name,config|
patterns.none? { |pattern| name.to_s =~ pattern }
}
end
end
end
| true |
954dfd6c12c21c3d7c310a83793ef3d5186d754d | Ruby | MathieuGilbert/litecoin-cracker | /word.rb | UTF-8 | 1,835 | 3.859375 | 4 | [] | no_license | class Word
SUBS = {
'a' => ['@'],
'e' => ['3'],
'g' => ['9'],
'h' => ['#'],
'i' => ['1', '!'],
'l' => ['1', '!'],
'o' => ['0'],
'r' => ['2'],
's' => ['$'],
't' => ['7']
}.freeze
attr_accessor :word_array
def initialize(the_word)
self.word_array = arrayify_letters(the_word)
expand_word
end
def explode
split(word_array.first)
self.word_array.map { |word| word.join '' }
end
private
def expand_word
add_case_options
add_substitution_options
end
# For each word in word_array:
# remove the word from word_array
# pass word into function
# function adds split words to word_array
# word = [ ["c", "C"], ["a", "@"], ["k"], ["e", "E", "3"] ]
def split(word, start_index = 0)
return if word.flatten.length == word.length
self.word_array.delete word
word.each_with_index do |letters, index|
next if index < start_index
next if letters.length == 1
letters.each do |letter|
a = []
i = 0
while i < index do
a << word[i]
i += 1
end
b = []
i = index + 1
while i < word.length do
b << word[i]
i += 1
end
split_word = a + [[letter]] + b
self.word_array << split_word
split(split_word, index)
end
end
end
def arrayify_letters(word)
[
word.split('').map { |letter| [letter] }
]
end
def add_case_options
self.word_array.first.first << self.word_array.first.first.first.upcase
self.word_array.first.last << self.word_array.first.last.first.upcase
end
def add_substitution_options
self.word_array.first.each do |letters|
if values = SUBS[letters.first]
values.each { |value| letters << value }
end
end
end
end
| true |
7054ecd954427b3b7cea6ba4421e6feea42f890e | Ruby | mare-imbrium/umbra | /lib/umbra/table.rb | UTF-8 | 8,837 | 2.671875 | 3 | [
"MIT"
] | permissive | # ----------------------------------------------------------------------------- #
# File: table.rb
# Description: widget for tabular data
# Author: j kepler http://github.com/mare-imbrium/umbra/
# Date: 2018-05-06 - 09:56
# License: MIT
# Last update: 2018-06-03 14:43
# ----------------------------------------------------------------------------- #
# table.rb Copyright (C) 2018 j kepler
=begin
## --------- Todo section ---------------
## - TODO paint lines as column separators. issue is panning.
## - TODO starting visual column (required when scrolling)
## - DONE change a value value_at(x,y, value) ; << ; delete_at
## - TODO change column width interactively, hide column , move column
## - TODO maybe even column_color(n, color_pair, attr)
## - TODO sort on column/s.
## - TODO selection will have to be added. maybe we should have extended listbox after all. Or made multiline selectable.
## - DONE how to format the header
## - DONE formatting rows
## - DONE if we want to color specific columns based on values then I think we have to format (render) the row at the last
## moment in print_row and not in advance
## - NOTE: we are setting the data in tabular, not list. So calling list() will give nil until a render has happened.
## callers will have to use data() instead of list() which is not consistent.
## - NOTE: current_index in this object refers to index including header and separator. It is not the offset in the data array.
## For that we need to adjust with @data_offset.
=end
require 'forwardable'
require 'umbra/tabular'
require 'umbra/multiline'
module Umbra
##
## A table of columnar data.
## This uses Tabular as a table model and extends Multiline.
#
class Table < Multiline
extend Forwardable
## tabular is the data model for Table.
## It may be passed in in the constructor, or else is created when columns and data are passed in.
attr_accessor :tabular
## color pair and attribute for header row
attr_accessor :header_color_pair, :header_attr
attr_accessor :rendered ## boolean, if data has changed, we need to re-render
## Create a Table object passing either a Tabular object or columns and list
## e.g. Table.new tabular: tabular
## Table.new columns: cols, list: mylist
##
def initialize config={}, &block
if config.key? :tabular
@tabular = config.delete(:tabular)
else
cols = config.delete(:columns)
data = config.delete(:list)
@tabular = Tabular.new cols
if data
@tabular.data = data
end
end
@rendered = nil
super
bind_key(?w, "next column") { self.next_column }
bind_key(?b, "prev column") { self.prev_column }
bind_key(KEY_RETURN, :fire_action_event)
## NOTE: a tabular object should be existing at this point.
end
## returns the raw data as array of arrays in tabular
def data
@tabular.list
end
def data=(list)
@rendered = false
@tabular.data = list
@repaint_required = true
self.focusable = true
@pstart = @current_index = 0
@pcol = 0
#$log.debug " before table data= CHANGED "
#fire_handler(:CHANGED, self) ## added 2018-05-08 -
end
## render the two-dimensional array of data as an array of Strings.
## Calculates data_offset which is the row offset from which data starts.
def render
@data_offset = 0
@data_offset +=1 if @tabular.use_separator
@data_offset +=1 if @tabular.columns
self.list = @tabular.render
end
## paint the table
def repaint
render if !@rendered
super
@rendered = true
end
## Specify how to print the header and separator.
## index can be 0 or 1
## returns an array of color_pair and attribute
def color_of_header_row index, state
arr = [ @header_color_pair || CP_MAGENTA, @header_attr || REVERSE ]
return arr if index == 0
[ arr[0], NORMAL ]
end
## Specify how the data rows are to be coloured.
## Override this to have customised row coloring.
## @return array of color_pair and attrib.
def color_of_data_row index, state, data_index
color_of_row(index, state) ## calling superclass here
end
## Print the row which could be header or data
## @param index [Integer] - index of list, starting with header and separator
def print_row(win, row, col, str, index, state)
if index <= @data_offset - 1
_print_headings(win, row, col, str, index, state)
else
data_index = index - @data_offset ## index into actual data object
_print_data(win, row, col, str, index, state, data_index)
end
end
## Print the header row
## index [Integer] - should be 0 or 1 (1 for optional separator)
def _print_headings(win, row, col, str, index, state)
arr = color_of_header_row(index, state)
win.printstring(row, col, str, arr[0], arr[1])
end
## Print the data.
## index is index into visual row, starting 0 for headings, and 1 for separator
## data_index is index into actual data object. Use this if checking actual data array
def _print_data(win, row, col, str, index, state, data_index)
data_index = index - @data_offset ## index into actual data object
arr = color_of_data_row(index, state, data_index)
win.printstring(row, col, str, arr[0], arr[1])
end
def color_of_column ix, value, defaultcolor
raise "unused yet"
end
def row_count
@tabular.list.size
end
## return rowid (assumed to be first column)
def current_id
data = current_row_as_array()
return nil unless data
data.first
end
# How do I deal with separators and headers here - return nil
## This returns all columns including hidden so rowid can be accessed
def current_row_as_array
data_index = @current_index - @data_offset ## index into actual data object
return nil if data_index < 0 ## separator and heading
data()[data_index]
end
## returns the current row as a hash with column name as key.
def current_row_as_hash
data = current_row_as_array
return nil unless data
columns = @tabular.columns
hash = columns.zip(data).to_h
end
## Move cursor to next column
def next_column
@coffsets = @tabular._calculate_column_offsets unless @coffsets
#c = @column_pointer.next
current_column = current_column_offset() +1
if current_column > @tabular.column_count-1
current_column = 0
end
cp = @coffsets[current_column]
@curpos = cp if cp
$log.debug " next_column #{@coffsets} :::: #{cp}, curpos=#{@curpos} "
set_col_offset @curpos
#down() if c < @column_pointer.last_index
#fire_column_event :ENTER_COLUMN
end
## Move cursor to previous column
def prev_column
@coffsets = @tabular._calculate_column_offsets unless @coffsets
#c = @column_pointer.next
current_column = current_column_offset() -1
if current_column < 0 #
current_column = @tabular.column_count-1
end
cp = @coffsets[current_column]
@curpos = cp if cp
$log.debug " next_column #{@coffsets} :::: #{cp}, curpos=#{@curpos} "
set_col_offset @curpos
#down() if c < @column_pointer.last_index
#fire_column_event :ENTER_COLUMN
end
# Convert current cursor position to a table column
# calculate column based on curpos since user may not have
# used w and b keys (:next_column)
# @return [Integer] column index base 0
def current_column_offset
_calculate_column_offsets unless @coffsets
x = 0
@coffsets.each_with_index { |i, ix|
if @curpos < i
break
else
x += 1
end
}
x -= 1 # since we start offsets with 0, so first auto becoming 1
return x
end
def header_row?
@current_index == 0 and @data_offset > 0
end
## Handle case where ENTER/RETURN pressed on header row (so sorting can be done).
def fire_action_event
if header_row?
# TODO sorting here
$log.debug " PRESSED ENTER on header row, TODO sorting here"
end
super
end
## delegate calls to the tabular object
def_delegators :@tabular, :headings=, :columns= , :add, :add_row, :<< , :column_width, :column_align, :column_hide, :convert_value_to_text, :separator, :to_string, :x=, :y=, :column_unhide
def_delegators :@tabular, :columns , :numbering
def_delegators :@tabular, :column_hidden, :delete_at, :value_at
end # class
end # module
# vim: comments=sr\:##,mb\:##,el\:#/,\:## :
| true |
7387d15236a5a0e7c456b23d5fb9226ef8c17c22 | Ruby | terchiem/ruby_tictactoe | /tictactoe.rb | UTF-8 | 3,103 | 3.609375 | 4 | [] | no_license | module SetSpace
def set(i, j, value)
if @spaces[i][j].nil?
@spaces[i][j] = value
return true
end
false
end
def clear
@spaces = Array.new(3){ Array.new(3) }
end
end
class Board
include SetSpace
def initialize
@spaces = Array.new(3){ Array.new(3) }
end
def display
puts "============="
@spaces.each do |row|
row.each { |cell| print " [#{cell.nil? ? " " : cell}]" }
puts ""
end
puts "=============\n\n"
end
def each
@spaces.each { |x| yield(x) }
end
def [](key)
@spaces[key]
end
end
class Player
include SetSpace
def initialize
@spaces = Array.new(3){ Array.new(3) }
end
def check_rows
@spaces.each do |row|
return true unless row.include?(nil)
end
false
end
def check_cols
3.times do |i|
return true if @spaces[0][i] && @spaces[1][i] && @spaces[2][i]
end
false
end
def check_diag
unless @spaces[1][1].nil?
if (@spaces[0][0] && @spaces[2][2]) ||
(@spaces[2][0] && @spaces[0][2])
return true
end
end
false
end
def winner?
check_rows || check_cols || check_diag
end
end
class Game
def initialize
@player = { "X" => Player.new, "O" => Player.new }
@board = Board.new
end
def start_game
round = 1
current_player = "X";
until game_over?
puts "Round #{round}"
@board.display
puts "#{current_player}'s Turn"
valid_move = false
until valid_move
x, y = prompt_user
valid_move = @board[x][y].nil?
puts "Invalid move." unless valid_move
end
make_move(x, y, current_player)
current_player = current_player == "X" ? "O" : "X"
round += 1
puts ""
end
@board.display
puts get_result
puts ""
new_game if new_game?
end
def prompt_user
while true
print "Enter coordinates (x,y): "
input = gets.chomp
if input.match?(/^\d\s*,\s*\d$/)
x, y = input.split(',').map(&:to_i)
if x.between?(0,2) && y.between?(0,2)
return [x, y]
else
puts "Coordinates out of range."
end
else
puts "Invalid coordinates entered."
end
end
end
def make_move(x, y, player)
@board.set(x, y, player)
@player[player].set(x, y, player)
end
def tie?
@board.each do |row|
row.each { |cell| return false if cell.nil? }
end
true
end
def game_over?
@player["X"].winner? || @player["O"].winner? || tie?
end
def get_result
if @player["X"].winner?
"Player 'X' wins!"
elsif @player["O"].winner?
"Player 'O' wins!"
else
"Tie game!"
end
end
def new_game?
while true
puts "Play again? (y/n)"
input = gets.chomp.downcase
puts ""
if input.match?(/^[yn]$/)
return input == "y" ? true : false
else
puts "Invalid choice."
end
end
end
def new_game
@board.clear
@player["X"].clear
@player["O"].clear
start_game
end
end
game = Game.new
game.start_game | true |
57dad704cdc6a130bd2062ceef1ff250b1aa728d | Ruby | juan-gm/RB101 | /lesson_4/practice_problem_1.rb | UTF-8 | 161 | 3.140625 | 3 | [] | no_license | flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"]
hsh = {}
flintstones.each_with_index do |word, index|
hsh[word] = index
end
puts hsh
| true |
3f45fbc5730e7a50d58682e57f7e020b9a218ccc | Ruby | jescriba/light_server | /lib/lights/server.rb | UTF-8 | 671 | 2.515625 | 3 | [] | no_license | require 'json'
require 'pi_piper'
module Lights
class Server
include PiPiper
def initialize
@row_handler = RowHandler.new
end
# Process JSON requests from web server
def listen(data)
## TODO: Check if needs to be updated by comparing to command history
data_table = JSON.parse(data)
update(data_table) # For now just calling update regardless
end
# Updates SPI status
def update(instructions)
@row_handler.update(instructions)
end
def clear
@row_handler.kill_animations()
@row_handler.clear_lights()
end
def configuration
@row_handler.configuration
end
end
end
| true |
5e94db983556c806049abfbd20b11c05a80d5c6b | Ruby | davesousa/2playergame | /two_player_game.rb | UTF-8 | 1,209 | 3.8125 | 4 | [] | no_license | @p1_score = 3
@p2_score = 3
@turn = 2
def lose_1
@p1_score -= 1
end
def lose_2
@p2_score -= 1
end
def question
"what is #{@num1} + #{@num2}"
end
def answer
@answer = @num1 + @num2
end
def turn
@turn += 1
end
def game
while @p1_score > 0 and @p2_score > 0
if @turn.even?
@num1 = Random.rand(1..20)
@num2 = Random.rand(1..20)
p "Player 1 go!"
p question
user_input = gets.chomp.to_i
if user_input == answer
p "correct"
else
p "wrong"
lose_1
p "Player 1, You have #{@p1_score} lives left"
end
turn
else
@num1 = Random.rand(1..20)
@num2 = Random.rand(1..20)
p "Player 2 go!"
p question
user_input = gets.chomp.to_i
if user_input == answer
p "correct"
else
p "wrong"
lose_2
p "Player 2, You have #{@p2_score} lives left"
end
turn
end
end
if @p1_score == 0
puts "Player 1 sucks, you lose"
puts "Player 2 WINS!"
else
puts "Player 1 sucks, you lose"
puts "Player 2 WINS!"
end
end
game
| true |
69c11f5e612182375f0d374ed9a9efbc3a10c51b | Ruby | 12ew/collections_practice_vol_2-prework | /collections_practice.rb | UTF-8 | 2,107 | 3.453125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def begins_with_r(array)
array.all? do |tool|
# binding.pry
tool[0] == "r"
end
end
def contain_a(array)
my_arr = []
array.each do |element|
if element.include?("a")
my_arr << element
end
end
my_arr
end
def first_wa(array)
array.each do |word|
if word.to_s.include?("wa") #or word[0,2] == "wa"
return word
end
end
end
def remove_non_strings(array)
new_arr = []
array.each do |element|
if (element == "#{element}")
new_arr << element
else
array.delete(element)
end
end
new_arr
end
def count_elements(array)
count = 0
arr = []
array.each do |x|
# binding.pry
count = array.count(x)
arr << x.merge(:count => count)
end
arr.uniq!
end
def find_cool(array)
my_arr = []
array.each do |key|
key.each do |k, v|
# binding.pry
return my_arr << key if v == "cool"
# end
end
end
end
def merge_data(keys, data)
merged = []
keys.each do |i|
data.first.each do |k,v|
if i.values[0] == k
then merged << i.merge(v)
# binding.pry
end
end
end
merged
end
# def organize_schools(array)
# locations = {}
# array.values.each do |location|
# # binding.pry
# locations[location.values[0]] = []
# array.each do |school, loc|
# # binding.pry
# locations[location.values[0]] << school if loc == location
# end
# end
# locations
# end
def organize_schools(array)
locations = {}
array.each do |school, loc_hash|
if locations[loc_hash[:location]]
locations[loc_hash[:location]] << school if !locations[loc_hash[:location]].include?(school)
else
locations[loc_hash[:location]] = []
locations[loc_hash[:location]] << school
end
end
locations
end
# def organize_schools(schools)
# locations_hash = {}
# schools.collect {|k,v|
# locations_hash[v[:location]] = []}
# locations_hash.each {|k,v|
# schools.each {|k1,v1|
# if k == v1[:location]
# then v << k1 end}}
# # binding.pry
# end
| true |
935c0b7fcaebfdbc28cbd5215224fa5987383e8c | Ruby | chenyan19209219/gitlab-ce | /lib/gitlab/i18n/metadata_entry.rb | UTF-8 | 1,037 | 2.53125 | 3 | [
"MIT",
"CC-BY-SA-4.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
module Gitlab
module I18n
class MetadataEntry
attr_reader :entry_data
# Avoid testing too many plurals if `nplurals` was incorrectly set.
# Based on info on https://www.gnu.org/software/gettext/manual/html_node/Plural-forms.html
# which mentions special cases for numbers ending in 2 digits
MAX_FORMS_TO_TEST = 101
def initialize(entry_data)
@entry_data = entry_data
end
def expected_forms
return unless plural_information
plural_information['nplurals'].to_i
end
def forms_to_test
@forms_to_test ||= [expected_forms, MAX_FORMS_TO_TEST].compact.min
end
private
def plural_information
return @plural_information if defined?(@plural_information)
if plural_line = entry_data[:msgstr].detect { |metadata_line| metadata_line.starts_with?('Plural-Forms: ') }
@plural_information = Hash[plural_line.scan(/(\w+)=([^;\n]+)/)]
end
end
end
end
end
| true |
b86b9cbad5a96a7ed239fc5eb1ed7cbaa3cd334d | Ruby | shentianyi/warehouse | /RailsClient/app/models/enum/impl_user_type.rb | UTF-8 | 845 | 2.796875 | 3 | [
"MIT"
] | permissive | class ImplUserType
SENDER = 0
RECEIVER = 1
EXAMINER = 2
REJECTOR = 3
def self.display(type)
case type
when SENDER
'发送人员'
when RECEIVER
'收货人员'
when EXAMINER
'质检人员'
when REJECTOR
'拒收人员'
end
end
def self.display_action(type)
case type
when SENDER
'发送'
when RECEIVER
'接收'
when EXAMINER
'质检通过'
when REJECTOR
'拒收'
end
end
def self.list_menu
data = []
self.constants.each do |c|
v = self.const_get(c.to_s)
data << [self.display(v),v]
end
data
end
def self.list_action_menu
data = []
self.constants.each do |c|
v = self.const_get(c.to_s)
data << [self.display_action(v),v]
end
data
end
end | true |
5f65d8d98b5e83ea1e5a1b17431506935ddfe959 | Ruby | mandarandriam/ruby-vendredi | /pyramide.rb | UTF-8 | 349 | 3.421875 | 3 | [] | no_license | print "Choisissez un nombre entre 1 et 25 et ça va sortir une pyramide à descendre de tant d'étages que ce nombre!!"
user_number = Integer(gets.chomp)
puts "\n"
start = 0
i = "#"
while user_number > 0 do
espace = " " * (user_number + 1)
brique = "#" * (start + 1)
user_number -= 1
start += 1
print "#{espace}#{brique} \n"
end | true |
a367d3b48820d94341690b88285544a1fa5176bb | Ruby | aldompe95/beerMe | /app/models/beer_log.rb | UTF-8 | 350 | 2.53125 | 3 | [] | no_license | class BeerLog < ApplicationRecord
belongs_to :user
belongs_to :beer
validates :user_id, presence: true
validates :quantity, presence: true
validates :date, presence: true
validate :is_future?
def is_future?
if date.present? && date > Date.today
errors.add(:date, "can't be of the future, are you drunk?")
end
end
end
| true |
14338c6718ba0b5668ad61e5d85f00fc7ef30c17 | Ruby | matz/mail | /lib/mail/fields/to_field.rb | UTF-8 | 1,485 | 2.859375 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
#
# = To Field
#
# The To field inherits to StructuredField and handles the To: header
# field in the email.
#
# Sending to to a mail message will instantiate a Mail::Field object that
# has a ToField as its field type. This includes all Mail::CommonAddress
# module instance metods.
#
# Only one To field can appear in a header, though it can have multiple
# addresses and groups of addresses.
#
# == Examples:
#
# mail = Mail.new
# mail.to = 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail.to #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
# mail[:to] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
# mail['to'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
# mail['To'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::ToField:0x180e1c4
#
# mail[:to].encoded #=> 'To: Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net\r\n'
# mail[:to].decoded #=> 'Mikel Lindsaar <mikel@test.lindsaar.net>, ada@test.lindsaar.net'
# mail[:to].addresses #=> ['mikel@test.lindsaar.net', 'ada@test.lindsaar.net']
# mail[:to].formatted #=> ['Mikel Lindsaar <mikel@test.lindsaar.net>', 'ada@test.lindsaar.net']
#
require 'mail/fields/common/common_address'
module Mail
class ToField < StructuredField
include Mail::CommonAddress
FIELD_NAME = 'to'
CAPITALIZED_FIELD = 'To'
def initialize(value = nil, charset = 'utf-8')
self.charset = charset
super(CAPITALIZED_FIELD, strip_field(FIELD_NAME, value), charset)
self
end
def encoded
do_encode(CAPITALIZED_FIELD)
end
def decoded
do_decode
end
end
end
| true |
1c86cfb393f46bb8ef3efe0dda615e6d38924d32 | Ruby | romanobrooks/pointswop | /itemtest.rb | UTF-8 | 370 | 3.5 | 4 | [] | no_license | array_test = ["first line","second line","third line"]
for item in array_test
puts item
end
$end
puts
print "This is in normal direction"
puts
#any value can be used.
for doos in array_test
print doos
end
$end
puts
print "This is in reverese"
puts
#any value can be used. This is in reverese
for surf in array_test.reverse
print surf
end
$end
| true |
be8a9415625a15ec00f66a9971e4dce1ec878f48 | Ruby | tsg-ut/tsgctf | /crypto/omega/writeup/make_problem.rb | UTF-8 | 1,748 | 3.0625 | 3 | [] | no_license | srand(68)
UNITS = [[0,1],[0,-1],[1,0],[-1,0],[1,1],[-1,-1]]
def to_complex(x)
a, b = x
w = Math::E ** Complex(0, Math::PI*2.0/3.0)
a + b*w
end
def add(x, y)
a, b = x
c, d = y
[a+c, b+d]
end
def sub(x, y)
a, b = x
c, d = y
[a-c, b-d]
end
def scalar(k)
[k, 0]
end
def mul(*xs)
r = [1, 0]
xs.each do |x|
a, b = r
c, d = x
r = [a*c - b*d, a*d + b*c - b*d]
end
r
end
def div(x, y)
xc, yc = to_complex(x), to_complex(y)
a, b = (xc / yc).rect
[(a + b/Math.sqrt(3)).round, (b*2.0/Math.sqrt(3)).round]
end
def mod(x, y)
100.times do
k = div(x, y)
x = sub(x, mul(k, y))
end
x
end
def norm(x)
a, b = x
a*a + b*b - a*b
end
flag = "TSGCTF{I_H34RD_S0ME_IN7EGERS_INCLUDING_EISENSTEIN'S_F0RM_EUCL1DE4N_R1NG!}"
msg = [flag[0,flag.size/2], flag[flag.size/2,flag.size]].map {|text| text.unpack("H*")[0].hex}
def extgcd(a, b)
if b == [0, 0]
case a
when [1,0]
{x: [1,0], y: [0,0], gcd: [1,0]}
when [-1,0]
{x: [-1,0], y: [0,0], gcd: [1,0]}
when [0,1]
{x: [-1,-1], y: [0,0], gcd: [1,0]}
when [0,-1]
{x: [1,1], y: [0,0], gcd: [1,0]}
when [1,1]
{x: [0,-1], y: [0,0], gcd: [1,0]}
when [-1,-1]
{x: [0,1], y: [0,0], gcd: [1,0]}
else
{x: [1,0], y: [0,0], gcd: a}
end
else
k = div(a, b)
prev = extgcd(b, sub(a, mul(k, b)))
{
x: prev[:y],
y: sub(prev[:x], mul(k, prev[:y])),
gcd: prev[:gcd]
}
end
end
modulos = 20.times.inject([]){|s, _|
x = nil
loop do
x = [rand(1000000), rand(1000000)]
break if s.all?{|y| UNITS.include? extgcd(x, y)[:gcd]}
end
s << x
}
res = modulos.map do |m|
[mod(msg, m), m]
end
puts 'MODULOS = %p' % [modulos]
puts 'PROBLEM = %p' % [res]
| true |
8f86579815fb9048e3e5b34a7f92271cf90d2a1c | Ruby | kikihakiem/geokit | /lib/geokit/geocoders/mapbox.rb | UTF-8 | 3,181 | 2.59375 | 3 | [
"MIT"
] | permissive | module Geokit
module Geocoders
# Mapbox geocoder implementation. Requires the Geokit::Geocoders::MapboxGeocoder:key variable to
# contain a Mapbox access token. Conforms to the interface set by the Geocoder class.
class MapboxGeocoder < Geocoder
config :key
self.secure = true
private
# Template method which does the reverse-geocode lookup.
def self.do_reverse_geocode(latlng, options = {})
latlng = LatLng.normalize(latlng)
url = "#{protocol}://api.tiles.mapbox.com/v4/geocode/mapbox.places-v1/"
url += "#{latlng.lng},#{latlng.lat}.json?access_token=#{key}"
process :json, url
end
# Template method which does the geocode lookup.
def self.do_geocode(address, options = {})
address_str = address.is_a?(GeoLoc) ? address.to_geocodeable_s : address
url = "#{protocol}://api.tiles.mapbox.com/v4/geocode/mapbox.places-v1/"
url += "#{Geokit::Inflector.url_escape(address_str)}.json?access_token=#{key}"
process :json, url
end
def self.parse_json(results)
return GeoLoc.new unless results['features'].count > 0
loc = nil
results['features'].each do |feature|
extracted_geoloc = extract_geoloc(feature)
if loc.nil?
loc = extracted_geoloc
else
loc.all.push(extracted_geoloc)
end
end
loc
end
def self.extract_geoloc(result_json)
loc = new_loc
loc.lng = result_json['center'][0]
loc.lat = result_json['center'][1]
set_address_components(result_json, loc)
set_precision(loc)
set_bounds(result_json['bbox'], loc)
loc.success = true
loc
end
def self.set_address_components(result_json, loc)
if result_json['context']
result_json['context'].each do |context|
if context['id'] =~ /^country\./
loc.country = context['text']
elsif context['id'] =~ /^province\./
loc.state = context['text']
elsif context['id'] =~ /^city\./
loc.city = context['text']
elsif context['id'] =~ /^postcode-/
loc.zip = context['text']
loc.country_code = context['id'].split('.')[0].gsub(/^postcode-/, '').upcase
end
end
if loc.country_code && !loc.country
loc.country = loc.country_code
end
end
if result_json['place_name']
loc.full_address = result_json['place_name']
end
end
PRECISION_VALUES = %w{unknown country state city zip full_address}
def self.set_precision(loc)
for i in 1...PRECISION_VALUES.length - 1
if loc.send(PRECISION_VALUES[i]) && loc.send(PRECISION_VALUES[i]).length
loc.precision = PRECISION_VALUES[i]
else
break
end
end
end
def self.set_bounds(result_json, loc)
if bounds = result_json
loc.suggested_bounds = Bounds.normalize([bounds[1], bounds[0]], [bounds[3], bounds[2]])
end
end
end
end
end
| true |
280b100a25bea30db5c1934ac056d8cc4962296a | Ruby | rahul-sekhar/story-rev | /spec/models/book_award_spec.rb | UTF-8 | 1,066 | 2.515625 | 3 | [] | no_license | require "spec_helper"
describe BookAward do
let(:book_award) { build(:book_award) }
subject { book_award }
describe "year" do
it "should be an integer" do
["1a", "0", 5.5].each do |x|
book_award.year = x
book_award.should be_invalid
end
end
it "should have a lower limit of 1001" do
book_award.year = 1001
book_award.should be_valid
book_award.year = 1000
book_award.should be_invalid
end
it "should have an upper limit of 2099" do
book_award.year = 2099
book_award.should be_valid
book_award.year = 2100
book_award.should be_invalid
end
end
describe "full name" do
before { book_award.award.stub(:full_name).and_return("Award Name") }
subject { book_award.full_name }
it "should include the year when it is present" do
book_award.year = 2010
subject.should == "Award Name 2010"
end
it "should omit the the year when it is nil" do
book_award.year = nil
subject.should == "Award Name"
end
end
end | true |
bc3620e0d76a807a156e5b09ec2032d5d32ab139 | Ruby | toramuryo796/bookact | /app/services/star_rate.rb | UTF-8 | 780 | 3.125 | 3 | [] | no_license | class StarRate
def self.rate(book)
introduces = book.introduces
if introduces.present?
array = []
sum = 0
introduces.each do |introduce|
array << introduce.title
sum += introduce.star.name
end
num = array.length
avg = (sum / num).round(1)
if avg >=4.8
avg = 5.0
elsif avg >= 4.3
avg = 4.5
elsif avg >= 3.8
avg = 4.0
elsif avg >= 3.3
avg = 3.5
elsif avg >= 2.8
avg = 3.0
elsif avg >= 2.3
avg = 2.5
elsif avg >= 1.8
avg = 2.0
elsif avg >= 1.3
avg = 1.5
elsif avg >= 0.8
avg = 1.0
elsif avg >= 0.3
avg = 0.5
else
avg = 0
end
return avg
end
end
end | true |
3fda2405b4ae032c460fb03d131fe77593dd9c68 | Ruby | annadolan/enigma | /lib/key_generator.rb | UTF-8 | 141 | 2.703125 | 3 | [] | no_license | class KeyGenerator
attr_reader :key
def initialize
@key = key
end
def key
@key = rand(0..99999).to_s.rjust(5, "0")
end
end
| true |
7683462ad4ec8e6dae62147b01f43a2ce98624d7 | Ruby | Mwriley1/ls_course_120 | /lesson1/exercises.rb | UTF-8 | 2,872 | 4.09375 | 4 | [] | no_license | class Student
attr_reader :name
def initialize(name, grade)
@name = name
@grade = grade
end
def better_grade_than?(person)
puts "Well done!" if self.grade < person.grade
end
protected
attr_reader :grade
end
joe = Student.new("Joe", "A")
bob = Student.new("Bob", "B")
p joe.better_grade_than?(bob)
# the method 'hi' in Bob is private and not accessible outside the class
# To fix this you could move the hi method above the private keyword in the
# class definition
module Towable
def can_tow?
true
end
end
class Vehicle
@@number_of_vehicles = 0
attr_accessor :color, :year, :model, :current_speed
def initialize(year, color, model)
@@number_of_vehicles += 1
@year = year
@color = color
@model = model
@current_speed = 0
end
def self.number_of_vehicles
puts "#{@@number_of_vehicles} vehicles have been created."
end
def self.gas_mileage(gallons, miles)
puts "Your gas mileage is #{miles / gallons} miles per gallon."
end
def speed_up(speed)
@current_speed += speed
puts "Speeding up #{speed} MPH!"
end
def brake(speed)
@current_speed -= speed
puts "Braking by #{speed} MPH!"
end
def display_current_speed
puts "You are going #{@current_speed} MPH."
end
def shut_off
@current_speed = 0
puts "Stopping and shutting off!"
end
def spray_paint(color)
self.color = color
puts "Spray painting #{color}!"
end
def to_s
puts "This is a #{self.color} #{self.year} #{self.model} traveling at a speed of #{self.current_speed} miles per hour."
end
def age
puts "The vehicle is #{years_old} years old!"
end
private
def years_old
Time.now.year - self.year
end
end
class MyCar < Vehicle
NUMBER_OF_WHEELS = 4
end
class MyTruck < Vehicle
include Towable
HAS_BED = true
end
car = MyCar.new(2013, 'Blue', 'Dodge Durango')
truck = MyTruck.new(2014, 'White', 'Toyota Tundra')
Vehicle.number_of_vehicles
p MyCar.ancestors
p MyTruck.ancestors
p Vehicle.ancestors
car.speed_up(80)
car.current_speed
car.brake(50)
car.current_speed
car.shut_off
car.current_speed
truck.speed_up(80)
truck.current_speed
truck.brake(50)
truck.current_speed
truck.shut_off
truck.current_speed
puts car.color
car.color = "Green"
puts car.color
puts car.year
car.spray_paint("Yellow")
puts car.color
MyCar.gas_mileage(50, 500)
car.age
# An error occurs because attr_reader only creates a getter method
# for :name not a setter method. When you try to use a name= method
# to set bob's name it doesn't exist. It can be fixed by changing
# attr_reader to attr_accessor, which will create both a getter and
# setter method for :name.
class Person
attr_accessor :name
def initialize(name)
self.name = name
end
end
bob = Person.new("Steve")
bob.name = "Bob"
p bob.name | true |
ba76f2f03df1518647d29f54e39f58015b05c9b6 | Ruby | ojammeh/algorithms | /time_slots.rb | UTF-8 | 215 | 2.546875 | 3 | [] | no_license | class TimeSlot
NUMOFDAYS = 0
NUMOFPERIODSPERDAY = 0
NUMTIMES = 0
NUMROOMS = 5
def t_slots(d, p)
rows, cols = d, p
slots = Array.new(rows) {Array.new(cols,0)}
return slots
end
end
| true |
96bf6b2ffe9041ddeb94834df5096272a8630560 | Ruby | BkBky/dos | /maraton_active records/maraton/db/seeds.rb | UTF-8 | 7,027 | 2.640625 | 3 | [] | no_license | # Este archivo sirve para crear registros de prueba
user1 = User.create(name: 'Erick', password: '123', email: 'erick@gmail.com')
user2 = User.create(name: 'Esme', password: '456', email: 'esme@gmail.com')
user3 = User.create(name: 'Fausto', password: '789', email: 'fausto@gmail.com')
#Deck
deck1 = Deck.create(name: 'Geografía')
deck2 = Deck.create(name: 'Historia')
deck3 = Deck.create(name: 'Entretenimiento')
#Round
round1 = Round.create(deck_id: deck1.id, user_id: user1.id)
round2 = Round.create(deck_id: deck3.id, user_id: user2.id)
round3 = Round.create(deck_id: deck2.id, user_id: user2.id)
round4 = Round.create(deck_id: deck3.id, user_id: user3.id)
round5 = Round.create(deck_id: deck1.id, user_id: user2.id)
#Geografia
question1 = Question.create(deck_id: deck1.id, question: '¿Cuál es el país menos turístico de Europa?')
question2 = Question.create(deck_id: deck1.id, question: 'A qué país pertenece la isla de Tasmania?')
question3 = Question.create(deck_id: deck1.id, question: '¿En cuál de los siguientes países NO hay ningún desierto?')
question4 = Question.create(deck_id: deck1.id, question: '¿Cuál es el código internacional para Cuba?')
question5 = Question.create(deck_id: deck1.id, question: '¿Cuál es la capital del estado de Arkansas?')
#Entreteniemiento
question6 = Question.create(deck_id: deck2.id, question: '¿Qué premiada serie de televisión tiene como protagonista a un publicista?')
question7 = Question.create(deck_id: deck2.id, question: '¿Como se llamaba la protagonista femenina de la serie de televisión Scrubs?')
question8 = Question.create(deck_id: deck2.id, question: '¿Cómo se llamaba el personaje que interpretaba John Travolta en Grease?')
question9 = Question.create(deck_id: deck2.id, question: '¿En qué año se estrenó la película de Disney Pinocho?')
question10 = Question.create(deck_id: deck2.id, question: '¿En qué país nació la Bauhaus?')
#Historia
question11 = Question.create(deck_id: deck3.id, question: '¿Cuál es la rama mayoritaria del Islam?')
question12 = Question.create(deck_id: deck3.id, question: '¿De qué fue ministro Manuel Fraga durante el franquismo?')
question13 = Question.create(deck_id: deck3.id, question: '¿En qué año tuvo lugar el ataque a Pearl Harbor?')
question14 = Question.create(deck_id: deck3.id, question: '¿Las revueltas de dónde son llamadas Intifadas?')
question15 = Question.create(deck_id: deck3.id, question: 'La Comuna de París fue un movimiento...')
#1
Answer.create(question_id: question1.id, answer: 'Armenia', value_answer: false)
Answer.create(question_id: question1.id, answer: 'Moldavia', value_answer: false)
Answer.create(question_id: question1.id, answer: 'Liechtenstein', value_answer: true)
#2
Answer.create(question_id: question2.id, answer: 'Estados Unidos', value_answer: false)
Answer.create(question_id: question2.id, answer: 'Australia', value_answer: true)
Answer.create(question_id: question2.id, answer: 'Portugal', value_answer: false)
#3
Answer.create(question_id: question3.id, answer: 'España', value_answer: false)
Answer.create(question_id: question3.id, answer: 'Chile', value_answer: false)
Answer.create(question_id: question3.id, answer: 'Alemania', value_answer: true)
#4
Answer.create(question_id: question4.id, answer: 'CA', value_answer: false)
Answer.create(question_id: question4.id, answer: 'CU', value_answer: true)
Answer.create(question_id: question4.id, answer: 'CB', value_answer: false)
#5
Answer.create(question_id: question5.id, answer: 'Kansas', value_answer: false)
#5 Geografía- correcta
Answer.create(question_id: question5.id, answer: 'Little Rock', value_answer: true)
Answer.create(question_id: question5.id, answer: 'Washington', value_answer: false)
#1 Entretenimiento correcta
Answer.create(question_id: question6.id, answer: 'Mad Men', value_answer: true)
Answer.create(question_id: question6.id, answer: 'Shameless', value_answer: false)
Answer.create(question_id: question6.id, answer: 'Juego de Tronos', value_answer: false)
#2 Entretenimiento correcta
Answer.create(question_id: question7.id, answer: 'Elliot', value_answer: true)
Answer.create(question_id: question7.id, answer: 'Sarah', value_answer: false)
Answer.create(question_id: question7.id, answer: 'Jordan', value_answer: false)
#3
Answer.create(question_id: question8.id, answer: 'Danny Puño', value_answer: false)
Answer.create(question_id: question8.id, answer: 'Danny Zuko', value_answer: true)
Answer.create(question_id: question8.id, answer: 'Danny Chulo', value_answer: false)
#4 Entretenimiento correcta
Answer.create(question_id: question9.id, answer: '1940', value_answer: true)
Answer.create(question_id: question9.id, answer: '1950', value_answer: false)
Answer.create(question_id: question9.id, answer: '1952', value_answer: false)
#5 Entretenimiento correcta
Answer.create(question_id: question10.id, answer: 'Alemania', value_answer: true)
Answer.create(question_id: question10.id, answer: 'Holanda', value_answer: false)
Answer.create(question_id: question10.id, answer: 'Rusia', value_answer: false)
#1 Historia
Answer.create(question_id: question11.id, answer: 'Chiísmo', value_answer: false)
Answer.create(question_id: question11.id, answer: 'Sunismo', value_answer: true)
Answer.create(question_id: question11.id, answer: 'Jariyismo', value_answer: false)
#2
Answer.create(question_id: question12.id, answer: 'De Interior', value_answer: false)
Answer.create(question_id: question12.id, answer: 'De Economía', value_answer: false)
Answer.create(question_id: question12.id, answer: 'De Información y Turismo', value_answer: true)
#3
Answer.create(question_id: question13.id, answer: '1939', value_answer: false)
Answer.create(question_id: question13.id, answer: '1940', value_answer: false)
Answer.create(question_id: question13.id, answer: '1941', value_answer: true)
#4
Answer.create(question_id: question14.id, answer: 'Montenegro', value_answer: false)
Answer.create(question_id: question14.id, answer: 'Kosovo', value_answer: false)
Answer.create(question_id: question14.id, answer: 'Palestina', value_answer: true)
#5
Answer.create(question_id: question15.id, answer: 'Del mayo de 68', value_answer: false)
Answer.create(question_id: question15.id, answer: 'Hippie de los años 60', value_answer: false)
Answer.create(question_id: question15.id, answer: 'Insurrecional autogestionario del XIX', value_answer: true)
RoundQuestion.create(round_id: round1.id, question_id:question15.id, answer_user: 'Del mayo de 68', score: 0)
RoundQuestion.create(round_id: round1.id, question_id:question15.id, answer_user: 'Insurrecional autogestionario del XIX', score: 1)
RoundQuestion.create(round_id: round1.id, question_id:question14.id, answer_user: 'Palestina', score: 1)
RoundQuestion.create(round_id: round2.id, question_id:question6.id, answer_user: 'Mad Men', score: 1)
RoundQuestion.create(round_id: round2.id, question_id:question7.id, answer_user: 'Elliot', score: 1)
RoundQuestion.create(round_id: round2.id, question_id:question8.id, answer_user: 'Danny Puño', score: 0) | true |
21d6c24185caab3e25654c2f3ce89db7cbd8a3c7 | Ruby | charleshenriponiard/pet-lost | /app/models/pet.rb | UTF-8 | 261 | 2.765625 | 3 | [] | no_license | class Pet < ApplicationRecord
SPECIES = ["cat", "dog", "bird"]
validates :species, inclusion: { in: SPECIES }
validates :name, presence: true
def found_days_ago
"#{self.name} has been found #{(Date.today - self.found_on).to_i} days ago!"
end
end
| true |
ebdcc899ea28ff3c6e0e2e2f1808ba530940b8cd | Ruby | mikeyduece/black_thursday | /modules/customer_analyst.rb | UTF-8 | 2,326 | 2.59375 | 3 | [] | no_license | module CustomerAnalyst
def ranked(params)
params.keys.sort_by {|customer_id| params[customer_id].reduce(:+)}.reverse
end
def unpaid_invoices
se.all_invoices.find_all {|invoice| !invoice.is_paid_in_full?}
end
# def customers_with_unpaid_invoices
# cust_ids = unpaid_invoices.group_by {|invoice| invoice.customer_id}
# cust_ids.keys.map {|id| se.customers.find_by_id(id)}
# end
def customer(id)
se.customers.find_by_id(id)
end
def customers_invoices(cust_id)
customer(cust_id).invoices.find_all {|invoice| invoice.is_paid_in_full?}
end
def cust_inv_year(cust_id, year)
customers_invoices(cust_id).find_all do |invoice|
invoice.created_at.to_s.split("-")[0].to_i == year
end
end
def cust_inv_items(cust_id, year)
cust_inv_year(cust_id, year).map do |invoice|
se.invoice_items.find_all_by_invoice_id(invoice.id)
end.flatten
end
def customers_inv_items(cust_inv)
cust_inv.map {|invoice| invoice.invoice_items}.flatten!
end
def customer_item_ids(cust_inv)
customers_inv_items(cust_inv).group_by {|inv_item| inv_item.item_id}
end
def cust_items_count(cust_inv)
customer_item_ids(cust_inv).keys.reduce({}) do |result, item|
result[item] = customer_item_ids(cust_inv)[item][0].quantity
result
end
end
def sorted_items_list(item_ids)
item_ids.map {|id| se.items.find_by_id(id)}
end
def paid_invoices_grpd_by_id
paid_invoices.group_by {|invoice| invoice.id}
end
def cust_inv_items_by_inv_id
invoices = paid_invoices_grpd_by_id
invoices.each_value do |invoices|
invoices.map! do |invoice|
invoice.invoice_items
end.flatten!
end
end
def customer_invoice_by_quantity
inv_item_ids = cust_inv_items_by_inv_id
inv_item_ids.keys.reduce({}) do |result, inv|
result[inv] = inv_item_ids[inv].map {|item|
item.quantity}.reduce(:+); result
end
end
def sorted_invoices_by_quantity
cust_invs = customer_invoice_by_quantity
cust_invs.keys.sort_by {|key| cust_invs[key]}.reverse
end
def one_invoice_customers
invoices = one_transaction_invoices
invoices.map {|invoice| invoice.customer}
end
def one_time_buyers_invoices
one_time_buyers.map {|customer| customer.invoices}.flatten.compact
end
end
| true |
04b0f2f2af119c008705bdadfe89ace87e34ae29 | Ruby | RyanSpartan117/Project-Euler | /euler2.rb | UTF-8 | 575 | 3.671875 | 4 | [] | no_license | require_relative 'spec/spec_helper'
class Fibonnaci
def fibonnaci_numbers number
fibArray = [1, 2]
currentFib = 1
secondFib = 2
i = 1
while i < number do
nextFib = currentFib += secondFib
fibArray.push(nextFib)
currentFib = secondFib
secondFib = nextFib
i = currentFib + secondFib
end
fibArray
end
def is_even_sum array
array.inject(0){|sum, x| x % 2 == 0 ? sum + x : sum}
end
def fib_numbers_up_to number
is_even_sum(fibonnaci_numbers(number))
end
end
fib = Fibonnaci.new
p fib.is_even_sum(fib.fibonnaci_numbers(4000000)) | true |
fa918acf5c5c1c6984aabfc10595a938ab4ffc1c | Ruby | dedayog/Learning-Ruby | /Rubyrush.ru/step066.rb | UTF-8 | 507 | 2.984375 | 3 | [] | no_license | require_relative 'win_stdin'
exit_loop = -1
until exit_loop == '0'
time = Time.now
time_str_to_file_name = time.strftime('%Y-%m-%d %H-%M')
file_name = __dir__ + '/face ' + time_str_to_file_name
if File.file?(file_name)
puts ("File #{file_name} already exist. Wait to create a new one")
else
file = File.new(file_name,'w:UTF-8')
file.puts ';-)'
file.puts exit_loop.to_s
file.close
end
print 'Create another one file or enter 0 for exit loop: '
exit_loop = gets.chomp
end
| true |
c579cfbe9408bd94d72a201d6316e77d2c7829df | Ruby | tdeo/advent_of_code | /2016/lib/18_like_a_rogue.rb | UTF-8 | 816 | 3.453125 | 3 | [] | no_license | # frozen_string_literal: true
class LikeARogue
def initialize(input)
@rows = []
@rows[0] = input.strip
end
def above_chars(i)
[
(i == 0 ? '.' : ''),
@rows.last[[i - 1, 0].max..[i + 1, @rows.last.size - 1].min],
(i == @rows.last.size - 1 ? '.' : ''),
].join
end
def next_row!
row = @rows.last
@rows << (0...row.size).map do |i|
case above_chars(i)
when '^^.', '.^^', '^..', '..^'
'^'
else '.'
end
end.join
end
def part1(rows = 40)
next_row! while @rows.size < rows
@rows.sum { |r| r.tr('^', '').size }
end
def part2(rows = 400_000)
visited = { @rows.last => 0 }
while @rows.size < rows
next_row!
visited[@rows.last] = @rows.size
end
@rows.sum { |r| r.tr('^', '').size }
end
end
| true |
b00ad9f82ebcab5ad4cb624f926361e2dd5d3c61 | Ruby | evilmartians/evil-client | /lib/evil/client/builder.rb | UTF-8 | 1,147 | 2.53125 | 3 | [
"MIT"
] | permissive | class Evil::Client
#
# @abstract
# Base class for scope/operation builders
#
# Every builder just wraps scope/operation schema along with
# preinitialized [#parent] settings of its super-scope.
# The instance method [#new] quacks like the lazy constructor
# for scope/operation instance whose options reload the [#parent]'s ones.
#
class Builder
Names.clean(self) # Remove unnecessary methods from the instance
# Load concrete implementations for the abstact builder
require_relative "builder/scope"
require_relative "builder/operation"
# The schema for an instance to be constructed via [#new]
# @return [Evil::Client::Schema]
attr_reader :schema
# The instance of parent scope carrying default settings
# @return [Evil::Client::Container::Scope]
attr_reader :parent
# Alias method for [#to_s]
#
# @return [String]
#
def to_str
to_s
end
# Alias method for [#to_s]
#
# @return [String]
#
def inspect
to_s
end
private
def initialize(schema, parent)
@schema = schema
@parent = parent
end
end
end
| true |
d408863beb21649570c9eada7b71470e17857a82 | Ruby | agata-anastazja/learn-to-program | /chap_10/test.rb | UTF-8 | 969 | 3.78125 | 4 | [] | no_license | def sort some_array # This "wraps" recursive_sort.
dict_sort some_array, []
end
def find_smallest(unsorted_array)
candidate_word = unsorted_array[0]
candidate_word_index = 0
unsorted_array.each_with_index do |word, index|
if word.downcase < candidate_word.downcase
candidate_word = word
candidate_word_index = index
end
end
return candidate_word, candidate_word_index
end
def dict_sort unsorted_array, sorted_array
#We’ll take our list of words, find the
#“smallest” word and stick it at the
# end of the already-sorted list.
# All of the other words go into the still-unsorted
while unsorted_array != []
smallest_word, smallest_word_index = find_smallest(unsorted_array)
unsorted_array.delete_at smallest_word_index
sorted_array.push smallest_word
dict_sort still_unsorted, sorted_array
end
sorted_array
end
print sort ["book", "aaaa", "azymut", "ARch"]
print sort ["book", "azymut", "ARch"]
| true |
091721add5ed8afda1a22610d7cb8bc58385113f | Ruby | jon-dominguez94/w2d1-proj | /chess/board.rb | UTF-8 | 1,496 | 3.65625 | 4 | [] | no_license | require_relative 'piece'
class Board
def initialize
@grid = Array.new(8) {Array.new(8) }
populate
end
def move_piece(start_pos, end_pos)
raise ArgumentError, "No piece at this pos!" if self[start_pos].nil?
raise ArgumentError, "Space is taken!" unless self[end_pos].nil?
start_piece = self[start_pos]
self[end_pos] = start_piece
self[start_pos] = nil
end
def self.valid_pos?(pos)
row,col = pos
row.between?(0, 7) && col.between?(0, 7)
end
def render(position)
grid.each_with_index do |row, i|
output = "|"
row.each_index do |j|
pos = [i, j]
if self[pos].nil?
temp = " \|"
temp = temp.bg_red if pos == position # highlight if current_pos == cursor_pos
output += temp
else
temp = " #{self[pos].value} \|"
temp = temp.bg_red if pos == position # highlight if current_pos == cursor_pos
output += temp
end
end
puts output
puts "----" * 8
end
end
private
attr_reader :grid
def [](pos)
row, col = pos
grid[row][col]
end
def []=(pos, val)
row,col = pos
grid[row][col] = val
end
def populate
grid.each_with_index do |row, i|
if [0, 1, 6, 7].include?(i)
row.each_index do |j|
pos = [i,j]
self[pos] = Piece.new("P")
end
end
end
nil #return nil bc we want to return grid for user to see
end
end
| true |
936b873cf5798421269d75d9fd36dca0f5930d21 | Ruby | mpfilbin/conductor | /lib/conductor/applications/stack.rb | UTF-8 | 626 | 2.71875 | 3 | [
"MIT"
] | permissive | require_relative 'interface'
module Conductor
module Applications
# Represents a collection of application interfaces within a given application stack
class Stack
include Enumerable
attr_accessor :applications
def initialize(interfaces)
@applications = []
load_interfaces(interfaces)
end
def each(&block)
applications.each { |application| block.call(application) }
end
private
def load_interfaces(interfaces)
interfaces.each do |interface|
applications << Interface.new(interface)
end
end
end
end
end
| true |
9fcc00f8b7c468a6de48105679e60efeb73e9b34 | Ruby | CrystalToh/LearnRubyTheHardWay | /Functions.rb | UTF-8 | 878 | 4.46875 | 4 | [] | no_license | def extra_credit(var1, var2)
puts "So, the first variable is #{var1}."
puts "And the second variable is #{var2}."
puts "I guess that's about it."
puts
end
puts "Integers:"
extra_credit(1, 2)
puts "Floating points:"
extra_credit(1.2, 3.4)
puts "Variables:"
x = 30
y = 40
extra_credit(x, y)
puts "Integer math:"
extra_credit(10 + 20, 30 - 40)
puts "Floating points math:"
extra_credit(9.8 * 7.6, 5.4 / 3.2)
puts "Variable math:"
a = 11
b = 22
extra_credit(a + b, b - a)
puts "Integer and floating points math:"
extra_credit(1 + 1.2, 2 - 3.4)
puts "Integer and variables math:"
i = 33
j = 44
extra_credit(3 * i, 4 / j)
puts "Floating points and variables math:"
variable1 = 55
variable2 = 66
extra_credit(5.6 + variable1, 7.8 + variable2)
puts "Variable concatenation:"
variable3 = "break"
variable4 = "fast"
extra_credit(variable3 + variable4, variable4 + variable3) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.