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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8775600d47bdf1027e6cf8d6898dc79422b92c62 | Ruby | marjielam/codewars-practice | /pig_it.rb | UTF-8 | 459 | 4.125 | 4 | [] | no_license | # Level: 5kyu
# Instructions
# Move the first letter of each word to the end of it, then add 'ay' to the end of the word.
def pig_it text
words = text.split
new_text = ""
words.each_with_index do |word, index|
if word.match(/\W/)
new_text += word
elsif index == words.length - 1
new_text += word[1..word.length - 1] + word[0] + "ay"
else
new_text += word[1..word.length - 1] + word[0] + "ay "
end
end
new_text
end
| true |
0bba701235bb9be71a3eef953de1aba6fe51b2fd | Ruby | kieranfraser/distributedsystems | /Lab4/Client.rb | UTF-8 | 3,143 | 3.65625 | 4 | [] | no_license | ## Simple Client implemented using sockets - sends a
## GET request to the server including some user defined
## text and the server returns the text in all caps.
## It's then printed to the screen to the user.
## @author Kieran Fraser
require "socket"
#Define the hostname and port number to connect to
hostname = "127.0.0.1"
port = ARGV[0]
JOIN_CHATROOM = "JOIN_CHATROOM: "
CLIENT_IP = "CLIENT_IP: "
PORT = "PORT: "
CLIENT_NAME = "CLIENT_NAME: "
JOINED_CHATROOM = "JOINED_CHATROOM: "
SERVER_IP = "SERVER_IP: "
ROOM_REF = "ROOM_REF: "
JOIN_ID = "JOIN_ID: "
CLIENT_NAME_HANDLE = "Kieran"
RECEIVED_JOIN = ""
LEAVE_CHATROOM = "LEAVE_CHATROOM:"
DISCONNECT = "DISCONNECT: "
CHATROOM_ONE = 1
CHATROOM_ONE_STR = "crone"
CHATROOM_TWO = 2
CHATROOM_TWO_STR = "crtwo"
def next_line_readable?(socket)
readfds, writefds, exceptfds = select([socket], nil, nil, 0.1)
#p :r => readfds, :w => writefds, :e => exceptfds
readfds #Will be nil if next line cannot be read
end
$socket
#Create a new TCP socket using the hostname and port of the server
def createSock
$socket = TCPSocket.open("127.0.0.1", 2000)
puts 'Connected to server'
end
def receive
#Read the response from the server, remove the lines user not interested in
#and print the all caps text
puts 'listening'
serverSock = $socket
#puts serverSock.gets
while next_line_readable?(serverSock)
line = serverSock.gets
serverSays = line
puts serverSays
end
puts 'finished'
end
def handleCommand(cmd="command")
checkCommand = cmd.chomp
case checkCommand
when "join"
puts 'join'
createSock
join
receive
when "leave"
puts 'leave'
#createSock
leave
receive
when "msg"
puts 'msg'
when "exit"
#Close the socket and finish
$socket.close
abort
when "dis"
puts 'dis'
dis
else
puts 'not found'
end
end
#Joining a chat room initiated by the client by sending:
# JOIN_CHATROOM: [chatroom name], CLIENT_IP: [IP Address of client if UDP | 0 if TCP]
# PORT: [port number of client if UDP | 0 if TCP], CLIENT_NAME: [string Handle to identifier client user]
# Client ip and port number empty for tcp
# Client name is user handle or nickname
def join
joinCommand = JOIN_CHATROOM+CHATROOM_ONE_STR+"\n"+
CLIENT_IP+"\n"+
PORT+"\n"+
CLIENT_NAME+CLIENT_NAME_HANDLE+"\n"
$socket.print(joinCommand)
puts 'writing to socket'
end
def leave
leaveCmd = LEAVE_CHATROOM+"1"+"\n"+
JOIN_ID+"89"+"\n"+
CLIENT_NAME+"kIERAN"+"\n"
$socket.print(leaveCmd)
puts 'writing to socket'
end
def dis
discmd = "DISDIS\n"
$socket.print(discmd)
puts 'writing to socket'
end
def message
end
#Get input from the user and format for use within the
#HTTP request - note the different format for Ruby
# input = $stdin.gets.chomp! #fixes error of reading in the argument at this point
# if( input == '1')
# socket.print("KILL_SERVICE\n")
# else
# if(input == '2')
# socket.print("HELO this could be anything\n")
# end
# if(input == '3')
# socket.print("This is other message\n")
# end
# end
while true
command = STDIN.gets
handleCommand command
end
#ruby Client.rb 2000
| true |
9f6c359eff2c82b93b33216971effe6b5179d196 | Ruby | melzreal/ruby-objects-has-many-lab-v-000 | /lib/author.rb | UTF-8 | 408 | 3.125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Author
attr_accessor :name, :author
def initialize(name)
@name = name
@posts = []
end
def add_post(post_title)
@posts << post_title
post_title.author = self
end
def add_post_by_title(post_title)
posting = Post.new(post_title)
@posts << posting
posting.author = self
end
def posts
@posts
end
def self.post_count
Post.all.count
end
end
| true |
4a903f90beb18fbb82c7bd1e119411edc38803c4 | Ruby | shyouhei/xmp2assert | /lib/xmp2assert/classifier.rb | UTF-8 | 2,506 | 2.578125 | 3 | [
"MIT"
] | permissive | #! /your/favourite/path/to/ruby
# -*- mode: ruby; coding: utf-8; indent-tabs-mode: nil; ruby-indent-level 2 -*-
# -*- frozen_string_literal: true -*-
# -*- warn_indent: true -*-
# Copyright (c) 2017 Urabe, Shyouhei
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'ripper'
require_relative 'namespace'
require_relative 'parser'
# Usually, you want to check LOTS of files that may or may not contain xmp
# comments at once, maybe from inside of a CI process. That's OK but we want
# to speed things up, so here we filter out files that are not necessary to
# convert.
#
# Typical usage:
#
# ```ruby
# Pathname.glob('**/*.rb').select do |f|
# XMP2Assert::Classifier.classify(f)
# end
# ```
module XMP2Assert::Classifier
# @param (see XMP2Assert::Parser.new)
# @return [<Symbol>] any combination of :=>, :>>, :!>, :~>, or empty.
# @note syntax error results in empty return value.
def self.classify obj, file = nil, line = nil
parser = XMP2Assert::Parser.new obj, file, line
rescue SyntaxError
return []
else
mid = %i[=> >> !> ~>]
return parser \
.tokens \
.map(&:to_sym) \
.sort \
.uniq \
.map {|i| case i when *mid then i else nil end } \
.compact
end
end
| true |
35b405b830ec562827aa5ad3c8bcf160a969156f | Ruby | craycode123/41-Anagrams-1-Detecting-Anagrams | /detecting_anagrams.rb | UTF-8 | 595 | 3.859375 | 4 | [] | no_license | # Write your solution here!
=begin
def is_anagram?(word1, word2)
#can also use 'chars' instead of 'split'
word1.downcase.split(//).sort == word2.downcase.split(//).sort
end
=end
def canonical(word)
word = word.downcase.split(//).sort
end
def is_anagram?(word1, word2)
canonical(word1) == canonical(word2)
end
#=> true
puts is_anagram?('cinema', 'iceman')
puts is_anagram?('iceman', 'cinema')
puts is_anagram?('pants', 'pants')
puts is_anagram?('CiNemA', 'iceman')
puts is_anagram?('abcde2', 'c2abed')
#=> false
puts is_anagram?('pants', 'turtle')
puts is_anagram?('123123', 'kjhasd')
| true |
efbce634f680a77b62aacbee6faa7de8b36807f1 | Ruby | RobinWagner/LaunchSchool | /programming_and_back-end_development/programming_foundations/lesson_2/calculator/calculator.rb | UTF-8 | 2,302 | 4.125 | 4 | [] | no_license | # Calculator
require 'yaml'
MESSAGES = YAML.load_file('calculator_messages.yml')
def prompt(message)
Kernel.puts("=> #{message}")
end
def number?(input)
integer?(input) || float?(input)
end
def integer?(input)
/^\d+$/.match(input)
end
def float?(input)
/\d/.match(input) && /^\d*\.?\d*$/.match(input)
end
def operation_to_message(op)
word = case op
when '1' then MESSAGES['de']['adding']
when '2' then MESSAGES['de']['subtracting']
when '3' then MESSAGES['de']['multiplying']
when '4' then MESSAGES['de']['dividing']
end
word
end
def first_loop
loop do
prompt(MESSAGES['de']['first_number'])
number1 = Kernel.gets().chomp()
if number?(number1)
return number1
else
prompt(MESSAGES['de']['invalid_number'])
end
end
end
def second_loop
loop do
prompt(MESSAGES['de']['second_number'])
number2 = Kernel.gets().chomp()
if number?(number2)
return number2
else
prompt(MESSAGES['de']['invalid_number'])
end
end
end
def operator_loop
loop do
operator = Kernel.gets().chomp()
if %w(1 2 3 4).include?(operator)
return operator
else
prompt(MESSAGES['de']['choose_option'])
end
end
end
prompt(MESSAGES['de']['welcome'])
name = ''
loop do
name = Kernel.gets().chomp()
if name.empty?()
prompt(MESSAGES['de']['valid_name'])
else
break
end
end
prompt("Hi #{name}!")
loop do # main loop
number1 = ''
number1 = first_loop()
number2 = ''
number2 = second_loop()
operator_prompt = <<-MSG
What operation would you like to perform?
1) add
2) subtract
3) multiply
4) divide
MSG
prompt(operator_prompt)
operator = ''
operator = operator_loop
prompt("#{operation_to_message(operator)} the two numbers...")
result = case operator
when '1' then number1.to_f() + number2.to_f()
when '2' then number1.to_f() - number2.to_f()
when '3' then number1.to_f() * number2.to_f()
when '4' then number1.to_f() / number2.to_f()
end
prompt("The result is #{result}")
prompt(MESSAGES['de']['other_calculation'])
answer = Kernel.gets().chomp()
break unless answer.downcase().start_with?('y')
end
prompt(MESSAGES['de']['thank_you'])
| true |
d5fc61f299b98d7812f13b566b043c875da96c5f | Ruby | rabGIT/assignment_data_structures | /queue.rb | UTF-8 | 1,101 | 3.6875 | 4 | [] | no_license | Node = Struct.new(:data, :next)
# ruby queue implementation
class Queue
def initialize
@first = nil
@last = nil
@len = 0
end
def enqueue(data)
empty? ? new_first(data) : add_node(data)
@len
end
def dequeue
return false if empty?
return finalitem if @len == 1
data = @last.data
current = @first
current = current.next until current.next == @last
@last = current
@len -= 1
data
end
def peek
return false if empty?
@last.data
end
def empty?
@len.zero?
end
private
def new_first(data)
@first = Node.new(data, nil)
@last = @first
@len += 1
end
def add_node(data)
second = @first
@first = Node.new(data, second)
@len += 1
end
# deals with nil pointers and variable testing of nil.next
def finalitem
data = @first.data
@len = 0
@first = nil
@last = nil
data
end
end
# test string enqueue/dequeue
my_queue = Queue.new
test_word = 'queue'
test_word.length.times do |iter|
my_queue.enqueue(test_word[iter])
end
puts my_queue.dequeue until my_queue.empty?
| true |
3ed369d38809597d08f24183e5cb8e921ebc9ff4 | Ruby | UpAndAtThem/practice_kata | /find_it.rb | UTF-8 | 159 | 2.953125 | 3 | [] | no_license | def find_it(seq)
seq.each_with_object(Hash.new(0)) { |int, int_count_hsh| int_count_hsh[int] += 1 }
.find_val { |int, count| count.odd?}
.first
end | true |
91d0af0c3eac099fb91e43fd493953b5e6b40b7e | Ruby | danpaulgo/s_and_p_analyzer | /lib/sp500_analyzer/data_point.rb | UTF-8 | 1,273 | 3.1875 | 3 | [] | no_license | require_relative "../../config/environment.rb"
class DataPoint
@@all = []
attr_accessor :id, :date, :price, :monthly_change, :yearly_change, :historical_max, :max_date
def initialize
@@all << self
end
def self.all
@@all
end
def previous_month
year = date.year
month = date.month
day = date.day
if month == 1
prev_month = 12
else
prev_month = month-1
end
Date.new(year, prev_month, day)
end
def previous_year
year = date.year
month = date.month
day = date.day
prev_year = year-1
Date.new(year-1, month, day)
end
def self.set_historical_max
all.each_with_index do |datapoint, index|
loop_index = 0
maximum = datapoint
until loop_index >= index
if all[loop_index].price >= maximum.price
maximum = all[loop_index]
end
loop_index += 1
end
datapoint.historical_max = maximum
end
nil
end
def self.find_by_year(year)
all.select do |datapoint|
datapoint.date.year == year
end
end
def self.find_by_date(date)
date_array = date.split("/")
all.detect do |datapoint|
datapoint.date.month == date_array[0].to_i && datapoint.date.year == date_array[1].to_i
end
end
end | true |
3387bd7f8d262af47b46041f46de44362d1d9ce2 | Ruby | hyuraku/Project_Euler | /section5/problem43.rb | UTF-8 | 403 | 3.125 | 3 | [] | no_license | arr = (0..9).to_a
max = 10
aa = arr.permutation(max).map do |a|
(a.join).to_i
end
aa = aa.select { |a|
a > (10 ** 9)
}
primes = [17,13,11,7,5,3,2]
sum = 0
aa.each do |a|
res = true
primes.each.with_index(0) do |prime, index|
target = a% (10**(index+3)) / (10**(index))
if (target%prime != 0)
res = false
break
end
end
if res
p a
sum += a
end
end
p sum
| true |
74767db9d06d2099812b7519affcf597f972bdde | Ruby | jasonmiles/introduction_to_programming | /medquiz1_question2.rb | UTF-8 | 213 | 2.71875 | 3 | [] | no_license | #Looked at your solution(ashamedly).
result = {}
letters = ('A'..'Z').to_a.concat( ('a'..'z').to_a )
letters.each do |letter|
count = statement.scan(letter.to_s).count
result[letter] = count if count > 0
end | true |
6c9ac0867f907f476159f1e4baf3389dbe8e9eab | Ruby | paulo-techie/code-wars-ruby-solutions | /last_digit_of_huge_number.rb | UTF-8 | 4,945 | 3.171875 | 3 | [] | no_license | # def last_digit(lst)
# return 1 unless lst[0]
# return 1 if lst.size == 2 && lst.all?{|n| n==0 }
# return 1 if lst.size < 2 && lst[0] < 1
# return 0 if lst.all?{|n| n==0 }
# return (lst[-2]**lst[-1]).digits.first if lst.size < 3
# return lst.reverse.reduce{|a, b| b**a}.digits.first if lst.all?{|n| n<10}
# t = 0
# lst.reverse.each_with_index do |n, i|
# t = (n.digits[1].to_s + n.digits[0].to_s).to_i and next if i == 0
# # n = (n.to_s.chars.reverse.join.to_s.to_i.to_s.reverse).to_i if n.digits.first == 0
# # t = (t.to_s.chars.reverse.join.to_s.to_i.to_s.reverse).to_i if t.digits.first == 0
# # p t
# # p n
# t = (n.digits[1].to_s + n.digits[0].to_s).to_i ** (t.digits[1].to_s + t.digits[0].to_s).to_i
# # p t
# end
# p t.digits
# t.digits.first
# end
# # def last_digit(lst)
# # last_digit_pattern = {
# # 0 => [0], 1 => [1], 2 => [4,8,6,2], 3 => [9,7,1,3], 4 => [6,4],
# # 5 => [5], 6 => [6], 7 => [9,3,1,7], 8 => [8,4,2,6], 9 => [1,9]
# # }
# # pattern_size = {
# # 0 => 1, 1 => 1, 2 => 4, 3 => 4, 4 => 2, 5 => 1, 6 => 1, 7 => 4, 8 => 4, 9 => 2
# # }
# # return 1 unless lst[0]
# # return 1 if lst.size == 2 && lst.all?{|n| n==0 }
# # return 1 if lst.size < 2 && lst[0] < 1
# # return 0 if lst.all?{|n| n==0 }
# # return lst[0].digits.first if lst.size < 2
# # return (lst[-2]**lst[-1]).digits.first if lst.size < 3
# # return lst.reverse.reduce{|a, b| b**a}.digits.first if lst.all?{|n| n<10}
# # t = 0
# # lst.reverse.each_with_index do |n, i|
# # next unless t
# # t = n.digits.first and next if i == 0
# # t = 0 and next if n == 0
# # p t
# # if pattern_size[n.digits.first] == 1
# # t = (n.digits.first)
# # p t
# # next
# # end
# # p pattern_size[n.digits.first]
# # p t
# # p n
# # p n.digits.first
# # p t
# # # t = (n**t).digits.first and next if n.digits.size < 3
# # t = t%pattern_size[n.digits.first]
# # t = last_digit_pattern[n.digits.first][-2] and next if t == 0
# # t = last_digit_pattern[n.digits.first][t]
# # p t
# # end
# # t
# # end
# ## Passess all test cases except 'attempt'
# def last_digit(lst)
# last_digit_pattern = {
# 0 => [0], 1 => [1], 2 => [4,8,6,2], 3 => [9,7,1,3], 4 => [6,4],
# 5 => [5], 6 => [6], 7 => [9,3,1,7], 8 => [8,4,2,6], 9 => [1,9]
# }
# pattern_size = {
# 0 => 1, 1 => 1, 2 => 4, 3 => 4, 4 => 2, 5 => 1, 6 => 1, 7 => 4, 8 => 4, 9 => 2
# }
# return 1 unless lst[0]
# return 1 if lst.size == 2 && lst.all?{|n| n==0 }
# return 1 if lst.size < 2 && lst[0] < 1
# return 0 if lst.all?{|n| n==0 }
# return lst[0].digits.first if lst.size < 2
# return (lst[-2]**lst[-1]).digits.first if lst.size < 3
# return lst.reverse.reduce{|a, b| b**a}.digits.first if lst.all?{|n| n<10}
# t = 0
# lst.reverse.each_with_index do |n, i|
# next unless t
# t = n.digits.first and next if i == 0
# t = 0 and next if n == 0
# p t
# if pattern_size[n.digits.first] == 1
# t = (n.digits.first)
# p t
# next
# end
# p pattern_size[n.digits.first]
# p t
# p n
# p n.digits.first
# p t
# # t = (n**t).digits.first and next if n.digits.size < 3
# t = t%pattern_size[n.digits.first]
# t = last_digit_pattern[n.digits.first][-2] and next if t == 0
# t = last_digit_pattern[n.digits.first][t]
# p t
# end
# t
# end
def last_digit(lst)
last_digit_pattern = {
0 => [0], 1 => [1], 2 => [2,4,8,6], 3 => [3,9,7,1], 4 => [4,6],
5 => [5], 6 => [6], 7 => [7,9,3,1], 8 => [8,4,2,6], 9 => [9,1]
}
pattern_size = {
0 => 1, 1 => 1, 2 => 4, 3 => 4, 4 => 2, 5 => 1, 6 => 1, 7 => 4, 8 => 4, 9 => 2
}
return 1 unless lst[0]
return 1 if lst.size == 2 && lst.all?{|n| n==0 }
return 1 if lst.size < 2 && lst[0] < 1
return 0 if lst.all?{|n| n==0 }
return lst[0].digits.first if lst.size < 2
return (lst[-2]**lst[-1]).digits.first if lst.size < 3
return lst.reverse.reduce{|a, b| b**a}.to_s(16).to_i(16).digits.first if lst.all?{|j| j < 11 }
t = 0
lst.reverse.each_with_index do |n, i|
p n
p t
t = n and next if i == 0 || t == 1
t = 0 and next if n.digits.first == 0
t = last_digit_pattern[n.digits.first][-1] and next if t == 0
# t = t.digits.first and next if pattern_size[t.digits.first] == 1
t = last_digit_pattern[n.digits.first][-1] and next if t%pattern_size[n.digits.first] == 0
t = last_digit_pattern[n.digits.first][(t%pattern_size[n.digits.first])+1]
end
t
end
[
[[], 1],
[[0, 0], 1],
[[0, 0, 0], 0],
[[1, 2], 1],
[[3, 4, 5], 1],
[[4, 3, 6], 4],
# [[7, 6, 21], 1],
[[12, 30, 21], 6],
# [[2, 2, 2, 0], 4],
[[937640, 767456, 981242], 0],
# [[123232, 694022, 140249], 6],
# [[499942, 898102, 846073], 6] | true |
9c949fbc3325d9514c907e8848f8df705c164629 | Ruby | Calvin0125/ruby-caesar-cipher | /caesar.rb | UTF-8 | 771 | 3.640625 | 4 | [] | no_license | print "enter a word \n"
user_word = gets.chomp
print "enter a shift factor \n"
shift = gets.chomp
if shift.to_i < 0
shift = shift.to_i * -1
shift = shift % 26
shift = shift.to_i * -1
p shift
elsif shift.to_i > 0
shift = shift.to_i % 26
end
p shift
user_array = user_word.split('')
char_codes = user_array.map do |letter|
letter = letter.ord
if letter > 64 && letter < 91
letter += shift
if letter > 90
letter -= 26
elsif letter < 65
letter += 26
end
elsif letter > 96 && letter < 123
letter += shift
if letter < 97
letter += 26
elsif letter > 122
letter -= 26
end
end
letter = letter.chr
end
puts char_codes.join('')
| true |
1dbf384f0c89e86a663195c72da6adf56b064fdd | Ruby | jsanchy/launch-school-exercises | /small_problems_ruby/easy1/array_average.rb | UTF-8 | 711 | 4.8125 | 5 | [] | no_license | =begin
examples:
puts average([1, 5, 87, 45, 8, 8]) == 25
puts average([9, 47, 23, 95, 16, 52]) == 40
inputs:
non-empty array of positive integers
output:
average of the numbers in the input array
algorithm:
create variable to keep track of sum, intialize to 0
loop through input array
add element to sum
divide sum by array.length to get average
return average
=end
def average(ints)
sum = 0
ints.each { |int| sum += int }
sum / ints.length
end
def average_float(ints)
sum = 0
ints.each { |int| sum += int }
sum.to_f / ints.length
end
puts average([1, 5, 87, 45, 8, 8]) == 25
puts average([9, 47, 23, 95, 16, 52]) == 40
puts average_float([1, 2]) == 1.5 | true |
79b82f57de0d55ad46f69fea538dd3864d1bee93 | Ruby | itb2/Code20402017 | /code2040techAsess.rb | UTF-8 | 2,491 | 2.578125 | 3 | [] | no_license | ________________Step1________________________________________________________________
require "http"
#My API Token: 8eacb8876d3324b2748d6f649cc15770
#Github: https://github.com/itb2/Code20402017.git
#reg endpoint: http://challenge.code2040.org/api/register
response = HTTP.post("http://challenge.code2040.org/api/register", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770",
:github => "https://github.com/itb2/Code20402017.git"
})
puts response.body.to_s
_________________Step 2______________________________________________________________
require "http"
response = HTTP.post("http://challenge.code2040.org/api/reverse", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770"
})
response = response.body.to_s
result = result.reverse
validate = HTTP.post("http://challenge.code2040.org/api/reverse/validate", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770",
:string => result
})
_________________Step 3______________________________________________________________
require "http"
response = HTTP.post("http://challenge.code2040.org/api/haystack", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770"
})
hash = JSON.parse(response.body.to_s)
vals = hash.values
needle = vals[0]
hay = vals[1]
result = hay.index(needle)
validate = HTTP.post("http://challenge.code2040.org/api/haystack/validate", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770",
:needle => result
})
puts validate.body.to_s
_________________Step 4_____________________________________________________________
require "http"
response = HTTP.post("http://challenge.code2040.org/api/prefix", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770"
})
dict = JSON.parse(response.body.to_s)
vals = dict.values
prefix = vals[0]
array = vals[1]
len = prefix.length
ary = Array.new
array.each do |x|
if x[0,len] != prefix
ary.push(x)
end
end
validate = HTTP.post("http://challenge.code2040.org/api/prefix/validate", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770",
:array => ary
})
puts validate.body.to_s
_________________Step 5______________________________________________________________
require "http"
response = HTTP.post("http://challenge.code2040.org/api/dating", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770"
})
dict = JSON.parse(response.body.to_s)
vals = dict.values
interval = vals[1]
time = Time.parse(vals[0])
future_time = time + interval
future_time = future_time.to_s
future_time = future_time.split(" ")
datestring = future_time[0]+ "T" + future_time[1]+"Z"
validate = HTTP.post("http://challenge.code2040.org/api/dating/validate", :json => {
:token => "8eacb8876d3324b2748d6f649cc15770",
:datestamp=> datestring
})
puts validate.body.to_s
| true |
b5f1087ed680a0914b0fd1e22296309a3a33d405 | Ruby | AkeelAli/Depot2 | /app/models/cart.rb | UTF-8 | 482 | 2.8125 | 3 | [] | no_license | class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity +=1
else
current_item= line_items.build(:product_id=>product_id)
end
current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
def total_lines
line_items.sum(:quantity)
end
def total_items
line_items.count
end
end
| true |
95dd28f2fc11edd2398dde91ad37f8423a3e8e19 | Ruby | thuyihan1206/algorithms | /trees/binary_search_tree.rb | UTF-8 | 3,478 | 3.765625 | 4 | [] | no_license | # frozen_string_literal: true
require_relative './binary_tree'
# Class for a binary search tree
class BinarySearchTree < BinaryTree
def add_node(value, local_root = @root)
if local_root.nil?
local_root = Node.new(value)
@root ||= local_root # set root for the tree
else
case value <=> local_root.value
when 0
raise 'duplicate value is not allowed'
when -1
local_root.left = add_node(value, local_root.left)
when 1
local_root.right = add_node(value, local_root.right)
end
end
local_root
end
def remove_node(value, local_root = @root)
return nil if local_root.nil?
case value <=> local_root.value
when 0
set_root = local_root.equal? @root
local_root = remove(local_root)
@root = local_root if set_root # reset root if local_root was root
when -1
local_root.left = remove_node(value, local_root.left)
when 1
local_root.right = remove_node(value, local_root.right)
end
local_root
end
def search(value, local_root = @root)
return false if local_root.nil?
case value <=> local_root.value
when 0
true
when -1
search(value, local_root.left)
when 1
search(value, local_root.right)
end
end
def inorder_traverse(local_root = @root)
return [] if local_root.nil?
inorder_traverse(local_root.left) + [local_root.value] + inorder_traverse(local_root.right)
end
private
# return the modified local root that does not contain node
def remove(node)
return node.left if node.right.nil? # node.left is okay to be nil
return node.right if node.left.nil?
# when node has 2 children, replace with largest item in the left tree (inorder predecessor)
if node.left.right.nil?
node.value = node.left.value
node.left = node.left.left
else
node.value = largest_child(node.left)
end
node
end
def largest_child(node)
return largest_child(node.right) if node.right.right
value = node.right.value
node.right = node.right.left
value
end
end
tree = BinarySearchTree.new
[1, 5, 3, 6, 23, 54, 0, 2, 4].each { |value| tree.add_node(value) }
# tree looks like this
# 1
# / \
# 0 5
# / \
# 3 6
# / \ \
# 2 4 23
# \
# 54
puts tree.to_s
p tree.search(1) # => true
p tree.search(5) # => true
p tree.search(6) # => true
p tree.height # => 5
p tree.size # => 9
p tree.inorder_traverse # => [0, 1, 2, 3, 4, 5, 6 23, 54]
puts '-------------'
tree.remove_node(1)
# tree now looks like this
# 0
# \
# 5
# / \
# 3 6
# / \ \
# 2 4 23
# \
# 54
puts tree.to_s
p tree.search(1) # => false
p tree.height # => 5
p tree.size # => 8
p tree.inorder_traverse # => [0, 2, 3, 4, 5, 6 23, 54]
puts '-------------'
tree.remove_node(5)
# tree now looks like this
# 0
# \
# 4
# / \
# 3 6
# / \
# 2 23
# \
# 54
puts tree.to_s
p tree.search(5) # => false
p tree.height # => 5
p tree.size # => 7
p tree.inorder_traverse # => [0, 2, 3, 4, 6 23, 54]
puts '-------------'
tree.remove_node(6)
# tree now looks like this
# 0
# \
# 4
# / \
# 3 23
# / \
# 2 54
puts tree.to_s
p tree.search(6) # => false
p tree.height # => 4
p tree.size # => 6
p tree.inorder_traverse # => [0, 2, 3, 4, 23, 54]
| true |
23e20a7168f0e2cb448cccb9bd37778596b78e3d | Ruby | descentintomael/include_date_scopes | /lib/include_date_scopes/date_scopes.rb | UTF-8 | 1,911 | 2.703125 | 3 | [
"MIT"
] | permissive | # Add the below date based scopes to a model.
#
# between(start_date_or_time, stop_date_or_time)
# on_or_before(date)
# before(date)
# on_or_after(date)
# after(date)
# on(date)
# day(date)
# last_24_hours() * DateTime only
# last_hour() * DateTime only
# last_week()
# last_month()
# today()
# yesterday()
# most_recent() * this is an order by, not a filter
#
# Example usage (from Payment):
#
# include_date_scopes_for :payment_date # default date scope -- ex: Payment.on(date)
# include_date_scopes_for :net_payment_settlement_date, true # prepend field name -- ex: Payment.net_payment_settlement_date_on(date)
#
#
require_relative 'define_timestamp_scopes'
require_relative 'define_date_scopes'
require_relative 'define_common_scopes'
module IncludeDateScopes
module DateScopes
extend ActiveSupport::Concern
module ClassMethods
include IncludeDateScopes::DefineTimestampScopes
include IncludeDateScopes::DefineDateScopes
include IncludeDateScopes::DefineCommonScopes
def include_date_scopes
include_date_scopes_for :created_at
end
def include_date_scopes_for(column,
prepend_name = false,
column_type = nil)
column_type ||= column_type_for(column)
return unless self.table_exists?
if column_type == :datetime
define_timestamp_scopes_for column, prepend_name
elsif column_type == :date
define_date_scopes_for column, prepend_name
end
rescue
warn "Not including date scopes for #{column} because of an error: #{$!.message}"
end
def include_named_date_scopes_for(column)
include_date_scopes_for column, true
end
def column_type_for(column)
columns_hash[column.to_s].type
end
end
end
end
| true |
21d0613692dc4cc260a9102b9a218db0bcefcf2b | Ruby | jonstafford/chess | /lib/board.rb | UTF-8 | 3,778 | 3.59375 | 4 | [
"MIT"
] | permissive | require_relative 'colors'
require_relative 'move_syntax_validation'
require_relative 'king'
class Board
include Colors
attr_reader :layout
def initialize(layout)
# @layout is an array of row arrays. So location [x, y] is at @layout[y][x].
@layout = layout
end
# Answers an array of lines which can be printed to the console to display
# the board.
def board_view
lines = []
count = 0
@layout.each_with_index do |row, y|
l = (y + 1).to_s + " "
row.each do |square|
count += 1
l += square.square_view(count % 2 == 0)
end
count += 1 # Because next row begins with the same color as last row ends
lines.unshift(l)
end
lines.unshift("") # Blank line before
lines << ""
lines << " " + "abcdefgh"
lines << "" # Blank line after
lines
end
def move_piece(from, to)
@layout[to[1]][to[0]] = @layout[from[1]][from[0]]
@layout[from[1]][from[0]] = Empty.new
end
def set_piece(location, piece)
@layout[location[1]][location[0]] = piece
end
def undo_move_piece(old_from, old_from_piece, old_to, old_to_piece)
set_piece(old_from, old_from_piece)
set_piece(old_to, old_to_piece)
end
def piece_at_location(location)
@layout[location[1]][location[0]]
end
# Answers hash of the pieces of the color given
def pieces(white, only_king=false)
result = {}
@layout.each_with_index do |row, y|
row.each_with_index do |square, x|
if (!square.empty? && square.white? == white && (!only_king || square.is_a?(King)))
result[[x, y]] = square
end
end
end
result
end
def move_leaves_player_in_check?(player_is_white, from, to)
from_piece = piece_at_location(from)
to_piece = piece_at_location(to)
move_piece(from, to)
result = in_check?(player_is_white)
undo_move_piece(from, from_piece, to, to_piece)
result
end
def in_check?(player_is_white)
player_king_location = pieces(player_is_white, true).keys[0]
other_player_pieces = pieces(!player_is_white)
other_player_pieces.each do |location, piece|
if (piece.is_move_possible(layout, location, player_king_location).possible?)
return true
end
end
return false
end
def has_move_so_not_in_check?(player_is_white)
pieces = pieces(player_is_white)
pieces.each do |location, piece|
@layout.each_with_index do |row, y|
row.each_with_index do |square, x|
to = [x, y]
return true if (move_possible(player_is_white, location, to).nil? &&
!move_leaves_player_in_check?(player_is_white, location, to))
end
end
end
return false
end
def move_possible(player_is_white, from, to)
piece = piece_at_location(from)
target_piece = piece_at_location(to)
error = nil
if (from == to)
error = "Start location is same as target location"
elsif (piece.empty? || piece.white? != player_is_white)
error = "Start location is not one of your pieces!"
elsif (!target_piece.empty? && target_piece.white? == player_is_white)
error = "Target location already has one of your pieces!"
else
possibility = piece.is_move_possible(layout, from, to)
if (possibility.possible?)
# The move shouldn't put the player into check or fail to get them
# out of check if they already are in check.
if (move_leaves_player_in_check?(player_is_white, from, to))
error = "That move would leave the " + (player_is_white ? "white" : "black") + " player in check."
end
else
error = possibility.error
end
end
error
end
end | true |
0ff16fb16208f5b354ff664af1505efd6eddd179 | Ruby | zachjamesgreen/SweaterWeather | /app/lib/current_weather.rb | UTF-8 | 1,012 | 2.921875 | 3 | [] | no_license | class CurrentWeather
attr_reader :datetime, :sunrise, :sunset, :temperature, :feels_like, :humidity, :uvi, :visibility, :conditions, :icon
def initialize(info)
@datetime = Time.at(info['current']['dt'])
@sunrise = Time.at(info['current']['sunrise'])
@sunset = Time.at(info['current']['sunset'])
@temperature = info['current']['temp']
@feels_like = info['current']['feels_like']
@humidity = info['current']['humidity']
@uvi = info['current']['uvi']
@visibility = info['current']['visibility']
@conditions = info['current']['weather'][0]['description']
@icon = info['current']['weather'][0]['icon']
end
def serialize
{
datetime: @datetime.to_s(:db),
sunrise: @sunrise.to_s(:db),
sunset: @sunset.to_s(:db),
temperature: @temperature,
feels_like: @feels_like,
humidity: @humidity,
uvi: @uvi,
visibility: @visibility,
conditions: @conditions,
icon: @icon
}
end
end
| true |
36b754990b893064adfeb662331a8c19db349385 | Ruby | ssjuampi23/sample_app | /spec/requests/user_pages_spec.rb | UTF-8 | 9,073 | 2.625 | 3 | [] | no_license | require 'spec_helper'
describe "UserPages" do
subject { page }
describe "signup page" do
before { visit signup_path }
it { should have_selector_h1("Sign up")}
it { should have_selector_title("Sign up")}
end
describe "profile page" do
let(:user){ FactoryGirl.create(:user) }#code to make a user variable
before { visit user_path(user)}
it { should have_selector_h1(user.name)}
it { should have_selector_title(user.name)}
describe "follow/unfollow buttons" do
let(:other_user){ FactoryGirl.create(:user) }
before { sign_in user } #sign_in user is declared on sessions_helper
describe "following an user" do
before { visit user_path(other_user) }
it "should increment the followed user count" do
expect do
click_button "Follow"
end.to change(user.followed_users, :count).by(1)
end
it "should increment the other user's followers count" do
expect do
click_button "Follow"
end.to change(other_user.followers,:count).by(1)
end
describe "toogling the button" do
before { click_button "Follow" }
it{ should have_selector('input',value: "Unfollow")}
end #toogling the button
end #following an user
describe "unfollowing an user" do
before do
user.follow!(other_user)
visit user_path(other_user)
end
it "should decrement the followed user count" do
expect do
click_button "Unfollow"
end.to change(user.followed_users, :count).by(-1)
end
it "should decrement the other user's followers count" do
expect do
click_button "Unfollow"
end.to change(other_user.followers, :count).by(-1)
end
describe "toogling the button" do
before { click_button "Unfollow" }
it{ should have_selector('input',value: "Follow")}
end #toogling the button
end #unfollowing an user
end #follow/unfollow buttons
end # profile page
describe "following/followers" do
let(:user){ FactoryGirl.create(:user) }
let(:other_user){ FactoryGirl.create(:user) }
before { user.follow!(other_user) }
describe "followed users" do
before do
sign_in user
visit following_user_path(user)
end
it { should have_selector('title', text: full_title('Following') ) }
it { should have_selector('h3', text: 'Following' ) }
it { should have_link(other_user.name, href: user_path(other_user )) }
end #followed users describe content
describe "followers" do
before do
sign_in other_user
visit followers_user_path(other_user)
end
it { should have_selector('title', text: full_title('Followers') ) }
it { should have_selector('h3', text: 'Followers' ) }
it { should have_link(user.name, href: user_path(user )) }
end #followers describe content
end #following/followers describe content
describe "signup" do
before { visit signup_path } #this simulates the user clicking the link to the Sign Up page
let(:submit){ "Create my account" }
describe "with invalid information" do
it "should not create a user" do
expect { click_button submit }.not_to change(User,:count) #here we are making a call to the variable "submit" that was previously created
end
end
#Exercise 2 from Chapter 7. Write tests for the error messages.
describe "after submission" do
before{ click_button submit }
it { should have_selector_title("Sign up")}
it{ should have_content_message('error')}
it{ should have_content_message("Password can't be blank")}
it{ should have_content_message("Name can't be blank")}
it{ should have_content_message("Email can't be blank")}
it{ should have_content_message("Email is invalid")}
it{ should have_content_message("Password is too short (minimum is 6 characters)")}
it{ should have_content_message("Password confirmation can't be blank")}
end
describe "with valid information" do
#TEST
before{ fill_user_information()}
#before{ click_button "Sign in" }
it "should create a user" do
#expect{ click_button "Confirmation" }.to change(User,:count).by(1)
expect{ click_button submit }.to change(User,:count).by(1)
end
describe "after saving the user" do
before{ click_button submit}
let(:user){ User.find_by_email('user@example.com') }
it{ should have_selector_h1(user.name)}
it{ should have_selector_title(user.name)}
it{ should have_success_message("Welcome to the Sample App!")}
it{ should have_link('Sign out')}
end
end # end valid information describe block
end # end sign up describe block
describe "edit" do
let(:user){ FactoryGirl.create(:user) }#code to make a user variable
before do
sign_in user
visit edit_user_path(user)
end
#Exercise 6 Chapter 9
#it "should be redirected to root URL in case the user wants to access the new/create actions" do
#visit signup_path # put is used to access the controller action, is the same as visit
#redirect_to(root_path)
#end
#before { visit edit_user_path(user)}
describe "page" do
it{ should have_selector_h1("Update your profile")}
it{ should have_selector_title("Edit User")}
it {should have_link('change', href: 'http://gravatar.com/emails')}
end
describe "with invalid information" do
before { click_button "Save changes" }
it{ should have_content('error') }
end
describe "with valid information" do
let(:new_name){ "New Name" }
let(:new_email){ "new@example.com" }
before do
fill_in "Name", with: new_name
fill_in "Email", with: new_email
fill_in "Password", with: user.password
fill_in "Confirm Password", with: user.password
click_button "Save changes"
end
it{ should have_selector('title', text: new_name)}
it{ should have_selector('div.alert.alert-success')}
it {should have_link('Sign out', href: signout_path)}
specify {user.reload.name.should == new_name }
specify {user.reload.email.should == new_email } # this reloads the user variable from the test database using user.reload
end # end valid information
end # end edit describe block
describe "index" do
let(:user){FactoryGirl.create(:user)}
before(:each) do
sign_in user
visit users_path
#sign_in FactoryGirl.create(:user)
#FactoryGirl.create(:user, name:"Bob", email: "bob@example.com")
#FactoryGirl.create(:user, name:"Ben", email: "ben@example.com")
#visit users_path
end
it { should have_selector('title', text: "All users") }
it { should have_selector('h1', text: "All users") }
describe "pagination" do
before(:all){ 30.times { FactoryGirl.create(:user) } }
after(:all){ User.delete_all }
it { should have_selector('div.pagination') }
it "should list each user" do
User.paginate(page: 1).each do |user|
#User.all.each do |user|
page.should have_selector('li', text: user.name)
end
end
end #end pagination
describe "delete links" do
it { should_not have_link('delete') }
describe "as an admin user" do
let(:admin){FactoryGirl.create(:admin)}
before do
sign_in admin
visit users_path
end
it { should have_link('delete', href: user_path(User.first))}
it "should be able to delete another user" do
expect { click_link('delete') }.to change(User,:count).by(-1)
end
it{should_not have_link('delete', href: user_path(admin))}
end #end describe as an admin user
end #end describe delete links
end # end index describe
describe "profile page" do
let(:user){ FactoryGirl.create(:user) } # here the user is created
let!(:m1){ FactoryGirl.create(:micropost, user: user, content: "Foo") }
let!(:m2){ FactoryGirl.create(:micropost, user: user, content: "Bar") }
before { visit user_path(user) }
it{ should have_selector('h1', text: user.name)}
it{ should have_selector('title', text: user.name)}
describe "microposts" do
it{ should have_content(m1.content)}
it{ should have_content(m2.content)}
it{ should have_content(user.microposts.count)} # we can use here the count method through the association
end # end describe microposts
end #end describe profile page
end
| true |
4604ff67c68e33f56ced82c27931d945f57d501f | Ruby | nkrsudha/neutral | /spec/dummy/config/initializers/neutral.rb | UTF-8 | 1,421 | 2.5625 | 3 | [
"MIT"
] | permissive | #Neutral engine Initializer
Neutral.configure do |config|
# Set to false wheter a voter cannot change(i.e. update or delete) his vote.
#config.can_change = true
# Configure method providing a voter instance.
# Also make sure your current voter method is accessible from your ApplicationController
# as a helper_method.
#config.current_voter_method = :current_user
# Determine wheter a voter is required to be logged in. Setting to false
# is not recommended.
#config.require_login = true
# Define a vote owner class(usually User, Client, Customer)
#config.vote_owner_class = 'User'
# Define default icon set. Used when no explicit icon set for helper
# 'voting_for' is passed.
#config.default_icon_set = :thumbs
end
# You can also define your custom icon set providing valid FontAwesome icon class definitions for
# positive, negative and remove icon. You cannot override icon sets that already exist('thumbs' and 'operations' by default).
# Beware of typos and non-existent FontAwesome icon classes.
# Then you can used your own icon set by passing its name to the view helper : 'voting_for voteable, icons: :mysupericons'
# Neutral.define do
# set :myicons do
# positive "fa-plus-circle"
# negative "fa-minus-circle"
# remove "fa-times"
# end
#
# set :mythumbs do
# positive "fa-thumbs-up"
# negative "fa-thumbs-down"
# remove "fa-times"
# end
# end
| true |
2005fd5c7c53302a3c212121ba4eae0477761742 | Ruby | eddygarcas/vortrics | /app/models/montecarlo.rb | UTF-8 | 595 | 3.03125 | 3 | [
"MIT"
] | permissive | class Montecarlo
attr_writer :number, :backlog, :focus, :iteration
def number
@number ||= 1000
end
def backlog
@backlog ||= 50
end
def focus
(@focus ||= 100).to_f / 100
end
def iteration
@iteration ||= 5
end
def initialize(params = {})
return unless params.dig(:montecarlo).present?
@number = params.dig(:montecarlo).fetch(:number, 1000).to_i
@backlog = params.dig(:montecarlo).fetch(:backlog, 50).to_i
@focus = params.dig(:montecarlo).fetch(:focus, 100).to_i
@iteration = params.dig(:montecarlo).fetch(:iteration, 5).to_i
end
end
| true |
70af9e6e6ac1adb8951953c45464f465c5f38c45 | Ruby | d3r1v3d/frisco-beer-crawler | /lib/frisco_beers.rb | UTF-8 | 449 | 2.796875 | 3 | [] | no_license | require 'mechanize'
module Frisco
def self.beers
spider = Mechanize.new { |agent|
agent.user_agent_alias = 'Windows Mozilla'
}
beers = []
page = spider.get('http://friscogrille.com/beers.php')
page.search('#keg-beers > ul li').each do |beer|
beers << beer.text
end
puts "Frisco Taphouse / Beers:"
beers.each_with_index do |beer, index|
puts "[#{index}] #{beer}"
end
end
end
Frisco.beers
| true |
b19750c0f9de031e06b4dfd5f1e191c1b1ffc7d6 | Ruby | GenSplice-Research-Development/version | /Chromosome Variation/Somys/nullisomy.rb | UTF-8 | 916 | 3.1875 | 3 | [] | no_license | def Nullisomy(b, a = 0)
eu = b #Even number
chrom = a #Chromosome number
return "only even numbers permitted" if eu.odd? == true
set = {2 => "||"}
if chrom == 0
hap = eu/2 #Creates haploid number
diploid = [2] * hap #Creates Karyotype
chromo_number = [*0..(diploid.count-1)].sample(1).pop
kary = diploid.count.times.map{|e| set[diploid[e]]}
kary_2 = kary.count.times.map{|h| kary[h] + " => " + "#{h + 1}"}
kary_2.delete_at(chromo_number)
kary_2
elsif chrom != 0
hap = eu/2 #Creates haploid number
diploid = [2] * hap #Creates Karyotype
chromo_number = [*1..(diploid.count)]
return "Chromosome number is beyond the scope" if chromo_number.include?(chrom) != true
kary = diploid.count.times.map{|e| set[diploid[e]]}
kary_2 = kary.count.times.map{|h| kary[h] + " => " + "#{h + 1}"}
kary_2.delete_at(chrom-1)
kary_2
end
end | true |
22603f627899b494bf0be23affc54771ab0480ca | Ruby | MrRogerino/ClapOnce-API | /app/controllers/users_controller.rb | UTF-8 | 2,080 | 2.859375 | 3 | [] | no_license | class UsersController < ApplicationController
include UsersHelper
def notify_users
epicenter = [params[:lat].to_i, params[:long].to_i]
severity = params[:severity]
@users = alert_users(epicenter, severity)
render json: {users: @users}.as_json, status: 201
end
def show
@user = User.find_by(id: params[:id])
render json: {user: @user, location: @user.location}.as_json, status: 201
end
def update_status
@user = User.find_by(id: params[:id])
if @user
@user.update_attribute(:status, params[:status])
end
render json: {user:@user}.as_json, status: 201
end
def update_location
@user = User.find_by(id: params[:id])
if @user
@user.update_attribute(:longitude, params[:long])
@user.update_attribute(:latitude, params[:lat])
end
render json: {location:@user.location}.as_json, status: 201
end
private
EARTH_RADIUS = 3961
def alert_users(epicenter, severity)
affected_users = []
User.find_each do |user|
if distance(epicenter, user.location) < radius_affected(severity)
affected_users << user
end
end
affected_users.each do |user|
change_status(user, "pending")
end
return affected_users
end
def radius_affected(severity)
case severity
when "moderate"
return 3
when "severe"
return 5
end
end
def distance(epicenter,user_location) #gets distance between two points (in miles)
d_longitude = toRadians((epicenter[1]-user_location[1]))
d_latitude = toRadians((epicenter[0]-user_location[0]))
sin_d_long = Math.sin(d_longitude)
sin_d_lat = Math.sin(d_latitude)
rad_epi_lat = toRadians(epicenter[0])
rad_user_lat = toRadians(epicenter[1])
a = sin_d_lat ** 2 + Math.cos(rad_epi_lat) * Math.cos(rad_user_lat) * (sin_d_long ** 2)
c = Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
return EARTH_RADIUS * c
end
def change_status(user, status)
user.update_attribute(:status, status)
end
def toRadians(degrees)
return degrees * Math::PI / 180
end
end
| true |
07b77b8d1f59ba8e408001eaf59f553920ce624f | Ruby | tony-gomes/futbol | /lib/game.rb | UTF-8 | 2,795 | 3.21875 | 3 | [] | no_license | class Game
@@games = {}
def self.add(game)
@@games[game.game_id] = game
end
def self.all
@@games
end
def self.number_of_games
@@games.length
end
def self.all_seasons
seasons = @@games.values.reduce([]) do |acc, game|
acc << game.season
end
seasons.uniq
end
def self.games_in_a_season(season)
@@games.select do |_game_id, game|
game.season == season
end
end
def self.find_games(season, type)
Game.all.select do |game_id, game_data|
game_data.season == season && game_data.type == type
end
end
def self.number_of_games_in_all_season
@@games.values.reduce(Hash.new(0)) do |games_by_season, game|
games_by_season[game.season.to_s] += 1
games_by_season
end
end
def self.total_goals_per_game(games = nil)
if games != nil
games.values.sum { |game| game.total_goals }.to_f
else
Game.all.sum { |_game_id, game| game.total_goals }.to_f
end
end
def self.find_all_scores(function = "add")
total_scores = Game.all.values.reduce([]) do |acc, value|
if function == "subtract"
acc << (value.home_goals - value.away_goals).abs
else
acc << value.home_goals + value.away_goals
end
end
total_scores.uniq.sort
end
def self.games_outcome_percent(outcome = nil)
games_count = 0.0
Game.all.each_value do |value|
away = (outcome == "away" && value.home_goals < value.away_goals)
home = (outcome == "home" && value.home_goals > value.away_goals)
draw = (outcome == "draw" && value.home_goals == value.away_goals)
if away || home || draw
games_count += 1
end
end
(games_count / Game.number_of_games).round(2)
end
def self.games_played_by_team(team)
Game.all.values.select do |game|
game.home_team_id == team.team_id || game.away_team_id == team.team_id
end
end
def self.all_games_by_team_id(team_id)
team_id = team_id.to_i if team_id.class != Integer
@@games.reduce([]) do |return_games, game|
if game.last.away_team_id == team_id || game.last.home_team_id == team_id
return_games << game.last
end
return_games
end
end
attr_reader :game_id,
:season,
:type,
:date_time,
:away_team_id,
:home_team_id,
:away_goals,
:home_goals,
:total_goals
def initialize(data)
@game_id = data[:game_id]
@season = data[:season].to_s
@type = data[:type]
@date_time = data[:date_time]
@away_team_id = data[:away_team_id]
@home_team_id = data[:home_team_id]
@away_goals = data[:away_goals]
@home_goals = data[:home_goals]
@total_goals = @away_goals + @home_goals
end
end
| true |
29345e0d96668795052945eb57c7cfdcf5d571d3 | Ruby | carlosadr11/Aplicaciones-WEB | /ruby/Tesoro.rb | UTF-8 | 401 | 3.5625 | 4 | [] | no_license | class Tesoro
def get_nombre
return @nombre
end
def set_nombre(nombre)
@nombre=nombre
end
def get_descripcion
return @descripcion
end
def set_nombre(descripcion)
@descripcion=descripcion
end
def to_s #sobreescribir el metodo por defecto to_s
"El tesoro #{@nombre} es #{@descripcion}\n"
end
end
mi_Tesoro = Tesoro.new
mitesoro.set_nombre("kiko")
print mi_Tesoro.get_nombre
| true |
3f2d6408861da730004d6aebab4fe3ecd6580f7e | Ruby | yusuke0024/barbar_guide_app | /spec/system/user_spec.rb | UTF-8 | 3,700 | 2.53125 | 3 | [] | no_license | require "rails_helper"
RSpec.describe "User", type: :system do
describe "ユーザー登録機能" do
before do
#新規ユーザー登録ページ
visit new_user_path
#正常範囲の入力値を入力
fill_in "user_name", with: "yusuke"
fill_in "user_email", with: "example@mail.com"
fill_in "user_password", with: "foobar"
end
context "ユーザー名50文字以内、メールアドレス不正ではないフォーマット、パスワード6文字以上のとき" do
it "正常に登録されること" do
expect {
click_on "登録"
}.to change(User, :count).by(1)
expect(current_path).to eq salons_path
end
end
context "ユーザー名入力フォームが空白のとき" do
let(:name) { "" }
before do
fill_in "user_name", with: name
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "ユーザー名を入力してください"
end
end
context "ユーザー名が51文字以上のとき" do
let(:name) { "じゅげむだ" * 10 + "よ" }
before do
fill_in "user_name", with: name
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "ユーザー名は50文字以内で入力してください"
end
end
context "メールアドレスが空白のとき" do
let(:email) { "" }
before do
fill_in "user_email", with: email
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "メールアドレスを入力してください"
end
end
context "同じメールアドレスで2回登録しようとしたとき" do
let(:email) { "example1@mail.com" }
before do
fill_in "user_email", with: email
click_on "登録"
visit new_user_path
fill_in "user_email", with: email
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "メールアドレスはすでに存在します"
end
end
context "メールアドレスが256文字以上のとき" do
let(:email) { "a" * 247 + "@mail.com" }
before do
fill_in "user_email", with: email
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "メールアドレスは255文字以内で入力してください"
end
end
context "メールアドレスのフォーマットが不正なとき" do
let(:email) { "hoge@mail" }
before do
fill_in "user_email", with: email
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "メールアドレスは不正な値です"
end
end
context "パスワードが空白のとき" do
let(:password) { "" }
before do
fill_in "user_password", with: password
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "パスワードを入力してください"
expect(page).to_not have_content "パスワードは6文字以上で入力してください"
end
end
context "パスワードが5文字以下のとき" do
let(:password) { "penta" }
before do
fill_in "user_password", with: password
click_on "登録"
end
it "エラーになること" do
expect(page).to have_content "パスワードは6文字以上で入力してください"
end
end
end
end
| true |
8233e3896e574511429b226f1cd9bc9e5d1f767f | Ruby | chrismear/rails-lighthouse-archive | /data/attachments/103259/batches.rb | UTF-8 | 4,104 | 2.921875 | 3 | [
"MIT"
] | permissive | module ActiveRecord
module Batches # :nodoc:
def self.included(base)
base.extend(ClassMethods)
end
# When processing large numbers of records, it's often a good idea to do so in batches to prevent memory ballooning.
module ClassMethods
# Yields each record that was found by the find +options+. The find is performed by find_in_batches
# with a batch size of 1000 (or as specified by the +batch_size+ option).
#
# Example:
#
# Person.find_each(:conditions => "age > 21") do |person|
# person.party_all_night!
# end
#
# Note: This method is only intended to use for batch processing of large amounts of records that wouldn't fit in
# memory all at once. If you just need to loop over less than 1000 records, it's probably better just to use the
# regular find methods.
def find_each(options = {})
find_in_batches(options) do |records|
records.each { |record| yield record }
end
self
end
# Yields each batch of records that was found by the find +options+ as an array. The size of each batch is
# set by the +batch_size+ option; the default is 1000.
#
# You can control the starting point for the batch processing by supplying the +start+ option. This is especially
# useful if you want multiple workers dealing with the same processing queue. You can make worker 1 handle all the
# records between id 0 and 10,000 and worker 2 handle from 10,000 and beyond (by setting the +start+ option on that
# worker).
#
# It's not possible to set the order. That is automatically set to ascending on the primary key ("id ASC")
# to make the batch ordering work.
#
# Example:
#
# Person.find_in_batches(:conditions => "age > 21") do |group|
# sleep(50) # Make sure it doesn't get too crowded in there!
# group.each { |person| person.party_all_night! }
# end
#
# Note: This method is not guaranteed to be concurrency-safe, and is not recommended if atomicity is a concern
#
def find_in_batches(options = {})
raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order]
new_options = options.merge(:order=>batch_order)
last_primary_key = new_options.delete(:start)
start_with_zero = new_options.delete(:start_with_zero)
start_with_zero = true if start_with_zero.nil?
batch_size = new_options.delete(:batch_size) || 1000
batch_offset = new_options.delete(:offset) || 0
new_options.delete(:limit)
new_options[:select] ||= "*"
new_options[:select] << ",#{table_name}.#{primary_key}" # it won't hurt if this gets selected twice
if last_primary_key.nil?
if start_with_zero
last_primary_key = 0
else
first_obj = find(:first,new_options) or return []
last_primary_key = first_obj.send(primary_key)
end
end
batch_limit=batch_size
count = 0 # number of recs we've pulled so far
batch_recs = []
while true do
if options[:limit]
limit_remaining = options[:limit] - count
batch_limit = (limit_remaining < batch_size) ? limit_remaining : batch_size
end
with_scope(:find=>new_options) do
conditions=["#{table_name}.#{primary_key}>#{count==0 ? '=' : ''}?",last_primary_key]
batch_recs = find(:all,:conditions=>conditions,:limit=>batch_limit,:offset=>batch_offset)
end
break if batch_recs.empty?
yield batch_recs
count += batch_recs.size
break if (count == options[:limit])
batch_offset=0 # we only needed this for the first batch, so we set it to 0 now
last_primary_key = batch_recs.last.send(primary_key)
end
batch_recs
end
private
def batch_order
"#{table_name}.#{primary_key} ASC"
end
end
end
end | true |
e68ff88f40a7a1e1ebe1669429955ce1764057e7 | Ruby | katguz3485/ruby-101-challenges | /04-Merge-and-sort-array/spec/merge_and_sort_array_spec.rb | UTF-8 | 332 | 2.5625 | 3 | [] | no_license | require_relative '../lib/merge_and_sort_array'
describe '#merge_and_sort_array' do
it 'should return an Array' do
expect(merge_and_sort_array(['B', 'C'], ['A', 'D'])).to be_a(Array)
end
it 'should return one sorted array' do
expect(merge_and_sort_array(['B', 'C'], ['A', 'D'])).to eq(['A', 'B', 'C', 'D'])
end
end
| true |
1aaa71ccc7718679cd63bc90c9ae2d668092e122 | Ruby | lastobelus/merb_global | /lib/merb_global/locale.rb | UTF-8 | 4,604 | 3.015625 | 3 | [
"MIT"
] | permissive | require 'merb_global/base'
require 'thread'
require 'weakref'
class Thread
attr_accessor :mg_locale
end
module Merb
module Global
class Locale
attr_reader :language, :country
def initialize(name)
# TODO: Understand RFC 1766 fully
@language, @country = name.split('-')
end
def as_rfc1766
if @country.nil?
"#{@language.downcase}"
else
"#{@language.downcase}-#{@country.downcase}"
end
end
#
# This method checks if the locale is 'wildcard' locale. I.e.
# if any locale will suit
#
def any?
language == '*' && country.nil?
end
#
# This method returns the parent locale - for locales for countries
# (such as en_GB) it returns language(en). For languages it returns nil.
#
def base_locale
if not @country.nil?
Locale.new(@language)
else
nil
end
end
def to_s
if country.nil?
"#{@language.downcase}"
else
"#{@language.downcase}_#{@country.upcase}"
end
end
if defined? RUBY_ENGINE and RUBY_ENGINE == "jruby"
#
# This method return corresponding java locales caching the result.
# Please note that if used outside jruby it returns nil.
def java_locale
require 'java'
@java_locale ||=
if @country.nil?
java.util.Locale.new(@language.downcase)
else
java.util.Locale.new(@language.downcase, @country.upcase)
end
end
else
def java_locale
nil
end
end
def self.parse(header) #:nodoc:
header = header.split(',')
header.collect! {|lang| lang.delete ' ' "\n" "\r" "\t"}
header.reject! {|lang| lang.empty?}
header.collect! {|lang| lang.split ';q='}
header.collect! do |lang|
if lang.size == 1
[lang[0], 1.0]
else
[lang[0], lang[1].to_f]
end
end
header.sort! {|lang_a, lang_b| lang_b[1] <=> lang_a[1]} # sorting by decreasing quality
header.collect! {|lang| Locale.new(lang[0])}
end
def self.from_accept_language(accept_language) #:nodoc:
unless accept_language.nil?
accept_language = Merb::Global::Locale.parse(accept_language)
accept_language.each_with_index do |lang, i|
if lang.any?
# In this case we need to choose a locale that is not in accept_language[i+1..-1]
return Merb::Global::Locale.choose(accept_language[i+1..-1])
elsif Merb::Global::Locale.support? lang
return lang
end
lang = lang.base_locale
return lang if lang && Merb::Global::Locale.support?(lang)
end
end
return nil
end
# Returns current locale
def self.current
Thread.current.mg_locale
end
# Sets the current locale
def self.current=(new_locale)
Thread.current.mg_locale = new_locale
end
class << self
alias_method :pure_new, :new
private :pure_new
end
@@current = {}
@@current_mutex = Mutex.new
# Create new locale object and returns it.
#
# Please note that this method is cached.
def self.new(name)
return nil if name.nil?
return name if name.is_a? Locale
@@current_mutex.synchronize do
begin
n = @@current[name]
if n.nil?
n = pure_new(name)
@@current[name] = WeakRef.new(n)
else
n = n.__getobj__
end
n
rescue WeakRef::RefError
n = pure_new(name)
@@current[name] = WeakRef.new(n)
n
end
end
end
# Checks if the locale is supported
def self.support?(locale)
supported_locales.include? locale.to_s
end
# Lists the supported locale
def self.supported_locales
Merb::Global::config('locales', ['en'])
end
# returns true if this locale is the first locale in supported_locales
def default?
self.to_s == Merb::Global::Locale.supported_locales.first
end
# Chooses one of the supported locales which is not in array given as
# argument
def self.choose(except)
new((supported_locales - except.map{|e| e.to_s}).first)
end
end
end
end
| true |
15956802368623c8b5592fb6300d975f095be900 | Ruby | devmichaelmcf/launchschool | /RB101/small_problems/easy1/sum_of_digits.rb | UTF-8 | 866 | 4.75 | 5 | [] | no_license | # Write a method that takes one argument, a positive integer, and returns the sum of its digits.
=begin
Problem: Take a Integer. Return the total of its visible digits.
Examples: Big num digits the method ignores the underscores. Input and output are integers.
Data structure: Array as a single ordered list should be sufficient.
Algorithm: Get integer. Set integer to string. Set string to an array of characters. Change array of string characters to array of integers.
Set a counting variable to 0. Using .each method add and reassgin the counting variable to each element.
=end
def sum(num)
counting_value = 0
num.to_s.chars { |element| counting_value += element.to_i }
counting_value
end
puts sum(23) == 5
puts sum(496) == 19
puts sum(123_456_789) == 45
# For a challenge, try writing this without any basic looping constructs (while, until, loop, and each). | true |
67203063856321f91f48c3064c7af51aeaf3c682 | Ruby | thomasstephane/flashquizz | /app/models/game.rb | UTF-8 | 976 | 2.875 | 3 | [] | no_license | class Game < ActiveRecord::Base
belongs_to :user
belongs_to :deck
validates :user_id, :deck_id, :presence => true
after_initialize :init
def init
self.cards_shown ||= 0
self.cards_correct ||= 0
end
def score
p self.cards_shown
if self.cards_shown == 0
0
else
p @score = ((self.cards_correct.to_f / self.cards_shown.to_f) * 100) .to_i
end
end
def progression(card, user_answer)
if card.check(user_answer)
self.cards_correct += 1
else
"wrong answer"
end
self.cards_shown += 1
self.save
end
def get_users
Game.where("deck_id = ?", self.deck_id)
end
def user_name
user = User.find_by_id(self.user_id)
user.username
end
def rank_list
list = []
get_users.each do |game|
list << { name: game.user_name, score: game.score }
end
list
end
def sorted_rank_list
rank_list.sort_by {|user_score| user_score[:score] }
end
def nb_cards
Deck.find(self.deck_id).number_of_cards
end
end
| true |
30dc15424f71cb5095f66c9bef5bb205d76641a7 | Ruby | Dahie/caramelize | /lib/caramelize/caramel.rb | UTF-8 | 2,461 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'caramelize/input_wiki/wikkawiki'
require 'caramelize/input_wiki/redmine_wiki'
## Example caramelize configuration file
# Within this method you can define your own Wiki-Connectors to Wikis
# not supported by default in this software
# Note, if you want to activate this, you need to uncomment the line below.
def customized_wiki
# This example is a reimplementation of the WikkaWiki-Connector.
# To connect to WikkaWiki, I suggest to use the predefined Connector below.
options = { host: "localhost",
username: "user",
database: "database_name",
password: 'Picard-Delta-5',
markup: :wikka}
wiki = Caramelize::InputWiki::Wiki.new(options)
wiki.instance_eval do
def read_pages
sql = "SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;"
results = database.query(sql)
results.each do |row|
titles << row["tag"]
author = @authors[row["user"]]
properties = { id: row["id"],
title: row["tag"],
body: row["body"],
markup: 'wikka',
latest: row["latest"] == "Y",
time: row["time"],
message: row["note"],
author: author,
author_name: row["user"]}
page = Page.new(properties)
revisions << page
end
titles.uniq!
revisions
end
end
wiki
end
# if you want to use one of the preset Wiki-Connectors uncomment the connector
# and edit the database logins accordingly.
def predefined_wiki
# For connection to a WikkaWiki-Database use this Connector
#options = { host: "localhost",
# username: "root",
# password: "root",
# database: "wikka" }
#return Caramelize::InputWiki::WikkaWiki.new(options)
# For connection to a Redmine-Database use this Connector
# Additional options:
# :create_namespace_overview => true/false (Default: true) - Creates a new wikipage at /home as root page for Gollum wiki
options = { host: "localhost",
username: "root",
password: "root",
database: "redmine_development" }
return Caramelize::InputWiki::RedmineWiki.new(options)
end
def input_wiki
# comment and uncomment to easily switch between predefined and
# costumized Wiki-connectors.
#return customized_wiki
return predefined_wiki
end
| true |
a8db72db89c80eef752e590585bae3731c084c09 | Ruby | bdurand/sunspot_index_queue | /lib/sunspot/index_queue.rb | UTF-8 | 7,168 | 2.796875 | 3 | [
"MIT"
] | permissive | module Sunspot
# Implementation of an asynchronous queue for indexing records with Solr. Entries are added to the queue
# defining which records should be indexed or removed. The queue will then process those entries and
# send them to the Solr server in batches. This has two advantages over just updating in place. First,
# problems with Solr will not cause your application to stop functioning. Second, batching the commits
# to Solr is more efficient and it should be able to handle more throughput when you have a lot of records
# to index.
class IndexQueue
autoload :Batch, File.expand_path('../index_queue/batch', __FILE__)
autoload :Entry, File.expand_path('../index_queue/entry', __FILE__)
autoload :SessionProxy, File.expand_path('../index_queue/session_proxy', __FILE__)
# This exception will be thrown if Solr is not responding.
class SolrNotResponding < StandardError
end
attr_accessor :retry_interval, :batch_size
attr_reader :session, :class_names
class << self
# Set the default priority for indexing items within a block. Higher priority items will be processed first.
def set_priority(priority, &block)
save_val = Thread.current[:sunspot_index_queue_priority]
begin
Thread.current[:sunspot_index_queue_priority] = priority.to_i
yield
ensure
Thread.current[:sunspot_index_queue_priority] = save_val
end
end
# Get the default indexing priority. Defaults to zero.
def default_priority
Thread.current[:sunspot_index_queue_priority] || 0
end
end
# Create a new IndexQueue. Available options:
#
# +:retry_interval+ - The number of seconds to wait between to retry indexing when an attempt fails
# (defaults to 1 minute). If an entry fails multiple times, it will be delayed for the interval times
# the number of failures. For example, if the interval is 1 minute and it has failed twice, the record
# won't be attempted again for 2 minutes.
#
# +:batch_size+ - The maximum number of records to try submitting to solr at one time (defaults to 100).
#
# +:class_names+ - A list of class names that the queue will process. This can be used to have different
# queues process different classes of records when they need to different configurations.
#
# +:session+ - The Sunspot::Session object to use for communicating with Solr (defaults to a session with the default config).
def initialize(options = {})
@retry_interval = options[:retry_interval] || 60
@batch_size = options[:batch_size] || 100
@batch_handler = nil
@class_names = []
if options[:class_names].is_a?(Array)
@class_names.concat(options[:class_names].collect{|name| name.to_s})
elsif options[:class_names]
@class_names << options[:class_names].to_s
end
@session = options[:session] || Sunspot::Session.new
end
# Provide a block that will handle submitting batches of records. The block will take a Batch object and must call
# +submit!+ on it. This can be useful for doing things such as providing an identity map for records in the batch.
# Example:
#
# # Use the ActiveRecord identity map for each batch submitted to reduce database activity.
# queue.batch_handler do
# ActiveRecord::Base.cache do |batch|
# batch.submit!
# end
# end
def batch_handler(&block)
@batch_handler = block
end
# Add a record to be indexed to the queue. The record can be specified as either an indexable object or as
# as hash with :class and :id keys. The priority to be indexed can be passed in the options as +:priority+
# (defaults to 0).
def index(record_or_hash, options = {})
klass, id = class_and_id(record_or_hash)
Entry.enqueue(self, klass, id, false, options[:priority] || self.class.default_priority)
end
# Add a record to be removed to the queue. The record can be specified as either an indexable object or as
# as hash with :class and :id keys. The priority to be indexed can be passed in the options as +:priority+
# (defaults to 0).
def remove(record_or_hash, options = {})
klass, id = class_and_id(record_or_hash)
Entry.enqueue(self, klass, id, true, options[:priority] || self.class.default_priority)
end
# Add a list of records to be indexed to the queue. The priority to be indexed can be passed in the
# options as +:priority+ (defaults to 0).
def index_all(klass, ids, options = {})
Entry.enqueue(self, klass, ids, false, options[:priority] || self.class.default_priority)
end
# Add a list of records to be removed to the queue. The priority to be indexed can be passed in the
# options as +:priority+ (defaults to 0).
def remove_all(klass, ids, options = {})
Entry.enqueue(self, klass, ids, true, options[:priority] || self.class.default_priority)
end
# Get the number of entries to be processed in the queue.
def total_count
Entry.total_count(self)
end
# Get the number of entries in the queue that are ready to be processed.
def ready_count
Entry.ready_count(self)
end
# Get the number of entries that have errors in the queue.
def error_count
Entry.error_count(self)
end
# Get the entries in the queue that have errors. Supported options are +:limit+ (default 50) and +:offset+ (default 0).
def errors(options = {})
limit = options[:limit] ? options[:limit].to_i : 50
Entry.errors(self, limit, options[:offset].to_i)
end
# Reset all entries in the queue to clear errors and set them to be indexed immediately.
def reset!
Entry.reset!(self)
end
# Process the queue. Exits when there are no more entries to process at the current time.
# Returns the number of entries processed.
#
# If any errors are encountered while processing the queue, they will be logged with the errors so they can
# be fixed and tried again later. However, if Solr is refusing connections, the processing is stopped right
# away and a Sunspot::IndexQueue::SolrNotResponding exception is raised.
def process
count = 0
loop do
entries = Entry.next_batch!(self)
if entries.nil? || entries.empty?
break if Entry.ready_count(self) == 0
else
batch = Batch.new(self, entries)
if defined?(@batch_handler) && @batch_handler
@batch_handler.call(batch)
else
batch.submit!
end
count += entries.select{|e| e.processed? }.size
end
end
count
end
private
# Get the class and id for either a record or a hash containing +:class+ and +:id+ options
def class_and_id(record_or_hash)
if record_or_hash.is_a?(Hash)
[record_or_hash[:class], record_or_hash[:id]]
else
[record_or_hash.class, Sunspot::Adapters::InstanceAdapter.adapt(record_or_hash).id]
end
end
end
end
| true |
9316412464b4ccd5a491ead1ba03792263cda84e | Ruby | ldlsegovia/organizer | /lib/organizer/source/collection.rb | UTF-8 | 551 | 2.625 | 3 | [
"MIT"
] | permissive | module Organizer
module Source
class Collection < Array
include Organizer::Error
include Organizer::Collection
include Organizer::Explainer
collectable_classes Organizer::Source::Item
def fill(_raw_collection)
raise_error(:invalid_collection_structure) unless _raw_collection.respond_to?(:each)
_raw_collection.inject(self) do |items, raw_item|
item = Organizer::Source::Item.new
item.define_attributes(raw_item)
items << item
end
end
end
end
end
| true |
24f1fee9949103e1a4aebcbd93ef7ecbdc26eb0f | Ruby | SudoEvrything/rubytuto | /the_odin_project/mastermind.rb | UTF-8 | 4,511 | 3.84375 | 4 | [] | no_license | class Mastermind
def initialize
@board = Board.new
@player = Player.new('Player', @board)
@computer = Computer.new('Computer', @board)
@current_player;
end
def start_game
loop do
puts "Which role do you want to play?"
puts "1. Codemaker 2. Codebreaker"
puts "Please select 1 or 2: "
@role = gets.chomp.to_i
break if @role == 1 || @role == 2
end
if @role == 1
@current_player = @computer
codemaker_mode
else
@current_player = @player
codebreaker_mode
end
end
def codebreaker_mode
instructions
@chances = 12
loop do
p @player.get_guess
p @board.give_clues(@player.guess)
chances_left
break if game_over?
end
end
def codemaker_mode
@board.secret = @player.make_code
@chances = 12
loop do
p @computer.make_guess(@board.clues)
p @board.give_clues_cpu(@computer.guess)
chances_left
break if game_over?
end
end
def instructions
puts "======================================="
puts "======= Welcome to Mastermind! ========"
puts "======================================="
puts "Your goal is to crack the secret code!"
puts "The secret code is 4 digits long. "
puts "The numbers are between 1-6 and can repeat."
puts "After each guess you will get some clues."
puts "'x' means right number and right spot."
puts "'o' means right number but wrong spot."
puts "You have a total of 12 chances."
puts "Have fun! :)"
end
def game_over?
victory? || out_of_chances?
end
def victory?
if @current_player.guess == @board.secret
puts '=== Congratulations, you won! ==='
true
end
end
def out_of_chances?
if @chances == 0
puts '=== Game Over! ==='
puts "The secret code was #{@board.secret}"
true
end
end
def chances_left
@chances -= 1
puts "You have #{@chances} chances left"
end
end
class Player
attr_reader :guess, :name
def initialize(name, board)
@name = name
@board = board
end
def get_guess
loop do
print "Enter a 4 digit number: "
@guess = gets.chomp
break if check_guess
end
print "Player guess: "
convert
end
def check_guess
if @guess.scan(/\D/).any?
puts "Numbers only. Please try again."
false
elsif @guess.length != 4
puts "4 digits only. Please try again."
false
elsif @guess.scan(/[^1-6]/).any?
puts "Only numbers between 1-6 are allowed."
false
else
true
end
end
def convert
converted = []
@guess = @guess.split('')
@guess.each { |x| converted << x.to_i }
@guess = converted
end
def make_code
loop do
print "Please enter a secret code: "
@guess = gets.chomp
break if check_guess
end
convert
end
end
class Computer
attr_reader :guess, :name
def initialize(name, board)
@name = name
@board = board
@guess = ['', '', '', '']
@garbage = [1,2,3,4,5,6]
end
def make_guess(clues)
@clues = clues
@guess.each_with_index do |num, index|
if @clues[index] == 'x'
next
elsif @clues[index] == '-'
@garbage -= [@guess[index]]
@guess[index] = @garbage.sample
else
@guess[index] = @garbage.sample
end
end
p @garbage
print "CPU guess: "
@guess
end
end
class Board
attr_accessor :secret, :clues
def initialize
@clues = ['-','-','-','-']
@secret = []
4.times do
@secret<< rand(1..6)
end
end
def give_clues(guess)
clues = []
remain = [0,1,2,3]
temp = []
guess.each_with_index do |num, index|
if num == @secret[index]
remain -= [index]
clues << 'x'
end
end
remain.each do |x|
temp << @secret[x]
end
remain.each do |x|
if temp.include?(guess[x])
clues << 'o'
end
end
print "Player clues: "
clues
end
def give_clues_cpu(guess)
@clues = []
remain = [0,1,2,3]
temp = []
guess.each_with_index do |num, index|
if num == @secret[index]
remain -= [index]
@clues[index] = 'x'
end
end
remain.each do |x|
temp << @secret[x]
end
remain.each do |x|
if temp.include?(guess[x])
@clues[x] = 'o'
else
@clues[x] = '-'
end
end
print "CPU clues: "
@clues
end
end
tt = Mastermind.new
tt.start_game | true |
ab09f552e1b4508604519086d3a13e93533c05f0 | Ruby | liaden/shokugeki | /spec/models/ingredient_graph_spec.rb | UTF-8 | 4,625 | 2.515625 | 3 | [] | no_license | describe IngredientGraph do
let(:graph) { IngredientGraph.new(search) }
let(:search) { build(:search_ingredient) }
let(:pair) { create(:ingredient_pairing, occurrences: 2) }
let(:zero_occurrence) { create(:ingredient_pairing, ingredients: [pair.first_ingredient, create(:ingredient, name: 'z')]) }
let(:hidden_edge) do
create(:ingredient_pairing, ingredients: [pair.first_ingredient, create(:ingredient, name: search.hidden_ingredient_names.first)])
end
describe "#edges" do
let(:search) { build(:search_ingredient, ingredients_csv: pair.first_ingredient.name) }
it "does not include zero occurrence pairings" do
zero_occurrence
expect(graph.edges).to_not include zero_occurrence
end
it "does not include unrelated pairings" do
unrelated_pairing = create(:ingredient_pairing)
expect(graph.edges).to_not include unrelated_pairing
end
it "does not include edges with hidden ingredients" do
hidden_edge
expect(graph.edges).to_not include hidden_edge
end
it "does not include edges below minimum_occurrences threshold" do
search.occurrences_minimum = 5
expect(graph.edges).to be_empty
end
context "including auxiliary edges" do
let(:searched_ingredient) { create(:ingredient, name: 'a.searched') }
let(:other1) { create(:ingredient, name: 'other1') }
let(:other2) { create(:ingredient, name: 'other2') }
let!(:pairing1) { create(:ingredient_pairing, occurrences: 1, ingredients: [searched_ingredient, other1]) }
let!(:pairing2) { create(:ingredient_pairing, occurrences: 1, ingredients: [searched_ingredient, other2]) }
let!(:auxiliary_edge) { create(:ingredient_pairing, occurrences: 2, ingredients: [other1, other2]) }
let(:search) { create(:search_ingredient, ingredients_csv: searched_ingredient.name, include_auxiliary_edges: true) }
it "includes qualify auxiliary edges" do
expect(graph.edges).to contain_exactly(pairing1, pairing2, auxiliary_edge)
end
it "does not include hidden ingredinets auxiliary edges" do
search.hidden_ingredients_csv = other2.name
expect(graph.edges).to_not include auxiliary_edge
end
it "does not include auxiliary edges with below minimum occurrences threshold" do
auxiliary_edge.update_attributes(occurrences: 0)
expect(graph.edges).to_not include auxiliary_edge
end
it "does not pick up dangling edges" do
dangling = create(:ingredient_pairing, occurrences: 1, ingredients: [other2, create(:ingredient)])
expect(graph.edges).to_not include dangling
end
end
end
describe "#edge_data" do
let(:search) { build(:search_ingredient, ingredients_csv: pair.first_ingredient.name) }
it "includes occurrences" do
expect(graph.edge_data.first[:occurrences]).to eq 2
end
it "includes source index" do
source_index = graph.edge_data.first[:source]
expect([0,1]).to include source_index
end
it "includes target index" do
target_index = graph.edge_data.first[:target]
expect([0,1]).to include target_index
end
end
describe "#nodes" do
let(:search) { build(:search_ingredient, ingredients_csv: pair.first_ingredient.name) }
let!(:unrelated) { create(:ingredient) }
it "includes searched ingredient and related ingredient only" do
expect(graph.nodes).to contain_exactly(*pair.ingredients)
end
it "does not include zero occurrence related nodes" do
zero_occurrence
expect(graph.nodes).to_not include zero_occurrence.second_ingredient
end
it "does not include hidden nodes" do
hidden_edge
hidden_node = Ingredient.find(search.hidden_ingredient_names.first)
expect(graph.nodes).to_not include hidden_node
end
end
describe "#node_data" do
let(:node) do
n = build(:ingredient)
allow(n).to receive(:recipes_count).and_return(2)
n
end
before { allow(graph).to receive(:nodes).and_return([node]) }
it "includes node's name" do
expect(graph.node_data.first[:name]).to eq node.name
end
it "flags searched ingredients" do
node.name = search.ingredient_names.first
expect(graph.node_data.first[:searched]).to eq true
end
it "flags unsearched ingredients" do
expect(graph.node_data.first[:searched]).to_not eq true
end
it "includes recipes count" do
expect(graph.node_data.first[:recipes_count]).to_not eq 0
expect(graph.node_data.first[:recipes_count]).to eq node.recipes_count
end
end
end | true |
2ffc225628a1a8b8177dfb7b16532bbba2010af9 | Ruby | iamjarvo/timelog | /features/step-definitions/timelog_steps.rb | UTF-8 | 208 | 2.921875 | 3 | [
"MIT"
] | permissive | require 'time'
Given /^the time is (\d+:\d+)$/ do |time|
@time = Time.parse(time)
end
Given /^(\d+) minutes has passed$/ do |minute_count|
seconds = minute_count.to_i * 60
@time = @time + seconds
end
| true |
c357863481d291ac824f1cbf890bed5e2aeab763 | Ruby | kenta-s/atcoder | /abc120/c02.rb | UTF-8 | 181 | 3.234375 | 3 | [] | no_license | s = gets.chomp.chars
stack = []
ans = 0
s.each do |c|
if stack.empty?
stack << c
elsif stack[-1] == c
stack << c
else
stack.pop
ans += 2
end
end
puts ans
| true |
4efc128bb58eaba5e681942af2d0b8a1e794c9ed | Ruby | sstelfox/patronus_fati | /lib/patronus_fati/event_handler.rb | UTF-8 | 806 | 2.671875 | 3 | [
"MIT"
] | permissive | module PatronusFati
class EventHandler
def handlers
@handlers ||= {}
end
def handlers_for(asset_type, event_type)
handlers[asset_type] ||= (asset_type == :any ? [] : {})
Array(handlers[:any]) | Array(handlers[asset_type][:any]) | Array(handlers[asset_type][event_type])
end
def on(asset_type, event_type = :any, &handler)
if asset_type == :any
handlers[:any] ||= []
handlers[:any].push(handler)
else
handlers[asset_type] ||= {}
handlers[asset_type][event_type] ||= []
handlers[asset_type][event_type].push(handler)
end
end
def event(asset_type, event_type, msg, optional = {})
handlers_for(asset_type, event_type).each { |h| h.call(asset_type, event_type, msg, optional) }
end
end
end
| true |
46a76b3c8bf871c8299c54177889d59f9acc5b8c | Ruby | konkit/konkit_worklogger | /lib/konkit_worklogger/printer.rb | UTF-8 | 1,398 | 3.515625 | 4 | [
"MIT"
] | permissive | class DaySummaryPrinter
def initialize(configuration)
@configuration = configuration
end
def print(year, month, day)
entry = DayEntryLoader.new(@configuration).load_from_file(year, month, day)
date_string = format('%d-%02d-%02d', year, month, day)
puts format('%s: %s - %s (%s)', date_string, entry.start_time, entry.end_time, entry.time_today)
end
end
class MonthSummaryPrinter
include Utils
def initialize(configuration)
@configuration = configuration
end
def print(year, month)
day_loader = DayEntryLoader.new(@configuration)
month_loader = MonthEntryLoader.new(day_loader)
entry = month_loader.load(year, month)
balance_with_carry = month_loader.balance_with_carry(year, month)
entry.day_entries.each do |day, minutes|
day_of_week_abbr = day_of_week(year, month, day)
puts format('%s %s - %s', day_of_week_abbr, day, minutes_to_time(minutes))
end
puts 'Days worked this month: %d' % entry.days_worked
puts format('Total count of work hours: %s/%s', minutes_to_time(entry.time_in_month), minutes_to_time(entry.days_worked * 8 * 60))
puts 'Balance in current month: %s ' % minutes_to_time(entry.month_balance)
puts 'Balance with carry in current month: %s ' % minutes_to_time(balance_with_carry)
end
def day_of_week(year, month, day)
Date.new(year, month, day).strftime('%A')[0..2]
end
end
| true |
3b96180b7ed6501b75696b510c0b31719813302b | Ruby | AviZurel/evigilo | /scrubber.rb | UTF-8 | 313 | 2.625 | 3 | [
"MIT"
] | permissive | class Scrubber
def initialize(app)
@app = app
end
def call(env)
scrub(env)
@app.call(env)
end
def scrub(env)
rack_input = env['rack.input'].read.force_encoding(Encoding::UTF_8)
env.update('rack.input' => StringIO.new(rack_input))
ensure
env['rack.input'].rewind
end
end
| true |
9433f064a700089cf9c34c030f18c9ddad795baf | Ruby | wulman16/sinatra-nested-forms-lab-superheros-atlanta-web-career-012819 | /app/models/team.rb | UTF-8 | 233 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Team
attr_reader :name, :motto
@@all = []
def initialize(name, motto)
@name = name
@motto = motto
@@all << self
end
def self.all
@@all
end
def members
Hero.all.select { |hero| hero.team == self }
end
end | true |
19a918d934e192d5cabf47ff06d41cf06e40cdd0 | Ruby | vprokopchuk256/algorithms | /spec/lib/algorithms/custom/lru_cache.rb | UTF-8 | 1,257 | 2.5625 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe Algorithms::Custom::LRUCache do
let(:capacity) { 2 }
subject(:cache) { described_class.new(capacity) }
describe '#initialize' do
its(:capacity) { is_expected.to eq(capacity) }
end
it 'ex1' do
cache.put(1, 1)
cache.put(2, 2)
expect(cache.get(1)).to eq(1)
cache.put(3, 3)
expect(cache.get(2)).to eq(-1)
cache.put(4, 4);
expect(cache.get(1)).to eq(-1)
expect(cache.get(3)).to eq(3)
expect(cache.get(4)).to eq(4)
end
it 'ex2' do
expect(cache.get(2)).to eq(-1)
cache.put(2, 6)
expect(cache.get(1)).to eq(-1)
cache.put(1, 5)
cache.put(1, 2)
expect(cache.get(1)).to eq(2)
expect(cache.get(2)).to eq(6)
end
context 'when capacity == 3' do
let(:capacity) { 3 }
it 'ex3' do
cache.put(1, 1)
cache.put(2, 2)
cache.put(3, 3)
cache.put(4, 4)
expect(cache.get(4)).to eq(4)
expect(cache.get(3)).to eq(3)
expect(cache.get(2)).to eq(2)
expect(cache.get(1)).to eq(-1)
cache.put(5, 5)
expect(cache.get(1)).to eq(-1)
expect(cache.get(2)).to eq(2)
expect(cache.get(3)).to eq(3)
expect(cache.get(4)).to eq(-1)
expect(cache.get(5)).to eq(5)
end
end
end
| true |
59811985b32ef481fe95b65d78c0282bb966267d | Ruby | takeshy/mongorilla | /lib/mongorilla/cursor.rb | UTF-8 | 895 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Mongorilla
class Cursor
include Enumerable
def [](idx)
if idx < 0
idx = @cursor.count + idx
return nil if idx < 0
else
return nil if idx >= @cursor.count
end
return @members[idx] if @members[idx]
ret = @cursor.skip(idx).limit(1).first
@cursor = @col.find(@cond,@opt)
@members[idx] = ret ? @klass.new(ret) : nil
end
def to_a
@cursor.map{|c| @klass.new(c)}
end
def to_yaml
to_a().map(&:to_hash).to_yaml
end
def to_json
to_a().map(&:to_hash).to_json
end
def each
@cursor.each do|v|
yield @klass.new(v)
end
end
def count
@cursor.count
end
def initialize(klass,cursor,col,cond,opt)
@members = {}
@klass = klass
@cursor = cursor
@col = col
@cond = cond
@opt = opt
end
end
end
| true |
a9194dd99e24f3c365714bcbe704d704a3235b30 | Ruby | luislaugga/bonekit | /examples/analog/potentiometer.rb | UTF-8 | 475 | 3.125 | 3 | [
"MIT"
] | permissive | # Potentiometer
#
# This example shows how to control the brightness of an LED using a potentiometer.
#
# The circuit:
# * LED with 180 ohm resistor attached from pin P9_42 to DGND.
# * Potentiometer attached to pin P9_39, VDD_ADC and GNDA_ADC.
#
require 'bonekit'
led = Pin.new P9_42 # LED connected to a pin that supports PWM
pot = Pin.new P9_39 # Potentiometer connected to an ADC pin
loop do
led.analog_value = pot.analog_value
sleep(0.01) # 100Hz refresh rate
end | true |
ee25172a0de93523894702606cd9291689ee0f1f | Ruby | christianreyes/272 | /notes/mp_lectures_2011/discounter/discounter_9.rb | UTF-8 | 1,331 | 3.234375 | 3 | [] | no_license | # discounter_9.rb
#
# Creating memoization writing a DSL in a block
# Based off original example by Dave Thomas (2008)
module Memoize
def remember(name, &block)
memory = Hash.new
define_method(name, &block)
meth = instance_method(name)
define_method(name) do |*args|
if memory.has_key?(args)
memory[args]
else
memory[args] = meth.bind(self).call(*args)
end
end
end
end
class Discounter
extend Memoize
remember :discount do |*skus|
expensive_discount_calculation(*skus)
end
private
def expensive_discount_calculation(*skus)
puts "Expensive calculation for #{skus.inspect}"
skus.inject {|m,n| m + n }
end
end
# TESTING
d = Discounter.new
puts d.discount(1,2,3)
puts d.discount(1,2,3)
puts d.discount(2,3,4)
puts d.discount(2,3,4)
puts
d1 = Discounter.new
puts d.discount(1,2,3)
puts
# BENCHMARKING
require 'benchmark'
n = 10000
Benchmark.bmbm do |bm|
bm.report("v9:") { n.times { d.discount(2,3,4) } }
end
# Rehearsal ---------------------------------------
# v9: 0.040000 0.000000 0.040000 ( 0.041687)
# ------------------------------ total: 0.040000sec
#
# user system total real
# v9: 0.040000 0.000000 0.040000 ( 0.040983) | true |
4c738b17810d3bca9da2c28c85771a7e1bdc836d | Ruby | dsisnero/power-panel | /lib/power/breaker.rb | UTF-8 | 1,338 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'virtus'
require File.join(File.dirname(__FILE__), 'slot')
module Power
class ABreaker
include Virtus
attribute :description, String
attribute :amps, Integer, :default => 20
def initialize(*args)
super(*args)
end
def to_array
[ number, description,amps]
end
end
class Breaker < ABreaker
include Virtus
attribute :slot, Slot
def breaker_hash
{ "brk_#{number}_amps" => amps,
"brk_#{number}_service" => description
}
end
def connect(slot)
slot.connect(self)
self[:slot] = slot
end
def slots
[slot]
end
def number
slot.number
end
def to_s
"[#{number}, #{description}, #{amps}]"
end
def remove
slot.remove_breaker
end
def doubled?
false
end
end
class DoubleBreaker < ABreaker
attribute :slot1, Slot
attribute :slot2, Slot
def number
[slot1.number, slot2.number]
end
def breaker_hash
slot1.breaker_hash.merge( slot2.breaker_hash)
end
def connect(s1,s2)
sorted_s1,sorted_s2 = [s1,s2].sort_by{|s| s.number}
sorted_s1.connect(self)
sorted_s2.connect(self)
self[:slot1] = sorted_s1
self[:slot2] = sorted_s2
end
def doubled?
true
end
end
end
| true |
d10b3414a0ce0649878564bd5b9d6255aadba4ad | Ruby | mattmanning/adventofcode2020 | /02/b.rb | UTF-8 | 304 | 3.203125 | 3 | [] | no_license | #!/usr/bin/env ruby
total = File.open('input').inject(0) do |sum, line|
cols = line.split(' ')
positions = cols[0].split('-').map(&:to_i)
letter = cols[1].split(':')[0]
if (cols[2][positions[0]-1] == letter) ^ (cols[2][positions[1]-1] == letter)
sum + 1
else
sum
end
end
puts total
| true |
03427b2d83b504722cfcfca27652e949e79aaae5 | Ruby | tommcgee/tictactoe_sinatra | /lib/presenters/message_presenter.rb | UTF-8 | 279 | 2.703125 | 3 | [] | no_license | require_relative '../sinatra_ui'
class MessagePresenter
@ui = Sinatra_UI.new
def self.get_status_message(board)
if board.over
@ui.print_winner(board)
else
@ui.print_player_turn
end
end
def self.get_games_completed()
@ui.print_games_completed()
end
end | true |
4586c409d5595997b73e48055cc083ff0858f103 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/word-count/5e854363948a468a96241e1703231f29.rb | UTF-8 | 319 | 3.46875 | 3 | [] | no_license | class Phrase
def initialize(text)
@text = text
end
def word_count
word_groups = parse_words.group_by{|x| x}
words_with_count = word_groups.map{|word, word_group| [word, word_group.length]}
Hash[words_with_count]
end
private
def parse_words
@text.scan(/\w+/).map(&:downcase)
end
end
| true |
294a0a8adf55445b3eaa10c817e9a24fcc22632a | Ruby | sarahhay7/ruby_talk_2019 | /csv_examples/blank_csv.rb | UTF-8 | 267 | 2.84375 | 3 | [] | no_license | require 'csv'
require 'fileutils'
FileUtils.touch('new_csv.csv')
puts "csv = CSV.open('new_csv.csv')"
csv = CSV.open('new_csv.csv')
puts "csv.class: #{csv.class}"
puts "csv.read: #{csv.read}"
puts "csv.read.class: #{csv.read.class}"
FileUtils.rm('new_csv.csv') | true |
c1d4a884aff8083b102b48b3e90d36b302985ddd | Ruby | Steveo00/launchschool | /ruby_basics/user_input/exercise_7.rb | UTF-8 | 330 | 3 | 3 | [] | no_license | USER_NAME = 'SteveO'
PASSWORD = 'plucker'
loop do
puts "Please enter your user name:"
user_name_response = gets.chomp
puts "Please enter your password:"
password_response = gets.chomp
break if ( user_name_response == USER_NAME ) && ( password_response == PASSWORD )
puts "Authorization failed."
end
puts "Welcome" | true |
1c436511a667edc0f64a75ca60d642a94dc51e28 | Ruby | ejbyne/ruby-mars-rovers | /spec/plateau_spec.rb | UTF-8 | 2,611 | 3.28125 | 3 | [] | no_license | require_relative '../app/models/plateau'
describe Plateau do
let(:plateau) { Plateau.new({ max_coords: '5 5', cell_class: cell_class }) }
let(:cell_class) { double :cell_class, new: cell }
let(:cell) { double :cell }
let(:rover) { double :rover }
context 'creating a grid' do
it 'does not allow missing or invalid coordinates' do
expect{ Plateau.new({ max_coords: '', cell_class: cell_class }) }.to raise_error('Invalid coordinates')
expect{ Plateau.new({ max_coords: '55', cell_class: cell_class }) }.to raise_error('Invalid coordinates')
end
it 'contains a grid according to the specified coordinates' do
expect(plateau.grid.count).to eq(36)
end
it 'has a cell for each coordinate' do
plateau.grid.each_value do |value|
expect(value).to eq(cell)
end
end
it 'knows the lengths of the x and y axes' do
expect(plateau.x_axis_length).to eq(6)
expect(plateau.y_axis_length).to eq(6)
end
it 'can split the grid values into rows' do
expect(plateau.split_grid_values_into_rows.length).to eq(6)
end
end
context 'placing rovers on the plateau' do
it 'allows a rover to be placed on a cell' do
coords = :'1 2'
expect(plateau.grid[coords]).to receive(:content=).with(rover)
plateau.place_rover(coords, rover)
end
it 'raises an error if the selected cell does not exist' do
expect{ plateau.place_rover(:'1 6', rover) }.to raise_error('Invalid coordinates')
end
end
context 'moving rovers on the plateau' do
it 'allows a rover to be moved to a different cell' do
start_coords = :'1 2'
end_coords = :'1 3'
expect(plateau.grid[end_coords]).to receive(:content)
expect(plateau.grid[start_coords]).to receive(:content=).with(nil)
expect(plateau.grid[end_coords]).to receive(:content=).with(rover)
plateau.move_rover(start_coords, end_coords, rover)
end
it 'raises an error if the rover tries to move outside the plateau' do
expect{ plateau.move_rover(:'1 5', :'1 6', rover) }.to raise_error('Cannot ' +
'move rover outside plateau. Rover stopped at coordinates 1 5')
end
it 'raises an error if the rover tries to move onto a cell occupied by another rover' do
end_coords = :'1 3'
allow(plateau.grid[end_coords]).to receive(:content).and_return(rover)
expect{ plateau.move_rover(:'1 2', end_coords, rover) }.to raise_error('Cannot move ' +
'rover onto cell occupied by another rover. Rover stopped at coordinates 1 2')
end
end
end
| true |
1bf2810e588dd4b7184c3e2800d6ff9102a592ce | Ruby | manbc/Ruby | /dfs.rb | UTF-8 | 1,376 | 3.765625 | 4 | [] | no_license | #depth first search implementation
$order = 0
def depth_first_search(matrix, vertices_array, vertex)
$order += 1
vertices_array[vertex] = $order
for i in 0...matrix.length
# if there is an edge and the vertex is not visited
if (matrix[vertex][i] == 1 && vertices_array[i] == 0)
depth_first_search(matrix, vertices_array, i)
end
end
end
#usage: can only be used after depth_first_search has been used
def display_order(vertices_hash)
vertices_hash.each { |key, value|
puts "Vertex #{key} was visited: #{value}"
}
end
#vertices: a b c d e f
ADJACENCY_MATRIX = [[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 1],
[1, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0],
[1, 1, 0, 0, 0, 1],
[0, 1, 1, 0, 1, 0]]
vertices = Hash.new(0)
for i in 0...6
vertices[i] = 0
end
vertices.each { |key, value|
if value == 0
depth_first_search(ADJACENCY_MATRIX, vertices, key)
end
}
display_order(vertices)
#a b c d
test_matrix = [[0,1,0,0],
[1,0,1,1],
[0,1,0,0],
[0,1,0,0]]
$order = 0
vertices2 = Hash.new(4)
for i in 0...4
vertices2[i] = 0
end
vertices2.each { |key, value|
if value == 0
depth_first_search(test_matrix, vertices2, key)
end
}
puts "Test Matrix"
display_order(vertices2)
| true |
9da00bdd63474b52a38a4e7170616464ddff0c11 | Ruby | aidanmc95/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-sea01-seng-ft-042020 | /nyc_pigeon_organizer.rb | UTF-8 | 426 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
pigeon_list = {}
data.each do |key1, value1|
value1.each do |key2, value2|
value2.each do |value3|
if pigeon_list[value3] == nil
pigeon_list[value3] = {}
end
if pigeon_list[value3][key1] == nil
pigeon_list[value3][key1] = []
end
pigeon_list[value3][key1].push(key2.to_s)
end
end
end
return pigeon_list
end
| true |
6351f8d09c9cb9fe8d1c8c98e0a447e68157e378 | Ruby | mizutaki/crawler | /chapter1/sbcr1.rb | UTF-8 | 396 | 2.78125 | 3 | [] | no_license | require 'cgi'
def parse(page_source)
dates = page_source.scan(%r!(\d+)年 ?(\d+)月 ?(\d+)日<br />!)
url_titles = page_source.scan(%r!^<a href="(.+?)">(.+?)</a><br />!)
url_titles.zip(dates).map{|(aurl, atitle),
ymd|[CGI.unescapeHTML(aurl),CGI.unescapeHTML(atitle),
Time.local(*ymd)]
}
end
x = parse(`/usr/local/bin/wget -q -O- http://crawler.sbcr.jp/samplepage.html`)
p x[0,1]
| true |
df399a8e8d47afa276e9f4b708e3eb4e20ead445 | Ruby | vecchp/sevenlanguages | /Ruby/Day 2/1.rb | UTF-8 | 305 | 3.9375 | 4 | [] | no_license | # Print the contents of an array. of sixteen numbers,
a = (1..16).to_a
## Four at a time, using just each.
tmp = []
a.each { |x|
tmp.push(x)
puts tmp.join(' '), tmp = [] if tmp.size % 4 == 0
}
puts tmp.join(' ') if tmp.size > 0
## With each_slice in Enumerable
a.each_slice(4){ |slice| p slice} | true |
fde57a58f8212d773fa14b88bedddb3776fa11a0 | Ruby | tmekkelisti/eventmanager | /app/models/event.rb | UTF-8 | 873 | 2.5625 | 3 | [] | no_license | class Event < ApplicationRecord
belongs_to :user
belongs_to :location
has_many :participations
has_many :participants, :through => :participations, :source => :user
has_many :comments, as: :commentable
validates :name, length: { minimum: 3 }
validates :description, length: { maximum: 500 }
validates :start_time, presence: true
validates :end_time, presence: true
validates :location_id, presence: true
validates :user_id, presence: true
validate :start_time_before_end_time
validate :start_time_in_past
def start_time_before_end_time
if self.start_time > self.end_time
errors.add(:start_time, " should be before end time")
end
end
def start_time_in_past
if self.start_time < DateTime.now
errors.add(:start_time, " can't be in the past")
end
end
def is_ended
self.end_time < DateTime.now
end
end
| true |
00c86e3eda66b09222331493c046a9991dcb74b8 | Ruby | l0v1s/yelp_clone | /spec/features/reviews_feature_spec.rb | UTF-8 | 911 | 2.609375 | 3 | [] | no_license | require 'rails_helper'
describe 'restaurant reviews' do
before do
Restaurant.create(name: "Wasabi", description: "Sushi and Asian food")
end
def leave_review(thoughts, rating)
visit '/restaurants'
click_link 'Add a review for Wasabi'
fill_in "review_thoughts", with: thoughts
select rating, :from => "review_rating"
click_button "Submit review"
end
it 'a user should be able to add a review for a restaurant' do
leave_review('The sushi is great but the tofu is awful', "4")
expect(current_path).to eq '/restaurants'
within('.show_review') do
expect(page).to have_content "The sushi is great but the tofu is awful"
expect(page).to have_content "4"
end
end
it 'displays an average rating for all reviews' do
leave_review('soso', '2')
leave_review('really soso', "4")
expect(page).to have_content("Average: ★★★☆☆")
end
end
| true |
7d9c8c38dffd6a306d5ed59b5bf7d6507b8e8d94 | Ruby | itggot-josef-andersson/master-ejaculator | /scenes/pause_scene.rb | UTF-8 | 570 | 2.6875 | 3 | [] | no_license | require_relative './scene'
require_relative '../handlers/game_handler'
require_relative '../enums/z_order'
require_relative '../enums/scene_id'
class PauseScene < Scene
def initialize
@font = Gosu::Font.new(25)
@keyboard_handler = GameHandler.get_instance.keyboard_handler
end
def update
return SceneID::GAME if @keyboard_handler.check_do_fast_press(key:Gosu::KbSpace)
SceneID::MENU if @keyboard_handler.check_do_fast_press(key:Gosu::KbEscape)
end
def draw
@font.draw('(space) to resume, (esc) to quit', 50, 50, ZOrder::GUI)
end
end | true |
35045b09f13b7379964a70778c78243212c78b0a | Ruby | jzaleski/hijack | /app/scripts/dragonrealms/juggle_script.rb | UTF-8 | 1,271 | 2.671875 | 3 | [] | no_license | load "#{SCRIPTS_DIR}/base/base_dragonrealms_script.rb", true
class JuggleScript < BaseDragonrealmsScript
ITS_EASIER_TO_JUGGLE = "It's easier to juggle"
YOU_CANNOT_JUGGLE = 'You cannot juggle'
YOU_TOSS = 'You toss'
JUGGLE_FAILURE_PATTERN = [
ITS_EASIER_TO_JUGGLE,
YOU_CANNOT_JUGGLE,
].join('|')
JUGGLE_PATTERN = [
ITS_EASIER_TO_JUGGLE,
YOU_CANNOT_JUGGLE,
YOU_TOSS,
].join('|')
def run
jugglies = @args[0] || config_jugglies
container = @args[1] || config_container
interloop_sleep_time = (config_interloop_sleep_time || 15.0).to_f
if open_my(container) && get_my(jugglies, container)
loop do
result = wait_for_match(
JUGGLE_PATTERN,
"juggle my #{jugglies}"
)
break if result.match(JUGGLE_FAILURE_PATTERN)
sleep interloop_sleep_time
end
end
store_my(jugglies, container)
close_my(container)
end
def validate_args
@args.length == 2 || (
config_jugglies.present? &&
config_container.present?
)
end
private
def config_container
@config[:juggle_container]
end
def config_interloop_sleep_time
@config[:juggle_interloop_sleep_time]
end
def config_jugglies
@config[:juggle_jugglies]
end
end
| true |
67aa339d4c9481b2185b726a506ab9fdf182e16b | Ruby | msgpack/msgpack-ruby | /spec/cruby/buffer_io_spec.rb | UTF-8 | 4,694 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'random_compat'
require 'stringio'
if defined?(Encoding)
Encoding.default_external = 'ASCII-8BIT'
end
describe Buffer do
r = Random.new
random_seed = r.seed
puts "buffer_io random seed: 0x#{random_seed.to_s(16)}"
let :source do
''
end
def set_source(s)
source.replace(s)
end
let :io do
StringIO.new(source.dup)
end
let :buffer do
Buffer.new(io)
end
it 'io returns internal io' do
buffer.io.should == io
end
it 'close closes internal io' do
expect(io).to receive(:close)
buffer.close
end
it 'short feed and read all' do
set_source 'aa'
buffer.read.should == 'aa'
end
it 'short feed and read short' do
set_source 'aa'
buffer.read(1).should == 'a'
buffer.read(1).should == 'a'
buffer.read(1).should == nil
end
it 'long feed and read all' do
set_source ' '*(1024*1024)
s = buffer.read
s.size.should == source.size
s.should == source
end
it 'long feed and read mixed' do
set_source ' '*(1024*1024)
buffer.read(10).should == source.slice!(0, 10)
buffer.read(10).should == source.slice!(0, 10)
buffer.read(10).should == source.slice!(0, 10)
s = buffer.read
s.size.should == source.size
s.should == source
end
it 'eof' do
set_source ''
buffer.read.should == ''
end
it 'eof 2' do
set_source 'a'
buffer.read.should == 'a'
buffer.read.should == ''
end
it 'write short once and flush' do
buffer.write('aa')
buffer.flush
io.string.should == 'aa'
end
it 'write short twice and flush' do
buffer.write('a')
buffer.write('a')
buffer.flush
io.string.should == 'aa'
end
it 'write long once and flush' do
s = ' '*(1024*1024)
buffer.write s
buffer.flush
io.string.size.should == s.size
io.string.should == s
end
it 'write short multi and flush' do
s = ' '*(1024*1024)
1024.times {
buffer.write ' '*1024
}
buffer.flush
io.string.size.should == s.size
io.string.should == s
end
it 'random read' do
r = Random.new(random_seed)
50.times {
fragments = []
r.rand(4).times do
n = r.rand(1024*1400)
s = r.bytes(n)
fragments << s
end
io = StringIO.new(fragments.join)
b = Buffer.new(io)
fragments.each {|s|
x = b.read(s.size)
x.size.should == s.size
x.should == s
}
b.empty?.should == true
b.read.should == ''
}
end
it 'random read_all' do
r = Random.new(random_seed)
50.times {
fragments = []
r.bytes(0)
r.rand(4).times do
n = r.rand(1024*1400)
s = r.bytes(n)
fragments << s
end
io = StringIO.new(fragments.join)
b = Buffer.new(io)
fragments.each {|s|
x = b.read_all(s.size)
x.size.should == s.size
x.should == s
}
b.empty?.should == true
lambda {
b.read_all(1)
}.should raise_error(EOFError)
}
end
it 'random skip' do
r = Random.new(random_seed)
50.times {
fragments = []
r.rand(4).times do
n = r.rand(1024*1400)
s = r.bytes(n)
fragments << s
end
io = StringIO.new(fragments.join)
b = Buffer.new(io)
fragments.each {|s|
b.skip(s.size).should == s.size
}
b.empty?.should == true
b.skip(1).should == 0
}
end
it 'random skip_all' do
r = Random.new(random_seed)
50.times {
fragments = []
r.rand(4).times do
n = r.rand(1024*1400)
s = r.bytes(n)
fragments << s
end
io = StringIO.new(fragments.join)
b = Buffer.new(io)
fragments.each {|s|
lambda {
b.skip_all(s.size)
}.should_not raise_error
}
b.empty?.should == true
lambda {
b.skip_all(1)
}.should raise_error(EOFError)
}
end
it 'random write and flush' do
r = Random.new(random_seed)
50.times {
s = r.bytes(0)
io = StringIO.new
b = Buffer.new(io)
r.rand(4).times do
n = r.rand(1024*1400)
x = r.bytes(n)
s << x
b.write(x)
end
(io.string.size + b.size).should == s.size
b.flush
io.string.size.should == s.size
io.string.should == s
}
end
it 'random write and clear' do
r = Random.new(random_seed)
b = Buffer.new
50.times {
s = r.bytes(0)
r.rand(4).times do
n = r.rand(1024*1400)
x = r.bytes(n)
s << x
b.write(x)
end
b.size.should == s.size
b.clear
}
end
end
| true |
93a84e2a2e59dd2d703f99ebfc4c61b179e403ed | Ruby | diegoarvz4/lexi-series | /app/helpers/series_helper.rb | UTF-8 | 251 | 2.625 | 3 | [
"MIT"
] | permissive | module SeriesHelper
def count_episodes(series)
series.episodes.all.count
end
def instructions(inst)
inst.gsub(/\s\s+/, "").split("+").reject{|n| n==""}
end
def sorted_episodes
@series.episodes.sort_by{|ep| ep.number}
end
end
| true |
140950477d7048a09cb4446b37e9e3c6f0c07d4d | Ruby | cgullickson/cg-cli-app | /lib/upcoming/concert.rb | UTF-8 | 365 | 2.8125 | 3 | [
"MIT"
] | permissive | require 'pry'
class Upcoming::Concert
attr_accessor :artist, :showtime, :price, :ticket_url, :location
@@all = []
def initialize(artist, showtime, price, ticket_url, location)
@artist = artist
@showtime = showtime
@price = price
@ticket_url = ticket_url
@location = location
@@all << self
end
def self.all
@@all
end
end
| true |
1db28a3a7d5608f8a22b2279f858e5bc63b7a794 | Ruby | jho406/dbc_anagrams | /app/controllers/index.rb | UTF-8 | 1,041 | 3.375 | 3 | [] | no_license | get '/' do
if params[:word]
# If we see a URL like /?word=apples redirect to /apples
#
# The HTTP status code 301 means "moved permanently"
# See: http://www.sinatrarb.com/intro#Browser%20Redirect
# http://en.wikipedia.org/wiki/HTTP_301
redirect to("/#{params[:word]}"), 301
else
# Look in app/views/index.erb
erb :index
end
end
get '/:word' do
@anagrams = Word.get_anagrams(params[:word])
erb :words
end
# Sinatra's get, post, put, etc. URL helpers match against the shape/form of a URL.
# That is,
#
# get '/:word' do
# ...
# end
#
# means "call this block any time we see a URL that looks like /<word>"
#
# The parts of a URL are separated by a /, so these match '/:word'
#
# /foo, /bar, /apple+pie, /four+score+and+seven+years+ago
#
# whereas these do not match '/:word'
#
# /, /word1/word2, /this/is/a/long/url, /articles/123
#
# This will bind whatever fits in the :word spot in the URL
# to params[:word], "as if" it were passed in via a query string
# like ?word=apples
| true |
eb96a93be9b7df86012c590a91ac0a0265baa978 | Ruby | alansparrow/learningruby | /classeval1.rb | UTF-8 | 460 | 3.546875 | 4 | [] | no_license | #!/usr/bin/env ruby
class Class
def add_accessor(accessor_name)
self.class_eval %Q{
attr_accessor :#{accessor_name}
}
end
end
class Person
end
person = Person.new
Person.add_accessor :name
Person.add_accessor :gender
person.name = "Peter Cooper"
person.gender = "male"
puts "#{person.name} is #{person.gender}"
class SomethingElse
add_accessor(:whatever)
end
my_object = SomethingElse.new
my_object.whatever = "asdas"
puts my_object.inspect
| true |
c8505db0f35b6ee4bcee4ca650b28d675428e0c1 | Ruby | scottcmerritt/custom_sort | /lib/custom_sort/magic.rb | UTF-8 | 1,980 | 2.546875 | 3 | [] | no_license | require "i18n"
module CustomSort
class Magic
attr_accessor :query_name, :options
def initialize(query_name:, **options)
@query_name = query_name
@options = options
end
def self.validate_period(period, permit)
permitted_periods = ((permit || CustomSort::FIELDS).map(&:to_sym) & CustomSort::FIELDS).map(&:to_s)
raise ArgumentError, "Unpermitted period" unless permitted_periods.include?(period.to_s)
end
class Enumerable < Magic
def sort_by(enum, &_block)
group = enum.group_by do |v|
v = yield(v)
raise ArgumentError, "Not a time" unless v.respond_to?(:to_time)
series_builder.round_time(v)
end
series_builder.generate(group, default_value: [], series_default: false)
end
def self.sort_by(enum, query_name, options, &block)
CustomSort::Magic::Enumerable.new(query_name: query_name, **options).group_by(enum, &block)
end
end
class Relation < Magic
def initialize(**options)
super(**options.reject { |k, _| [:default_value, :carry_forward, :last, :current].include?(k) })
@options = options
end
def self.generate_relation(relation, field:, **options)
magic = CustomSort::Magic::Relation.new(**options)
# generate ActiveRecord relation
relation =
RelationBuilder.new(
relation,
column: field,
query_name: magic.query_name
).generate
# add Groupdate info
#magic.group_index = relation.group_values.size - 1
#(relation.groupdate_values ||= []) << magic
relation
end
# allow any options to keep flexible for future
def self.process_result(relation, result, **options)
relation.customsort_values.reverse.each do |gv|
result = gv.perform(relation, result, default_value: options[:default_value])
end
result
end
end
end
end | true |
912b33895747b74b35483749349fc4916dfc9a86 | Ruby | srikanthgurram/TimeSheets | /db/seeds.rb | UTF-8 | 1,272 | 2.53125 | 3 | [] | no_license |
# Companies
if !(Company.count > 0)
Company.create(name: "Company ABC");
Company.create(name: "Company XYZ");
else
puts "Companies table is not Empty, skipping seed data"
end
# Clients
if !(Client.count > 0)
Client.create(name: "Client DE", company_id: Company.find_by(name: 'Company ABC').id);
Client.create(name: "Client PQ", company_id: Company.find_by(name: 'Company ABC').id);
else
puts "Clients table is not Empty, skipping seed data"
end
# Projects
if !(Project.count > 0)
Project.create(name: "Project A1", client_id: Client.find_by(name: 'Client DE').id);
Project.create(name: "Project B2", client_id: Client.find_by(name: 'Client DE').id);
else
puts "Projects table is not Empty, skipping seed data"
end
# Employee seed data
if !(Employee.count > 0)
Employee.create(name: "Employee E1", company_id: Company.find_by(name: 'Company ABC').id);
Employee.create(name: "Employee E2", company_id: Company.find_by(name: 'Company ABC').id);
else
puts "Employees table is not Empty, skipping seed data"
end
# # Works
# # Employee seed data
# if !(Work.count > 0)
# Work.create(name: "Employee E1", client_id: Client.find_by(name: 'Client DE'));
# Work.create(name: "Employee E2");
# else
# puts "Employees table is not Empty, skipping seed data"
| true |
95e6126afdd7410df130e11f421bfc0ca2a184d4 | Ruby | beauby/jsonapi-validations | /lib/jsonapi/validations/relationship.rb | UTF-8 | 1,949 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'jsonapi/parser'
module JSONAPI
module Validations
module Relationship
module_function
# Validate the types of related objects in a relationship update payload.
#
# @param [Hash] document The input JSONAPI document.
# @param [Hash] params Validation parameters.
# @option [Symbol] kind Whether it is a :has_many or :has_one.
# @option [Array<Symbol>] types Permitted types for the relationship.
# @raise [JSONAPI::Parser::InvalidDocument] if document is invalid.
def validate_relationship!(document, params = {})
JSONAPI.parse_relationship!(document)
validate_types!(document['data'], params[:types])
end
# @api private
def validate_types!(rel, rel_types, key = nil)
rel_name = key ? " #{key}" : ''
if rel_types[:kind] == :has_many
unless rel['data'].is_a?(Array)
raise JSONAPI::Parser::InvalidDocument,
"Expected relationship#{rel_name} to be has_many."
end
return unless rel_types[:types]
rel['data'].each do |ri|
next if rel_types[:types].include?(ri['type'].to_sym)
raise JSONAPI::Parser::InvalidDocument,
"Type mismatch for relationship#{rel_name}: " \
"#{ri['type']} should be one of #{rel_types}"
end
else
return if rel['data'].nil?
unless rel['data'].is_a?(Hash)
raise JSONAPI::Parser::InvalidDocument,
"Expected relationship#{rel_name} to be has_one."
end
return unless rel_types[:types]
ri = rel['data']
return if rel_types[:types].include?(ri['type'].to_sym)
raise JSONAPI::Parser::InvalidDocument,
"Type mismatch for relationship#{rel_name}: " \
"#{ri['type']} should be one of #{rel_types}"
end
end
end
end
end
| true |
2b037e589a22eb66cd212d66b28dbbac91407037 | Ruby | ekemi/school-domain-onl01-seng-ft-012120 | /lib/school.rb | UTF-8 | 646 | 3.359375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # code here!
require "pry"
class School
def initialize(name)
@name = name
@roster ={}
end
def roster
@roster
end
def add_student (student_name, student_grade)
@roster [student_grade] ||=[]
@roster[student_grade] << student_name
# binding.pry
end
def grade (level)
@roster.detect do |x,y|
if x == level
return y
end
end
end
require "pry"
def sort
nu = {}
@roster.each do |n,m|
nu[n]=m.sort
end
nu
end
end
#school = School.new #("Bayside High School") | true |
2726ab1a915c0632f05f5c5618f6de4a1c44f9d3 | Ruby | SethMusulin/Intro_to_tdd | /spec/num_calc_spec.rb | UTF-8 | 844 | 3.125 | 3 | [
"MIT"
] | permissive | require 'num_calc'
describe NumCalc do
it"has a method that returns the sum of two numbers" do
calc = NumCalc.new
expected = 3
actual = calc.add(2,1)
expect(actual).to eq expected
end
it" has a method that returns the difference of two numbers" do
calc = NumCalc.new
expected = 1
actual = calc.sub(2,1)
expect(actual).to eq expected
end
it "has a method that allows you to save a number to NumCalc's memory" do
calc = NumCalc.new
expected = 1
actual = calc.save(1)
expect(actual).to eq expected
end
it "has a method that clears NumCalc's memory" do
calc = NumCalc.new
expected = 0
actual = calc.clear
expect(actual).to eq expected
end
it "has a method that gets NumCalc's memory" do
calc = NumCalc.new
expect(calc.clear).to eq 0
end
end
| true |
e586c3216aa3f0fe5cd64fbfb01a46ef5279549a | Ruby | hai-nguyen1112/simple-math-dc-web-career-01719 | /lib/math.rb | UTF-8 | 533 | 3.359375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def addition(num1, num2)
return num1 + num2
end
addition(5, 4)
def subtraction(num1, num2)
return num1 - num2
end
subtraction(10, 5)
def division(num1, num2)
return num1 / num2
end
division(50, 2)
def multiplication(num1, num2)
return num1 * num2
end
multiplication(4, 30)
def modulo(num1, num2)
return num1 % num2
end
modulo(34, 5)
def square_root(num)
return Math.sqrt(num)
end
square_root(81)
def order_of_operation(num1, num2, num3, num4)
return num1 + ((num2 * num3) / num4)
end
order_of_operation(7, 43, 23, 83)
| true |
95e73b7ad0a73088e67d99ce56da291d7259a439 | Ruby | KirAbrosimov/RoR-BSU-2015 | /ruby0.1.rb | UTF-8 | 278 | 3.015625 | 3 | [] | no_license | file0 = File.open('animation0.txt')
file1 = File.open('animation1.txt')
file2 = File.open('animation2.txt')
animation = []
animation[0] = file0.to_a
animation[1] = file1.to_a
animation[2] = file2.to_a
loop do
animation.each do |print|
puts print
sleep 0.2
end
end
| true |
08de5f207f176cb42086a393f3d6d6f33e10a468 | Ruby | corydissinger/political-buzz | /app/models/api_request.rb | UTF-8 | 4,488 | 2.609375 | 3 | [] | no_license | require 'json'
require 'httparty'
class ApiRequest
$urlEngine = nil
def initialize
$urlEngine = UrlEngine.new
end
def getCategoryArticleHashForStatement(statement)
$troveResults = getTroveAnalysis(statement)
$entities = $troveResults['entities']['resolved']
$categoryUrlPairs = Hash.new
#TODO - Is it possible to parse NPR JSON less confusingly?
# Don't bash me for this until you try interpreting NPR json!
$entities.each do |entity|
$aTopic = entity['resource']['name']
$nprList = getNprArticles($aTopic)
$entityUrlArray = []
$nprList.each_pair do |story, val|
if isNprValueValid(val)
val['story'].each do |links|
$entityUrlArray << links['link'][0]['$text']
end
end
end
$categoryUrlPairs[$aTopic] = $entityUrlArray
end
return $categoryUrlPairs
end
def isNprValueValid(aVal)
if aVal.is_a? String or aVal.is_a? Array then
return false
elsif aVal.has_key?('story')
return true
else
return false
end
end
def getFirstStatementJson
$anUrl = $urlEngine.getFirstStatementListUrl
$jsonResult = getJson($anUrl)
return $jsonResult
end
def getIssueResults(anIssue)
$anUrl = $urlEngine.getUrlForIssue(anIssue)
$jsonResult = getJson($anUrl)
return $jsonResult
end
def getNextResults(nextUrl)
$anUrl = $urlEngine.getNextIssueUrl(nextUrl)
$jsonResult = getJson($anUrl)
return $jsonResult
end
def getNprArticles(entity)
entity.gsub!(/\s+/,'%20')
$nprUrl = $urlEngine.getNprArticlesUrl(entity)
$jsonResult = getJson($nprUrl)
return $jsonResult
end
def getTroveAnalysis(text)
$troveUrl = $urlEngine.troveAnalysis()
return getJsonByPost(text, $troveUrl)
end
def getStatementById(statementId)
$anUrl = $urlEngine.getStatementUrlById(statementId)
$jsonResult = getJson($anUrl)
return $jsonResult
end
def getJson(targetUrl)
url = URI.encode(targetUrl)
$redoCounter = 0
begin
response = HTTParty.get(url)
rescue Timeout::Error
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'Timed out for URL: ' + url
Rails.logger.info '-------END EXCEPTION--------'
rescue EOFError
if $redoCounter < 3
$redoCounter += 1
redo
else
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'EOFerror after 3 attempts on URL ' + url
Rails.logger.info '-------END EXCEPTION--------'
$redoCounter = 0
end
end
result = {}
begin
result = JSON.parse(response.body)
rescue Exception => e
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'Encountered following exception' + e
Rails.logger.info 'getJsonBy failed - The following input returned no parseable JSON'
Rails.logger.info url
Rails.logger.info '-------END EXCEPTION--------'
end
return result
end
def getJsonByPost(text, targetUrl)
url = URI.encode(targetUrl)
params = {'doc' => {'body' => text}.to_json}
begin
response = HTTParty.post(url,
:body => params)
rescue Timeout::Error
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'Timed out for post on URL ' + url
Rails.logger.info 'Text body was: ' + text
Rails.logger.info '-------END EXCEPTION--------'
rescue EOFError
if $redoCounter < 3
$redoCounter += 1
redo
else
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'EOFerror after 3 attempts on URL ' + url
Rails.logger.info '-------END EXCEPTION--------'
$redoCounter = 0
end
end
result = {}
begin
result = JSON.parse(response.body)
rescue Exception => e
Rails.logger.info '-------BEGIN EXCEPTION--------'
Rails.logger.info 'Encountered following exception' + e
Rails.logger.info 'getJsonByPost failed - The following input returned no parseable JSON'
Rails.logger.info url
Rails.logger.info text
Rails.logger.info '-------END EXCEPTION--------'
end
return result
end
end | true |
8810fa8022422c287e32cd87a2d06dcd60c0df52 | Ruby | chrisadames/introduction_to_programming | /flow_control/flow_control_exercises.rb | UTF-8 | 2,739 | 4.71875 | 5 | [] | no_license | # flow_control_exercises.rb
# 1. Write down whether the following expressions return true or false. Then type the expressions into irb to see the
# results.
(32 * 4) >= 129 # false
false != !true # false
true == 4 # false
false == (847 == '847') # true
(!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false # true
# 2. Write a method that takes a string as argument. The method should return a new, all-caps version of the string,
# only if the string is longer than 10 characters. Example: change "hello world" to "HELLO WORLD". (Hint: Ruby's String
# class has a few methods that would be helpful. Check the Ruby Docs!)
def a(string)
if string.length > 10
string.upcase
else
puts "string length is too short"
end
end
puts a("this is only a test")
# 3. Write a program that takes a number from the user between 0 and 100 and reports back whether the number is between
# 0 and 50, 51 and 100, or above 100.
puts "please enter a number between 0 - 100"
a = gets.chomp.to_i
answer = case
when a < 0
"please put a number more then zero"
when a < 51 && a > 0
"#{a} is a number between 0 and 50"
when a > 50 && a < 101
"#{a} is a number between 51 and 100"
else
"#{a} is a number higher then 100"
end
puts answer
# 4. What will each block of code below print to the screen? Write your answer on a piece of paper or in a text editor
# and then run each block of code to see if you were correct.
1. '4' == 4 ? puts("TRUE") : puts("FALSE") # puts("FALSE")
2. x = 2
if ((x * 3) / 2) == (4 + 4 - x - 3) # 3 = 3 Did you get it right?
puts "Did you get it right?"
else
puts "Did you?"
end
3. y = 9
x = 10
if (x + 1) <= (y)
puts "Alright."
elsif (x + 1) >= (y) # true, Alright now!
puts "Alright now!"
elsif (y + 1) == x
puts "ALRIGHT NOW!"
else
puts "Alrighty!"
end
# 5. Rewrite your program from exercise 3 using a case statement. Wrap this new case statement in a method and
# make sure it still works.
puts "please enter a number between 0 - 100"
a = gets.chomp.to_i
def answer(a)
answer = case
when a < 0
"please put a number more then zero"
when a < 51 && a > 0
"#{a} is a number between 0 and 50"
when a > 50 && a < 101
"#{a} is a number between 51 and 100"
else
"#{a} is a number higher then 100"
end
puts answer
end
answer(a)
# 6. When you run the following code...
def equal_to_four(x)
if x == 4
puts "yup"
else
puts "nope"
end
end
equal_to_four(5)
# You get the following error message..
# syntax error, unexpected end-of-input, expecting keyword_end
# Why do you get this error and how can you fix it? because we need to close/end the def equal_to_four. | true |
59706d47ac0b9307a065f43841c70dce9d96cdf0 | Ruby | scryptmouse/dux | /spec/support/blank_helpers.rb | UTF-8 | 1,837 | 2.640625 | 3 | [
"MIT"
] | permissive | module DuxTesting
module BlankHelpers
NOTHING = Object.new.freeze
module SpecMethods
def test_blankness_of(value: NOTHING, expectation:, description: nil, &block)
label =
if description.nil?
unless value.equal?(NOTHING)
"`#{value.inspect}`"
else
raise 'Provide a description when block is given'
end
else
description.to_s
end
specify(label) do
test_method(:blankish?, value: value, &block).to ( expectation ? be_truthy : be_falsey )
test_method(:presentish?, value: value, &block).to ( expectation ? be_falsey : be_truthy )
end
end
def blank_test(*args, &block)
value, description =
if args.length == 1 && block_given?
[NOTHING, args[0]]
elsif args.length == 1
[args[0], nil]
elsif args.length == 2
args
else
raise 'invalid args'
end
test_blankness_of(value: value, expectation: true, description: description, &block)
end
def presence_test(value, description = nil, &block)
test_blankness_of(value: value, expectation: false, description: description, &block)
end
end
module ExampleMethods
def test_method(method_name, value: NOTHING, &block)
actual_value =
unless value.equal?(NOTHING)
value
else
raise 'Must pass a block if value unspecified' unless block_given?
instance_eval(&block)
end
expect(Dux.__send__(method_name, actual_value))
end
end
end
end
RSpec.shared_context 'testing blankness' do
include DuxTesting::BlankHelpers::ExampleMethods
extend DuxTesting::BlankHelpers::SpecMethods
end
| true |
b5aee6c78182919aa1606112d51c78333d66a3e4 | Ruby | s11rikuya/worlder | /point_calculation.rb | UTF-8 | 947 | 2.921875 | 3 | [] | no_license | module PointCalculation
require 'json'
require 'open-uri'
DISTANCE_API = 'http://vldb.gsi.go.jp/sokuchi/surveycalc/surveycalc/bl2st_calc.pl?'.freeze
def distance(lat1, lng1, lat2, lng2)
req_params = {
outputType: 'json', # 出力タイプ
ellipsoid: 'bessel', # 楕円体
latitude1: lat1, # 出発点緯度
longitude1: lng1, # 出発点経度
latitude2: lat2, # 到着点緯度
longitude2: lng2 # 到着点経度
}
req_param = req_params.map { |k, v| "#{k}=#{v}" }.join('&')
result = JSON.parse(open(DISTANCE_API + req_param).read)
result['OutputData']['geoLength']
end
def calculation(range_indexes)
distanes = []
range_indexes.each_cons(2) do |a, b|
c = distance(a["lat"], a["lng"], b["lat"], b["lng"])
c = c.to_i
distanes.push(c)
end
sum_distance = distanes.inject(:+) / 1000
return sum_distance
end
end
| true |
fbe84c752a85b91e04cd310c2fe15c0170b14ece | Ruby | sdmalek44/date_night | /test/binary_search_test.rb | UTF-8 | 3,037 | 3.03125 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require './lib/binary_search.rb'
class BinarySearchTest < Minitest::Test
def test_if_it_exists
tree = BinarySearchTree.new
assert_instance_of BinarySearchTree, tree
end
def test_insert_and_include
tree = BinarySearchTree.new
assert_equal 0, tree.insert(88, 'movie', 0)
assert_equal 1, tree.insert(66, 'movie2', 0)
assert_equal 1, tree.insert(99, 'movie3', 0)
assert_equal 2, tree.insert(55, 'movie4', 0)
assert tree.include?(66)
refute tree.include?(44)
end
def test_depth_of
tree = BinarySearchTree.new
tree.insert(80, 'movie')
tree.insert(60, 'movie1')
tree.insert(40, 'movie2')
assert_equal 2, tree.depth_of(40)
assert_equal 1, tree.depth_of(60)
assert_nil tree.depth_of(50)
end
def test_max
tree = BinarySearchTree.new
tree.insert(88, 'movie', 0)
tree.insert(66, 'movie2', 0)
tree.insert(99, 'movie3', 0)
tree.insert(55, 'movie4', 0)
expected = {"movie3" => 99}
actual = tree.max
assert_equal expected, actual
end
def test_min
tree = BinarySearchTree.new
tree.insert(88, 'movie', 0)
tree.insert(26, 'movie2', 0)
tree.insert(90, 'movie3', 0)
tree.insert(55, 'movie4', 0)
expected = {"movie2" => 26}
actual = tree.min
assert_equal expected, actual
end
def test_sort
tree = BinarySearchTree.new
tree.insert(88, 'movie', 0)
tree.insert(26, 'movie2', 0)
tree.insert(90, 'movie3', 0)
tree.insert(55, 'movie4', 0)
expected = [{"movie2"=>26}, {"movie4"=>55}, {"movie"=>88}, {"movie3"=>90}]
actual = tree.sort
assert_equal expected, actual
end
def test_load
tree = BinarySearchTree.new
tree.load('./test/movies.txt')
assert tree.include?(41)
assert tree.include?(10)
assert_equal 6, tree.total_nodes
end
def test_health
tree = BinarySearchTree.new
tree.insert(45, "movie")
tree.insert(56, "movie2")
tree.insert(30, "movie4")
tree.insert(40, "movie2")
tree.insert(20, "movie2")
expected = [[45, 5, 100]]
actual = tree.health(0)
assert_equal expected, actual
expected_1 = [[30, 3, 60], [56, 1, 20]]
actual_1 = tree.health(1)
assert_equal expected_1, actual_1
end
def test_child_count
tree = BinarySearchTree.new
tree.insert(45, "movie")
tree.insert(40, "movie2")
tree.insert(30, "movie4")
tree.insert(42, "movie4")
expected = 4
actual = tree.child_count
assert_equal expected, actual
end
def test_leaves
tree = BinarySearchTree.new
tree.insert(45, "movie")
tree.insert(56, "movie2")
tree.insert(30, "movie4")
tree.insert(40, "movie2")
tree.insert(20, "movie2")
assert_equal 3, tree.leaves
end
def test_height
tree = BinarySearchTree.new
tree.insert(45, "movie")
tree.insert(56, "movie2")
tree.insert(30, "movie4")
tree.insert(40, "movie2")
tree.insert(20, "movie2")
assert_equal 2, tree.height
end
end
| true |
6c5cd3a829c65b2b6082e2ce410314736bdcb620 | Ruby | ahopkins94/battle2 | /app.rb | UTF-8 | 579 | 2.609375 | 3 | [] | no_license | require 'sinatra'
require_relative 'lib/player'
require_relative 'lib/game'
class Battle < Sinatra::Base
enable :sessions
before do
@game = Game.instance
end
get '/' do
erb(:index)
end
post '/names' do
player_1 = Player.new(params[:player_1])
player_2 = Player.new(params[:player_2])
@game = Game.create(player_1, player_2)
redirect '/play'
end
get '/play' do
erb(:play)
end
get '/hit_play' do
@game.attack(@game.player_2)
@game.switch_turns
redirect '/game_over' if @game.game_over?
erb(:hit_play)
end
get '/game_over' do
erb(:game_over)
end
end
| true |
54cc50cf64b7593f35fb4ebf89f4905cf86de3da | Ruby | drinkyouroj/domain-checker | /domain-checker.rb | UTF-8 | 727 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'whois'
input_list = ARGV.first
input_file = open(input_list)
input_file.each_line { |domain|
whois = Whois::Client.new(:timeout => 10)
record = whois.lookup(domain.downcase.chomp)
registrar_url = record.registrar.url
registrar_name = record.registrar.name
gd_url = false
gd_name = false
if registrar_url == nil then
# puts "#{domain.chomp} registrar has no URL."
elsif registrar_url.downcase =~ /.*godaddy.*/
gd_url = true
end
if registrar_name == nil then
# puts "#{domain.chomp} registrar has no name."
elsif registrar_name.downcase =~ /.*godaddy.*/
gd_name = true
end
if (gd_url || gd_name) then
puts "#{domain.chomp} registrar is GoDaddy."
end
}
input_file.close
| true |
ec152c17966eabc60e431d3e2be54bc9206ecde8 | Ruby | YSavir/TDD-tic-tac-toe | /spec/lib/tic_tac_toe/player_spec.rb | UTF-8 | 2,030 | 2.890625 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe TicTacToe::Player, :type => :model do
describe 'When initialized' do
describe 'as a human player' do
it 'should be human' do
player = build :human_player
expect(player.human?).to be true
end
end
describe 'as a computer player' do
it 'should not be human' do
player = build :computer_player
expect(player.human?).to be false
end
end
describe 'with \'X\' as a symbol' do
it 'should have \'X\' as a symbol' do
player = build :human_player
expect(player.symbol).to eq('X')
end
end
describe 'with \'☯\' as a symbol' do
it 'should have \'☯\' as a symbol' do
player = TicTacToe::Player.new('☯', true)
expect(player.symbol).to eq('☯')
end
end
end
describe '#choose_cell_from' do
describe 'when the player is a computer' do
it 'should pick a random cell' do
cells = build(:grid).cells
player = build :computer_player
expect(cells).to include(player.choose_cell_from(cells))
end
end
describe 'when the player is human' do
it 'should let the player pick a cell' do
grid = build :grid
available_cells = grid.available_cells
player = build :human_player
io_channel do |channel|
channel.set_input '1, 1'
expect(player.choose_cell_from(available_cells)).to be(grid[1,1])
end
end
it 'should continue to ask until the player picks a valid cell' do
grid = build :grid
player = build :human_player
output = io_channel do |channel|
channel.set_input '4, 4', 'some, gibberish', 'gibberish', '4', '2, 2'
player.choose_cell_from(grid.available_cells)
end
error_lines = output.select do |line|
line.match /Sorry, .* is not a valid cell/
end
expect(error_lines).to have_exactly(4).lines
end
end
end
end
| true |
bbe145155858e9a41a0b246ca152a2f5df5cec9c | Ruby | fastmezon/reconstructor | /spec/coef_calc_spec.rb | UTF-8 | 1,393 | 2.625 | 3 | [] | no_license | require 'spec_helper'
describe CoefCalc do
let(:wkt_reader) { Geos::WktReader.new}
describe '.gen_pixel' do
let(:pixel) { wkt_reader.read('POLYGON((0.5 0.5, 1.5 0.5, 1.5 1.5, 0.5 1.5, 0.5 0.5))') }
it { expect(subject).to respond_to(:gen_pixel).with(3).arguments }
it 'return correct pixel' do
expect(subject.gen_pixel(0.5,0.5,1)).to eq(pixel)
end
end
describe '.gen_scope' do
let(:polygon) { wkt_reader.read('POLYGON((1 -2, 0 -2, 0 2, 1 2, 1 -2))') }
it { expect(subject).to respond_to(:gen_scope).with(4).arguments }
it 'return correct polygon' do
expect(subject.gen_scope(0, -1, 2, Math::PI)).to be_almost_equals(polygon)
end
end
describe '.calc' do
let(:expected_result) { 0.75 }
let(:delta) { 0.0001 }
let(:xb) { 1 }
let(:yb) { 0 }
let(:s_xt) { 0 }
let(:s_xb) { 1 }
let(:h) { 1000 }
let(:f) { Math::PI*1.5+Math.asin(1/5**0.5) }
it { expect(subject).to respond_to(:calc).with(6).arguments }
it "return correct coefficient" do
result = subject.calc(xb,yb,s_xt,s_xb,h,f)
expect((subject.calc(xb,yb,s_xt,s_xb,h,f) - expected_result).abs < delta).to eql(true)
end
it 'return zero if no intersection' do
result = subject.calc(100,-10,s_xt,s_xb,h,f)
expect((subject.calc(xb,yb,s_xt,s_xb,h,f) - expected_result).abs < delta).to eql(true)
end
end
end
| true |
e63e0ff935d68d171033d2b3e87c72bc6a8bf935 | Ruby | samuelvary1/my-select-001-prework-web | /lib/my_select.rb | UTF-8 | 191 | 3.40625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_select(collection)
# your code here!
i = 0
selected_array = []
while collection[i]
selected_array << collection[i] if yield(collection[i])
i += 1
end
selected_array
end
| true |
605d2b49563305d581845b5b75f6c1d31f9dbd6c | Ruby | sienna-kopf/sweater_weather | /spec/services/map_quest_service_spec.rb | UTF-8 | 1,594 | 2.625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe MapQuestService do
context 'instance methods' do
context '#lat_long' do
it "takes in a location and transforms it into lat and long coordinates", :vcr do
location = "denver, co"
service = MapQuestService.new
response = service.lat_long(location)
expect(response).to be_a Hash
expect(response[:results]).to be_an Array
target_result = response[:results][0]
expect(target_result).to have_key :locations
expect(target_result[:locations]).to be_an Array
target_location = target_result[:locations][0]
expect(target_location).to have_key :latLng
expect(target_location[:latLng]).to have_key :lat
expect(target_location[:latLng]).to have_key :lng
expect(target_location[:latLng][:lat]).to be_a Float
expect(target_location[:latLng][:lng]).to be_a Float
expect(target_location[:latLng][:lat]).to eq(39.738453)
expect(target_location[:latLng][:lng]).to eq(-104.984853)
end
end
context '#road_trip' do
it "takes in origin and destination locations to determine the travel time between locations", :vcr do
origin = "denver, co"
destination = "pueblo, co"
service = MapQuestService.new
response = service.road_trip(origin, destination)
expect(response).to be_a Hash
expect(response[:route]).to be_a Hash
expect(response[:route]).to have_key :formattedTime
expect(response[:route][:formattedTime]).to be_a String
end
end
end
end
| true |
ac015b8403d5a1aec6b2152869bc376f22eed5d9 | Ruby | tquillin/main | /db/seeds.rb | UTF-8 | 313 | 2.53125 | 3 | [] | no_license | require 'csv'
puts 'Parsing File'
data = CSV.foreach('./School_Progress_Report_2010-2011.csv', headers: true).map do |row|
{
name: row['SCHOOL'],
admin: row['PRINCIPAL'],
level: row['SCHOOL LEVEL'],
grade: row['2010-2011 OVERALL GRADE']
}
end
puts 'Placing in Database'
Score.create(data);
| true |
1352a813719f5954b1d6e783cd42f43f5db4f394 | Ruby | NancyKo/age-facts | /lib/user.rb | UTF-8 | 254 | 2.890625 | 3 | [] | no_license | require 'open-uri'
class User
attr_accessor :day, :month, :year
def initialize(month, day, year)
@day = day
@year = year
@month = month
end
def birthday_trivia
open("http://numbersapi.com/#{@month}/#{@day}").read
end
end
| true |
39585c42a2bf8405285804a33e4f02a6e41229eb | Ruby | wtartanus/Hotel | /hotel_chain.rb | UTF-8 | 642 | 2.8125 | 3 | [] | no_license | #class Hotel_chain
class Hotel_chain
#shoudl have
#name #hotels
attr_accessor :name, :hotels
def initialize(name, hotels)
@name = name
@hotels = hotels
end
#methods
#check another hotels for room avability
def check_avabality
hotel_avability = []
for hotel in @hotels
hotel_avability << hotel.name
room_numbers = 0
for room in hotel.rooms
if room.booking_status[:status] == false && room.guest_in == ""
room_numbers += 1
end
end
hotel_avability << room_numbers
end
return hotel_avability
end
end
| true |
74d6df459001ed404e21c4cf5e2803910aa66c5a | Ruby | irocho/ruby | /rubitos/factorial.rb | UTF-8 | 286 | 2.921875 | 3 | [] | no_license | ################################
#
# openHPI
# Factorial dun número
#
# executar en vim como :!ruby %
# executar no terminal como ruby factorial.rb
# en Sublime Text con mazá B
#
###############################
#
def factorial(n)
n==0?1:n*factorial(n-1)
end
puts factorial(5)
| true |
e24ed96c90e6e39f041a6e95f0d7b2fea63cb9d4 | Ruby | nvenky/splay | /app/models/scenario.rb | UTF-8 | 1,382 | 2.96875 | 3 | [] | no_license | class Scenario
attr_accessor :side, :range, :market_type, :min_odds, :max_odds
def initialize(*h)
if h.length == 1 && h.first.kind_of?(Hash)
h.first.each { |k,v| send("#{k}=",v) }
end
end
def back?
@side == 'BACK'
end
def lay?
@side == 'LAY'
end
def lay_sp?
@side == 'LAY (SP)'
end
def size
@size
end
def size=(size)
@size = size.to_i
end
def position
@position
end
def position=(pos)
@position = pos.class == String ? pos.split(',').map{|p| p.strip.to_i - 1} : [pos.to_i - 1]
end
def positions(size)
@range.blank? ? position.select{|p| p < size} : positions_from_range(size)
end
def odds_in_range?(odds)
(min_odds.nil? || odds >= min_odds) && (max_odds.nil? || odds <= max_odds )
end
def min_odds=(odds)
@min_odds = odds.to_d unless odds.blank?
end
def max_odds=(odds)
@max_odds = odds.to_d unless odds.blank?
end
private
def positions_from_range(size)
if range == 'ALL'
(0..(size - 1)).to_a
elsif range == 'TOP 1/2'
(0..((size * 0.5).round - 1)).to_a
elsif range == 'BOTTOM 1/2'
((size * 0.5).round..size-1).to_a
elsif range == 'TOP 1/3'
(0..((size * 0.33).round - 1)).to_a
elsif range == 'BOTTOM 1/3'
((size * 0.66).round..size - 1).to_a
else
raise "UNKNOWN range: #{range}"
end
end
end
| true |
446e8c74d9f1c604e98b75a9553a23793106b3f6 | Ruby | mbrand12/t10 | /test/unit/thesaurus_test.rb | UTF-8 | 796 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class ThesaurusTest < Minitest::Test
def setup
@thesaurus = T10::Thesaurus
@sample_verbs = {
go: %i(go walk move),
look: %i(look stare glare fixate)
}
@sample_nouns = {
cat: %i(cat kitty tabby),
dragon: %i(dragon)
}
@sample_modifiers = {
}
T10::Thesaurus.add_words(@sample_verbs, @sample_nouns, @sample_modifiers)
end
def test_scan_woking_properly
text = "walk! dragon t@ab!by n,@ow!"
verbs, nouns, modifiers = @thesaurus.scan(text)
assert verbs, [:go]
assert nouns, [:cat,:dragon]
end
def test_scan_empty
text = "pat dog now!"
verbs, nouns, modifiers = @thesaurus.scan(text)
assert verbs, []
assert nouns, []
assert modifiers, [:no_words]
end
end
| true |
feedec8c979b4e53b07ee3931fe3ebf3c114d994 | Ruby | andrzejsliwa/cqrs-es-twitter-app | /lib/read_model/user.rb | UTF-8 | 392 | 2.546875 | 3 | [] | no_license | module ReadModel
class User
def initialize(redis)
@redis = redis
end
def handle_event(event)
case event
when Events::UserSignedUp
redis.hset("user:#{event.user_id}", :username, event.auth_info.username)
redis.hset("user:#{event.user_id}", :full_name, event.auth_info.full_name)
end
end
private
attr_reader :redis
end
end
| true |
631975e51ec302ed4a29ded9af3596709546df28 | Ruby | aiywatch/Robot-mock-test | /lib/battery.rb | UTF-8 | 182 | 2.84375 | 3 | [] | no_license | require_relative 'item'
class Battery < Item
NAME = 'Battery'
WEIGHT = 25
def initialize
super(NAME, WEIGHT)
end
def recharge(robot)
robot.recharged()
end
end | true |
58ff97ae3886c4444492b635d20b13986b75751a | Ruby | drbrain/AOC | /2018/02b.rb | UTF-8 | 938 | 3.328125 | 3 | [] | no_license | require_relative "../aoc"
test <<-INPUT, "fgij"
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
INPUT
##
# This implementation uses +catch+ and +throw+ to break out of nested blocks.
# Using +return+ requires a method. Extracting a method seemed like more work
# than indenting the code one level and wrapping it in +catch+.
#
# Originally the <code>id.select.with_index</code> used Array#zip, but I
# didn't like that I had to either record the matching characters as a
# side-effect in the comparison block, or repeat the work to get the matching
# letters of the ID.
input 2018, 2 do |ids|
ids = ids.lines.map { |id|
id.strip.chars
}
catch :done do
ids.each_with_index do |id, i|
((i + 1)...ids.length).each do |j|
other = ids[j]
common = id.select.with_index { |a, k|
a == other[k]
}
throw :done, common.join if common.length == id.length - 1
end
end
end
end
| true |
c8eb020adc2aa373e3ab2becb7c6fdcd5beaef9f | Ruby | davidqin/Note_archive | /ruby/fiber/producer_and_consumer.rb | UTF-8 | 365 | 3.203125 | 3 | [] | no_license | # coding: utf-8
require 'fiber'
def send(x)
Fiber.yield x
end
def receiver producer
producer.transfer
end
def producer
Fiber.new do
while true
x = gets.chomp
send(x)
end
end
end
def consumer(producer)
while true
x = receiver(producer)
break if x == 'quit'
puts x
end
end
if $0 == __FILE__
consumer(producer())
end
| true |
41a1b1616ced067eca1565f0625333515c08728e | Ruby | Suraj-Surendran/Fizz-Buzz | /main.rb | UTF-8 | 152 | 3.734375 | 4 | [] | no_license | #Fizz Buzz
for i in 1..100
if i%3==0 && i%5==0
puts "Fizz Buzz"
elsif i%3==0
puts "Fizz"
elsif i%5==0
puts "Buzz"
else
puts "#{i}"
end
end | true |
ff0070db767297792c1c0868802ef0ac2a5552b6 | Ruby | schadenfred/handsome_fencer-crypto | /lib/handsome_fencer/crypto.rb | UTF-8 | 2,241 | 2.796875 | 3 | [
"MIT"
] | permissive |
require "handsome_fencer/crypto/version"
require "openssl"
require "base64"
module HandsomeFencer::Crypto
class << self
def generate_key
@cipher = OpenSSL::Cipher.new 'AES-128-CBC'
@salt = '8 octets'
@new_key = @cipher.random_key
Base64.encode64(@new_key)
end
def write_to_file(data, filename)
File.open(filename, "w") { |io| io.write data }
end
def generate_key_file(directory, environment)
write_to_file(generate_key, directory + "/" + environment + ".key")
end
def source_files(directory=nil, extension=nil)
Dir.glob(directory + "/**/*#{extension}")
end
def build_cipher(environment)
@cipher = OpenSSL::Cipher.new 'AES-128-CBC'
@salt = '8 octets'
@pass_phrase = get_key(environment)
@cipher.encrypt.pkcs5_keyivgen @pass_phrase, @salt
end
def encrypt(file, environment=nil)
environment ||= file.split('.')[-2].split('/').last
build_cipher(environment)
encrypted = @cipher.update(File.read file) + @cipher.final
write_to_file(Base64.encode64(encrypted), file + '.enc')
end
def decrypt(file, environment=nil)
environment ||= file.split('.')[-3].split('/').last
build_cipher(environment)
encrypted = Base64.decode64 File.read(file)
@cipher.decrypt.pkcs5_keyivgen @pass_phrase, @salt
decrypted = @cipher.update(encrypted) + @cipher.final
decrypted_file = file.split('.enc').first
write_to_file decrypted, decrypted_file
end
def obfuscate(env=nil, dir=nil, ext=nil)
ext = ext || "#{env}.env"
source_files(dir, ext).each { |file| encrypt(file, env) }
end
def expose(env=nil, dir=nil, ext=nil)
ext = ext || "#{env}.env.enc"
source_files(dir, ext).each { |file| decrypt(file, env) }
end
def get_key(environment, directory=nil)
env_key = environment.upcase + '_KEY'
key_file = source_files('./.', "#{directory}/#{environment}.key").first
case
when ENV[env_key].nil? && key_file.nil?
raise DeployKeyError, "No #{env_key} set."
when ENV[env_key]
ENV[env_key]
when File.exist?(key_file)
File.read(key_file).strip
end
end
end
end
| true |
b14f5c794bcb0c0da36cb518aa401003c092c770 | Ruby | kivanio/brcobranca | /lib/brcobranca/boleto/credisis.rb | UTF-8 | 4,462 | 3.015625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | # frozen_string_literal: true
module Brcobranca
module Boleto
# CrediSIS
class Credisis < Base
validates_length_of :agencia, maximum: 4, message: 'deve ser menor ou igual a 4 dígitos.'
validates_length_of :conta_corrente, maximum: 7, message: 'deve ser menor ou igual a 7 dígitos.'
validates_length_of :carteira, is: 2, message: 'deve ser menor ou igual a 2 dígitos.'
validates_length_of :convenio, is: 6, message: 'deve ser menor ou igual a 6 dígitos.'
validates_length_of :nosso_numero, maximum: 6, message: 'deve ser menor ou igual a 6 dígitos.'
validates_presence_of :documento_cedente, message: 'não pode estar em branco.'
validates_numericality_of :documento_cedente, message: 'não é um número.'
# Nova instancia do CrediSIS
# @param (see Brcobranca::Boleto::Base#initialize)
def initialize(campos = {})
campos = { carteira: '18' }.merge!(campos)
super(campos)
end
# Codigo do banco emissor (3 dígitos sempre)
#
# @return [String] 3 caracteres numéricos.
def banco
'097'
end
# Carteira
# @return [String] 2 caracteres numéricos.
def carteira=(valor)
@carteira = valor.to_s.rjust(2, '0') if valor
end
# Dígito verificador do banco
#
# @return [String] 1 caracteres numéricos.
def banco_dv
'3'
end
# Retorna dígito verificador da agência
#
# @return [String] 1 caracteres numéricos.
def agencia_dv
agencia.modulo11(mapeamento: { 10 => 'X' })
end
# Conta corrente
# @return [String] 7 caracteres numéricos.
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(7, '0') if valor
end
# Número do convênio/contrato do cliente junto ao banco.
# @return [String] 6 caracteres numéricos.
def convenio=(valor)
@convenio = valor.to_s.rjust(6, '0') if valor
end
# Dígito verificador da conta corrente
# @return [String] 1 caracteres numéricos.
def conta_corrente_dv
conta_corrente.modulo11(mapeamento: { 10 => 'X' })
end
# Nosso número
# @return [String] 6 caracteres numéricos.
def nosso_numero=(valor)
@nosso_numero = valor.to_s.rjust(6, '0')
end
# Nosso número para exibir no boleto.
# @return [String]
# @example
# boleto.nosso_numero_boleto #=> "10000000027000095-7"
def nosso_numero_boleto
"097#{documento_cedente_dv}#{agencia}#{convenio}#{nosso_numero}"
end
# Agência + conta corrente do cliente para exibir no boleto.
# @return [String]
# @example
# boleto.agencia_conta_boleto #=> "0001-9 / 0000002-7"
def agencia_conta_boleto
"#{agencia}-#{agencia_dv} / #{conta_corrente}-#{conta_corrente_dv}"
end
# X – Módulo 11 do CPF/CNPJ (incluindo dígitos verificadores) do Beneficiário emissor
# Obs.: Caso for CPF, utilizar 9 como limitador da multiplicação.
# Caso for CNPJ, utilizar 8 no limitador da multiplicação.
def documento_cedente_dv
options = { mapeamento: { 0 => 1, 10 => 1, 11 => 1 } }
options.merge(multiplicador: [8, 7, 6, 5, 4, 3, 2]) if documento_cedente.to_s.size > 11
documento_cedente.modulo11(options)
end
# Segunda parte do código de barras.
# @return [String] 25 caracteres numéricos.
# 1. - Número do Banco: “097”
# 2. - Moeda: “9”
# 3. - DV do Código de Barras, Baseado no Módulo 11 (Vide Anexo X).
# 4. - Fator de Vencimento do Boleto (Vide Anexo VII).
# 5. - Valor do Título, expresso em Reais, com 02 casas decimais.
# 6. - Fixo Zeros: Campo com preenchimento Zerado “00000”
# 7. - Composição do Nosso Número: 097XAAAACCCCCCSSSSSS, sendo:
# Composição do Nosso Número
# 097 - Fixo
# X - Módulo 11 do CPF/CNPJ (Incluindo dígitos verificadores) do Beneficiário.
# AAAA - Código da Agência CrediSIS ao qual o Beneficiário possui Conta.
# CCCCCC - Código de Convênio do Beneficiário no Sistema CrediSIS
# SSSSSS - Sequencial Único do Boleto
def codigo_barras_segunda_parte
"00000097#{documento_cedente_dv}#{agencia}#{convenio}#{nosso_numero}"
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.