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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6e2b060a03871daaf03deb6cc9d4d959a72cbdc4 | Ruby | dyet92k/reel | /lib/reel/response/writer.rb | UTF-8 | 1,763 | 2.71875 | 3 | [
"MIT"
] | permissive | module Reel
class Response
class Writer
CRLF = "\r\n"
def initialize(socket)
@socket = socket
end
# Write body chunks directly to the connection
def write(chunk)
chunk_header = chunk.bytesize.to_s(16)
@socket << chunk_header + CRLF
@socket << chunk + CRLF
rescue IOError, SystemCallError => ex
raise Reel::SocketError, ex.to_s
end
# Finish the response and reset the response state to header
def finish_response
@socket << "0#{CRLF * 2}"
end
# Render a given response object to the network socket
def handle_response(response)
@socket << render_header(response)
return response.render(@socket) if response.respond_to?(:render)
case response.body
when String
@socket << response.body
when IO
Celluloid::IO.copy_stream(response.body, @socket)
when Enumerable
response.body.each { |chunk| write(chunk) }
finish_response
when NilClass
# Used for streaming Transfer-Encoding chunked responses
return
else
raise TypeError, "don't know how to render a #{response.body.class}"
end
response.body.close if response.body.respond_to?(:close)
end
# Convert headers into a string
def render_header(response)
response_header = "#{response.version} #{response.status} #{response.reason}#{CRLF}"
unless response.headers.empty?
response_header << response.headers.map do |header, value|
"#{header}: #{value}"
end.join(CRLF) << CRLF
end
response_header << CRLF
end
private :render_header
end
end
end
| true |
c80edc49c41341ff533ea61133fb75e67df2af29 | Ruby | kattak/phase-0-tracks | /ruby/list/list.rb | UTF-8 | 414 | 3.5625 | 4 | [] | no_license | class TodoList
def initialize(ary)
@items = ary
#@ means an instance variable, accessed by other methods within the class
#don't use @? it would have been a variable within this method
end
def get_items
return @items
end
def add_item(item1)
@items.push(item1)
end
def delete_item(item)
@items.delete(item)
end
def get_item(idx)
return @items[idx]
end
end | true |
88cc311e5e38e06f2f1785cd7433f7e52158d780 | Ruby | trose618/my-each-dumbo-web-102918 | /my_each.rb | UTF-8 | 126 | 3.203125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def my_each(array)
# code here
indx = 0
while indx < array.length
yield array[indx]
indx+=1
end
array
end | true |
c5808a0f1adbac44fbafeead71aeb3a471d07cbb | Ruby | charlesbjohnson/super_happy_interview_time | /rb/lib/leetcode/lc_19.rb | UTF-8 | 923 | 3.5625 | 4 | [
"MIT"
] | permissive | # frozen_string_literal: true
module LeetCode
# 19. Remove Nth Node From End of List
module LC19
ListNode = Helpers::LeetCode::LinkedList::ListNode
# Description:
# Given a linked list, remove the nth node from the end of list and return its head.
# Examples:
# Input: head = [1, 2, 3, 4, 5], n = 2
# Output: [1, 2, 3, 5]
#
# Input: head = [1], n = 1
# Output: []
#
# Input: head = [1,2], n = 1
# Output: [1]
#
# Notes:
# - Given n will always be valid.
# - Try to do this in one pass.
#
# @param {ListNode} head
# @param {Integer} n
# @return {ListNode}
def remove_nth_from_end(head, n)
s = ListNode.new(nil, head)
i = s
j = s
while n >= 0
j = j.next
n -= 1
end
while j
i = i.next
j = j.next
end
i.next = i.next.next
s.next
end
end
end
| true |
a75619dfe7c09c426671bbdbe5ff84e0b33a86b0 | Ruby | Galaxylaughing/ride-share-rails | /test/models/driver_test.rb | UTF-8 | 9,892 | 2.90625 | 3 | [] | no_license | require "test_helper"
describe Driver do
let (:new_driver) {Driver.new(name: "Kari", vin: "123", active: true, car_make: "Cherry", car_model: "DR5")}
it "can be instantiated" do
# Assert
expect(new_driver.valid?).must_equal true
end
it "will have the required fields" do
# Arrange
new_driver.save
driver = Driver.first
[:name, :vin, :active, :car_make, :car_model].each do |field|
# Assert
expect(driver).must_respond_to field
end
end
describe "relationships" do
it "can have many trips" do
# Arrange
new_driver.save
new_passenger = Passenger.create(name: "Kari", phone_num: "111-111-1211")
trip_1 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 5, cost: 1234)
trip_2 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 3, cost: 6334)
# Assert
expect(new_driver.trips.count).must_equal 2
new_driver.trips.each do |trip|
expect(trip).must_be_instance_of Trip
end
end
end
describe "validations" do
it "must have a name" do
# Arrange
new_driver.name = nil
# Assert
expect(new_driver.valid?).must_equal false
expect(new_driver.errors.messages).must_include :name
expect(new_driver.errors.messages[:name]).must_equal ["can't be blank"]
end
it "must have a VIN number" do
# Arrange
new_driver.vin = nil
# Assert
expect(new_driver.valid?).must_equal false
expect(new_driver.errors.messages).must_include :vin
expect(new_driver.errors.messages[:vin]).must_equal ["can't be blank"]
end
end
# Tests for methods you create should go here
describe "custom methods" do
describe "average rating" do
it "can calculate the average rating of multiple trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
trip_two = Trip.create(date: Date.current, rating: 3, cost: 1400, driver_id: driver.id, passenger_id: passenger.id)
# assert
expect(driver.average_rating).must_equal 4
end
it "can calculate the average rating of one trip" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
# assert
expect(driver.average_rating).must_equal 5
end
it "can calculate the average rating of multiple trips where one is not rated" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
trip_two = Trip.create(date: Date.current, rating: nil, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
# assert
expect(driver.average_rating).must_equal 5
end
it "returns nil for a driver with no trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# assert
expect(driver.average_rating).must_be_nil
end
end
describe "total earnings" do
it "can calculate the total earnings for multiple trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
trip_two = Trip.create(date: Date.current, rating: 3, cost: 1400, driver_id: driver.id, passenger_id: passenger.id)
# assert
expect(driver.total_earnings).must_equal 2600
end
it "can calculate the total earnings for one trip" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
# assert
expect(driver.total_earnings).must_equal 1200
end
it "returns 0 for a driver with no trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# assert
expect(driver.total_earnings).must_equal 0
end
end
describe "driver earnings" do
it "can calculate the driver's earnings for multiple trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
trip_two = Trip.create(date: Date.current, rating: 3, cost: 1400, driver_id: driver.id, passenger_id: passenger.id)
# 1200 + 1400 = 2600
# 2600 - 165 = 2435
# 2435 * 0.8 = 1948
# assert
expect(driver.driver_earnings).must_equal 1948
end
it "can calculate the driver's earnings for one trip" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# create a passenger for the trips
passenger = Passenger.create(name: "Nina", phone_num: "560.815.3059")
# create two trips
trip_one = Trip.create(date: Date.current, rating: 5, cost: 1200, driver_id: driver.id, passenger_id: passenger.id)
# 1200 - 165 = 1035
# 1035 * 0.8 = 828
# assert
expect(driver.driver_earnings).must_equal 828
end
it "returns 0 for a driver with no trips" do
# arrange
driver = Driver.create(name: "Kari", vin: "123")
# assert
expect(driver.driver_earnings).must_equal 0
end
end
describe "can go online" do
it "makes active true if it is false" do
# arrange
driver = Driver.create(name: "Micky", vin: "777", active: false)
driver_id = driver.id
# act
driver.go_online
updated_driver = Driver.find_by(id: driver_id)
# assert
expect(updated_driver.active).must_equal true
end
it "should be idempotent" do
# arrange
driver = Driver.create(name: "Micky", vin: "777", active: false)
driver_id = driver.id
# act
driver.go_online
driver.go_online
updated_driver = Driver.find_by(id: driver_id)
# assert
expect(updated_driver.active).must_equal true
end
end
describe "can go offline" do
it "makes active false if it is true" do
# arrange
driver = Driver.create(name: "Micky", vin: "777", active: true)
driver_id = driver.id
# act
driver.go_offline
updated_driver = Driver.find_by(id: driver_id)
# assert
expect(updated_driver.active).must_equal false
end
it "should be idempotent" do
# arrange
driver = Driver.create(name: "Micky", vin: "777", active: true)
driver_id = driver.id
# act
driver.go_offline
driver.go_offline
updated_driver = Driver.find_by(id: driver_id)
# assert
expect(updated_driver.active).must_equal false
end
end
# You may have additional methods to test
describe "get driver" do
it "should select the first available driver" do
unavailable_driver = Driver.create(name: "I am unavailable", vin: "unavailable", active: false)
driver1 = Driver.create(name: "Bernardo Prosacco", vin: "WBWSS52P9NEYLVDE9", active: true)
driver2 = Driver.create(name: "available driver", vin: "13245", active: true)
selected_driver = Driver.get_driver
expect(selected_driver).must_be_instance_of Driver
expect(selected_driver.name).must_equal driver1.name
expect(selected_driver.vin).must_equal driver1.vin
expect(selected_driver.active).must_equal false
end
it "should return nil if there are no inactive drivers" do
unavailable_driver = Driver.create(name: "I am unavailable", vin: "unavailable", active: false)
selected_driver = Driver.get_driver
expect(selected_driver).must_be_nil
end
end
describe "avatar image" do
it "must return an image link" do
driver = Driver.create(name: "M. Random", vin: "88888888", active: false)
avatar_url = driver.avatar_image
url_beginning = !!(avatar_url =~ /\Ahttps:\/\//)
url_ending = !!(avatar_url =~ /\.png\Z/)
expect(url_beginning).must_equal true
expect(url_ending).must_equal true
end
end
end
end
| true |
3e6763d1918e3a4ffaad245ee88d02b4902f8bea | Ruby | makevoid/headshot | /models/hshot.rb | UTF-8 | 1,087 | 2.75 | 3 | [] | no_license | class SiteNotFound < Exception
def initialize(site)
@site = site
end
def message
"error in finding the site, got: #{@site} - review your list of sites, or the site you are calling"
end
end
class HShot
require 'url2png'
require 'net/http'
include Url2png::Helpers::Common
def initialize(sites)
@sites = sites
end
def get(site)
site = if site.is_a? Symbol
@sites[site]
else
# TODO: check if the url is valid
site if valid?(site)
end
raise SiteNotFound.new(site) if site.nil?
get_url site
end
private
def valid?(site)
site =~ URI::regexp
end
def async(&block)
t = Thread.new{
block.call
}
t.abort_on_exception
end
def get_url(url)
Url2png::Config.public_key = 'P4E548D4E3A596'
Url2png::Config.shared_secret = File.read("#{ENV["HOME"]}/.url2png").strip
async do
prefetch_image url
end
site_image_url url, :size => '1200x800'
end
def prefetch_image(url)
uri = URI.parse url
Net::HTTP.get_response uri
end
end | true |
70cee05d03cd42aa31b4a86dea7d1843bd8716ca | Ruby | tomecho/PrimeSpeedTest | /prime.rb | UTF-8 | 376 | 3.78125 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/ruby
def test(prime)
for i in 2...prime
if(prime % i == 0)
return false
end
end
return true
end
def main
if ARGV[0] == nil
puts 'please call me like "ruby prime.rb range"'
exit 1
else
@range = ARGV[0].to_i
end
primes = []
for i in 0...@range
if(test(i))
primes.push(i)
end
end
puts primes.length
end
main
| true |
55458a5656f0413415636a6b677f358b8c2a1675 | Ruby | marzily/sales_engine | /lib/repository.rb | UTF-8 | 1,235 | 3.078125 | 3 | [] | no_license | require 'date'
require_relative 'model_object'
class Repository
attr_reader :collection, :engine
def initialize(data, engine)
@collection = generate(data)
@engine = engine
end
def generate(data)
data.map { |object_data| model_class.new(object_data, self) }
end
def all
collection
end
def random
collection.sample
end
def hash_repo(index_key)
index_keys = index_key.split(".")
Hash.new([]).merge(all.group_by do |se_object|
index_keys.inject(se_object) { |object, key| object.method(key).call }
end)
end
def find_all_by_id(id)
@all_by_id ||= hash_repo("id")
@all_by_id[id]
end
def find_by_id(id)
find_all_by_id(id).first
end
def find_all_by_created_at(time_stamp)
@all_by_created_at ||= hash_repo("created_at")
@all_by_created_at[time_stamp]
end
def find_by_created_at(time_stamp)
find_all_by_created_at(time_stamp).first
end
def find_all_by_updated_at(time_stamp)
@all_by_updated_at ||= hash_repo("updated_at")
@all_by_updated_at[time_stamp]
end
def find_by_updated_at(time_stamp)
find_all_by_updated_at(time_stamp).first
end
def inspect
"#<#{self.class} #{collection.size} rows>"
end
end
| true |
bfc5d46f4ddd6ded8c7e2fcc8435b1134b293dc4 | Ruby | marlomajor/enigma | /lib/enigma_one.rb | UTF-8 | 484 | 2.703125 | 3 | [] | no_license | require_relative 'encrypt'
require_relative 'decrypt'
require_relative 'message_encrypter'
require 'pry'
# FILEIO for ENCRYPT
if __FILE__ == $0
decrypted_file = ARGV[1]
encrypted_file = ARGV[0]
encrypted_message = File.read(encrypted_file)
decrypted_message = MessageEncrypter.new(encrypted_message).encrypts
File.write(decrypted_file, decrypted_message)
puts "Created '#{decrypted_file}' with the key #{KeyGenerator.new.key} and date #{Encrypt.new.date_file}"
end
| true |
d92e46b4a8d27c7dfc8092dc1231bc7498d5d66d | Ruby | metacoder87/maze_solver | /lib/minotaur.rb | UTF-8 | 5,481 | 4.25 | 4 | [] | no_license | # meta_coder (Gary Miller) =)
# gmiller052611@gmail.com
# https://github.com/metacoder87/maze_solver
class Maze
attr_reader :grid
# reads the maze file and creates the grid array for easy solving
def initialize(*maze)
unless maze[0]
@maze = gets_maze
else @maze = maze[0]
end
@grid = []
IO.readlines(@maze).each do |line|
@grid << line.chomp.split('')
end
end
# Asks the user for the maze they want solved
def gets_maze
puts "Enter the name of a text file: maze, labyrinth, trap, tartarus\n
and prepare to be AMAZED!"
maze = gets.chomp.to_s
if maze.include?(".txt")
maze
else maze + '.txt'
end
end
# Determines is a given space is empty or not
def empty?(location)
if @grid[location[0]][location[1]] == " "
true
else false
end
end
# Returns an array of all the spaces that are available
def free_space
spaces = []
@grid.each_with_index do |row, idx|
row.each_with_index do |col, i|
location = [idx, i]
if empty?(location) || @grid[location[0]][location[1]] == "E"
spaces << location
end
end
end
spaces
end
# Returns an array containing the location of the starting S
def start_space
location = []
@grid.each_with_index do |row, idx|
row.each_with_index do |col, i|
if @grid[idx][i] == "S"
location << idx
location << i
end
end
$x = location[0]
$y = location[1]
end
location
end
# Returns an array containing the location of the ending E
def end_space
location = []
@grid.each_with_index do |row, idx|
row.each_with_index do |col, i|
if @grid[idx][i] == "E"
location << idx
location << i
end
end
end
location
end
# Determines if the given maze is actually solvable
def dead_end?
over = [end_space[0] - 1, end_space[1]]
under = [end_space[0] + 1, end_space[1]]
left = [end_space[0], end_space[1] - 1]
right = [end_space[0], end_space[1] + 1]
if free_space.include?(over)
false
elsif free_space.include?(under)
false
elsif free_space.include?(left)
false
elsif free_space.include?(right)
false
else true
end
end
# Places the X on the next chosen available space
def take_step
if @grid[$x][$y] != "E"
@grid[$x][$y] = "X"
else end_reached
end
end
# Prints out the maze with whatever moves have been made
def print
@grid.each { |line| puts line.join("") }
end
# Signals the end of the maze has been found
def end_reached
print
puts "You have escaped the Labyrinth!\n You are free, Minotaur!"
end
# Places the X above the S or the last X
def move_up
$x -= 1
take_step
end
# Determines if the space above is a free space
def up?
free_space.include?([$x.to_i - 1, $y])
end
# Places the X below the S or the last X
def move_down
$x += 1
take_step
end
# Determines if the space below is a free space
def down?
free_space.include?([$x.to_i + 1, $y])
end
# Places the X to the right of the S or the last X
def move_right
$y += 1
take_step
end
# Determines if the space to the right is a free space
def right?
free_space.include?([$x, $y.to_i + 1])
end
# Places the X to the left of the S or the last X
def move_left
$y -= 1
take_step
end
# Determines if the space to the left is a free space
def left?
free_space.include?([$x, $y.to_i - 1])
end
# Escapes the maze if it can be done.
# remove the # blocking out the print statements below to see the path unfold
def path_finder
print
puts "Starting space is #{start_space}"
puts "Ending space is #{end_space}"
if dead_end?
puts "You are trapped forever in an inescapable labyrinth.\n
These things happen to Minotaurs sometimes."
else
while [$x, $y] != end_space
if up?
move_up
# print
elsif right?
move_right
# print
elsif down?
move_down
# print
elsif left?
move_left
# print
end
end
end
end
end
# Tests (comment out for less clutter in the RSPEC results)
# solvable
Maze.new('maze.txt').path_finder
Maze.new('labyrinth.txt').path_finder
# inescapable
Maze.new('trap.txt').path_finder
Maze.new('tartarus.txt').path_finder
# pick your own maze on the cmd line
Maze.new.path_finder
# meta_coder (Gary Miller) =)
# gmiller052611@gmail.com
# https://github.com/metacoder87/maze_solver | true |
422703db29471357f3e6f7cd6884fe83e68a2a3b | Ruby | tommottom/ruby | /whats_empty?.rb | UTF-8 | 119 | 2.671875 | 3 | [] | no_license |
p "".empty?
p "ruby".empty?
#文字列の長さが0のときにtrue
#文字列の長さが0以上にときにfalse
| true |
11d9f54a81b2a26c4a28c5e1849b5337440ce824 | Ruby | alrawi90/anagram-detector-re-coded-000 | /lib/anagram.rb | UTF-8 | 421 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Your code goes here!
class Anagram
attr_accessor :word
@matched=[]
def initialize(word)
@word=word
@matched=[]
end
def matched
@matched
end
def match(arr)
#arr=text.split(" ")
arr.each do |w|
if word.split("").sort==w.split("").sort
matched.push(w)
end
end
return matched
end
end
obj=Anagram.new("listen")
#puts obj.match("enlists google inlets banana")
| true |
ec5f001b8c8ea2d76653e14601d4b1b35afd66b4 | Ruby | danigunawan/Itinerant | /backend/app/models/itinerary.rb | UTF-8 | 2,495 | 2.671875 | 3 | [] | no_license | class Itinerary < ApplicationRecord
has_many :user_itineraries
has_many :users, through: :user_itineraries
has_many :cities
has_many :areas, through: :cities
has_many :attractions, through: :areas
has_many :plans, through: :cities
before_save :default_values
def default_values
self.vital_info ||= "Flight info, hotel reservations, etc"
self.helpful_info ||= "Train tables, tour reservations, etc"
self.notes ||= "Check out this New York Times article..."
end
def attractions_by_distance (lat, lng)
self.attractions.sort_by{|att| Math.sqrt((att.latitude.to_f - lat)**2 + (att.longitude.to_f - lng)**2)}
end
def plans_by_date
self.plans.group_by{|i| i.date}.keys.sort
end
def full_itinerary
itinerary_hash = {}
itinerary_hash[:details] = self
itinerary_hash[:schedule] = self.plans_by_date
itinerary_hash[:users] = self.users
itinerary_hash[:attractions] = self.attractions
itinerary_hash[:cities] = []
self.cities.each do |city|
area_array = []
city.areas.each do |area|
area_array.push({id: area.id, name: area.name, content: area.content, attractions: area.attractions})
end
itinerary_hash[:cities].push(id: city.id, name: city.name, country: city.country, content: city.content, areas: area_array, plans: city.plans_by_date)
end
itinerary_hash
end
def export_attractions
# CSV.open("csv/#{file_name}.csv", "w+") do |csv|
# csv << ["Latitude, Longitude", "Name", "Address", "Cost", "Classification", "Description"]
# keys = ["name", "address", "cost", "classification", "description"]
# self.attractions.each do |att|
# attraction_array = []
# attraction_array.push(att.lat_lng)
# keys.each do |k|
# attraction_array.push(att[k])
# end
# csv << attraction_array
# end
# end
# this downloads a csv to the server...
csv = []
csv << ["Latitude, Longitude", "Name", "Address", "Cost", "Classification", "Description"]
keys = ["name", "address", "cost", "classification", "description"]
self.attractions.each do |att|
attraction_array = []
attraction_array.push(att.lat_lng)
keys.each do |k|
attraction_array.push(att[k])
end
csv << attraction_array
end
return csv
end # This correctly exports attractions in a format that is easily imported into Google's My Maps. Now to get the site to give it to the user...
end
| true |
f920d9684c40e36f6f7fdcdf2c721dd7d97087fe | Ruby | sisinduku/finance | /spec/finance/income_spec.rb | UTF-8 | 1,764 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
RSpec.describe Finance::Income do
subject { described_class.new }
let(:first_report) { Finance::Report.new(1000, 200, 'INDIVIDUAL', Date.parse('2021-01-01')) }
let(:second_report) { Finance::Report.new(2000, 100, 'INDIVIDUAL', Date.parse('2021-02-01')) }
let(:third_report) { Finance::Report.new(2000, 100, 'INDIVIDUAL', Date.parse('2021-03-01')) }
let(:reports) { [first_report, second_report, third_report] }
let(:start_date) { Date.parse('2021-02-01') }
let(:end_date) { Date.parse('2021-03-01') }
let(:date_range) { Finance::DateRange.new(start_date, end_date) }
describe '#get_total_net_income' do
let(:expected_total_net_income) { 720 + 1900 - 190 + 1900 - 190 }
it 'returns total net income from reports' do
expect(subject.get_total_net_income(reports)).to eq(expected_total_net_income)
end
end
describe '#total_income_in' do
let(:expected_result) { 4000 }
it 'returns total net income' do
expect(subject.total_income_in(date_range, reports)).to eq(expected_result)
end
end
describe '#total_expense_in' do
let(:expected_result) { 200 }
it 'returns total expense in specified date range' do
expect(subject.total_expense_in(date_range, reports)).to eq(expected_result)
end
end
describe '#total_net_income_in' do
let(:expected_result) { 3420.0 }
it 'returns total net income in specified date range' do
expect(subject.total_net_income_in(date_range, reports)).to eq(expected_result)
end
end
describe '#average_income_in' do
let(:expected_result) { 142.0 }
it 'returns average income in specified date range' do
expect(subject.average_income_in(date_range, reports)).to eq(expected_result)
end
end
end
| true |
1ab16dccd8437bd852a9736f3098d6bc38bbc8be | Ruby | JeremyDownes/LS-Ruby-Object-Oriented-Programming-Exercises | /OOP Easy 1.rb | UTF-8 | 2,985 | 3.703125 | 4 | [] | no_license | # Banner Class
class Banner
def initialize(message)
@werds = message
@leng = @werds.length
end
def to_s
[horizontal_rule, empty_line, message_line, empty_line, horizontal_rule].join("\n")
end
private
def horizontal_rule
hr = "+"
(@leng+2).times {hr += "-"}
hr += "+"
end
def empty_line
el = "|"
(@leng+2).times {el += " "}
el += "|"
end
def message_line
"| #{@werds} |"
end
end
# What's the Output? This may have been fixed in development
class Pet # It seems to work normally
attr_reader :name # Instantiate new object states reflect changes
# Idk what we're trying to do here. .upcase! ?
def initialize(name)
@name = name.to_s
end
def to_s
"My name is #{@name.upcase}."
end
end
# Fix the Program - Books (Part 1)
class Book
attr_reader :author, :title
def initialize(author, title)
@author = author
@title = title
end
def to_s
%("#{title}", by #{author})
end
end
# Fix the Program - Books (Part 2)
class Book
attr_accessor :author, :title
def to_s
%("#{title}", by #{author})
end
end
# Fix the Program - Persons
class Person
def initialize(first_name, last_name)
@first_name = first_name.capitalize
@last_name = last_name.capitalize
end
def first_name= (name)
@first_name = name.capitalize
end
def last_name= (name)
@last_name = name.capitalize
end
def to_s
"#{@first_name} #{@last_name}"
end
end
# Fix the Program - Flight Data
class Flight
attr_accessor :flights_database
def initialize(flight_number)
@flights_database = Database.init
@flight_number = flight_number
end
end
# Buggy Code - Car Mileage
class Car
attr_accessor :mileage
def initialize
@mileage = 0
end
def increment_mileage(miles)
@mileage += miles
end
def print_mileage
puts @mileage
end
end
# Rectangles and Squares
class Rectangle
def initialize(height, width)
@height = height
@width = width
end
def area
@height * @width
end
end
class Square < Rectangle
def initialize(size)
@height = size
@width = size
end
end
class Pet
def initialize(name, age,*)
@name = name
@age = age
end
end
class Cat < Pet
def initialize(name, age, color)
@color = color
super
end
def to_s
"My cat #{@name} is #{@age} years old and has #{@color} fur."
end
end
# Refactor Vehicles
class Vehicle
attr_reader :make, :model, :wheels
def initialize(make, model,*)
@make = make
@model = model
end
def to_s
"#{make} #{model}"
end
end
class Car < Vehicle
def initialize(make, model)
super
@wheels = 4
end
end
class Motorcycle < Vehicle
def initialize(make, model)
super
@wheels = 2
end
end
class Truck < Vehicle
attr_reader :payload
def initialize(make, model, payload)
super
@payload = payload
@wheels = 6
end
end | true |
05d0f6df707ad2e695f8a939635e5aa3d59e98f4 | Ruby | RodCardenas/AppAcademyProjects | /HIR/problems/spec/valid_walk_spec.rb | UTF-8 | 1,334 | 4.03125 | 4 | [] | no_license | # ### Valid Walk ####
# You have a walking robot. Given a string of compass directions (e.g., "nesw"
# or "nnssen"), it will travel one mile in each of those directions. Write a
# method to determine whether a set of directions will lead your robot back to
# its starting position.
# Example:
# valid_walk?("nnnn") # => false
# valid_walk?("nenessww") # => true
describe "#valid_walk?" do
context 'requirements' do
it 'returns true if the path returns you to your inital position' do
expect(valid_walk?('nesw')).to be true
end
it 'returns false if the path leaves you somewhere else' do
expect(valid_walk?('nes')).to be false
end
it 'keeps the Nort-South and East-West axes separate' do
expect(valid_walk?('nw')).to be false
end
it 'returns true for a complex valid path' do
expect(valid_walk?('wsseenwwwnnees')).to be true
end
it 'returns true for an empty string (no path at all)' do
expect(valid_walk?('')).to be true
end
end
context 'bonus' do
it 'is case insensitive' do
expect(valid_walk?('neSW')).to be true
expect(valid_walk?('nsE')).to be false
end
it 'ignores invalid characters' do
expect(valid_walk?('yum wendy\'s!')).to be true
expect(valid_walk?('[not cool], wesley')).to be false
end
end
end
| true |
702c2c6daed1e63f50861c34915cfa6c98549f3b | Ruby | hegwin/Design-Patterns-in-Ruby | /Meta-Programming/playground.rb | UTF-8 | 489 | 2.875 | 3 | [] | no_license | require_relative './composite_base'
class Tiger < CompositeBase
member_of :population
member_of :classification
end
class Jungle < CompositeBase
composite_of :population
end
class Species < CompositeBase
composite_of :classification
end
tiger = Tiger.new('Tony')
jungle = Jungle.new('Northeastern Jungle')
jungle.add_sub_population(tiger)
species = Species.new('Panthera tigris')
species.add_sub_classification(tiger)
p tiger.parent_population
p tiger.parent_classification
| true |
def1ce573623cee271041f6e6e1c3a3d6b87a304 | Ruby | kevinjcoleman/studentideals | /app/models/category_loader.rb | UTF-8 | 868 | 2.6875 | 3 | [] | no_license | class CategoryLoader
attr_accessor :file_name
def initialize(file_name)
@file_name = file_name
end
def import!
CSV.open("tmp/category_errors.csv", "wb") do |errors|
CSV.foreach(file_name, headers: true) do |row|
begin
row_hash = row_hash(row)
business = Business.find_by_biz_id(row_hash[:biz_id])
next unless business
SubCategory.create_subcategory_and_tree_from_row(row_hash.except(:biz_id), business)
rescue => e
errors << row.to_hash.values.push(e.message)
errors.flush
end
end
end
end
def biz_id(row)
row["biz_hrs_id"]
end
def row_hash(row)
{biz_id: row["biz_id"],
metadata_name: row["metadata_name"],
metadata_value: row["metadata_value"],
label: row["Label"],
category_path: row["category_path"]}
end
end
| true |
9612f19e6efaf1ee6da84477dfe8f60b00577f24 | Ruby | inosyo/ABC | /def_rubiocci.rb | UTF-8 | 1,649 | 3.734375 | 4 | [] | no_license | #!/usr/koeki/bin/ruby
# -*- coding: utf-8 -*-
def cry(ct)
ct.times do
print("ぴよ\t")
end
print("\n")
sleep(0.5)
end
def message(usr, tame)
STDERR.printf("%sを世話しよう: \n", usr)
for line in 0 .. tame.length - 1
STDERR.printf("[%d]\t%s\n", line + 1, tame[line])
end
end
def fat(perday, exercise)
extra = 4 * perday - exercise
printf("%d日目\n",perday + 1)
# printf("体重増加分 %d\n", extra)
return extra
end
def select(lines)
# p lines
words = Array.new
i = 0
open(lines, "r:utf-8") do |choice|
while line = choice.gets
# p line
if /(\S+)/ =~ line
words[i] = $1
i += 1
end
end
end
words
end
gamefile = "rubiocci.csv"
gamedef = select(gamefile)
printf("たまごを拾った。\n")
STDERR.printf("どんな名前にする?: ")
name = gets.chomp
if name == ""
name = "るびおっち"
end
printf("%sという名前になった。\n",name)
happy = 1 # しあわせ度
weight = 1 # 体重
day = 0 # 育てた日付
printf("よく鳴くと大きくなるよ\n")
while true
message(name, gamedef)
ans = gets.to_i
cry(ans)
happy += day * ans
# printf("しあわせ度 happy=%d\n", happy)
weight += fat(day,ans)
# printf("体重 weight=%d\n", weight)
if happy > 4 || weight > 4
break
else
day += 1
end
end
STDERR.print("変化した!\n")
cry(weight) # 最終段階の体重が鳴き声になる
printf("%sは", name)
if weight > 8
print("ふくろう")
elsif weight <= 5
print("すずめ")
else
print("からす")
end
print("みたいになりました\n")
| true |
de8abbbef54c1467147be7eee4cb9210b2b7a330 | Ruby | jes5199/nodegel | /app/models/user.rb | UTF-8 | 319 | 2.515625 | 3 | [] | no_license | class User < ActiveRecord::Base
has_secure_password
validates_format_of :name, with: /\A[''a-zA-Z0-9!?. _-]+\z/
validate :no_weird_spacing
def to_s
return self.name
end
def no_weird_spacing
if name != name.strip.gsub(" ", " ")
errors.add(:name, "can't have weird spaces")
end
end
end
| true |
c6b5f33d0a9087ce549a91a6ac0819d3b996e06d | Ruby | nuclearsandwich/sbpprb | /08_query_method.rb | UTF-8 | 173 | 2.90625 | 3 | [] | no_license | # Query Method
# Ruby has a syntactical edge on this one: there is a clear and
# well-known idiom for naming predicate methods.
class Switch
def on?
# ...
end
end
| true |
a861cbdb830891eeb91d2f61eac7dcca93265e48 | Ruby | BenitolSantos/model-class-methods-reading-v-000 | /app/controllers/posts_controller.rb | UTF-8 | 2,010 | 2.765625 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class PostsController < ApplicationController
#added to ensure access to params hash
helper_method :params
#Note: You can use helper_method in a controller to expose, or make available, a controller method in your view, but, as we'll talk about soon, this isn't always a great idea.
def index
@posts = Post.all
# provide a list of authors to the view for the filter control
@authors = Author.all
if !params[:author].blank?
@posts = Post.by_author(params[:author])
#So having something that looks like this...
#@posts = Post.where(author: params[:author])
#...isn't the best application of MVC and separation of concerns.
#You'll notice that it's essentially the same code that we had in the controller, but it's now properly encapsulated in the model. This way, a controller doesn't have to query the database — it just has to ask for posts by_author.
elsif !params[:date].blank?
if params[:date] == "Today"
@posts = Post.from_today
else
@posts = Post.old_news
end
else
# if no filters are applied, show all posts
@posts = Post.all
end
end
=begin
#added to index.html.erb
<div>
<% if !params[:author].blank? %>
<% @posts = Post.where(author: params[:author]) %>
<% end %>
<!-- new code ends here -->
<h1>Believe It Or Not I'm Blogging On Air</h1>
<h3>Filter posts:</h3>
<%= form_tag("/posts", method: "get") do %>
<%= select_tag "author", options_from_collection_for_select(Author.all, "id", "name"), include_blank: true %>
<%= submit_tag "Filter" %>
<% end %>
</div>
=end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(params)
@post.save
redirect_to post_path(@post)
end
def update
@post = Post.find(params[:id])
@post.update(params.require(:post))
redirect_to post_path(@post)
end
def edit
@post = Post.find(params[:id])
end
end
| true |
bc413b275baf63246527ceaeabbef997d4657c47 | Ruby | svenfuchs/travis-activity | /lib/stats/table.rb | UTF-8 | 725 | 2.75 | 3 | [] | no_license | class Stats
class Table
ROW_COUNTS = {
month: 12,
week: 52,
day: 365
}
attr_reader :repos, :user, :interval
def initialize(options = {})
@repos = options[:repos] || REPOS
@user = options[:user]
@interval = options[:interval] || :week
end
def data
[header] + rows
end
def colors
COLORS.values_at(*repos)
end
def header
[interval.to_s] + repos
end
def rows
(1..ROW_COUNTS[interval.to_sym]).to_a.map do |key|
[key] + stats.map { |data| data[key] || 0 }
end
end
def stats
@stats ||= repos.map do |repo|
Record.new(repo, user, interval).data
end
end
end
end
| true |
4098c274ff25647ee0be5b5aed127fb1c1a3ab36 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/sum-of-multiples/d0f59e37780c46a89445c09ad010ec2c.rb | UTF-8 | 279 | 3.734375 | 4 | [] | no_license | class SumOfMultiples
def initialize(*multiples)
@multiples = multiples
end
def self.to(n)
SumOfMultiples.new(3, 5).to(n)
end
def to(n)
(1...n).select do |i|
@multiples.any? do |m|
i % m == 0
end
end.reduce(0, :+)
end
end
# puts SumOfMultiples.to(1)
| true |
e351fd040f4bf2e5119fca82d6c01a4e81363673 | Ruby | tfb34/chess | /player/chess_pieces/piece.rb | UTF-8 | 3,665 | 3.5625 | 4 | [] | no_license |
require_relative File.expand_path("../gameboard/board.rb",File.dirname(__FILE__))
class Piece
attr_reader :location, :coat, :color, :route
BLACK = "black"
WHITE = "white"
def get_x
@location[0]
end
def get_y
@location[1]
end
def add_to_route(value)
@route = [] if @route.nil?
@route << value
end
def empty_route?
return true if @route.nil? || @route.empty?
end
def delete_route
@route = []
end
def set_location(location)
@location = location
end
def opponent_color
if @color == BLACK
return WHITE
else
return BLACK
end
end
#the following 3 functions are called inside the 'clear_path?' function
#in the bishop, queen, rook class
def vertical_path_clear?(record_route = false,row,col)
return true if (row-get_x).abs == 1
if get_x < row
(get_x+1).upto(row-1) do |x|
add_to_route([x,col])
if !@board.empty?(x,col)
delete_route
return false
end
end
else
(get_x-1).downto(row+1) do |x|
add_to_route([x,col])
if !@board.empty?(x,col)
delete_route
return false
end
end
end
delete_route if !record_route
true
end
def horizontal_path_clear?(record_route=false,row,col)
return true if (col-get_y).abs == 1
if get_y <col
(get_y+1).upto(col-1) do |y|
add_to_route([row,y])
if !@board.empty?(row,y)
delete_route
return false
end
end
else
(get_y-1).downto(col+1) do |y|
add_to_route([row,y])
if !@board.empty?(row,y)
delete_route
return false
end
end
end
delete_route if !record_route
true
end
def diagonal_path_clear?(record_route=false,row,col)#Assumption: position row,col is located diagonally
return true if (row - get_x).abs == 1#adjacent
return check_right_side?(record_route,row,col) if col > get_y #right side
return check_left_side?(record_route,row,col) #otherwise, left side
end
#the following functions are called within the 'diagonal_path_clear?' function only
private
def check_right_side?(record_route=false,row,col)
if row < get_x #upward #x-1, y+1
x = get_x-1
y = get_y+1
while(x>row && y<col)
if !@board.empty?(x,y)
delete_route
return false
end
add_to_route([x,y])
x-=1 ; y+=1
end
else #downward ; x+1, y+1
x = get_x+1
y = get_y+1
while(x<row && y<col)
if !@board.empty?(x,y)
delete_route
return false
end
add_to_route([x,y])
x+=1 ; y+=1
end
end
delete_route if !record_route
true
end
def check_left_side?(record_route=false,row,col)
if row <get_x #up
x = get_x-1
y = get_y-1
while(x>row && y >col)
if !@board.empty?(x,y)
delete_route
return false
end
add_to_route([x,y])
x-=1 ; y-=1
end
else#down
x = get_x+1
y = get_y-1
while(x<row && y>col)
if !@board.empty?(x,y)
delete_route
return false
end
add_to_route([x,y])
x+=1 ; y-=1
end
end
delete_route if !record_route
true
end
end | true |
cd829322ceba87492cf0bcb31eb75cabd6c46001 | Ruby | lortza/project_tdd_minesweeper | /lib/row.rb | UTF-8 | 182 | 2.984375 | 3 | [] | no_license | require_relative 'cell'
class Row
def build(board_size)
cell_qty = board_size - 1
row = Array.new(cell_qty) { Cell.new }
row << Mine.new
row.shuffle!
end
end
| true |
7393b02aa8c7377d734b2b7965c0ca1912924b69 | Ruby | MoiRouhs/livecursor | /libs/livecurses.rb | UTF-8 | 10,597 | 2.6875 | 3 | [] | no_license | #!/usr/bin/ruby
require 'curses'
include Curses
class Ventana < Window
# Define la forma de usar los colores
def pintar arg = 'nil'
abreviacion = {
'nn' => 0, 'rn' => 1, 'vn' => 2, 'an' => 3, 'zn' => 4, 'mn' => 5, 'cn' => 6, 'bn' => 7,
'nr' => 8, 'rr' => 9, 'vr' => 10, 'ar' => 11, 'zr' => 12, 'mr' => 13, 'cr' => 14, 'br' => 15,
'nv' => 16, 'rv' => 17, 'vv' => 18, 'av' => 19, 'zv' => 20, 'mv' => 21, 'cv' => 22, 'bv' => 23,
'na' => 24, 'ra' => 25, 'va' => 26, 'aa' => 27, 'za' => 28, 'ma' => 29, 'ca' => 30, 'ba' => 31,
'nz' => 32, 'rz' => 33, 'vz' => 34, 'az' => 35, 'zz' => 36, 'mz' => 37, 'cz' => 38, 'bz' => 39,
'nm' => 40, 'rm' => 41, 'vm' => 42, 'am' => 43, 'zm' => 44, 'mm' => 45, 'cm' => 46, 'bm' => 47,
'nc' => 48, 'rc' => 49, 'vc' => 50, 'ac' => 51, 'zc' => 52, 'mc' => 53, 'cc' => 54, 'bc' => 55,
'nb' => 56, 'rb' => 57, 'vb' => 58, 'ab' => 59, 'zb' => 60, 'mb' => 61, 'cb' => 62, 'bb' => 63
}
cordenadas = {
0.0 => 0, 1.0 => 1, 2.0 => 2, 3.0 => 3, 4.0 => 4, 5.0 => 5, 6.0 => 6, 7.0 => 7,
0.1 => 8, 1.1 => 9, 2.1 => 10, 3.1 => 11, 4.1 => 12, 5.1 => 13, 6.1 => 14, 7.1 => 15,
0.2 => 16, 1.2 => 17, 2.2 => 18, 3.2 => 19, 4.2 => 20, 5.2 => 21, 6.2 => 22, 7.2 => 23,
0.3 => 24, 1.3 => 25, 2.3 => 26, 3.3 => 27, 4.3 => 28, 5.3 => 29, 6.3 => 30, 7.3 => 31,
0.4 => 32, 1.4 => 33, 2.4 => 34, 3.4 => 35, 4.4 => 36, 5.4 => 37, 6.4 => 38, 7.4 => 39,
0.5 => 40, 1.5 => 41, 2.5 => 42, 3.5 => 43, 4.5 => 44, 5.5 => 45, 6.5 => 46, 7.5 => 47,
0.6 => 48, 1.6 => 49, 2.6 => 50, 3.6 => 51, 4.6 => 52, 5.6 => 53, 6.6 => 54, 7.6 => 55,
0.7 => 56, 1.7 => 57, 2.7 => 58, 3.7 => 59, 4.7 => 60, 5.7 => 61, 6.7 => 62, 7.7 => 63
}
if arg.kind_of? String and abreviacion.key?(arg)
arg = abreviacion[arg]
elsif arg.kind_of? Float and cordenadas.key?(arg)
fr = arg.round(1)
arg = cordenadas[fr]
elsif arg.kind_of? Integer and arg >= 0 and arg <= 63
arg = arg
else
arg = 0
end
self.attrset(color_pair(arg))
end
alias :ptr :pintar
# Define la posición de la ventana
def mover sy = 'nil', sx = 'nil', y: self.begy, x:self.begx
if sy != 'nil' and sx != 'nil' and sy.kind_of? Integer and sx.kind_of? Integer
self.move(sy,sx)
elsif y.kind_of? Integer and x.kind_of? Integer
self.move(y,x)
else
self.move(self.begy,self.begx)
end
end
alias :mvr :mover
# Define el tamaño de la ventana
def redimensionar sy='nil', sx='nil', y:'nil', x:'nil'
if sy != 'nil' and sx != 'nil' and sy.kind_of? Integer and sx.kind_of? Integer
self.resize(sy,sx)
elsif y !='nil' or x !='nil'
if y.kind_of? Integer and x.kind_of? Integer
self.resize(y,x)
end
else
self.resize(Curses.lines,Curses.cols)
end
end
alias :rdr :redimensionar
# Define la posición y el tamaño de la ventana
def colocar *a, c:'nil', v:'nil', h:'nil', m:'nil'
if a.length() >= 1
case a.length
when 0
self.mvr y:a[0],x:a[0]
self.rdr y:a[0], x:a[0]
when 1
self.mvr y:a[0],x:a[0]
self.rdr y:a[1], x:a[1]
when 2
self.mvr y:a[0],x:a[1]
self.rdr y:a[2], x:a[2]
when 3
self.mvr y:a[0],x:a[1]
self.rdr y:a[2], x:a[3]
end
elsif (0..3).include?(c)
case c
when 0
self.mvr y:0,x:0
self.rdr y:lines / 2, x:cols / 2
when 1
self.mvr y:0, x:cols / 2
self.rdr y:lines / 2, x:cols / 2
when 2
self.mvr y:lines / 2, x:cols / 2
self.rdr y:lines / 2, x:cols / 2
when 3
self.mvr y:lines / 2, x:0
self.rdr y:lines / 2, x:cols / 2
end
elsif (0..3).include?(v)
case v
when 0
self.mvr y:0,x:0
self.rdr y:lines, x:cols / 4
when 1
self.mvr y:0, x:cols / 4
self.rdr y:lines, x:cols / 4
when 2
self.mvr y:0, x:cols / 2
self.rdr y:lines, x:cols / 4
when 3
self.mvr y:0, x:3*cols / 4
self.rdr y:lines, x:cols / 4
end
elsif (0..3).include?(h)
case h
when 0
self.mvr y:0,x:0
self.rdr y:lines / 4, x:cols
when 1
self.mvr y:lines / 4, x:0
self.rdr y:lines / 4, x:cols
when 2
self.mvr y:lines / 2, x:0
self.rdr y:lines / 4, x:cols
when 3
self.mvr y:3*lines / 4, x:0
self.rdr y:lines / 4, x:cols
end
elsif (0..3).include?(m)
case m
when 0
self.mvr y:0,x:0
self.rdr y:lines / 2, x:cols
when 1
self.mvr y:0, x:0
self.rdr y:lines, x:cols / 2
when 2
self.mvr y:lines / 2, x:0
self.rdr y:lines / 2, x:cols
when 3
self.mvr y:0, x: cols / 2
self.rdr y:lines, x:cols / 2
end
end
end
alias :clr :colocar
# Define los bordes de la ventana
def bordes *a, y:"nil", x:"nil"
if y != "nil" and x != "nil"
y = y.to_s
x = x.to_s
elsif a.length() >= 1
if a.length() == 1
y = a[0].to_s
x = a[0].to_s
elsif a.length() == 2
y = a[0].to_s
x = a[1].to_s
end
end
self.box(x, y)
end
alias :bds :bordes
# Define la posición del cursor
def cursor_posicion *a, y:'nil', x:'nil'
if y != "nil" or x != "nil"
y = y.to_i
x = x.to_i
elsif a.length() >= 1
if a.length() == 1
y = a[0].to_i
x = a[0].to_i
elsif a.length() == 2
y = a[0].to_i
x = a[1].to_i
end
end
self.setpos(y, x)
end
alias :cps :cursor_posicion
# Asigna un caracter
def texto arg="·"
self.addstr(arg.to_s)
end
alias :txt :texto
def punto *a, y:'nil', x:'nil', cps:[], ptr:'nil', txt:'nil'
if a.length() >= 1
if a.length() == 1
self.cps(a[0])
self.ptr()
self.txt(' ')
elsif a.length() == 2
self.cps(a[0],a[1])
self.ptr()
self.txt(' ')
elsif a.length() == 3
self.cps(a[0],a[1])
self.ptr(a[2])
self.txt(' ')
elsif a.length() == 4
self.cps(a[0],a[1])
self.ptr(a[2])
self.txt(a[3])
end
else
if y != 'nil' and x == 'nil'
self.cps(y)
elsif y != 'nil' and x != 'nil'
self.cps(y,x)
elsif cps.length() == 1
self.cps(cps[0])
elsif cps.length() == 2
self.cps(cps[0], cps[1])
else
self.cps()
end
if ptr != 'nil'
self.ptr(ptr)
else
self.ptr()
end
if txt != 'nil'
self.txt(txt)
else
self.txt(' ')
end
end
end
alias :pt :punto
# Define fondo de la ventana
def fondo *a, ptr:'nil', txt:'nil'
if a.length() >= 1
case a.length()
when 1
color = a[0]
caracter = ' '
when 2
color = a[0]
caracter = a[1]
end
elsif ptr != 'nil' or txt != 'nil'
if ptr != 'nil' or txt != 'nil'
color = ptr
caracter = txt
elsif ptr != 'nil' or txt == 'nil'
color = ptr
caracter = ' '
elsif ptr == 'nil' or txt != 'nil'
color ='nil'
caracter = txt
end
else
end
(0..self.maxy).each do |y|
(0..self.maxx).each do |x|
self.pt y, x, color, caracter
end
end
end
alias :fn :fondo
# bytebeat para generar cosas abstractas
def bytebeat *a, d:'nil', r:64, i:1, txt:'nil', ec:'nil'
ec2 = 'nil'
txt2 = 'nill'
d1 = self.maxx
d2 = self.maxy
if d != 'nil'
case d
when 'horizontal', 'h'
d1 = self.maxy
d2 = self.maxx
when 'vertical', 'v'
d1 = self.maxx
d2 = self.maxy
end
end
if a.length() >= 1
if a.length() == 1
ec = a[0]
elsif a.length() == 2
ec = a[0]
txt = a[1]
end
end
c = 0
(0...d1).each do |x|
(0...d2).each do |y|
if ec != 'nil'
cc = eval(ec)
#begin
# cc = eval(ec)
# ec2 = ec
#rescue
# cc = eval(ec2)
#end
else
cc = c
end
if txt == 'nil'
etxt = ' '
elsif txt.length == 1
etxt = txt
else
etxt = (1 + (eval(txt)).abs).chr(Encoding::UTF_8)
#begin
# etxt = (1 + (eval(txt)).abs).chr(Encoding::UTF_8)
# txt2 = txt
#rescue
# etxt = (1 + (eval(txt2)).abs).chr(Encoding::UTF_8)
#end
end
if d == 'horizontal' or d == 'h'
self.pt x, y, cc, etxt
else
self.pt y, x, cc, etxt
end
if c < r
c += i
else
c = 0
end
end
end
end
alias :bb :bytebeat
# asciiart para generar cosas no abstractas
def asciiart *a, cps:[], n:'nil', t:'nil', c:'nil', txt:'nil'
if a.length() >= 3
if a.length() == 3
y = a[0].to_i
x = a[0].to_i
n = a[1]
t = $contenido[n]['t']
c = $contenido[n]['c']
txt = a[2]
elsif a.length() == 4
y = a[0].to_i
x = a[1].to_i
n = a[2]
t = $contenido[n]['t']
c = $contenido[n]['c']
txt = a[3]
end
else
case cps.length
when 1
y = cps[0]
x = cps[0]
when 2
y = cps[0]
x = cps[1]
end
if t == 'nil'
t = $contenido[n]['t']
end
if c == 'nil'
c = $contenido[n]['c']
end
end
case t
when 'fuente', 'f'
maxd = 0
txt.split('').each do |w|
l = $contenido[n]['e'][w].length
l.times do |i|
d = $contenido[n]['e'][w][i]
self.pt y + i, x, c, d
maxd = maxd.to_i < d.length ? d.length : maxd
end
x = x + maxd
maxd = 0
end
when 'dibujo', 'd'
case txt
when String
l = $contenido[n]['e'][txt].length
l.times do |i|
self.pt y + i, x, c, $contenido[n]['e'][txt][i]
end
when Array
l = $contenido[n]['e'][txt[$t%txt.length]].length
l.times do |i|
self.pt y + i, x, c, $contenido[n]['e'][txt[$t%txt.length]][i]
end
end
end
end
alias :aa :asciiart
end
| true |
60b82a509f00da0235a63fc70fa171120e02bdbc | Ruby | jonstokes/irongrid | /spec/fixtures/stretched/registrations/ironsights/extensions/normalization.rb | UTF-8 | 7,491 | 2.640625 | 3 | [] | no_license | Stretched::Extension.define "ironsights/extensions/normalization" do
extension do
def normalize_punctuation(text)
return unless text.present?
str = " #{text} "
str.gsub!(/\d\,\d{3}(\D)/) do |match|
match.sub!(",", "")
end
str.gsub!(/\,|\!|\;/, " ")
str.strip.squeeze(" ")
end
def normalize_inches(text)
return unless text.present?
str = " #{text} "
str.gsub!(/\d{1,2}+\s{0,1}\"\.?\,?\s+/i) do |match|
match.sub!(/\s{0,1}\"(\s?|\,?)/i, " inch ")
end
str.gsub!(/\d{1,2}+\s{0,1}in\.?\,?\s+/i) do |match|
match.sub!(/\s{0,1}in(\s?|\,?)/i, " inch ")
end
str.gsub!(/\s+/," ")
str.try(:strip!)
str
end
def normalize_color(text)
return unless text.present?
str = " #{text} "
str.gsub!(/\s+blk\s+/i, " black ")
str.gsub!(/\s+slv\s+/i, " silver ")
str.gsub!(/\s+/," ")
str.strip.squeeze(" ")
end
def normalize_caliber(text)
return unless text.present?
str = " #{text} "
#
# Normalize dots
# Dash with non-point calibers
str.gsub!(/\s\.?(6|10|17|18|19|21|22|23|25|30|300|308|32|327|357|375|38|380|40|41|44|440|445|45|475|480|575|28|50|500|65|8|9)\-[abcnmhsrjlwcgvpud]/i) { |m| m = m.sub!(/\-/, " ") }
# Dash with point calibers
str.gsub!(/\s(9\.3|\d\.6|\d\.75|\d\.7|\d\.35|\d\.5|6\.8|\d\.62|\d\.65|5\.56|\d\.45|7\.92)\-[abcnmhsrjlwcgvpud]/i) { |m| m = m.sub!(/\-/, " ") }
# Space with non-point calibers
str.gsub!(/\s\.?(6|10|17|18|19|21|22|23|25|30|300|308|32|327|357|375|38|380|40|41|44|440|445|45|475|480|575|28|50|500|65|8|9)[abcnmhsrjlwcgvpud]/i) do |match|
i = match.index(/[abcnmhsrjlwcgvpud]/i)
match = match.insert(i, " ")
end
# Space with point calibers
str.gsub!(/\s(9\.3|\d\.6|\d\.75|\d\.7|\d\.35|\d\.5|6\.8|\d\.62|\d\.65|5\.56|\d\.45|7\.92)[abcnmhsrjlwcgvpud]/i) do |match|
i = match.index(/[abcnmhsrjlwcgvpud]/i)
match = match.insert(i, " ")
end
# Pre-caliber dot with dashes
str.gsub!(/\s\.(25|250|30|38|40|44|45|50|56|577)(\s|\-)/) do |match|
match.sub!(/\./,"")
end
# Pre-caliber dot 200's
str.gsub!(/\s\.(17|22|220|221|223|224|225|240|243|257|260|264|270|275|280|284)\s/) do |match|
match.sub!(/\./,"")
end
# Pre-caliber dot 300's
str.gsub!(/\s\.(300|308|32|327|338|340|348|35|350|351|356|370|38|357|370|375|376|378|380)\s/) do |match|
match.sub!(/\./,"")
end
# Pre-caliber dot 400's
str.gsub!(/\s\.(41|44|45|400|404|405|416|426|440|445|450|454|455|458|460|475|470|475|480)\s/) do |match|
match.sub!(/\./,"")
end
# Pre-caliber dot 500's
str.gsub!(/\s\.(50|500|505|510|577)\s/) do |match|
match.sub!(/\./,"")
end
#
# Normalize suffixes
#+P variants
str.gsub!(/(\d|\w)\+p/i) do |match|
match.sub!(/\+p/i, " +P")
end
# S&W
str.gsub!(/(\.|\s)(32|38|40|44|460|500)\s{0,1}(s\&w|smith \& wesson|smith and wesson|s \& w|s and w|sw)\.?\,?\s+/i) do |match|
match.sub!(/s\&w|smith \& wesson|smith and wesson|s \& w|s and w|sw/i, " S&W")
end
str.squeeze!(" ")
# H&R
str.gsub!(/(\.|\s)32\s{0,1}(h\&r|h & r|h and r|hr)\.?\,?\s+/i) do |match|
match.sub!(/h\&r|h & r|h and r|hr/i, " H&R")
end
str.squeeze!(" ")
# Rem
str.gsub!(/(\.|\s)(357|mm|6\.8|6\.5|416|35|350|300|30|223|280|260|25(\s|\-)06|222|17|41)\s{0,1}(remington|rem)\.?\,?\s+/i) do |match|
match.sub!(/remington|rem|rem\./i, " Rem")
end
str.squeeze!(" ")
# Win
str.gsub!(/(\.|\s)(38(\-|\s)40|45|300|308)\s{0,1}(winchester|win)\.?\,?\s+/i) do |match|
match.sub!(/winchester|win|win\./i, " Win")
end
str.squeeze!(" ")
# Magnum
str.gsub!(/(\.|\s)(32|327|357|41|44|445|45|460|475|500|300).{0,6}(mag|magnum)\.?\,?\s+/i) do |match|
match.sub!(/(magnum|mag\.{0,1})/i, " Mag")
end
str.squeeze!(" ")
# WSM
str.gsub!(/(\.|\s)(270|300|325|benchrest|mm|7mm|17)\s{0,1}(winchester short mag)\.?\,?\s+/i) do |match|
match.sub!(/(winchester short mag\.{0,1})/i, " WSM")
end
str.squeeze!(" ")
# Special
str.gsub!(/(\.|\s)(38|s\&w)\s{0,1}(special|spcl|spl|spc|sp)\.?\,?\s+/i) do |match|
match.sub!(/special|spcl|spl|spc|sp/i, " Special")
end
str.squeeze!(" ")
# Super
str.gsub!(/(\.|\s)(38|45|445)\s{0,1}(super|sup|spr)\.?\,?\s+/i) do |match|
match.sub!(/super|sup|spr/i, " Super")
end
str.squeeze!(" ")
# Cor-Bon
str.gsub!(/(\.|\s)(440|400)\s{0,1}(cor-bon|corbon|cor bon)\.?\,?\s+/i) do |match|
match.sub!(/cor-bon|corbon|cor bon/i, " Cor-Bon")
end
str.squeeze!(" ")
# Mini mag
str.gsub!(/(\.|\s)(22|lr|lrhp|hp|long rifle)\s{0,1}(mini-mag|mini mag)\.?\,?\s+/i) do |match|
match.sub!(/mini-mag|mini mag/i, " Mini Mag")
end
str.squeeze!(" ")
# 9x18 etc.
str.gsub!(/(\.|\s)(6|7|2|3|5|8|9)\s{0,1}x\s{0,1}(30|28|25|38|21|22|23|25|18|19)\.?\,?\s+/i) do |match|
match.sub!(/\s{0,1}x\s{0,1}/i, "x")
end
str.squeeze!(" ")
# Millimeter
str.gsub!(/(\.|\s)(30|75|28|35|25|21|8|9|10|22|18|23)\s{0,1}(mm|millimeter|milimeter|mil)\.?\,?\s+/i) do |match|
match.sub!(/mm|millimeter|milimeter|mil/i, " mm")
end
str.squeeze!(" ")
str.gsub!(/(\.|\s)(30|75|28|35|25|21|8|9|10|22|18|23)\s{0,1}(mm|millimeter|milimeter|mil)\.?\,?\s+/i) do |match|
match.gsub!(/\smm/i,"mm")
end
str.squeeze!(" ")
# Gauge
str.gsub!(/(\.|\s)(10|12|16|20|24|28|32|410)(\s{0,1}|\-)(gauge|guage|ga|g)\.?\,?\s+/i) do |match|
match.sub!(/(\s{0,1}|\-)(gauge|guage|ga|g)/i, " gauge")
end
# .22 long rifle
str.gsub!(/(\.|\s)(22 lo?ng\s+ri?f?l?e?)\.?\,?\s+/i) do |match|
match.sub!(/(\s{0,1}|\-)(lo?ng\s+ri?f?l?e?)/i, " lr")
end
str.strip.squeeze(" ")
#
# Restore dots
# Pre-caliber dot with dashes
str.gsub!(/\s(25|250|30|38|338|40|44|45|450|50|56|577)(\s|\-)\d{1,3}/) do |match|
i = match.index(/\d{2,3}(\s|\-)\d{1,3}/i)
match = match.insert(i,".")
end
# Pre-caliber dot 200's
str.gsub!(/\s(17|22|25 acp|25 naa|22[01345]|240|243|257|260|264|270|275|280|284)(lr\s|\s)/i) do |match|
i = match.index(/\d{2,3}\s/)
match = match.insert(i,".")
end
# Pre-caliber dot 300's
str.gsub!(/\s(30\s?\-?ma(u|us|user)?|30[0378]|318|32|325|327|333|338|340|348|35|35[0168]|357|370|375|378|38|380)\s/i) do |match|
i = match.index(/30\s?\-?ma(u|us|user)?|\d{2,3}\s/i)
match = match.insert(i,".")
end
# Pre-caliber dot 400's
str.gsub!(/\s(40\s(s&w|super)|(4[145]|400)\s?\-?[capn][\w\-]{1,7}|404|405|416|426|440|445|450|454|455|458|460|470|475|480)\s/i) do |match|
i = match.index(/40\s(s&w|super)|4[145]|400\s?\-?[capn](\w{1,6}|\-)|\d{3}\s/i)
match = match.insert(i,".")
end
# Pre-caliber dot 500's
str.gsub!(/\s(50\s?\-?[bmgeiac]{2}\w{0,5}|500\s?\-?[ajnlsw][a-z&\s\-]{1,16}|505|510)\s/i) do |match|
i = match.index(/50\s?\-?[bmgeiac]{2}\w{0,5}|500\s?\-?[ajnlsw][a-z&\s\-]{1,16}|505|510\s/i)
match = match.insert(i,".")
end
str.strip.squeeze(" ")
end
end
end
| true |
dd00d0b5e6ba630a5d5ca8051ab7a673e7cf7e1e | Ruby | email2jie/AppAcademyProjects | /Week1/W1D4/recursion_exercises2.rb | UTF-8 | 1,268 | 4.40625 | 4 | [] | no_license | def fibonacci_iterative(length)
fibonacci_nums = []
fibonacci_nums << 0
fibonacci_nums << 1 if length > 1
while fibonacci_nums.length < length
fibonacci_nums << fibonacci_nums[-1] + fibonacci_nums[-2]
end
fibonacci_nums
end
def fibonacci_recursive(length)
if length == 1
[0]
elsif length == 2
[0,1]
else
fibonacci_nums = fibonacci_recursive(length-1)
fibonacci_nums << fibonacci_nums[-1] + fibonacci_nums[-2]
fibonacci_nums
end
end
#Checking the iterative methods
p fibonacci_iterative(1)
p fibonacci_iterative(2)
p fibonacci_iterative(20)
#Checking the recursive methods
p fibonacci_recursive(1)
p fibonacci_recursive(2)
p fibonacci_recursive(20)
#Binary Search
def bsearch(arr, target)
if arr.empty?
puts "Value not in array"
return 0
end
middle = (arr.length)/2
if arr[middle] == target
middle
elsif arr[middle] < target
middle + bsearch(arr[middle..-1], target)
else
bsearch(arr[0...middle], target)
end
end
animals = ["cat", "dog", "giraffe", "mouse", "rat"]
#Checks the index against the bsearch value
puts animals.index("cat")
puts bsearch(animals, "cat")
puts animals.index("giraffe")
puts bsearch(animals, "giraffe")
puts animals.index("rat")
puts bsearch(animals, "rat")
| true |
7d0550e635b11d99d064d6b027b1027269066fc0 | Ruby | castor4bit/leetcode | /0300/349.Intersection_of_Two_Arrays/test_349.rb | UTF-8 | 417 | 2.75 | 3 | [] | no_license | require 'test/unit'
require './349'
class LeetCodeSolutionTest < Test::Unit::TestCase
def test_349
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
assert_equal [2].sort, intersection(nums1, nums2).sort
nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]
assert_equal [9, 4].sort, intersection(nums1, nums2).sort
nums1 = []
nums2 = []
assert_equal [].sort, intersection(nums1, nums2).sort
end
end
| true |
d638709b77a4bae4c8a532c25416c0b429ebd6fb | Ruby | seok0801/Kepre | /app/controllers/tool_factory.rb | UTF-8 | 328 | 2.671875 | 3 | [
"MIT"
] | permissive | class ToolFactory
def self.build (item, *args)
case item
when "MHC I"
MhciItem.new(*args)
when "MHC II"
MhciiItem.new(*args)
when "KBIO MHC I"
KbioMhciItem.new(*args)
when "KBIO MHC II"
KbioMhciiItem.new(*args)
end
end
end | true |
f9e5977d9d3ec4bc25e1901f51797e96abe5dfe3 | Ruby | sandipransing/number_to_indian_currency | /test/number_to_indian_currency_test.rb | UTF-8 | 1,105 | 2.609375 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class NumberToIndianCurrencyTest < Minitest::Test
def subject
@subject ||= begin
object = Object.new
object.extend(::NumberToIndianCurrency::CurrencyHelper)
object
end
end
def test_that_it_has_a_version_number
refute_nil ::NumberToIndianCurrency::VERSION
end
def test_number_to_indian_currency_format
assert_equal "Rs.12", subject.number_to_indian_currency(12)
assert_equal "Rs.12,000", subject.number_to_indian_currency(12000)
assert_equal "Rs.1,20,000", subject.number_to_indian_currency(120000)
assert_equal "Rs.12,00,000", subject.number_to_indian_currency(1200000)
end
def test_number_to_indian_currency_when_text_option
assert_equal "Rupees:12", subject.number_to_indian_currency(12, text: 'Rupees:')
end
def test_number_to_indian_currency_when_web_rupee_option
subject.stubs(:content_tag).with(:span, 'Rs.', {:class => :WebRupee}).returns("<span class='WebRupee'>Rs.</span>")
assert_equal "<span class='WebRupee'>Rs.</span>12", subject.number_to_indian_currency(12, web_rupee: true)
end
end
| true |
230327e10fdce77036025d3c768b374217c29979 | Ruby | charrednewth/Succubus-Rhapsodia-ENG | /Scripts - manually insert these/153 - Window_Battle_Command.rb | SHIFT_JIS | 5,436 | 2.796875 | 3 | [] | no_license | #==============================================================================
# Window_BoxLeft
#------------------------------------------------------------------------------
# @{bNXʂŁAaĂ閲̖O\EBhEB
#==============================================================================
class Window_Battle_Command < Window_Base
#--------------------------------------------------------------------------
# JCX^Xϐ
#--------------------------------------------------------------------------
attr_accessor :index # J[\ʒu
attr_accessor :window #
attr_accessor :skill # XL
attr_accessor :item # ACe
attr_accessor :change # p[eB
attr_accessor :escape #
attr_accessor :help # R}h
attr_accessor :fade_flag # tF[hp
#--------------------------------------------------------------------------
# IuWFNg
#--------------------------------------------------------------------------
def initialize
super(0, 300, 640, 100)
self.opacity = 0
self.active = false
self.visible = false
@index = 0
@fade_flag = 0
#
@window = Sprite.new
@window.y = -12
@window.z = 4
@window.bitmap = RPG::Cache.windowskin("command_window")
@window.opacity = 51
# XL
@skill = Sprite.new
@skill.y = -20
@skill.z = 4
@skill.bitmap = RPG::Cache.windowskin("command_skill")
@skill.opacity = 100
# ACe
@item = Sprite.new
@item.y = -20
@item.z = 4
@item.bitmap = RPG::Cache.windowskin("command_item")
@item.opacity = 100
# p[eB
@change = Sprite.new
@change.y = -20
@change.z = 4
@change.bitmap = RPG::Cache.windowskin("command_change")
@change.opacity = 100
#
@escape = Sprite.new
@escape.y = -20
@escape.z = 4
@escape.bitmap = RPG::Cache.windowskin("command_escape")
@escape.opacity = 100
# R}h
@help = Sprite.new
@help.x = 220
@help.y = 390
@help.z = 100
@help.bitmap = Bitmap.new(300, 200)
@help.bitmap.font.size = $default_size_mini
end
#--------------------------------------------------------------------------
# tbV
#--------------------------------------------------------------------------
def refresh
if @help.bitmap != nil
@help.bitmap.clear
end
x = 0
y = 0
case self.index
when 0 # XL
@skill.opacity = 255
@item.opacity = 100
@change.opacity = 100
@escape.opacity = 100
@help.bitmap.draw_text(x, y, 200, 30, "Use a technique", 1)
when 1 # ACe
@skill.opacity = 100
@item.opacity = 255
@change.opacity = 100
@escape.opacity = 100
@help.bitmap.draw_text(x, y, 200, 30, "Use an item", 1)
when 2 # p[eB
@skill.opacity = 100
@item.opacity = 100
@change.opacity = 255
@escape.opacity = 100
@help.bitmap.draw_text(x, y, 200, 30, "Switch partner", 1)
when 3 #
@skill.opacity = 100
@item.opacity = 100
@change.opacity = 100
@escape.opacity = 255
@help.bitmap.draw_text(x, y, 200, 30, "Run away", 1)
end
end
#--------------------------------------------------------------------------
# |[Ypꎞo/B
#--------------------------------------------------------------------------
def hide
for i in [@window,@skill,@item,@change,@escape,help]
i.visible = false
end
end
def appear
for i in [@window,@skill,@item,@change,@escape,help]
i.visible = true
end
end
#--------------------------------------------------------------------------
# tF[h
#--------------------------------------------------------------------------
def fade
case @fade_flag
when 1 # tF[hC
# o
if @window.opacity < 255
@window.opacity += 51
end
if @window.y > -20
@window.y -= 1
end
@fade_flag = 0 if window.y == -20
when 2 # tF[hAEg
end
end
#--------------------------------------------------------------------------
# t[XV
#--------------------------------------------------------------------------
def update
if @fade_flag > 0
fade
return
end
if self.active == true
# bZ[W\̏ꍇ̓{bNXbN
if $game_temp.message_window_showing
return
end
# E{^ꂽꍇ
if Input.repeat?(Input::RIGHT)
# SE t
Audio.se_play("Audio/SE/005-System05", 80, 100)
if @index == 3
@index = 0
else
@index += 1
end
refresh
end
# {^ꂽꍇ
if Input.repeat?(Input::LEFT)
# SE t
Audio.se_play("Audio/SE/005-System05", 80, 100)
if @index == 0
@index = 3
else
@index -= 1
end
refresh
end
end
end
end
| true |
c12fa51f81138160f84dfa4bdf08ee1840be371f | Ruby | hackhands/Ruby-on-Rails-4-Course | /Ruby/metaprogramming-example/open-class.rb | UTF-8 | 112 | 3.125 | 3 | [] | no_license | class Fixnum
def hour
self * 3600
end
def hours
self * 3600
end
end
puts 1.hour
puts 3.hours | true |
f413d317a0d0bdec68c080b0266d2bdab8f313ff | Ruby | akira-kuriyama/sssummary | /lib/Sssummary.rb | UTF-8 | 3,584 | 2.8125 | 3 | [
"MIT"
] | permissive | # -*- encoding: utf-8 -*-
require 'sqlite3'
require 'csv'
class Sssummary
public
def execute(options, sql)
begin
set_up(options, sql)
@records = get_records
create_table
import
result_records = execute_sql
@messages << get_output(result_records)
@exit_status = 0
rescue FileEmptyError
@exit_status = 1
@messages << "Error : input data is empty!\n"
ensure
drop unless @db.nil?
end
return @exit_status, @messages.join("\n")
end
private
def set_up(options, sql)
@messages = []
@messages << 'options : ' + options.to_s if options[:verbose]
@options = options
@sql = sql
@input_file = get_input_file(options)
@options[:import_separator] ||= "\t"
@options[:output_separator] ||= "\t"
@options[:db_name] ||= 'sssummary'
@options[:table_name] ||= 't'
end
def get_input_file(options)
input_file = nil
if options[:file].nil?
if File.pipe?(STDIN)
input_file = STDIN
end
else
input_file = open(options[:file])
end
input_file.gets if options[:ignore_header] && !input_file.nil?
input_file
end
def get_records
raise FileEmptyError if @input_file.nil?
options = {:col_sep => @options[:import_separator], :skip_blanks => true}
records = CSV.parse(@input_file, options)
raise FileEmptyError if records.empty?
records
end
def import
insert_sql = 'INSERT INTO ' + @options[:table_name] +' VALUES('
insert_sql += Array.new(@options[:column_names].length, '?').join(',')
insert_sql +=');'
@messages << 'insert sql : ' + insert_sql if @options[:verbose]
stmt = nil
begin
stmt = @db.prepare(insert_sql)
@db.transaction do
@records.each do |record|
stmt.execute(record)
end
end
ensure
stmt.close unless stmt.nil?
end
end
def get_output(result_records)
return if result_records.nil?
@messages << 'sql : ' + @sql if @options[:verbose]
options = {:col_sep => @options[:output_separator]}
csv = CSV.generate('', options) do |csv|
result_records.each do |record|
csv << record
end
end
@messages << 'result : ' if @options[:verbose]
csv
end
def create_table
@db = SQLite3::Database.new(get_dbfile_path)
@messages << 'created Database at ' + get_dbfile_path if @options[:verbose]
@db.execute(drop_table_sql)
@db.execute(create_table_sql)
end
def get_dbfile_path
dbfile_path = nil
if @options[:dbfile].nil?
dbfile_path = `pwd`.strip
else
dbfile_path = @options[:dbfile]
end
dbfile_path += '/' unless dbfile_path.end_with?('/')
dbfile_path += @options[:db_name] + '.db'
end
def create_table_sql
sql = "CREATE TABLE #{@options[:table_name]} ("
sql += get_column_sql
sql += ');'
@messages << 'create table sql : ' + sql if @options[:verbose]
sql
end
def get_column_sql
column_names = @options[:column_names]
if column_names.nil?
column_names = []
@records[0].length.times do |i|
column_names << "c#{i+1}"
end
@options[:column_names] = column_names
end
column_sql = column_names.map do |column|
s = column.split(':')
if s.length == 1
s << 'text'
end
s.join(' ')
end
column_sql.join(',')
end
def execute_sql
return if @sql.nil?
@db.execute(@sql)
end
#create index automatically by analyzing where clause.
def create_index
#TODO
end
def drop_table_sql
"DROP TABLE IF EXISTS #{@options[:table_name]};"
end
def drop
@db.close
unless @options[:leave_database]
File.delete(get_dbfile_path)
@messages << 'drop Database at ' + get_dbfile_path if @options[:verbose]
end
end
class FileEmptyError < StandardError;
end
end
| true |
ab074200109ce7228c09b7e670f5648f893a4fd3 | Ruby | jennifercford/homework | /lib/homework/github.rb | UTF-8 | 1,665 | 2.53125 | 3 | [
"MIT"
] | permissive | module Homework
class Github
include HTTParty
base_uri "https://api.github.com"
def initialize
@headers = {
"Authorization" => "token #{ENV["OAUTH_TOKEN"]}",
"User-Agent" => "HTTParty"
}
end
def get_user(username)
Github.get("/users/#{username}", headers: @headers)
end
def list_members_by_team_name(org, team_name)
teams = list_teams(org)
team = teams.find { |team| team["name"] == team_name }
list_team_members(team["id"])
end
def list_teams(organization)
Github.get("/orgs/#{organization}/teams", headers: @headers)
end
def list_team_members(team_id)
Github.get("/teams/#{team_id}/members", headers: @headers)
end
def list_issues(owner, repo)
Github.get("/repos/#{owner}/#{repo}/issues", headers: @headers)
end
def close_an_issue(owner, repo,number)
# number.to_i
Github.patch("/repos/#{owner}/#{repo}/issues/#{number}",
headers: @headers, body: {"state": "closed"}.to_json)
end
def list_comments(owner,repo)
Github.get("/repos/#{owner}/#{repo}/issues/comments",
headers: @headers)
end
def make_a_comment(owner,repo,number, comment)
Github.post("/repos/#{owner}/#{repo}/issues/#{number}/comments",
header: @headers, body: {"body" => comment}.to_json)
end
def get_gist(id)
Github.get("/gists/#{id}", headers: @headers)
end
def create_issue(owner, repo, title, options={})
params = options.merge{"title" =>title}).to_json
Github.post("/repos/#{owner}/#{repo}/issues", headers: @headers,
body: params)
end
end
end
| true |
554beb48f8ee15e12ae70aa971b23285704b1ef9 | Ruby | swaption2009/rbnd-survivr-part2 | /lib/tribe.rb | UTF-8 | 559 | 3.34375 | 3 | [] | no_license | class Tribe
attr_accessor :name, :members
def initialize(options={})
@name = options[:name]
@members = options[:members]
puts "#{@name.to_s.white} has been added with the following members: "
@members.each { |x| puts x.name.capitalize.pink }
end
def to_s
@name
end
def tribal_council(options={})
immune = options[:immune]
vulnerable_members = @members.select { |member| member != immune }
voted_off_member = vulnerable_members.sample
@members.delete(voted_off_member)
return voted_off_member
end
end | true |
dc6e8050180568e3cb7b4f2093a12892d2c965d4 | Ruby | maconaco/ruby_mal | /main.rb | UTF-8 | 937 | 2.90625 | 3 | [] | no_license | require "./tokenizer"
require "./parser"
#tokenizer = Tokenizer.new("(+ 10 22 (+ 1 2) 3)", 0)
tokenizer = Tokenizer.new("(+ 1 2 (+ 3 4))", 0,)
puts tokenizer.call
p "tokenize --------------------------"
tokens = p tokenizer.tokenize
index = 0
# インスタンス化する時に空配列わたすの、だいたい頭の悪いパターンなのでやめとく
parser = Parser.new(0,tokens)
p "parse -----------------------------"
p parser.parse
=begin
[
{:type=>:Exprr,
:val=>{:type=>:OPERATOR, :val=>"+"},
:children=>[
{:type=>:NumberNode,:val=>{:type=>:NUMBER, :val=>3}},
{:type=>:NumberNode, :val=>{:type=>:NUMBER, :val=>4}}
]
},
{:type=>:Exprr,
:val=>{:type=>:OPERATOR, :val=>"+"},
:children=>[
{:type=>:NumberNode, :val=>{:type=>:NUMBER, :val=>1}},
{:type=>:NumberNode, :val=>{:type=>:NUMBER, :val=>2}}
]
}
]
=end
p "node -----------------------------"
| true |
2e05b75eaa5138f6ef71dd1ee4ba130054ffa628 | Ruby | 0cha/mrubyc_for_ESP32_Arduino | /examples/bmp085/code.rb | UTF-8 | 291 | 3.078125 | 3 | [
"BSD-3-Clause"
] | permissive | # -*- coding: utf-8 -*-
bmp085 = BMP085.new
bmp085.begin()
while true
puts bmp085.readTemperature
puts bmp085.readPressure
puts bmp085.readAltitude
puts bmp085.readSealevelPressure
puts bmp085.readSealevelPressure(10500)
puts bmp085.readSealevelPressure(10500.0)
sleep(10)
end
| true |
39395b567584b0c5ddcf361c9d8dbb1a879b47b1 | Ruby | Azzerty23/THP | /THP-jour25/airbnb/db/seeds.rb | UTF-8 | 2,477 | 2.53125 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# Pense bien sûr à faire un petit seed qui va :
require 'faker'
# Détruire ta base actuelle
# Créer 20 utilisateurs
# Créer 10 villes
# Créer 50 listings
# Pour chaque listing
# Créer 5 réservations dans le passé
# Créer 5 réservations dans le futur
User.destroy_all
City.destroy_all
Listing.destroy_all
Reservation.destroy_all
user_array = []
city_array = []
listing_array = []
reservation_array = []
# Faker::Config.locale = 'fr-FR'
20.times do |i|
u = User.create!(id: i+1,
email: Faker::Internet.email,
phone_number: "+33#{Faker::Number.number(digits: 9)}", # Faker::PhoneNumber.phone_number
description: Faker::Lorem.sentence(word_count: 50, supplemental: false, random_words_to_add: 4))
user_array << u
end
tp User.all
# pp user_array
puts "Users created"
10.times do
c = City.create!(name: Faker::Address.city,
zip_code: "34#{Faker::Number.number(digits: 3)}")
city_array << c
end
puts "Cities created"
50.times do
l = Listing.create!(available_beds: Faker::Number.non_zero_digit,
price: Faker::Number.within(range: 5..100),
description: Faker::Lorem.sentence(word_count: 50, supplemental: false, random_words_to_add: 4),
has_wifi: rand(0..1),
welcome_message: Faker::Lorem.sentence(word_count: 5),
administrator: user_array.sample,
city: city_array.sample)
listing_array << l
end
puts "Listings created"
listing_array.each do |listing|
5.times do
start_date = Faker::Date.between(from: 1.year.ago, to: 6.month.ago)
r = Reservation.create!(start_date: start_date,
end_date: Faker::Date.between(from: start_date + 1, to: 1.day.ago),
guest: user_array.sample,
listing: listing_array.sample)
listing.reservations << r
start_date = Faker::Date.between(from: 1.day.from_now, to: 1.month.from_now)
r = Reservation.create!(start_date: start_date,
end_date: Faker::Date.between(from: start_date + 1, to: 1.year.from_now),
guest: user_array.sample,
listing: listing_array.sample)
listing.reservations << r
end
end
puts "Reservations created"
| true |
889f382a7bb8d6b6f04d9d79489da8489ab68405 | Ruby | carolyny/launchschool | /Backend/101/Exercises/finddup.rb | UTF-8 | 134 | 3.3125 | 3 | [] | no_license | def find_dup(array)
array.each do |number|
if array.count(number)==2
return number
else
end
end
end
puts find_dup([4,5,3,3,1]) == 3 | true |
90debb622162706bbd82155ca28e0a67c732391d | Ruby | NazarOliynyk/test_api_mailjet | /lib/reporter/custom_logger.rb | UTF-8 | 649 | 2.84375 | 3 | [] | no_license | require 'log4r'
require 'fileutils'
module CustomLogger
class MyLogger
attr_accessor :logger
def initialize(file_path)
@logger = Log4r::Logger.new('my_logger')
format = Log4r::PatternFormatter.new(pattern: '[%d]: %l - %m')
create_path(file_path)
@logger.outputters << Log4r::FileOutputter.new('file', filename: file_path, formatter: format, trunc: true)
@logger
end
def info(message)
logger.info(message)
end
private
def create_path(path)
dirname = File.dirname(path)
unless File.directory?(dirname)
FileUtils.mkdir_p(dirname)
end
end
end
end
| true |
cf0628631c20a2b981e7c7b7ce9e87c75ad6cf94 | Ruby | NetsoftHoldings/growl | /scripts/nib-to-xib.rb | UTF-8 | 639 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | #!/usr/bin/ruby
require 'find'
require 'fileutils'
def xibify(path)
Find.find(path) do |subpath|
if File.extname(subpath) == '.nib'
newsubpath = File.dirname(subpath) + "/" + File.basename(subpath, '.nib') + '.xib'
command = "ibtool --upgrade \"#{subpath}\" --write \"#{newsubpath}\""
puts "#{subpath} to #{newsubpath}"
system command
system "hg add \"#{newsubpath}\""
system "hg rm \"#{subpath}\""
Find.prune
end
end
end
def main
path = ARGV[0]
xibify(path)
end
if __FILE__ == $0
main()
end | true |
9fb32a8ef8d4c8504eac93fcf267b182bc7150ce | Ruby | sPesce/advanced-hashes-building-hashketball-wdc01-seng-ft-060120 | /hashketball.rb | UTF-8 | 1,569 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def game_hash
nets_players =
[
player("Alan Anderson", 0, 16, 22, 12, 12, 3, 1, 1),
player("Reggie Evans" , 30, 14, 12, 12, 12, 12, 12, 7),
player("Brook Lopez" , 11, 17, 17, 19, 10, 3, 1, 15),
player("Mason Plumlee", 1, 19, 26, 11, 6, 3, 8, 5),
player("Jason Terry" , 31, 15, 19, 2, 2, 4, 11, 1)
]
hornets_players =
[
player("Jeff Adrien", 4, 18, 10, 1, 1, 2, 7, 2),
player("Bismack Biyombo", 0, 16, 12, 4, 7, 22, 15, 10),
player("DeSagna Diop", 2, 14, 24, 12, 12, 4, 5, 5),
player("Ben Gordon", 8, 15, 33, 3, 2, 1, 1, 0),
player("Kemba Walker", 33, 15, 6, 12, 12, 7, 5, 12)
]
team = team_helper
team[:home][:players] = nets_players
team[:away][:players] = hornets_players
team
end
#return team with details and empty player array
def team_helper
top =
{
:home => {},
:away => {}
}
mid_Nets =
{
:team_name => "Brooklyn Nets",
:colors => ['Black', 'White'],
:players => []
}
mid_Hornets =
{
:team_name => "Charlotte Hornets",
:colors => ["Turquoise", "Purple"],
:players => []
}
top[:home] = mid_Nets
top[:away] = mid_Hornets
top
end
#create hash for each player
def player(name, number, shoe, points, rebounds, assists, steals, blocks, slam_dunks)
player =
{
:player_name => name,
:number => number,
:shoe => shoe,
:points => points,
:rebounds => rebounds,
:assists => assists,
:steals => steals,
:blocks => blocks,
:slam_dunks => slam_dunks
}
end | true |
b56460043b5743bfa12ed9717f5b9011748ddb9f | Ruby | jetthoughts/jetmeter | /test/jetmeter/csv_formatter_test.rb | UTF-8 | 1,861 | 2.6875 | 3 | [
"BSD-2-Clause"
] | permissive | require 'minitest/autorun'
require 'csv'
require 'jetmeter/csv_formatter'
class Jetmeter::CsvFormatterTest < Minitest::Test
def test_builds_commulative_table
flows = {
'Backlog' => {
Date.new(2017, 4, 9) => [1, 2, 3],
Date.new(2017, 4, 10) => [4, 5, 6, 7],
Date.new(2017, 4, 12) => [8, 9],
Date.new(2017, 5, 12) => [10, 11, 12],
Date.new(2017, 6, 1) => [13]
},
'Ready' => {
Date.new(2017, 5, 9) => [1, 2]
},
'WIP' => {
Date.new(2017, 5, 10) => [1, 3],
Date.new(2017, 5, 19) => [2],
},
'Closed' => {
Date.new(2017, 5, 22) => [2],
Date.new(2017, 6, 5) => [1, 11, 13]
}
}
config = OpenStruct.new(flows: {})
flows.keys.each do |flow_name|
config.flows[flow_name] = OpenStruct.new(accumulative?: true)
end
config.flows['Backlog'][:accumulative?] = false
reducer = OpenStruct.new(flows: flows)
io = StringIO.new('', 'wb')
Jetmeter::CsvFormatter.new(config, reducer).save(io)
rows = CSV.parse(io.string)
assert_equal(['Date', 'Backlog', 'Ready', 'WIP', 'Closed'], rows[0])
assert_equal(['2017-05-08', '9', '0', '0', '0' ], rows[30])
assert_equal(['2017-05-09', '9', '2', '0', '0' ], rows[31])
assert_equal(['2017-05-10', '9', '3', '2', '0' ], rows[32])
# ...
assert_equal(['2017-05-12', '12', '3', '2', '0' ], rows[34])
# ...
assert_equal(['2017-05-19', '12', '3', '3', '0' ], rows[41])
# ...
assert_equal(['2017-05-22', '12', '3', '3', '1' ], rows[44])
# ...
assert_equal(['2017-06-01', '13', '3', '3', '1' ], rows[54])
# ...
assert_equal(['2017-06-05', '13', '5', '5', '4' ], rows[58])
end
end
| true |
23d2e77e13019af89920b58b98161e5f58862b05 | Ruby | vannak1/algorithm | /sum_of_two.rb | UTF-8 | 395 | 4.25 | 4 | [] | no_license | # You have two integer arrays, a and b, and an integer target value v. Determine whether there is a pair of numbers, where one number is taken from a and the other from b, that can be added together to get a sum of v. Return true if such a pair exists, otherwise return false.
#
# Example
#
# For a = [1, 2, 3], b = [10, 20, 30, 40], and v = 42, the output should be
# sumOfTwo(a, b, v) = true.
| true |
e4c98069fc5845250037474f72e78111fe50d14e | Ruby | hiendinhngoc/ruby | /modul/stack.rb | UTF-8 | 355 | 3.3125 | 3 | [] | no_license | require "./stacklike"
class Stack
include Stacklike
end
# Create and using an instance of class Stack
s = Stack.new
s.add_to_stack("item one")
s.add_to_stack("item two")
s.add_to_stack("item three")
puts "Objects currently on the stack: "
puts s.stack
taken = s.take_from_stack
#taken = s.take_from_stack
puts "Removed this object: "
puts s.stack | true |
5663591dd0e45ebf4e1909bcc43cb1e7c7e40706 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/src/1023.rb | UTF-8 | 289 | 3.40625 | 3 | [] | no_license | def compute (x,y)
if x.length <= y.length
strand_size = x.length
else
strand_size = y.length
end
hamming_distance = 0
for i in (0..(strand_size-1))
if x[i] != y[i]
hamming_distance += 1
end
end
return hamming_distance
end | true |
dde4fa99ef69b081b97136a37544ce9371228c8c | Ruby | chrisswk/sinatra-best-practices | /app2.rb | UTF-8 | 1,425 | 2.578125 | 3 | [
"MIT"
] | permissive | #app2
require 'sinatra/base'
require_relative 'helpers'
require_relative 'routes/secrets'
require_relative 'routes/sessions'
class SimpleApp < Sinatra::Base
set :root, File.dirname(__FILE__)
enable :sessions
helpers Sinatra::SampleApp::Helpers
register Sinatra::SampleApp::Routing::Sessions
register Sinatra::SampleApp::Routing::Secrets
end
#helpers.rb
module Sinatra
module SampleApp
module Helpers
def require_logged_in
redirect('/sessions/new') unless is_authenticated?
end
def is_authenticated?
return !!session[:user_id]
end
end
end
end
#routes/secrets.rb
module Sinatra
module SampleApp
module Routing
module Secrets
def self.registered(app)
show_secrets = lambda do
require_logged_in
erb :secrets
end
app.get '/secrets', &show_secrets
end
end
end
end
end
module Sinatra
module SampleApp
module Routing
module Sessions
def self.registered(app)
show_login = lambda do
erb :login
end
receive_login = lambda do
session[:user_id] = params["user_id"]
redirect '/secrets'
end
app.get '/', &show_login
app.get '/sessions/new', &show_login
app.post '/sessions', &receive_login
end
end
end
end
end
| true |
04e6c6d21c32d54d28aa2e1c26eea3024f8fe3c5 | Ruby | AlexHorch/AoC_Python | /2018/day04/solution.rb | UTF-8 | 700 | 3.015625 | 3 | [] | no_license | require 'date'
#[1518-02-05 00:55] wakes up
#[1518-07-08 00:02] falls asleep
#[1518-05-22 23:50] Guard #797 begins shift
input = File.open("input.txt").read.split"\n"
f = File.open("output.txt", "w")
input.sort_by! {|line| DateTime.parse(line.split(/[\[\]]/)[1])}.each do |line| f.write line + "\n" end
class Entry
def initialize(text)
@timestamp = DateTime.parse(text.split(/[\[\]]/)[1])
@msg = text.split("] ")[1]
end
attr_accessor :timestamp
attr_accessor :msg
end
class Guard
def initialize(id)
@id = id
@sleepcycle = Array.new(60, 0)
@shifts = Hash.new
end
def start_shift(month, day) end
attr_accessor :id
end | true |
80878ef875cc53c371d0549ae2c16716173938ae | Ruby | CaptainSpectacular/black_thursday | /test/item_repository_test.rb | UTF-8 | 1,255 | 2.734375 | 3 | [] | no_license | require './test/test_helper'
require './lib/item_repository'
class ItemRepositoryTest < MiniTest::Test
def setup
csv = './data/items.csv'
@ir = ItemRepository.new(csv, nil)
end
def test_existence
assert_instance_of ItemRepository, @ir
end
def test_all
assert_equal 99, @ir.all.size
end
def test_find_by_id
assert_nil @ir.find_by_id(-1)
assert_instance_of Item, @ir.find_by_id(102)
end
def test_find_by_name
assert_nil @ir.find_by_name('Farquad')
assert_instance_of Item, @ir.find_by_name('Free standing Woden letters')
end
def test_find_all_with_description
assert_equal 3, @ir.find_all_with_description("A4 or A5 prints available").size
assert_equal [], @ir.find_all_with_description('Did you ever hear the tragedy of...')
end
def test_find_all_by_price
assert_equal 5, @ir.find_all_by_price(25).size
assert_equal [], @ir.find_all_by_price(0)
end
def test_find_all_by_price_in_range
assert_equal 3, @ir.find_all_by_price_in_range(1..3).size
assert_equal [], @ir.find_all_by_price_in_range(-1..-2)
end
def test_find_all_by_merchant_id
assert_equal 1, @ir.find_all_by_merchant_id(209).size
assert_equal [], @ir.find_all_by_merchant_id(-22)
end
end
| true |
fdafe6a826272d37fc711ed9a59f8c728ee8202f | Ruby | Sifuri/rubyAlgorithms | /CelsiusToFahrenheit.rb | UTF-8 | 690 | 3.765625 | 4 | [] | no_license | =begin
@author Lemuel M. Uhuru
@Date July 14, 2013
Book Title: From Control Structures through Objects by Tony Gaddis
Page: 268 Challenge 11: Celsius to Fahrenheit Table
@Description Write a program that displays a table of the Celsius temperatures
0 through 20 and their Fahrenheit equivalents. Your program should use a loop
to display the table.
=end
# Table header
puts " Temperature (Degrees)"
puts " -----------------------------------------------------"
puts " Celsius " + " Fahrenheit"
# Times loop to calculate fahrenheit
# and display table data.
21.times do |x|
fahrenheit = 9/5.0*x+32
puts " #{x}" + " #{sprintf('%.1f' , fahrenheit)}"
end | true |
ef28cd11078da1bf51b7d4164213b8cbf516718e | Ruby | learn-co-students/london-web-030920 | /04-oo-otm/virus.rb | UTF-8 | 586 | 3.546875 | 4 | [] | no_license | class Virus
@@all = []
attr_accessor :name
def initialize(virus_name)
@name = virus_name
@@all << self
end
def self.number_of_cases
Person.all.select {|person| person.virus }.size
end
def number_of_cases
people_infected.length
end
def people_infected
# self used in a instance method
# refrences the instance
Person.all.select {|person| person.virus == self }
end
def avg_age_of_a_infected_person
people = people_infected.map {|person| person.age }
people.sum / people.size.to_f
end
def self.all
@@all
end
end | true |
140ce5f4c6703a166d5c7ca739a22856c27a2b96 | Ruby | eyi1/my-select-nyc-web-040218 | /lib/my_select.rb | UTF-8 | 164 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_select(collection)
arr = []
i = 0
while i<collection.length
if yield(collection[i])
arr.push(collection[i])
end
i+=1
end
arr
end
| true |
c6afbaf982752ad88260b9ee0548006efe3608ee | Ruby | pbusswood/fizzbuzz | /fizzbuzz.rb | UTF-8 | 868 | 4.03125 | 4 | [] | no_license | # Version 1
# puts (1..100).map { |num|
# output = num + " "
# if num % 3 == 0
# output = output + 'fizz'
# end
# if num % 5 == 0
# output = output + 'buzz'
# end
# puts output
# }
# Version 2
# puts (1..100).map { |num|
# f = b = output = '';
# if num % 3 == 0
# f = 'fizz'
# end
# if num % 5 == 0
# b = 'buzz'
# end
# if f == '' && b == ''
# output = num
# else
# output = f + b
# end
# puts output
# }
# Version 3
# puts (1..100).map { |num|
# output = ''
# if num % 3 == 0
# output += 'fizz'
# end
# if num % 5 == 0
# output += 'buzz'
# end
# if output == ''
# output = num
# end
# puts output
# }
# Version 4
(1..100).map { |num|
output = ''
if num % 3 == 0
output += 'fizz'
end
if num % 5 == 0
output += 'buzz'
end
puts output.empty? ? num : output
} | true |
e277262b3e5b392514b333de85703eaa48ddbeba | Ruby | omgannie/litmus | /app/models/song.rb | UTF-8 | 3,087 | 2.640625 | 3 | [
"MIT"
] | permissive | class Song < ActiveRecord::Base
scope :recent, -> { order("created_at DESC").limit(5) }
validates :artist_name, :song_title, presence: true
has_one :lyric
belongs_to :genre
def self.most_recent_with_lyrics
Song.recent.select do |song|
song.genre.has_lyrics
end
end
def self.song_ids
song_ids = []
Song.recent.each do |song|
song_ids.push(song.id)
end
song_ids
end
def self.match_lyric_to_song(recent_lyrics)
song_lyric_matches = []
recent_lyrics.each do |lyric_object|
if Song.song_ids.include?(lyric_object.song_id)
song_lyric_matches.push(lyric_object)
end
end
song_lyric_matches
end
def self.strongest_emotion_matches(song_lyric_matches)
emotion_object_matches = []
song_lyric_matches.each do |lyric_object|
emotions = Emotion.where(emotionable_id: lyric_object.id)
emotions.each do |emotion|
emotion_object_matches.push(emotion)
end
end
emotion_object_matches
end
def self.chosen_song
final_lyric = nil
final_song = nil
if Song.most_recent_with_lyrics.length == 0
final_song = Song.recent.offset(rand(Song.recent.count)).first
elsif Song.most_recent_with_lyrics.length >= 1
lyrics = Lyric.recent
song_lyric_matches = Song.match_lyric_to_song(lyrics)
emotion_object_matches = Song.strongest_emotion_matches(song_lyric_matches)
values = Emotion.strongest_matches(emotion_object_matches)
final_value = Emotion.compare_matches(values)
strongest_passage_emotion = Passage.last.emotion.strongest_emotion
strongest_passage_emotion
emotion_object_matches.each do |emotion_object|
if emotion_object.read_attribute(strongest_passage_emotion) == final_value
final_lyric = Lyric.find_by(id: emotion_object.emotionable_id)
final_song = final_lyric.song
end
end
end
final_song
end
def map_emotions(primary_emotion)
case primary_emotion
when "Anger"
{min_valence: 0.3, max_valence: 0.6, min_energy: 0.7}
when "Disgust"
{min_valence: 0.3, max_valence: 0.7, min_energy: 0.6, max_acousticness: 0.2}
when "Fear"
{min_valence: 0.3, max_valence: 0.7, min_energy: 0.5, max_acousticness: 0.2}
when "Joy"
{min_valence: 0.7}
when "Sadness"
{max_valence: 0.3}
end
end
def get_recommendations(genre_hash, primary_emotion)
authenticate = RSpotify.authenticate(ENV['SPOTIFY_CLIENT_ID'], ENV["SPOTIFY_CLIENT_SECRET"])
RSpotify.raw_response = true
options_hash = map_emotions(primary_emotion)
options_hash[:limit] = 5
options_hash[:seed_genres] = genre_hash[:seed_genres]
recommendations = RSpotify::Recommendations.generate(options_hash)
JSON.parse(recommendations)
end
def parse_recommendations(recommendations)
metadata_list = []
recommendations["tracks"].each do |track|
metadata_list << {"artist" => track["artists"][0]["name"], "track" => track["name"], "uri" => track["uri"]}
end
metadata_list
end
end
| true |
dbd989df5a432f13580dbd12cb442cb2871c9c47 | Ruby | jrobertson/gtk2html | /lib/gtk2html.rb | UTF-8 | 12,711 | 2.765625 | 3 | [] | no_license | #!/usr/bin/env ruby
# file: gtk2html.rb
require 'gtk2svg'
require 'htmle'
# module InspectArray is located in dom_render.rb
module Gtk2HTML
class Render < DomRender
def initialize(x, width, height)
@width, @height = width.to_i, height.to_i
super x
end
def body(e, attributes, raw_style)
style = style_filter(attributes).merge(raw_style)
margin = style[:margin].values
coords = [nil, nil, nil, nil]
padding = style[:padding].values
[[:draw_box, margin, coords, padding, style], render_all(e)]
end
def strong(e, attributes, raw_style)
style = style_filter(attributes).merge(raw_style)
margin = style[:margin].values
coords = [nil, nil, nil, nil]
padding = style[:padding].values
[[:draw_box, margin, coords, padding, style], render_all(e)]
end
alias b strong
def div(e, attributes, raw_style)
style = style_filter(attributes).merge(raw_style)
margin = style[:margin].values
coords = [nil, nil, nil, nil]
padding = style[:padding].values
[[:draw_box, margin, coords, padding, style], render_all(e)]
end
def html(e, attributes, style)
margin = [0, 0, 0, 0] # style[:margin].values
coords = [0, 0, @width, @height]
padding = [0, 0, 0, 0] # style[:padding].values
[[:draw_box, margin, coords, padding, style], render_all(e)]
end
def input(e, attributes, style)
margin = [0, 0, 0, 0] # style[:margin].values
coords = [0, 0, @width, @height]
padding = [0, 0, 0, 0] # style[:padding].values
[[:add_inputbox, margin, coords, padding, style], render_all(e)]
end
def style(*args)
end
private
def fetch_style(attribute)
h = super attribute
r2 = %i(margin padding).inject(h) do |r,x|
if h.has_key? x then
a = expand_shorthand(h[x])
a.map! do |v|
# note: there is 16px in 1em, see http://pxtoem.com/
v =~ /em$/i ? v.to_f * 16 : v.to_f
end
r.merge!(x => Hash[%i(top right bottom left).zip(a)])
else
r
end
end
r3 = %i(height width).inject(r2) do |r,x|
if r.has_key? x then
v = r[x]
# note: there is 16px in 1em, see http://pxtoem.com/
r[x] = v =~ /em$/i ? v.to_f * 16 : v.to_f
r
else
r
end
end
r3
end
def style_filter(attributes)
%i(bgcolor).inject({}) do |r,x|
attributes.has_key?(x) ? r.merge(x => attributes[x]) : r
end
end
end
class Layout
include InspectArray
attr_reader :to_a
def initialize(instructions, width: 320, height: 240)
pcoords = [0, 0, width, height]
@pcoords = [0,0,0,0]
a = lay_out(instructions, pcoords)
@a = del_pcoords a
end
def to_a(inspect: false, verbose: false)
if inspect or verbose then
scan @a
@a
else
@a
end
end
private
def del_pcoords(a)
if a.first.is_a? Array then
a.map {|row| del_pcoords row if row}
else
a.pop
a
end
end
def lay_out(a, pcoords=[])
if a.first.is_a? Symbol then
@text_style = %i(font-size color).inject({})\
{|r,x| r.merge(x => a[4][x]) }
set_row(a, pcoords)
elsif a.first.is_a? String then
[a.first, @pcoords.take(2), @text_style, pcoords]
elsif a.first.is_a? Array
if a.first.empty? then
a.delete a.first
lay_out a, pcoords
else
if a.first.first.is_a? Symbol then
item, children = a
r = lay_out(item, pcoords)
pcoords = r[-1]
if children.any? then
r2 = lay_out(children, pcoords)
r = [r,r2]
else
r
end
#r << pcoords
else
a.map do |row|
row2 =lay_out(row, pcoords)
pcoords[1] = row2[1][2]
row2
end
end
end
else
a.map {|row| lay_out(row, pcoords) }
end
end
def set_row(row, pcoords)
name, margin, raw_coords, padding, style = row
coords = raw_coords.map.with_index {|x,i| x ? x : pcoords[i]}
width, height = style[:width], style[:height]
x1 = coords[0] + margin[0]
y1 = coords[1] + margin[1]
if width then
x2 = x1 + width.to_f
x2 += margin[2]
else
x2 = coords[2] - margin[2]
end
if height then
y2 = y1 + height.to_f
y2 += margin[3]
else
y2 = coords[3] - margin[3]
end
new_coords = [x1, y1, x2, y2]
@pcoords[0] = x1 + padding[0]
@pcoords[1] = y1 + padding[1]
@pcoords[2] = x2 - padding[2]
@pcoords[3] = y2 - padding[3]
pcoords = @pcoords.clone
[name, margin, new_coords, padding, style, pcoords]
end
end
class DrawingInstructions
attr_accessor :layout
attr_reader :widgets
def initialize(layout=nil)
@layout = layout if layout
@widgets = []
end
def draw_box(margin, coords, padding, style)
h2 = style.clone
h2.delete :color
x1, y1, x2, y2 = coords
width = x2 - x1
height = y2 - y1
gc = gc_ini(h2)
@layout.bin_window.draw_rectangle(gc, 1, x1, y1, width, height)
end
def draw_layout(text, coords, style)
x, y = coords
text ||= ''
h2 = style.clone
h2.delete :'background-color'
layout = Pango::Layout.new(Gdk::Pango.context)
layout.font_description = Pango::FontDescription.\
new('Sans ' + style[:'font-size'])
layout.text = text
gc = gc_ini(h2)
@layout.bin_window.draw_layout(gc, x, y, layout)
end
def window(args)
end
def render(a)
draw a
end
def script(args)
end
private
def draw(a)
return unless a
if a.first.is_a? Symbol then
name, margin, coords, padding, style, _, *children = a
method(name).call(margin, coords, padding, style) if name =~ /^draw_/
draw children
elsif a.first.is_a? String and not a.first.empty?
coords, style = a[1..-1]#remaining
method(:draw_layout).call(a.first, coords, style)
else
a.each do |row|
next unless row
x = row
case row[0].class.to_s.to_sym
when :Symbol
name, margin, coords, padding, style, _, *children = x
method(name).call(margin, coords, padding, style) if name =~ /^draw_/
draw children
when :'Rexle::Element::Value' then
next if x.empty?
coords, style = row[1..-1]#remaining
method(:draw_layout).call(*row)
when :Array
draw row
else
name, *args = x
method(name).call(args) if name =~ /^draw_/
draw row[-1]
end
end
end
end
def set_colour(c)
colour = case c
when /^rgb/
regex = /rgb\((\d{1,3}), *(\d{1,3}), *(\d{1,3})\)$/
r, g, b = c.match(regex).captures.map {|x| x.to_i * 257}
colour = Gdk::Color.new(r, g, b)
when /^#/
Gdk::Color.parse(c)
else
Gdk::Color.parse(c)
end
colormap = Gdk::Colormap.system
colormap.alloc_color(colour, false, true)
colour
end
def gc_ini(style)
gc = Gdk::GC.new(@layout.bin_window)
color, bgcolor = style[:color], style[:'background-color']
gc.set_foreground(set_colour(color)) if color
gc.set_foreground(set_colour(bgcolor)) if bgcolor
gc
end
end
class WidgetInstructions
attr_accessor :layout
def initialize(layout=nil)
@layout = layout if layout
end
def add_inputbox(margin, coords, padding, style)
h2 = style.clone
h2.delete :color
x1, y1, x2, y2 = coords
width = x2 - x1
height = y2 - y1
entry = Gtk::Entry.new
entry.set_text('type something')
@layout.put entry, 10,40
end
def render(a)
add a
end
private
def add(a)
return unless a
if a.first.is_a? Symbol then
name, margin, coords, padding, style, _, *children = a
return if name =~ /^draw_/
method(name).call(margin, coords, padding, style)
add children
else
a.each do |row|
next unless row
x = row
case row[0].class.to_s.to_sym
when :Symbol
name, margin, coords, padding, style, _, *children = x
next if name =~ /^draw_/
method(name).call(margin, coords, padding, style)
add children
when :'Rexle::Element::Value' then
next
when :Array
if row[-1][0].is_a? String then
next
else
add row[-1]
end
else
name, *args = x
next if name =~ /^draw_/
method(name).call(args)
add row[-1]
end
end
end
end
end
class Main
attr_accessor :doc, :html, :layout_instructions
attr_reader :width, :height, :window
def initialize(html, irb: false)
@html = html
@doc = Htmle.new(html, callback: self)
@area = area = Gtk::DrawingArea.new
@layout = layout = Gtk::Layout.new
widgets = nil
client_code = []
window = Gtk::Window.new
@width = 320
@height = 240
@window = window
window.set_default_size(@width, @height)
@dirty = true
layout.signal_connect("expose_event") do
width, height = window.size
@dirty = true if [@width, @height] != [width, height]
if @dirty then
@layout_instructions = prepare_layout @doc
end
drawing = Gtk2HTML::DrawingInstructions.new layout
drawing.render @layout_instructions
@dirty = false
end
area.add_events(Gdk::Event::POINTER_MOTION_MASK)
area.signal_connect('motion_notify_event') do |item, event|
@doc.root.xpath('//*[@onmousemove]').each do |x|
eval x.onmousemove() if x.hotspot? event.x, event.y
end
end
area.add_events(Gdk::Event::BUTTON_PRESS_MASK)
area.signal_connect "button_press_event" do |item,event|
@doc.root.xpath('//*[@onmousedown]').each do |x|
eval x.onmousedown() if x.hotspot? event.x, event.y
end
end
layout_instructions = prepare_layout @doc
widgets = Gtk2HTML::WidgetInstructions.new layout
widgets.render layout_instructions
@layout.put area, 0, 0
window.add(@layout).show_all
window.show_all.signal_connect("destroy"){Gtk.main_quit}
irb ? Thread.new {Gtk.main } : Gtk.main
end
def onmousemove(x,y)
end
def refresh()
@dirty = true
@area.queue_draw
end
def html=(html)
@html = html
@doc = Htmle.new(svg, callback: self)
end
private
def prepare_layout(doc)
Thread.new { doc.root.xpath('//script').each {|x| eval x.text.unescape } }
@width, @height = window.size
instructions = Gtk2HTML::Render.new(doc, @width, @height).to_a
Gtk2HTML::Layout.new(instructions).to_a
end
end
end | true |
dafc4b9f19b1f030bc7e191f07dc5326b6865744 | Ruby | kwatch/rubinius | /spec/library/mailbox/receive_spec.rb | UTF-8 | 1,335 | 2.890625 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../../spec_helper'
require 'mailbox'
describe "Mailbox#receive" do
before :each do
@mbox = Mailbox.new
end
it "returns objects" do
objects = ["hello there", 100, :asdf, Object.new]
objects.each {|o| @mbox.send(o) }
results = []
objects.size.times { results << @mbox.receive }
results.should == objects
end
it "filters on message type" do
Foo = Struct.new :item
Bar = Struct.new :item
Baz = Struct.new :item
Bla = Struct.new :item
@mbox.send(Foo.new("aaaa"))
@mbox.send(Bar.new("bbbb"))
@mbox.send(Baz.new(100))
@mbox.send(Bla.new(:asdf))
@mbox.receive do |f|
f.when Baz do |msg| msg.item end
end.should == 100
@mbox.receive do |f|
f.when Foo do |msg| msg.item end
end.should == "aaaa"
end
it "times out using filter#after with [seconds]" do
complete = 0
@mbox.receive do |f|
f.when Object do |value| value end
f.after(0.001) do
complete += 1
end
end
complete.should == 1
items = [:foo, "bar", 100]
items.each {|v| @mbox.send v }
(items.size + 10).times do
@mbox.receive do |f|
f.when Object do |value| value end
f.after(0) do
complete += 1
end
end
end
complete.should == 11
end
end
| true |
ad99f25b40d15f6f7eaf7c22a2096c48ea6dafcf | Ruby | kojinhiga/ruby- | /01_5.rb | UTF-8 | 723 | 3.84375 | 4 | [] | no_license | puts <<~TEXT
旅行プランを選択してください
1. 沖縄旅行(¥10000)
2. 北海道旅行(¥20000)
3. 九州旅行(¥15000)
TEXT
print "プランを選択 > "
plan = gets.to_i
if plan == 1
puts "沖縄旅行ですね、何人で行きますか?"
print "人数を入力 > "
num = gets.to_i
total_price = 10000 * num
elsif plan == 2
puts "北海道旅行ですね、何人で行きますか?"
print "人数を入力 > "
num = gets.to_i
total_price = 20000 * num
elsif plan == 3
puts "九州旅行ですね、何人で行きますか?"
print "人数を入力 > "
num = gets.to_i
total_price = 15000 * num
end
puts "合計料金:¥#{total_price}"
| true |
8824355be1c2e6e85860c461e01fa3e8a9a2722d | Ruby | danieljanowski/Snowman_game | /specs/hiddenword_specs.rb | UTF-8 | 673 | 2.8125 | 3 | [] | no_license | require ('minitest/autorun')
require ('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative('../hiddenword')
require_relative("../player")
class HiddenwordTest< Minitest::Test
def setup()
@hiddenword1 = Hiddenword.new("poland rules")
@player1= Player.new("Daniel")
end
def test_obscure_word()
assert_equal("****** *****", @hiddenword1.obscured_word.join())
end
def test_player_giving_letter_o()
#letter= @player1.give_letter()
letter = "o"
partial_revealed_word= @hiddenword1.determine_if_correct_letter_given(letter)
assert_equal("*o**** *****", partial_revealed_word)
end
end
| true |
65cf16bbabfd2828633f2127d96591ec8c391b68 | Ruby | gglaine/todoux | /app/helpers/application_helper.rb | UTF-8 | 2,956 | 2.515625 | 3 | [] | no_license | module ApplicationHelper
require 'open_weather'
def time_greeting
gday = "Bonjour"
night = "Bonne nuit"
@time = DateTime.current
if @time.strftime("%H").to_i > 18
return night
else
return gday
end
end
CITY_IDS = {
:paris => "2988506",
:argenteuil => "6457376",
:dakar => "2253350",
:fdf => "6690660",
:wwa =>"6695624",
:montreal => "6077265",
:beijing => "2038349"
}
APPKEY = "#{ENV['OPEN_WEATHER_API_KEY']}"
def argenteuil
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:argenteuil]}", options)
end
def dakar
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:dakar]}", options)
end
def varsovie
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:wwa]}", options)
end
def fdf
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:fdf]}", options)
end
def montreal
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:montreal]}", options)
end
def beijing
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:beijing]}", options)
end
def min_arg
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("2988506", options)
temperature = response["main"]
minimale = response["main"]["temp_min"]
end
def max_arg
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("2988506", options)
temperature = response["main"]
maximale = response["main"]["temp_max"]
end
def dakar_temp
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:dakar]}", options)
maximale = response["main"]["temp_max"]
end
def wwa_temp
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:wwa]}", options)
maximale = response["main"]["temp_max"]
end
def fdf_temp
kiki = "#{ENV['OPEN_WEATHER_API_KEY']}"
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:fdf]}", options)
maximale = response["main"]["temp_max"]
end
def beijing_temp
kiki = "#{ENV['OPEN_WEATHER_API_KEY']}"
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:beijing]}", options)
maximale = response["main"]["temp_max"]
end
def montreal_temp
kiki = "#{ENV['OPEN_WEATHER_API_KEY']}"
options = { units: "metric", APPID: "#{APPKEY}"}
response = OpenWeather::Current.city_id("#{CITY_IDS[:montreal]}", options)
maximale = response["main"]["temp_max"]
end
end
| true |
669cbd3142f23567543e469bde50a920affaa29f | Ruby | jgraichen/acfs | /lib/acfs/service/middleware/stack.rb | UTF-8 | 1,401 | 2.546875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # frozen_string_literal: true
module Acfs
class Service
module Middleware
class Stack
include Enumerable
MUTEX = Mutex.new
IDENTITY = ->(i) { i }
attr_reader :middlewares
def initialize
@middlewares = []
end
def call(request)
build! unless @app
@app.call request
end
def build!
return if @app
MUTEX.synchronize do
return if @app
@app = build
end
end
def build(app = IDENTITY)
middlewares.reverse.inject(app) do |next_middleware, current_middleware|
klass, args, block = current_middleware
args ||= []
if klass.is_a?(Class)
klass.new(next_middleware, *args, &block)
elsif klass.respond_to?(:call)
lambda do |env|
next_middleware.call(klass.call(env, *args))
end
else
raise "Invalid middleware, doesn't respond to `call`: #{klass.inspect}"
end
end
end
def insert(index, klass, *args, &block)
middlewares.insert(index, [klass, args, block])
end
def each
middlewares.each {|x| yield x.first }
end
def clear
middlewares.clear
end
end
end
end
end
| true |
09114b663734f8c44931649315ba8903c5159268 | Ruby | Areid0093/OO-mini-project-austin-web-091619 | /app/models/Ingredient.rb | UTF-8 | 338 | 3.09375 | 3 | [] | no_license | class Ingredient
attr_accessor :ingredient_name
@@all = []
def initialize(ingredient_name)
@ingredient_name = ingredient_name
@@all << self
end
def self.all
@@all
end
def self.most_common_allergen
Allergy.all.max_by {|a| a.ingredient.count(a)}
end
end
| true |
8c4aac074b948d37de4e152eae5f4e016a8f0dab | Ruby | teoucsb82/pokemongodb | /lib/pokemongodb/pokemon/exeggutor.rb | UTF-8 | 1,288 | 2.59375 | 3 | [] | no_license | class Pokemongodb
class Pokemon
class Exeggutor < Pokemon
def self.id
103
end
def self.base_attack
232
end
def self.base_defense
164
end
def self.base_stamina
190
end
def self.buddy_candy_distance
2
end
def self.capture_rate
0.16
end
def self.cp_gain
40
end
def self.description
"Exeggutor originally came from the tropics. Its heads steadily grow larger from exposure to strong sunlight. It is said that when the heads fall off, they group together to form Exeggcute."
end
def self.flee_rate
0.06
end
def self.height
2.0
end
def self.max_cp
2955.18
end
def self.moves
[
Pokemongodb::Move::Confusion,
Pokemongodb::Move::ZenHeadbutt,
Pokemongodb::Move::Psychic,
Pokemongodb::Move::SeedBomb,
Pokemongodb::Move::SolarBeam
]
end
def self.name
"exeggutor"
end
def self.types
[
Pokemongodb::Type::Grass,
Pokemongodb::Type::Psychic
]
end
def self.weight
120.0
end
end
end
end
| true |
574289d47d68f1ec34d0543850069cdce062cae3 | Ruby | louisraymond/looping-while-until-prework | /lib/until.rb | UTF-8 | 174 | 2.59375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_until
levitation_force = 6
#your code here
counter = 0
until levitation_force == 10
puts "Wingardium Leviosa"
levitation_force += 1
end
end
| true |
d7c2e3008deb42eabdfc8af2d9de6d20ee561e60 | Ruby | darkelv/qna | /db/seeds.rb | UTF-8 | 1,433 | 2.71875 | 3 | [] | no_license | Question.destroy_all
User.destroy_all
user1 = User.create(
email: 'user1@yandex.ru',
password: 'secret1',
password_confirmation: 'secret1',
)
user2 = User.create(
email: 'user2@yandex.ru',
password: 'secret2',
password_confirmation: 'secret2',
)
user3 = User.create(
email: 'user3@yandex.ru',
password: 'secret3',
password_confirmation: 'secret3',
)
q1, q2, q3 = Question.create(
[
{
title: 'First programming language',
body: 'Which programming language is best to learn first?',
user: user1
},
{
title: 'Programming book for a beginner?',
body: 'What programming book would you recommend for learning Elixir?',
user: user2
},
{
title: 'Framework for REST API',
body: 'What are the best framework to create a REST API in a very short time?',
user: user3
}
]
)
Answer.create(
[
{
body: 'I have no idea',
question: q2,
user: user1
},
{
body: 'What is REST API?',
question: q3,
user: user1
},
{
body: 'Structure and Interpretation of Computer Programs',
question: q1,
user: user2
},
{
body: 'Ruby on Rails',
question: q3,
user: user2
},
{
body: 'Cobol',
question: q1,
user: user3
},
{
body: 'Structure and Interpretation of Computer Programs',
question: q2,
user: user3
}
]
)
| true |
55218cd2a59f8096f1436422c1fd4bd462dc4151 | Ruby | gropmor/dragonquest_program | /monster.rb | UTF-8 | 270 | 3.453125 | 3 | [] | no_license | require "./character.rb"
class Monster < Character
def appear
puts "#{@name}があらわれた!"
end
def attack(brave)
puts "#{@name}の攻撃!"
calculate_damage(brave)
puts "#{brave.name}は#{@damage}のダメージを受けた!"
end
end | true |
fa86bd4c219c7c13445e90d190e746cd1f306b7c | Ruby | phongnh/threetaps_client | /lib/threetaps_client/core_ext/hash.rb | UTF-8 | 858 | 3.140625 | 3 | [
"MIT"
] | permissive | class Hash
# Returns a "flatten" hash representation of the receiver:
#
# { :source => 'CRAIG', :location => { :country => 'USA' } }.flatten
# # => { :source => 'CRAIG', :"location.country" => 'USA' }
#
# { :param => 1, :nested => { :param => 2, :nested => { :param => 2 } } }.flatten
# # => { :param => 1, :"nested.param" => 2, :"nested.nested.param" => 2}
#
# An optional prefix can be passed to enclose the key names:
#
# { :country => 'USA', :state => 'CA' }.flatten('location')
# # => { :"location.country" => 'USA', :"location.state" => 'CA' }
def flatten(prefix=nil)
prefix = "#{prefix}." if prefix
inject({}) do |hash, (key, value)|
if value.is_a?(Hash)
hash.merge! value.flatten("#{prefix}#{key}")
else
hash[:"#{prefix}#{key}"] = value
end
hash
end
end
end
| true |
3276d200538084ce41d9d4d796961f3121a8def0 | Ruby | nicoledag/reverse-each-word-online-web-sp-000 | /reverse_each_word.rb | UTF-8 | 198 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
def reverse_each_word(string)
string = string.split
reversed_string = []
string.collect do |word|
reversed_string << word.reverse
end
return reversed_string.join(' ')
end
| true |
dfb62222b0f9df392dd55859514ad8f7c453a6c5 | Ruby | jkopczyn/AdventOfCode | /2015/day18.rb | UTF-8 | 1,541 | 3.390625 | 3 | [] | no_license | require 'byebug'
def life_lights(filename, steps)
light_array = []
File.open(filename, 'r') do |file|
file.each do |line|
light_array.push(line.strip.split('').map {|c| c == '#'})
end
light_array[0][0] = true
light_array[0][-1] = true
light_array[-1][-1] = true
light_array[-1][0] = true
end
pretty_grid(light_array)
steps.times do
#pretty_grid(light_array)
light_array = evolve(light_array)
end
pretty_grid(light_array)
light_array.map {|line| line.count {|b| b} }.inject(&:+)
end
def evolve(light_grid)
new_grid = []
light_grid.each_with_index do |line, y|
new_grid.push(line.each_with_index.map do |pixel, x|
neighbor_locs = neighbors([y,x], light_grid.count, light_grid[0].count)
lit_neighbors = neighbor_locs.map do |posn|
light_grid[posn[0]][posn[1]]
end.count {|b| b}
lit_neighbors == 3 or (pixel and lit_neighbors == 2)
end)
end
new_grid[0][0] = true
new_grid[0][-1] = true
new_grid[-1][-1] = true
new_grid[-1][0] = true
new_grid
end
def neighbors(posn, height, width)
[[-1, -1], [-1, 0], [-1, 1], [0, -1],
[0, 1], [1, -1], [1, 0], [1, 1]].map do |vector|
[posn[0]+vector[0],posn[1]+vector[1]]
end.select do |loc|
y, x = loc
0 <= y and y < height and 0 <= x and x < width
end
end
def pretty_grid(light_grid)
puts (light_grid.map do |line|
line.map { |pixel| pixel ? '#' : '.' }.join('')
end).join("\n")
puts "\n"
end
puts life_lights("testinput18.txt", 5)
puts life_lights("input18.txt", 100)
| true |
d4cf8475b8c0b0501495955088a3252933872fb8 | Ruby | yoshida-keita/aoj | /course/Introduction_to_Programming_I/10_2.rb | UTF-8 | 216 | 3.140625 | 3 | [] | no_license |
a,b,c=gets.split.map(&:to_f)
sin=Math.sin((c/180)*Math::PI)
cos=Math.cos((c/180)*Math::PI)
puts sprintf("%.8f",(a*b*sin/2.0))
puts sprintf("%.8f",a+b+((a**2)+((b**2)-2*a*b*cos))**(1/2.0))
puts sprintf("%.8f",sin*b)
| true |
e4fc15a0f2aa36aa3569c0a1ac773dc34b489057 | Ruby | prettymuchbryce/princessfrenzy | /websocketserver/messaging.rb | UTF-8 | 2,967 | 3.078125 | 3 | [] | no_license | # This module is used for nothing more than sending messages.
# It doesn't care about state. It just knows how to send particular messages.
# Do you get the message ?
module Messaging
DEBUG = true
DELIMITER = "%"
LOGIN = "L"
LEVEL = "E"
BANNED = "B"
CHAT = "C"
QUIT = "Q"
DIE = "D"
MOVE = "M"
BULLET = "A"
ACCEPT_LOGIN = "K"
SERVER_MESSAGE = "S"
NPC_MOVE = "N"
def self.send_accept_login_message(game,ws,user)
message = ACCEPT_LOGIN + DELIMITER + user.id
ws.send message
if DEBUG
puts message
end
end
def self.send_move_message(game,ws,user)
message = MOVE + DELIMITER + user.id + DELIMITER + user.name + DELIMITER + user.dir.to_s + DELIMITER + user.x.to_s + DELIMITER + user.y.to_s + DELIMITER + user.dead.to_s
ws.send message
if DEBUG
puts message
end
end
def self.send_quit_message(game,ws,id)
message = QUIT + DELIMITER + id
ws.send message
if DEBUG
puts message
end
end
def self.send_npc_move_message(game,ws,npc)
message = NPC_MOVE + DELIMITER + npc.id + DELIMITER + npc.name + DELIMITER + npc.asset.to_s + DELIMITER + npc.dir.to_s + DELIMITER + npc.x.to_s + DELIMITER + npc.y.to_s + DELIMITER + npc.dead.to_s
ws.send message
if DEBUG
puts message
end
end
def self.send_specific_npc_move_message(game,ws,npc,x,y)
message = NPC_MOVE + DELIMITER + npc.id + DELIMITER + npc.name + DELIMITER + npc.asset.to_s + DELIMITER + npc.dir.to_s + DELIMITER + x.to_s + DELIMITER + y.to_s + DELIMITER + npc.dead.to_s
ws.send message
if DEBUG
puts message
end
end
def self.send_specific_move_message(game,ws,user,x,y)
message = MOVE + DELIMITER + user.id + DELIMITER + user.name + DELIMITER + user.dir.to_s + DELIMITER + x.to_s + DELIMITER + y.to_s + DELIMITER + user.dead.to_s
ws.send message
if DEBUG
puts message
end
end
def self.send_server_message_message(game,ws,message)
message = SERVER_MESSAGE + DELIMITER + message
ws.send message
if DEBUG
puts message
end
end
def self.send_bullet_message(game,ws,bullet)
message = BULLET + DELIMITER + bullet.id + DELIMITER + bullet.dir.to_s + DELIMITER + bullet.x.to_s + DELIMITER + bullet.y.to_s + DELIMITER + bullet.level.file
ws.send message
if DEBUG
puts message
end
end
def self.send_level_message(game,ws,file)
message = LEVEL + DELIMITER + file
ws.send message
if DEBUG
puts message
end
end
def self.send_die_message(game,ws,user)
message = DIE + DELIMITER + user.id
ws.send message
if DEBUG
puts message
end
end
def self.send_banned_message(game,ws)
message = BANNED
ws.send message
if DEBUG
puts message
end
end
def self.send_chat_message(game,ws,sender,message)
message = CHAT + DELIMITER + sender + DELIMITER + message.to_s
ws.send message
if DEBUG
puts message
end
end
end | true |
2e7b0d7bff2d840fa1f4faee0c13eb4a8d57814e | Ruby | randallr18/nyc-mhtn-web-060418 | /10-intro-tdd/program.rb | UTF-8 | 114 | 3.140625 | 3 | [] | no_license | def is_palindrome?(word)
# 'dad'
word = word.split(' ').join('')
word.downcase == word.downcase.reverse
end
| true |
3ea8d814e870693adf73793a281780932d702351 | Ruby | bitfluent/wheneva | /vendor/plugins/hoptoad_notifier/lib/hoptoad_notifier.rb | UTF-8 | 4,694 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'net/http'
require 'net/https'
require 'rubygems'
require 'active_support'
require 'hoptoad_notifier/configuration'
require 'hoptoad_notifier/notice'
require 'hoptoad_notifier/sender'
require 'hoptoad_notifier/catcher'
require 'hoptoad_notifier/backtrace'
# Plugin for applications to automatically post errors to the Hoptoad of their choice.
module HoptoadNotifier
VERSION = "2.0.3"
API_VERSION = "2.0"
LOG_PREFIX = "** [Hoptoad] "
HEADERS = {
'Content-type' => 'text/xml',
'Accept' => 'text/xml, application/xml'
}
class << self
# The sender object is responsible for delivering formatted data to the Hoptoad server.
# Must respond to #send_to_hoptoad. See HoptoadNotifier::Sender.
attr_accessor :sender
# A Hoptoad configuration object. Must act like a hash and return sensible
# values for all Hoptoad configuration options. See HoptoadNotifier::Configuration.
attr_accessor :configuration
# Tell the log that the Notifier is good to go
def report_ready
write_verbose_log("Notifier #{VERSION} ready to catch errors")
end
# Prints out the environment info to the log for debugging help
def report_environment_info
write_verbose_log("Environment Info: #{environment_info}")
end
# Prints out the response body from Hoptoad for debugging help
def report_response_body(response)
write_verbose_log("Response from Hoptoad: \n#{response}")
end
# Returns the Ruby version, Rails version, and current Rails environment
def environment_info
info = "[Ruby: #{RUBY_VERSION}]"
info << " [Rails: #{::Rails::VERSION::STRING}]" if defined?(Rails)
info << " [Env: #{configuration.environment_name}]"
end
# Writes out the given message to the #logger
def write_verbose_log(message)
logger.info LOG_PREFIX + message if logger
end
# Look for the Rails logger currently defined
def logger
if defined?(Rails.logger)
Rails.logger
elsif defined?(RAILS_DEFAULT_LOGGER)
RAILS_DEFAULT_LOGGER
end
end
# Call this method to modify defaults in your initializers.
#
# @example
# HoptoadNotifier.configure do |config|
# config.api_key = '1234567890abcdef'
# config.secure = false
# end
def configure(silent = false)
self.configuration ||= Configuration.new
yield(configuration)
self.sender = Sender.new(configuration)
report_ready unless silent
end
# Sends an exception manually using this method, even when you are not in a controller.
#
# @param [Exception] exception The exception you want to notify Hoptoad about.
# @param [Hash] opts Data that will be sent to Hoptoad.
#
# @option opts [String] :api_key The API key for this project. The API key is a unique identifier that Hoptoad uses for identification.
# @option opts [String] :error_message The error returned by the exception (or the message you want to log).
# @option opts [String] :backtrace A backtrace, usually obtained with +caller+.
# @option opts [String] :request The controller's request object.
# @option opts [String] :session The contents of the user's session.
# @option opts [String] :environment ENV merged with the contents of the request's environment.
def notify(exception, opts = {})
send_notice(build_notice_for(exception, opts))
end
# Sends the notice unless it is one of the default ignored exceptions
# @see HoptoadNotifier.notify
def notify_or_ignore(exception, opts = {})
notice = build_notice_for(exception, opts)
send_notice(notice) unless notice.ignore?
end
def build_lookup_hash_for(exception, options = {})
notice = build_notice_for(exception, options)
result = {}
result[:action] = notice.action rescue nil
result[:component] = notice.component rescue nil
result[:error_class] = notice.error_class if notice.error_class
result[:environment_name] = 'production'
unless notice.backtrace.lines.empty?
result[:file] = notice.backtrace.lines.first.file
result[:line_number] = notice.backtrace.lines.first.number
end
result
end
private
def send_notice(notice)
if configuration.public?
sender.send_to_hoptoad(notice.to_xml)
end
end
def build_notice_for(exception, opts = {})
if exception.respond_to?(:to_hash)
opts = opts.merge(exception)
else
opts = opts.merge(:exception => exception)
end
Notice.new(configuration.merge(opts))
end
end
end
| true |
f9d83c916b5d26d72b80b69ae1ba4c4e7985296c | Ruby | malinovskymax/files-names-parser | /app/models/parser.rb | UTF-8 | 1,173 | 3.078125 | 3 | [] | no_license | class Parser
VALID_ID_PATTERN = /^u\d{1,15}/i
VALID_TYPE_PATTERN = /(account)|(activity)|(position)|(security)/i
SIMPLE_DATE_PATTERN = /\d{8}/
VALID_FILENAME_PATTERN = /#{VALID_ID_PATTERN}_#{VALID_TYPE_PATTERN}_#{SIMPLE_DATE_PATTERN}\.*/i
# VALID_FILENAME_PATTERN = /^u\d{1,15}_((account)|(activity)|(position)|security)_\d{8}\.*/i
class << self
def parse(source)
parsed_data = {}
Dir.foreach(source) do |item|
if is_valid_file?(source, item)
item.gsub!(VALID_ID_PATTERN, '')
account = $&.capitalize
begin
date = Time.parse(item[SIMPLE_DATE_PATTERN]).strftime('%F')
rescue ArgumentError
next
end
parsed_data[account] ||= {}
parsed_data[account][date] ||= []
parsed_data[account][date] << item[VALID_TYPE_PATTERN]
end
end
parsed_data.each_value { |account| account.each_value { |types| types.sort_by! { |type| type.downcase! } } }
end
private
def is_valid_file?(source, filename)
File.file?(source.join(filename)) && filename.match(VALID_FILENAME_PATTERN) ? true : false
end
end
end | true |
ec7af2e7e1c3a45dc4406c7606b0a81186c764b8 | Ruby | cloudhead/prose | /lib/prose.rb | UTF-8 | 8,581 | 3.109375 | 3 | [] | no_license | require 'cgi'
require 'json'
require 'yaml'
##
# Copyright (c) 2009 Alexis Sellier
#
# Prose - A lightweight text to html parser inspired by Markdown & Textile
#
class Prose < String
#
# Usage:
#
# Prose.new(text).parse
# or
# Prose.parse text
#
# lite mode (no headers, escape html):
#
# text = Prose.new(text).parse(true)
#
# Parser:
#
# Document Title <h1>
# ==============
#
# Header <h2>
# ------
#
# # Sub-Header <h3>
# ## Sub-sub-Header <h4>
# ..etc..
#
# <ul> <ol>
# - Milk 1. Milk
# - Apples 2. Apples
# - Coffee 3. Coffee
#
# << Blockquote >> <blockquote>
#
# "Click Here":http://www.github.com <a>
# Click:http://www.google.com <a>
#
# +-+-+-+ <hr>, must have empty line before and after
# +=+=+
# ---
#
# *milk* <strong>milk</strong>
# _milk_ <em>milk</em>
# %mlik% <code>milk</code>
# -milk- <del>milk</del>
# "milk" <q>milk</q>
#
# hot--milk &mdash
# hot - milk &ndash
# (C),(R) ©, ®
# 2 x 2 / 5 ×, ÷
# ... Ellipsis
#
# // Secret Comment, won't show up in html
# /* Secret */
#
# @author: Cloudhead
#
# #
#
VERSION = '0.2'
#
# Glyph definitions
#
QuoteSingleOpen = '‘'
QuoteSingleClose = '’'
QuoteDoubleOpen = '“'
QuoteDoubleClose = '”'
QuoteDoubleLow = '„'
Apostrophe = '’'
Ellipsis = '…'
Emdash = '—'
Endash = '–'
Multiply = '×'
Divide = '÷'
Trademark = '™'
Registered = '®'
Copyright = '©'
Backslash = '\'
StartProse = "<!-- prose -->\n"
EndProse = "\n<!-- /prose -->"
#
# *match* => <strong>replace</strong>
#
TAGS = {
'*' => 'strong',
'_' => 'em',
'"' => 'q',
'%' => 'code',
'-' => 'del'
}
#
# Match => Replace
#
GLYPHS = {
# Comments
/[ \t]*[^:]\/\/.*(\n|\Z)/ => '\\1',
/\/\*.*?\*\//m => '',
# Metadata
/^@.+?: *.+?\n/ => '',
# Horizontal Rulers
/\n\n[ \t]*[-=+]+(\n\n|\Z)/ => "\n\n<hr />\n\n",
# em-dash and en-dash
/( ?)--( ?)/ => '\\1' + Emdash + '\\2',
/\s-(?:\s|\Z)/ => ' ' + Endash + ' ',
# ...
/\b( )?\.{3}/ => '\\1' + Ellipsis,
# Arithmetics: 2 x 3, 6 / 2
/(\d+)( ?)x( ?)(?=\d+)/ => '\\1\\2' + Multiply + '\\3',
/(\d+)( ?)\/( ?)(?=\d+)/ => '\\1\\2' + Divide + '\\3',
# (tm) (r) and (c)
/\b ?[\(\[]tm[\]\)]/i => Trademark,
/\b ?[\(\[]r[\]\)]/i => Registered,
/\b ?[\(\[]c[\]\)]/i => Copyright,
# Blockquotes
/<< ?(.+) ?>>\n/m => "<blockquote>\\1</blockquote>\n",
/\n\n[\t ]+(.+?)\n\n/m => "<blockquote>\\1</blockquote>\n"
}
# Defines the order of the parsing.
# When a tuple is used, Prose checks
# if the second value matches @lite,
# before running it.
PARSERS = [
:whitespace,
[:html, true],
[:headers, false],
:links,
:lists,
:glyphs,
:paragraphs,
:tags,
:backslashes
]
def initialize string
@title = nil
@id = nil
super
end
def self.parse( text, lite = false )
new( text ).to_html( lite )
end
def to_html( lite = false )
#
# Run all the parsing in order
#
# #
# The operations are done on +self+ as it is
# the string to be parsed.
# We go through each parser, checking if it matches
# the current mode, and run, it if does.
#
@lite = lite
PARSERS.inject( self ) do |text, parser|
( parser.is_a?(Array) && parser.last == @lite ) ||
parser.is_a?(Symbol) ?
send( parser.is_a?(Array) ? parser.first : parser, text ) : text
end
end
alias parse to_html
def to_json( lite = false )
#
# JSON output
#
# #
# Additional data such as title, id and date are then
# generated (or specified by the user), and added too.
# `self` is then parsed, and added to the `body` field.
#
self.metadata.merge({
title: title,
id: Time.now.strftime("%Y-%m-%d") + '-' + id,
uri: Time.now.strftime("/%Y/%m/%d/") + id,
timestamp: Time.now.to_i,
date: "#{ Time.now.strftime("%B") } #{ ordinal( Time.now.day ) } #{ Time.now.year }",
body: self.parse( lite ).gsub("<h1>#@title</h1>", ''), # Parse, and remove title
}).to_json
end
def to_yaml( lite = false )
#
# YAML output
#
self.metadata.merge({
title: title,
date: Time.now.strftime("%Y/%m/%d"),
body: self.parse( lite ).gsub("<h1>#@title</h1>", '')
}).to_yaml
end
def metadata
#
# Scan `self` for metadata in the form of:
# @author: "cloudhead"
# Return a hash containing all the key/value pairs
#
self.to_s.scan(/^@(\w+?): *"?(.+?)"?$/).inject({}) do |data, (key, value)|
data.merge key => value
end
end
def id
@id || title.downcase.gsub(/[^a-z0-9]+/, '-') # Return current id, or generate one from the `title`
end
def id= s
s.scan(/[^a-z0-9\-]/).empty? ? @id = s : raise # Raise an exception if non-standard characters were detected
end
def whitespace text
#
# Remove extraneous white-space
#
text.strip.
gsub("\r\n", "\n"). # Convert DOS to UNIX
gsub(/\n{3,}/, "\n\n"). # 3+ to 2
gsub(/\n[ \t]+\n/, "\n\n") + # Empty lines
"\n\n" # Add whitespace at the end
end
def html text
CGI.escapeHTML text
end
def backslashes text
# Remove single backslashes,
# escape double ones
text.gsub('\\\\', Backslash).delete '\\'
end
def tags text
#
# Parse *bold* _em_ -del- etc
#
TAGS.inject( text ) do |text, (style, tag)|
style = Regexp.escape( style )
text.gsub(/([^\w\\]) # Non-word or backslash
#{style} # Opening tag
([^\n\t#{style}]+?) # Contents, which must not include the tag
#{style} # Closing tag
([^\w]) # Non-word character
/x,
"\\1<#{tag}>\\2</#{tag}>\\3")
end
end
def glyphs text
#
# Replace some chars with better ones
#
GLYPHS.inject( text ) do |text, (match, replace)|
text.gsub( match, replace )
end
end
TitleRegexp = /^(.+)[ \t]*\n=+[ \t]*\n+/
def title
@title ||= self.match( TitleRegexp ).captures.join
end
def headers text
text.
gsub( TitleRegexp ) do |match| # ======
"<h1>" + $1.to_s + "</h1>\n\n"
end.
gsub(/^(.+)[ \t]*\n-+[ \t]*\n+/, "<h2>\\1</h2>\n\n"). # ------
gsub(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/) do |match| # #
lvl = ( $1.length + 2 ).to_s
"<h#{ lvl }>" + $2.to_s + "</h#{ lvl }>\n\n"
end
end
def lists text
#
# Match the whole list, then replace the individual rows
#
marker = /-|\d\./ # - or 1.
text.gsub(/^ # Start on a new-line
(#{marker}) # Any list marker
(.+?) # Everything, including new-lines, but not greedy
\n(?!#{marker}) # A new-line which is not followed by a marker
/xm) do |match|
type = ($1 == '-') ? 'ul' : 'ol'
"<#{type}>\n" +
match.gsub(/^#{marker} ?(.+)$/, "\t<li>\\1</li>") +
"</#{type}>\n"
end
end
def paragraphs text
#
# Parse: \n\nfoo\n\n
# Into: <p>foo</p>
#
# # Split text into blocks.
# If it's not already enclosed in tags, or an hr,
# enclose it inside <p> tags
text.split("\n\n").collect do |block|
if ! block.match(/^(<.+?>.+<.+?>)|(<hr \/>)$/m)
"\n<p>" + block + "</p>\n"
else
block
end
end.join
end
# Line breaks
def breaks text
text.gsub(/([^\n])\n([^\n])/, "\\1<br />\n\\2")
end
def links text
#
# Parse: "link":http://www.link.com
# Into: <a href="http://www.link.com">link</a>
#
nofollow = "rel='nofollow'" if @lite
text.gsub(/"([\w\s]+)":(http:\/\/[^\s]+)/,
"<a #{nofollow} href='\\2'>\\1</a>").
gsub(/(^":)http:\/\/[^\s]+/,
"<a #{nofollow} href='\\1'>\\1</a>")
end
def ordinal number
# 1 => 1st
# 2 => 2nd
# 3 => 3rd
# ...
number = number.to_i
case number % 100
when 11..13; "#{number}th"
else
case number % 10
when 1; "#{number}st"
when 2; "#{number}nd"
when 3; "#{number}rd"
else "#{number}th"
end
end
end
end
| true |
739e5b8c7e1049195a1128863e108656b0611816 | Ruby | bernardoamc/labs | /ruby/cryptopals/03_set/18.rb | UTF-8 | 281 | 2.53125 | 3 | [] | no_license | require_relative '../helpers'
require 'openssl'
input = base64_decode(
'L77na/nrFsKvynd6HzOoG7GHTLXsTVu9qvY/2syLXzhPweyyMTJULu/6/kXX0KSvoOLSFQ=='
)
key = 'YELLOW SUBMARINE'.unpack('C*')
nonce = 0
puts(aes_ctr_decrypt(input, key, nonce).pack('C*'))
puts(
"Success: #{aes_ctr_encrypt(aes_ctr_decrypt(input, key, nonce), key, nonce) == input}"
)
| true |
7e2d28debb79925fa7d0417c8e1f363e4d9c7627 | Ruby | kpapacostas/todo-ruby-basics-web-103017 | /lib/ruby_basics.rb | UTF-8 | 355 | 3.296875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def division(num1, num2)
quotient = num1/num2
quotient
end
def assign_variable(value)
name = value
name
end
def argue(argument)
argument
end
def greeting(greeting, name)
end
def return_a_value
comment = "Nice"
comment
end
def last_evaluated_value
qualifier = "expert"
qualifier
end
def pizza_party(topping = "cheese")
topping
end
| true |
8b409f4c59e0f026e5c641859fb2854a25b8d320 | Ruby | tanvir002700/RubyDesignPattern | /Creational patterns/factory/src.rb | UTF-8 | 206 | 2.6875 | 3 | [] | no_license | require './factory.rb'
require './mega_factory.rb'
require './warrior_factory.rb'
m = Factory.new MegaFactory.new
m.create 10
puts m.members
w = Factory.new WarriorFactory.new
w.create 10
puts w.members
| true |
288fc08d52640e7b699a1f407532a002dc9704e8 | Ruby | susmitabhowmik/conference_app | /meeting_notes.rb | UTF-8 | 392 | 2.796875 | 3 | [] | no_license | require 'http'
p "If you would like the meeting notes from a particualar meeting, please enter the number of the meeting else enter 'all':"
meeting_id = gets.chomp.to_i
if meeting_id == 0
meeting_notes = HTTP.get('http://localhost:3000/api/meetings')
p meeting_notes.parse
else
meeting_notes = HTTP.get("http://localhost:3000/api/meetings/#{meeting_id}")
p meeting_notes.parse
end | true |
c919059ae0982a1c385d15aa0c829311eb156b56 | Ruby | potamus/fujirockive | /main.rb | UTF-8 | 6,627 | 2.65625 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/cross_origin'
require 'sinatra/reloader'
require 'active_record'
require 'mysql2'
require 'youtube_search'
require 'json'
require 'rexml/document'
require 'cgi'
require 'kconv'
require 'yaml'
enable :cross_origin
set :bind, '0.0.0.0'
# DB設定の読み込み
ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'] || YAML.load_file(File.join(__dir__, 'database.yml'))['development'])
#ActiveRecord設定
class Artist < ActiveRecord::Base
has_many :timetables
end
class Timetable < ActiveRecord::Base
belongs_to :artist
end
#Youtube情報検索メソッド
def youtube_search(aid,artistsong,seq=5)
artist = Artist.where(:id => aid)
#動画の検索クエリ作成
#ランダムに作成した数字から1ずつ引いてデータがあれば出力、0になれば終了
query =[]
num = artistsong == true ? seq : rand(5) + 1
favorite_song = ("favorite" + num.to_s).to_sym
until num <= 0 do
if artist[0].send(favorite_song)
query = [artist[0].name, artist[0].send(favorite_song)]
break
end
num -= 1
end
#動画IDの検索取得
keyword = "#{query[0]} #{query[1]}"
video = YoutubeSearch::search(keyword).first
h = {}
if video then
unless video["title"].scan(/#{query[0]}/i).empty?
h = { "video_id" => video["video_id"],
"title" => video["title"],
"artist" => query[0],
"artist_id" => aid
}
end
end
return h
end
#トップ
get '/' do
erb :index
end
#年指定での曲リスト取得
get '/yearsong/:y/:d/:list' do |y, d, list|
result = []
#検索用ハッシュの作成
hash = {}
hash.store(:year, y) unless y == "all"
hash.store(:day, d) unless d == "all"
timetable = Timetable.where(hash)
timetable_count = timetable.count
#listの数だけ曲を取得する(10回検索してだめならおわり)
10.times do
artistid = timetable[rand(timetable_count)].artist_id
video = youtube_search(artistid,false)
unless video.empty?
result.push(video)
end
break if result.length == list.to_i
end
result.to_json
end
#ステージ指定での曲リスト取得
get '/stagesong/:sid/:y/:d/:list' do |sid, y, d, list|
result = []
#検索用ハッシュ
hash = {}
hash.store(:stage_id, sid)
hash.store(:year, y) unless y == "all"
hash.store(:day, d) unless d == "all"
timetable = Timetable.where(hash)
timetable_count = timetable.count
#listの数だけ曲を取得する(10回検索してだめならおわり)
10.times do
artistid = timetable[rand(timetable_count)].artist_id
video = youtube_search(artistid,false)
unless video.empty?
result.push(video)
end
break if result.length == list.to_i
end
result.to_json
end
#artist指定での曲リスト取得
get '/artistsong/:aid' do |aid|
result = []
5.downto(1) do |i|
video = youtube_search(aid,true,i)
unless video.empty?
result.push(video)
end
end
result.to_json
end
#年指定で情報取得
get '/year/:y' do |y|
result = []
if y == "all" then
timetable = Timetable.all.order("year desc, day asc, stage_id asc, num asc")
else
timetable = Timetable.where(year: y).order("day asc, stage_id asc, num asc")
end
timetable.each do |data|
if data
artist = Artist.where(:id => data.artist_id)
h = { "year" => data.year,
"day" => data.day,
"stage_id" => data.stage_id,
"order" => data.num,
"artist_id" => data.artist_id,
"artist_name" => artist[0].name
}
result.push(h)
end
end
result.to_json
end
#ステージ情報
get '/stage/:sid/:y' do |sid, y|
result = []
if y == "all" then
timetable = Timetable.where(stage_id: sid).order("year desc, day asc, num asc")
else
timetable = Timetable.where(stage_id: sid, year: y).order("day asc, num asc")
end
timetable.each do |data|
if data
artist = Artist.where(:id => data.artist_id)
h = { "year" => data.year,
"day" => data.day,
"stage_id" => data.stage_id,
"order" => data.num,
"artist_id" => data.artist_id,
"artist_name" => artist[0].name
}
result.push(h)
end
end
result.to_json
end
#アーティスト情報
get '/artist/:aid' do |aid|
result = {}
artist = Artist.where(:id => aid)
if artist[0]
result.store(:name, artist[0].name)
result.store(:info, artist[0].info)
result.store(:aid, artist[0].id)
#人気曲
favorites = []
1.upto(5).each do |i|
favorite = "favorite" + i.to_s
if fsong = artist[0].send(favorite.to_sym)
favorites.push(fsong)
end
end
result.store(:favorite, favorites)
#関連アーティスト検索
similars = []
1.upto(10).each do |i|
sim = "similar" + i.to_s
if simartist = Artist.where(:lastname => artist[0].send(sim.to_sym))
if simartist[0]
similars.push([simartist[0].id, simartist[0].name])
end
end
end
result.store(:similar,similars)
#出演年
actyears = []
timetable = Timetable.where(:artist_id => aid)
actyears.push(timetable[0].year)
result.store(:actyear,actyears)
#lastfmから写真を取得
pictures = []
if lname = artist[0].lastname
qartist = CGI.escape(Kconv.toutf8(lname))
begin
open('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist='+ qartist +'&lang=jp&autocorrect=1&api_key=3b7599fb321f51cb3f6532095e85decd&format=json') do |file|
infodoc = JSON.parse(file.read)
if infodoc.has_key?('artist')
pictureurls = infodoc['artist']['image']
pictureurls.each do |pic|
if pic['size'] == "large" then
pictures.push(pic['#text'])
end
end
end
end
rescue
end
end
result.store(:picture,pictures)
#setlistfmから最新セットリストを取得
setlists = []
unless artist[0].mbid.empty? or artist[0].mbid.nil?
mbid = artist[0].mbid
begin
open('http://api.setlist.fm/rest/0.1/artist/' + mbid + '/setlists') do |file|
sets = REXML::Document.new(file.read)
sets.elements.each('setlists/setlist[1]/sets/set/song') do |element|
if element
setlists.push(element.attributes['name'])
end
end
end
rescue
end
end
result.store(:setlist,setlists)
end
result.to_json
end | true |
4f05ea6c5d653596af999cc6905381bbfb344593 | Ruby | grantcottle/kovid | /lib/kovid/request.rb | UTF-8 | 2,570 | 2.9375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'json'
require_relative 'tablelize'
require_relative 'cache'
require_relative 'uri_builder'
module Kovid
class Request
COUNTRIES_PATH = UriBuilder.new('/countries').url
STATES_URL = UriBuilder.new('/states').url
class << self
def by_country(country_name)
response = fetch_country(country_name)
Kovid::Tablelize.country_table(response)
rescue JSON::ParserError
no_case_in(country_name)
end
def by_country_full(country_name)
response = fetch_country(country_name)
Kovid::Tablelize.full_country_table(response)
rescue JSON::ParserError
no_case_in(country_name)
end
def state(state)
response = fetch_state(state)
Kovid::Tablelize.full_state_table(response)
end
def by_country_comparison(list)
array = fetch_countries(list)
Kovid::Tablelize.compare_countries_table(array)
end
def by_country_comparison_full(list)
array = fetch_countries(list)
Kovid::Tablelize.compare_countries_table_full(array)
end
def cases
response ||= JSON.parse(Typhoeus.get(UriBuilder.new('/all').url, cache_ttl: 900).response_body)
Kovid::Tablelize.cases(response)
end
def history(country, last)
history_path = UriBuilder.new('/historical').url
response ||= JSON.parse(Typhoeus.get(history_path + "/#{country}", cache_ttl: 900).response_body)
Kovid::Tablelize.history(response, last)
end
private
def no_case_in(country)
rows = [['No reported cases OR wrong spelling of country/state!']]
Terminal::Table.new headings: ["You checked: #{country.capitalize}"], rows: rows
end
def fetch_countries(list)
array = []
list.each do |country|
array << JSON.parse(Typhoeus.get(COUNTRIES_PATH + "/#{country}", cache_ttl: 900).response_body)
end
array = array.sort_by { |json| -json['cases'] }
end
def fetch_country(country_name)
country_url = COUNTRIES_PATH + "/#{country_name}"
JSON.parse(Typhoeus.get(country_url, cache_ttl: 900).response_body)
end
def fetch_state(state)
states_array = JSON.parse(Typhoeus.get(STATES_URL, cache_ttl: 900).response_body)
states_array.select { |state_name| state_name['state'] == capitalize_words(state) }.first
end
def capitalize_words(string)
string.split.map(&:capitalize).join(' ')
end
end
end
end
| true |
cda9e85391082aa996a0484ec66984495bd25901 | Ruby | atomic-changes/procedure | /lib/procedure/helpers/errors/default_errors.rb | UTF-8 | 1,172 | 2.59375 | 3 | [] | no_license | # frozen_string_literal: true
module Procedure
module Helpers
module Errors
MESSAGES = {
new_records: "isn't a saved model",
nils: "can't be nil",
required: 'is required',
}.merge(
ARRAY_MESSAGES,
DATATYPE_MESSAGES,
DATE_MESSAGES,
NUMERIC_MESSAGES,
STRING_MESSAGES
)
ARRAY_MESSAGES = { class: "isn't the right class" }.freeze
DATATYPE_MESSAGES = {
array: "isn't an array",
boolean: "isn't a boolean",
hash: "isn't a hash",
integer: "isn't an integer",
model: "isn't the right class",
string: "isn't a string"
}.freeze
DATE_MESSAGES = {
date: "date doesn't exist",
before: "isn't before given date",
after: "isn't after given date"
}.freeze
NUMERIC_MESSAGES = {
max: 'is too big',
min: 'is too small'
}.freeze
STRING_MESSAGES = {
empty: "can't be blank",
in: "isn't an option",
matches: "isn't in the right format",
max_length: 'is too long',
min_length: 'is too short'
}.freeze
end
end
end
| true |
4e027de1ea0a8b306551914c14e0b03da3c89089 | Ruby | benrodenhaeuser/repetitions | /109_prep/more_exercises/quick_sort_rep.rb | UTF-8 | 1,857 | 4.40625 | 4 | [] | no_license | def swap(array, index1, index2)
temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
array
end
def partition(array, left_pointer, right_pointer)
pivot_pointer = right_pointer
pivot = array[pivot_pointer]
right_pointer -= 1
loop do
while array[left_pointer] < pivot
left_pointer += 1
end
while array[right_pointer] > pivot
right_pointer -= 1
end
if left_pointer >= right_pointer
break
else
swap(array, left_pointer, right_pointer)
end
end
swap(array, left_pointer, pivot_pointer) # we swap array[0] and array[2]
left_pointer # we return 0
end
def quick_sort(array, left_pointer = 0, right_pointer = array.size - 1)
if left_pointer < right_pointer
pivot_pointer = partition(array, left_pointer, right_pointer)
quick_sort(array, left_pointer, pivot_pointer - 1)
quick_sort(array, pivot_pointer + 1, right_pointer)
end
array
end
# array = []
# p quick_sort(array) # []
#
# array = [10]
# p quick_sort(array) # [10]
#
# array = [3, 2, 1]
# p quick_sort(array) # [1, 2, 3]
#
# array = [1, 5, 2, 0, 6, 3]
# p quick_sort(array) # [0, 1, 2, 3, 5, 6]
#
# array = [9, 7, 5, 11, 12, 2, 14, 3, 10, 6]
# p quick_sort(array) # [2, 3, 5, 6, 7, 9, 10, 11, 12, 14]
# using the built-in partition method.
# return a *new* array
def quick_sort(array)
if array.size < 2
array
else
pivot = array.last
partition = array[0...-1].partition { |elem| elem < pivot }
quick_sort(partition.first) + [pivot] + quick_sort(partition.last)
end
end
array = []
p quick_sort(array) # []
array = [10]
p quick_sort(array) # [10]
array = [3, 2, 1]
p quick_sort(array) # [1, 2, 3]
array = [1, 5, 2, 0, 6, 3]
p quick_sort(array) # [0, 1, 2, 3, 5, 6]
array = [9, 7, 5, 11, 12, 2, 14, 3, 10, 6]
p quick_sort(array) # [2, 3, 5, 6, 7, 9, 10, 11, 12, 14]
| true |
602506076a5d733dc451c06f9e21ce58188440d1 | Ruby | sanger/traction-service | /spec/support/request_helpers.rb | UTF-8 | 1,975 | 2.578125 | 3 | [] | no_license | # frozen_string_literal: true
module RequestHelpers
def json_api_headers
{
'Content-Type' => 'application/vnd.api+json',
'Accept' => 'application/vnd.api+json'
}
end
#
# Returns a hash representing the decoded json response
#
# @return [Hash] The decoded json
#
def json
ActiveSupport::JSON.decode(response.body)
end
#
# Find a resource record in the provided json
#
# @param json [Hash] decoded response object
# @param id [String, Integer] The ID of the resource to find
# @param type [String] The resource type to find
# @param from ['data','included'] Whether to look in the data or included resources
#
# @return [Hash] Hash representation of the given resource
#
def find_resource(id:, type:, from: 'data', json: self.json)
find_id_and_type(id:, type:, data: json.fetch(from))
end
# Find a resource record in the included section of the provided json
#
# @param json [Hash] decoded response object
# @param id [String, Integer] The ID of the resource to find
# @param type [String] The resource type to find
#
# @return [Hash] Hash representation of the given resource
#
def find_included_resource(id:, type:, json: self.json)
find_resource(id:, type:, from: 'included', json:)
end
#
# Find a resource record in the provided array
#
# @param data [Array] Array of resource objects
# @param id [String, Integer] The ID of the resource to find
# @param type [String] The resource type to find
#
# @return [Hash] Hash representation of the given resource
#
def find_id_and_type(data:, id:, type:)
matching_resource = data.detect do |resource|
resource.values_at('type', 'id') == [type, id.to_s]
end
expect(matching_resource).not_to be_nil, lambda {
found = data.map { |resource| resource.values_at('type', 'id').join(':') }
"Could not find #{type}:#{id}. Found #{found.to_sentence}"
}
matching_resource
end
end
| true |
f5b2ea3cab4eb24e60cf261be7587d37e07dc3ab | Ruby | nielsabels/understanding-computation | /chapter3/005.nfa.rulebook.rb | UTF-8 | 2,528 | 4.0625 | 4 | [] | no_license | # Moving on to non-deterministic finite automata
# Relaxing the determinism constraints has produced an imaginary machine that is very different from the real, deterministic computers we’re familiar with. An NFA deals in possibilities rather than certainties; we talk about its behavior in terms of what can happen rather than what will happen.
# We’re using the Set class, from Ruby’s standard library, to store the collection of possible states returned by #next_states. We could have used an Array, but Set has three useful features:
# 1. It automatically eliminates duplicate elements. Set[1,2,2,3,3,3] is equal to Set[1,2,3].
# 2. It ignores the order of elements. Set[3,2,1] is equal to Set[1,2,3].
# 3. It provides standard set operations like intersection (#&), union (# +), and subset testing (#subset?).
# Assignment: create a rulebook for a non-deterministic finite automaton according to the below contract.
# >> rulebook = NFARulebook.new([
# FARule.new(1, 'a', 1), FARule.new(1, 'b', 1), FARule.new(1, 'b', 2), FARule.new(2, 'a', 3), FARule.new(2, 'b', 3),
# FARule.new(3, 'a', 4), FARule.new(3, 'b', 4)
# ])
# => #<struct NFARulebook rules=[...]>
# >> rulebook.next_states(Set[1], 'b') => #<Set: {1, 2}>
# >> rulebook.next_states(Set[1, 2], 'a') => #<Set: {1, 3}>
# >> rulebook.next_states(Set[1, 3], 'b') => #<Set: {1, 2, 4}>
require 'set'
class FARule < Struct.new(:current_state, :character, :next_state)
def applies_to?(state, character)
self.current_state == state and self.character == character
end
def follow
next_state
end
def inspect
"#<FARule #{state.inspect} --#{character}--> #{next_state.inspect}>"
end
end
class NFARulebook < Struct.new(:rules)
def next_states(states, character)
states.flat_map{ |state| follow_rule(state, character) }.to_set
end
def follow_rule(state, character)
rules_applies_for(state, character).map(&:follow)
end
def rules_applies_for(state, character)
rules.select {|rule| rule.applies_to?(state, character)}
end
end
rulebook = NFARulebook.new([
FARule.new(1, 'a', 1), FARule.new(1, 'b', 1), FARule.new(1, 'b', 2), FARule.new(2, 'a', 3), FARule.new(2, 'b', 3),
FARule.new(3, 'a', 4), FARule.new(3, 'b', 4)
])
puts rulebook.next_states(Set[1], 'b').inspect # => #<Set: {1, 2}>
puts rulebook.next_states(Set[1, 2], 'a').inspect # => #<Set: {1, 3}>
puts rulebook.next_states(Set[1, 3], 'b').inspect # => #<Set: {1, 2, 4}>
| true |
9c622445dc0d92c508d60c8b44b7f6a27a4caec1 | Ruby | S-zebra/gaba-web-dev | /app/models/account.rb | UTF-8 | 508 | 2.640625 | 3 | [] | no_license | class Account < ApplicationRecord
has_many :posts, dependent: :destroy
validates :user_id, presence: true, uniqueness: true, length: {minimum: 5, maximum: 20}
validates :password, presence: true, length: {minimum: 5}
validate :encrypt_password
def encrypt_password
self.password = BCrypt::Password.create(self.password)
end
class << self
def authenticate(id, pass)
acc = Account.find_by(user_id: id)
acc && BCrypt::Password.new(acc.password) == pass
return acc
end
end
end
| true |
421ae63872379ac73acbcd8820d672c6c97f3bb2 | Ruby | cpcsacggc/RubySchool.US | /arc/18/net_demo8.rb | UTF-8 | 260 | 2.53125 | 3 | [] | no_license | require 'net/http'
require 'uri'
def is_wrong_password password
uri = URI.parse 'http://mynetwd/'
response = Net::HTTP.post_form(uri, :login => "admin", :password => password).body
response.include? "denied"
end
puts is_wrong_password "Number10"
| true |
30d1b8f86cf03a8a9f7d11e7cc57d350fbd08a99 | Ruby | jjc224/Matasano | /Ruby/matasano_lib/aes_128_common.rb | UTF-8 | 894 | 2.90625 | 3 | [] | no_license | module MatasanoLib
module AES_128_COMMON
BLOCKSIZE = 16
class << self
# Expects a hex-encoded ciphertext.
def detect_mode(ciphertext)
blocks = ciphertext.scan(/.{1,32}/) # Split into 16-byte blocks; working with hex, so 32 characters.
blocks_dups = {}
# Iterate through the unique elements.
# Store the count of each duplicate element in a hash for output.
blocks.uniq.select do |block|
count = blocks.count(block)
blocks_dups[block] = count if count > 1
end
blocks_dups.empty? ? 'CBC' : 'ECB'
end
def determine_blocksize(char = 'A')
input = char
curr_size = yield(input).length
loop do
input << char
break if yield(input).length > curr_size
end
yield(input).length - curr_size
end
end
end
end
| true |
9331e13529337011fd86171f5753475f94b5be4d | Ruby | rnadler/fg-csv-processor | /lib/converters/heated_tube_type_converter.rb | UTF-8 | 319 | 2.890625 | 3 | [] | no_license | require_relative '../constants'
class HeatedTubeTypeConverter
def self.convert(value)
case value
when 'None'
0
when '15mm'
1
when '19mm'
2
when 'NULL'
NULL_VALUE
else
raise "HeatedTubeTypeConverter: Unknown value: #{value}"
end
end
end
| true |
8c20a1c824f9f3c3384d8447fc611b489ba6b63c | Ruby | Jagaa/site_scaffold | /generators/products_catalog/templates/models/product.rb | UTF-8 | 1,036 | 2.640625 | 3 | [
"MIT"
] | permissive | class Product < ActiveRecord::Base
belongs_to :product_category
has_many :product_images, :dependent=>:destroy
validates_presence_of :name, :product_category_id
validates_length_of :short_description, :maximum => 30, :message => "breve descrição deve ser menor que %d"
after_update :save_images
#setter for virtual atribute images_attributes
def images_attributes=(image_attributes)
image_attributes.each do |attributes|
product_images.build(attributes)
end
end
#setter for virtual atribute update_images
def update_images=(image_attributes)
image_attributes.each do |attributes|
product = product_images.detect {|n| n.id == attributes[:id].to_i}
product.attributes = attributes
end
end
#apos salvar post verifica em cada imagem se deve apagala ou atualizar
def save_images
product_images.each do |n|
if n.should_destroy?
n.destroy
else
n.save(false)
end
end
end
end
| true |
11b8f1fa780cbcd45acc73efd1e476890e69ad3e | Ruby | daroleary/HeadFirstRuby | /animals/dog.rb | UTF-8 | 97 | 2.828125 | 3 | [] | no_license | require './animal'
class Dog < Animal
def to_s
"#{@name} the dog, aged #{@age}"
end
end | true |
7c771d6c9f050b7f4f0d51dbd6f1ec617da63645 | Ruby | janicky/fifteen-puzzle-solver | /spec/depth_first_search_spec.rb | UTF-8 | 856 | 2.875 | 3 | [] | no_license | require "fifteen_puzzle_solver"
require_relative "../lib/fifteen_puzzle_solver/depth_first_search"
RSpec.describe "DepthFirstSearch" do
before do
# 1 2 3
# 4 0 6
# 7 5 8
@board = FifteenPuzzleSolver::Board.new([1, 2, 3, 4, 0, 6, 7, 5, 8], 3, 3)
@dfs = FifteenPuzzleSolver::DepthFirstSearch.new(@board, "rdul")
@dfs.perform
end
it "correctly solve specified board" do
expect(@dfs.status).to eq("solved")
end
it "returns correct solution path" do
expect(@dfs.solution).to eq("rdlurdlurd")
end
it "returns correct recursion depth" do
expect(@dfs.depth).to eq(10)
end
it "returns correct elapsed time" do
expect(@dfs.elapsed_time).not_to eq(0)
end
it "returns visited nodes and processed nodes" do
expect(@dfs.visited_nodes).to be(10)
expect(@dfs.processed_nodes).to be(12)
end
end
| true |
d4a4252b0cab9be17ccd2ec821edaa170c3f4480 | Ruby | bp50fathoms/alpha | /src/genetic_fitness.rb | UTF-8 | 882 | 3.15625 | 3 | [] | no_license | module GeneticFitness
MAXFIT = 1e6
FUNC = {
:< => { true => lambda { |a,b| a < b ? 0 : a - b + 1 },
false => lambda { |a,b| a < b ? b - a : 0 } },
:<= => { true => lambda { |a,b| a <= b ? 0 : a - b },
false => lambda { |a,b| a <= b ? b - a + 1 : 0 } },
:== => { true => lambda { |a,b| a == b ? 0 : (b - a) ** 2 },
false => lambda { |a,b| a == b ? (1 + (b - a) ** 2) * 1e-1 : 0 } },
:> => { true => lambda { |a,b| FUNC[:<][true].call(b,a) },
false => lambda { |a,b| FUNC[:<][false].call(b,a) } },
:>= => { true => lambda { |a,b| FUNC[:<=][true].call(b,a) },
false => lambda { |a,b| FUNC[:<=][false].call(b,a) } },
:atom => { true => lambda { |a| a ? 0 : MAXFIT },
false => lambda { |a| a ? MAXFIT : 0 } }
}
def fitness(op, goal, *args)
FUNC[op][goal].call(*args)
end
module_function :fitness
end
| true |
e27686f7fa22570d7e9a5d39e8ce5abfb7795e37 | Ruby | akshaya-9/III-year-Lab | /SL/Experiment 10/exp10(2).rb | UTF-8 | 176 | 3.09375 | 3 | [] | no_license | s = Hash.new 0
s['English'] = 80
s['telugu'] = 75
s['hindi'] = 91
total_marks = 0
s.each {|key,value|
total_marks +=value
}
puts "Total Marks: "+total_marks.to_s | true |
588bc233c07ebfbc11441ccd8c5b572b234e88e3 | Ruby | ympek/uw-team-faq-downloader | /uw-team-faq-grabber.rb | UTF-8 | 955 | 2.953125 | 3 | [] | no_license | require 'net/http'
puts 'UW-TEAM FAQ DOWNLOADER'
puts 'This script will download all the materials present on http://www.uw-team.org/faq.html'
$dir = "uwteam"
Dir.mkdir $dir if not Dir.exist? $dir
uri = URI('http://www.uw-team.org/faq.html')
site = Net::HTTP.get(uri)
$origin = "http://www.uw-team.org/data"
# find all links and returns a list of them
def scan_for_links(str)
list = []
match_data = str.scan(/<a href="data([^"]+)/)
puts "Found " + match_data.length.to_s + " links to files."
return match_data.to_a
end
$paths = scan_for_links(site)
# does all the job
def download
$paths.each do |p|
p = p[0] # shit comes as array length 1
path = $dir + p
File.open(path, "wb") do |file|
print "Downloading " + p + "... "
file.write(Net::HTTP.get(URI($origin + p)))
print "Saved to " + path + "\n"
end
end
end
download()
puts "success"
| true |
80b5256f01ee85319eb582f718d9c9086aa28cec | Ruby | tlopo-ruby/svcdeps_tasks | /lib/probe.rb | UTF-8 | 3,145 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'socket'
require 'timeout'
require 'etc'
require 'yaml'
require 'net/http'
require 'openssl'
class Probe
def initialize(opts)
@type = opts[:type].downcase
@timeout = opts[:timeout] || 5
@opts = opts
end
def tcp_probe
host = @opts[:host]
port = @opts[:port]
Timeout::timeout(@timeout) do
TCPSocket.new(host, port).close
end
end
def udp_probe
host = @opts[:host]
port = @opts[:port]
Timeout::timeout(@timeout) do
u = UDPSocket.new
u.connect(host,port)
u.puts "check"
end
end
def command_probe
cmd = @opts[:command]
run_as = @opts[:run_as]
if run_as.nil?
run_as = 'nobody' if Process.uid.zero?
else
warn "WARNNG: Option 'run_as' requires root, ignoring it." unless Process.uid.zero?
run_as = nil unless Process.uid.zero?
end
Timeout::timeout(@timeout) do
user = Etc.getpwnam(run_as) if run_as
pid = Process.fork do
STDOUT.reopen('/dev/null')
STDERR.reopen('/dev/null')
unless run_as.nil?
Process.egid = Process.gid = user.gid
Process.euid = Process.uid = user.uid
end
exec cmd
end
status = Process.wait pid
exit_status = $?.exitstatus
raise "Command [#{cmd}] exited with #{exit_status}" if exit_status > 0
end
end
def http_probe
url = @opts[:url]
method = @opts[:method] || 'get'
payload = @opts[:payload] if @opts.key? :payload
insecure = @opts[:insecure] || false
headers = @opts[:headers] || {}
Timeout::timeout(@timeout) do
uri = URI(url)
is_https = uri.scheme == 'https'
uri.path = '/' if uri.path.empty?
req = Object.const_get("Net::HTTP::#{method.capitalize}").new(uri.path)
req.body = payload
headers.each {|k,v| req[k] = v }
opts = {}
if is_https
if @opts[:ca_file]
opts[:ca_file] = @opts[:ca_file]
end
if @opts[:cert_file]
opts[:cert] = OpenSSL::X509::Certificate.new( File.read @opts[:cert_file] )
end
if @opts[:key_file]
opts[:key] = OpenSSL::PKey::RSA.new( File.read @opts[:key_file] )
end
end
opts[:use_ssl] = is_https
opts[:verify_mode] = OpenSSL::SSL::VERIFY_NONE if is_https && insecure
Net::HTTP.start( uri.host, uri.port, opts ) do |http|
res = http.request(req)
raise "Request to #{url} returned code #{res.code}" unless res.code == '200'
end
end
end
def error_wrapper(&block)
begin
instance_eval(&block) if block_given?
raise 'block should be passed to error_wrapper' unless block_given?
rescue => e
return "#{e.class} => #{e.message}"
end
"SUCCESS"
end
def run
case @type
when 'tcp'
error_wrapper { tcp_probe }
when 'udp'
error_wrapper { udp_probe }
when 'command'
error_wrapper { command_probe }
when 'http'
error_wrapper { http_probe }
else
raise "Type '#{@type}' not supported"
end
end
end
| true |
9603e428c1032692c7c24e01e50c96e5981bd807 | Ruby | kyle-cook/hash-search | /lib/util/names.rb | UTF-8 | 719 | 2.96875 | 3 | [
"MIT"
] | permissive | module HashSearch
class Names
@@Names = [
"Alice",
"Bob",
"Charles",
"Daniel",
"Eve",
"Felicia",
"George",
"Harriet",
"Igor",
"Jessica",
"Kevin",
"Laura",
"Michael",
"Nancy",
"Oscar",
"Priscilla",
"Quinton",
"Rachael",
"Stephen",
"Terrisa",
"Uthgar",
"Victoria",
"Wayne",
"Xandillia",
"Yavanaus",
"Zed"
]
def self.RandomName
@@Names.sample
end
end
end | true |
6eb6a13c62645e508df43548c9d71b9e30955e11 | Ruby | ocktagon/phase_0_unit_2 | /week_6/4_PezDispenser_solo_challenge/my_solution.rb | UTF-8 | 2,833 | 4.1875 | 4 | [] | no_license | # U2.W6: PezDispenser Class from User Stories
# I worked on this challenge [with: Adam Dziuk].
# 1. Review the following user stories:
# - As a pez user, I'd like to be able to "create" a new pez dispenser with a group of flavors that
# represent pez so it's easy to start with a full pez dispenser.
# - As a pez user, I'd like to be able to easily count the number of pez remaining in a dispenser
# so I can know how many are left.
# - As a pez user, I'd like to be able to take a pez from the dispenser so I can eat it.
# - As a pez user, I'd like to be able to add a pez to the dispenser so I can save a flavor for later.
# - As a pez user, I'd like to be able to see all the flavors inside the dispenser so I know the order
# of the flavors coming up.
# 2. Pseudocode
# CREATE Class PezDispenser
# DEFINE initialize method that takes single arg(*flavors)
# CREATE attr_accessor for flavors
# CREATE array pez that stores flavors
# DEFINE pez_count method
# Count number of elements in array pez
# DEFINE get_pez method
# DEFINE variable my_pez
# Set variable to be sampled pez in array pez
# DELETE my_pez from array pez
# DEFINE add_pez method that takes single arg (*flavor)
# FOR EACH flavor, PUSH into array pez
# DEFINE see_all_pez
# return array pez
# END class PezDispenser
# 3. Initial Solution
class PezDispenser
attr_accessor :pez
def initialize(*flavors)
@pez = []
flavors.flatten.each{ |flavor| pez << flavor}
end
def pez_count
pez.length
end
def get_pez
my_pez = pez.sample
pez.delete(my_pez)
end
def add_pez(*flavor)
flavor.flatten.each{ |flavor| pez << flavor }
end
def see_all_pez
pez
end
end
# 4. Refactored Solution
# class PezDispenser
# attr_accessor :pez
# def initialize(*flavors)
# @pez = []
# flavors.flatten.each{ |flavor| pez << flavor}
# end
# def pez_count
# pez.length
# end
# def get_pez
# my_pez = pez.sample
# pez.delete(my_pez)
# end
# def add_pez(*flavor)
# flavor.flatten.each{ |flavor| pez << flavor }
# end
# def see_all_pez
# pez
# end
# end
# 1. DRIVER TESTS GO BELOW THIS LINE
flavors = %w(cherry chocolate cola grape lemon orange peppermint raspberry strawberry).shuffle
super_mario = PezDispenser.new(flavors)
puts "A new pez dispenser has been created. You have #{super_mario.pez_count} pez!"
puts "Here's a look inside the dispenser:"
puts super_mario.see_all_pez
puts "Adding a purple pez."
super_mario.add_pez("purple") # mmmmm, purple flavor
puts "Now you have #{super_mario.pez_count} pez!"
puts "Oh, you want one do you?"
puts "The pez flavor you got is: #{super_mario.get_pez}"
puts "Now you have #{super_mario.pez_count} pez!"
# 5. Reflection | true |
af90f6decf1a9fb5aaa151ce36760e7f12160aea | Ruby | carlypecora/algorithm-practice | /are_there_duplicates.rb | UTF-8 | 1,124 | 4.625 | 5 | [] | no_license | # Implement a function called, areThereDuplicates which accepts a variable number of arguments, and checks whether there are any duplicates among the arguments passed in. You can solve this using the frequency counter pattern OR the multiple pointers pattern.
# // Examples:
# // areThereDuplicates(1, 2, 3) // false
# // areThereDuplicates(1, 2, 2) // true
# // areThereDuplicates('a', 'b', 'c', 'a') // true
# def are_there_duplicates(*args)
# counter = args.each_with_object({}) do |char, hsh|
# !hsh[char] ? hsh[char] = 1 : hsh[char] += 1
# end
# counter.each do |k, v|
# puts v
# if v > 1
# return true
# end
# end
# false
# end
#OR
# def are_there_duplicates(*args)
# counter = args.each_with_object({}) do |char, hsh|
# if hsh[char]
# return true
# else
# hsh[char] = true
# end
# end
# false
# end
#OR
def are_there_duplicates(*args)
sorted = args.sort
sorted.each_with_index do |arg, i|
if arg == sorted[i + 1]
return true
end
end
false
end
puts are_there_duplicates(1, 2, 3)
puts are_there_duplicates(1, 2, 2)
puts are_there_duplicates('a', 'b', 'c', 'a')
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.