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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b67cc1bb85a9100effd4fab582c128e28dc29af0 | Ruby | Superbuddha/bus-stop-lab | /specs/bus_stop_spec.rb | UTF-8 | 590 | 3.015625 | 3 | [] | no_license | require("minitest/autorun")
require("minitest/rg")
require_relative("../bus_stop.rb")
require_relative("../person.rb")
class BusStopTest <MiniTest::Test
def setup()
@stop = BusStop.new("Buchanan Terminal")
@passenger1 = Person.new("Mark", 37)
@passenger2 = Person.new("Joanna", 32)
@Passenger3 = Person.new("Dean", 22)
end
def test_stop_has_name
assert_equal("Buchanan Terminal", @stop.name())
end
def test_stop_starts_empty
assert_equal(0, @stop.queue_count)
end
def test_add_person_to_queue
@stop.add_passenger(@passenger1)
assert_equal(1, @stop.queue_count)
end
end
| true |
f0f4c0e9d106d936c266a593b3514ea44da36e6a | Ruby | detonih/oneBitCode_ruby_puro | /chamadas_web/web_get_google.rb | UTF-8 | 251 | 3.140625 | 3 | [] | no_license | require 'net/http'
# Chama module Net classe HTTP metodo get
google = Net::HTTP.get('www.google.com', '/')
# Se não existir o arquivo sera criado. 'w' sobrescreve o conteudo do arquivo
File.open('google.html', 'w') do |line|
line.puts(google)
end | true |
8b235f9cff55dc9b46f52eefd733c494b88a2d69 | Ruby | Diazc1/cocktails | /lib/cli.rb | UTF-8 | 1,877 | 3.46875 | 3 | [
"MIT"
] | permissive | class CLI
def initialize
API.new.get_margarita_data
end
def start
greeting
menu
end
def user_input
gets.strip
end
def menu
selection = user_input
if selection == "margarita"
margaritas_list
menu
elsif selection == "continue"
margaritas_list
menu
elsif selection == "exit"
goodbye
else
invalid_entry
menu
end
end
def greeting
puts "**********************************************"
puts "Welcome to the 'Make Your Own Margarita Bar'!"
puts "**********************************************"
puts " "
puts "To see available margaritas, enter 'margarita'"
puts " "
end
def margaritas_list
puts "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~"
Margarita.all.each.with_index(1) do |margarita, index|
puts "#{index}. #{margarita.strDrink}"
end
margarita_instructions_selection
end
def margarita_instructions_selection
puts "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ "
puts "Which margarita would you like the instructions for?"
puts " "
selection = user_input
margarita = Margarita.find_margarita(selection)
margarita_instructions(margarita)
end
def margarita_instructions(margarita)
puts " ∨∨∨ "
puts "Instructions: #{margarita.strInstructions}"
puts "ENJOY! :D"
puts " "
puts " "
puts "To make another selection, enter 'continue'"
puts "or to exit menu enter 'exit'"
end
def invalid_entry
puts "Invalid entry, try again"
end
def goodbye
puts "Don't drink and drive! Goodbye."
end
end | true |
2d25cc534a1a79f83c1bd811be50a94eeff4639a | Ruby | fishcereal/programming-univbasics-nds-nds-to-insight-with-methods-atlanta-web-010620 | /lib/nds_extract.rb | UTF-8 | 886 | 3.515625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'directors_database'
# Write a method that, given an NDS creates a new Hash
# The return value should be like:
#
# { directorOne => allTheMoneyTheyMade, ... }
def directors_totals(nds)
# p nds[:movies]
result = {}
nil
# start outside loop
counter = 0
while counter < nds.length do
total = 0
# p 'blah blah blah'
total = gross_for_director(nds[counter])
p total
result.store(nds[counter][:name],total)
counter+=1
end
return result
end
# Find a way to accumulate the :worldwide_grosses and return that Integer
# using director_data as input
def gross_for_director(director_data)
# pp director_data
result = {}
nil
counter = 0
total = 0
while counter < director_data[:movies].length do
total += director_data[:movies][counter][:worldwide_gross]
counter +=1
end
return total
end
| true |
5df9baf092727a7fe4f098aa39f8ad00369ca657 | Ruby | AliZainoul/mini_jeu_POO | /app1.rb | UTF-8 | 1,821 | 3.328125 | 3 | [] | no_license | require 'bundler'
Bundler.require
require_relative 'lib/game'
require_relative 'lib/player'
#binding.pry
puts "------------------------------------------------
|Bienvenue sur 'ILS VEULENT TOUS MA POO' ! |
|Le but du jeu est d'être le dernier survivant !|
-------------------------------------------------"
puts "Veuillez entrer votre prénom ou pseudo: \n"
puts ">"
var = gets.chomp
player = HumanPlayer.new(var)
array = []
player1 = Player.new ("Josiane")
puts "#{player1.name}"
array << player1
player2 = Player.new ("José")
puts "#{player2.name}"
array << player2
puts "#{array}"
while player.life_points > 0 && (player1.life_points > 0 || player2.life_points > 0)
puts player.show_state
puts "Quelle action voulez-vous effectuer ?"
print "a - chercher une meilleure arme ? \n"
print "s - chercher a se soigner ? \n"
print "\n"
puts "Attaquer un joueur en vue : "
print "0 - #{player1.name} a #{player1.life_points} points de vie. \n"
print "1 - #{player2.name} a #{player2.life_points} points de vie. \n"
print ">"
varr = gets.chomp.to_s
case varr
when "a"
player.search_weapon
when "s"
player.search_health_pack
when "0"
player.attacks(player1)
when "1"
player.attacks(player2)
end
if player1.life_points > 0 || player2.life_points > 0
puts "Les autres joueurs vous attaquent ! \n"
end
array.each do |x|
if x.life_points == 0
then
break
elsif x.life_points == 0
break
else
if player.life_points == 0
then
break
else x.attacks(player)
end
end
end
end
if player.life_points > 0
then
puts "Le jeu est fini, vous en ressortez gagnant! Félicitations !! :)."
else
puts "Le jeu est fini, boom boom boom, malheuresement pour vous, vous aviez perdu. Réessayez encore. :) "
end
| true |
85eed88df136c78ccd6a2c310105813e160c1cda | Ruby | pironim/yummy_mummy | /lib/tasks/compare_yml.rake | UTF-8 | 1,221 | 2.828125 | 3 | [] | no_license | # https://gist.github.com/dommmel/7da6ee376866771c7514
desc "Compare two yml files: bundle exec rake compare_yml['coc/en','coc/pl']"
task :compare_yml, [:locale1, :locale2] => :environment do |t, args|
LOCALE_1 = "config/locales/#{args[:locale1]}.yml"
LOCALE_2 = "config/locales/#{args[:locale2]}.yml"
require 'yaml'
def flatten_keys(hash, prefix="")
keys = []
hash.keys.each do |key|
if hash[key].is_a? Hash
current_prefix = prefix + "#{key}."
keys << flatten_keys(hash[key], current_prefix)
else
keys << "#{prefix}#{key}"
end
end
prefix == "" ? keys.flatten : keys
end
def compare(locale_1, locale_2)
yaml_1 = YAML.load(File.open(File.expand_path(locale_1)))
yaml_2 = YAML.load(File.open(File.expand_path(locale_2)))
keys_1 = flatten_keys(yaml_1[yaml_1.keys.first])
keys_2 = flatten_keys(yaml_2[yaml_2.keys.first])
missing = keys_2 - keys_1
file = locale_1.split('/').last
if missing.any?
puts "Missing for #{file} vs #{locale_2} :"
missing.each { |key| puts " - #{key}" }
exit(1) # error for CI
else
puts "Nothing missing for #{file}."
end
end
compare(LOCALE_1, LOCALE_2)
end
| true |
e6cf1838a063f5d370eb99898ee2066aaf48a1cb | Ruby | devacademyla/ruby-ejemplos | /fundamentos/06-hashes.rb | UTF-8 | 1,681 | 3.546875 | 4 | [] | no_license | # Los hashes son diccionarios de datos donde se tiene una llave y un valor.
# Un hash puede declararse asi:
comunidades = Hash.new {}
# Tambien existe esta otra forma:
comunidad_anillo = Hash[ :elfo, 'Legolas' , :mago, 'Gandalf' , :enano, 'Gimli' ]
# Otra manera de declarar es la siguiente:
comunidad_anillo = Hash[ :elfo => 'Legolas' , :mago => 'Gandalf' , :enano => 'Gimli' ]
# La mas facil es asi
comunidad_anillo = { :elfo => 'Legolas' , :mago => 'Gandalf' , :enano => 'Gimli' }
# Para saber cuanto mide el hash hacemos lo siguiente:
puts 'La medida del hash es :'
puts comunidad_anillo.size
# Para ver un personaje de la comunidad se escribe la llave.
puts 'Imprimiendo a un personaje'
puts comunidad_anillo[:elfo]
# Para imprimir las llaves y elementos del hash es el siguientes.
puts 'Imprimiendo todo el hash,'
puts comunidad_anillo
# Para imprimir a todos los elementos del hash es el siguientes.
puts 'Imprimiendo solo los valores del hash'
puts comunidad_anillo.values
# Imprimiremos el la llave que contiene al valor.
puts 'Imprimiendo la llave del valor'
puts comunidad_anillo.key('Legolas')
# Como a esta comunidad le falta un hobbit y un humano lo agregaremos
comunidad_anillo.update( :hobbit => 'Frodo', :humano => 'Aragorn' )
puts 'Imprimiendo valores del hash para comprobar insercion'
puts comunidad_anillo.values
# Tambien se puede hacer actualizacion de elementos
comunidad_anillo.update( :elfo => 'Tauriel' )
puts 'Imprimiendo valores del hash para comprobar actualizacion'
puts comunidad_anillo.values
# POr ultimo borraremos al elfo
comunidad_anillo.delete(:elfo)
puts 'Imprimiendo valores del hash para comprobar eliminacion'
puts comunidad_anillo.values
| true |
b9c0cf759ba17fe767863e17aef3302f8f9437cc | Ruby | elmward/adventofcode2020 | /6/part2.rb | UTF-8 | 278 | 2.96875 | 3 | [] | no_license | def count_answers(group)
group.join.chars.group_by { |answer| answer }.count { |_, answers| answers.count == group.count }
end
def main
puts(File.foreach('./input.txt', "\n\n").map do |group|
count_answers(group.split)
end.sum)
end
main if __FILE__ == $PROGRAM_NAME
| true |
75b5dc792d3907aa1cf21305bb326d2ccbde5976 | Ruby | vkurnavenkov/algorithms | /data-structures/lru_cache.rb | UTF-8 | 2,111 | 3.765625 | 4 | [] | no_license | Node = Struct.new(:key, :value, :next, :prev)
class LRUCache
=begin
:type capacity: Integer
=end
def initialize(capacity)
@capacity = capacity
@size = 0
@data = {}
@head = nil
@tail = nil
end
=begin
:type key: Integer
:rtype: Integer
=end
def get(key)
return -1 unless @data[key]
node = @data[key]
extract(node)
add_to_head(node)
node.value
end
=begin
:type key: Integer
:type value: Integer
:rtype: Void
=end
def put(key, value)
if @data[key]
node = @data[key]
extract(node)
add_to_head(node)
else
if @capacity <= @size
@data.delete(@tail.key)
extract(@tail)
@size -= 1
end
node = Node.new(key, value)
@data[key] = add_to_head(node)
@size += 1
end
node.value = value
end
private
def extract(node)
return nil unless node
if node.next
node.next.prev = node.prev
else
@tail = node.prev
end
if node.prev
node.prev.next = node.next
else
@head = node.next
end
# puts "extracted #{node.value}"
@head
end
def add_to_head(node)
return nil unless node
node.next = @head
node.prev = nil
if @head
@head.prev = node
else
@tail = node
end
# puts "added #{node.value}"
@head = node
end
end
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache.new(capacity)
# param_1 = obj.get(key)
# obj.put(key, value)
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
| true |
cde93df27db210a71e7cd89332b81ae8c198c36f | Ruby | Srjordao/One-Bit-Code | /Aula7/Animal/app.rb | UTF-8 | 217 | 2.734375 | 3 | [] | no_license | require_relative 'animal'
require_relative 'cachorro'
puts "-- Animal---"
animal = Animal.new
animal.pular
animal.dormir
puts "---Cachorro---"
cachorro = Cachorro.new
cachorro.pular
cachorro.dormir
cachorro.latir | true |
59562775def2b25565d8bb07018c0e85cdfbd629 | Ruby | jarosser06/netapp | /spec/netapp_volume_spec.rb | UTF-8 | 1,086 | 2.890625 | 3 | [
"MIT"
] | permissive | require_relative '../lib/netapp.rb'
describe NetApp::Volume do
before :each do
@volume = NetApp::Volume.new("test_vol", 419430400, 209715200, 629145600)
end
describe "#new" do
it "creates a new volume object" do
@volume.class.should == NetApp::Volume
end
end
describe "#name" do
it "returns the name of the volume" do
@volume.name.should == "test_vol"
end
end
describe "#used" do
it "returns the amount of amount used by the volume" do
@volume.used.should == 419430400
end
end
describe "#free" do
it "returns the amount free in the volume" do
@volume.free.should == 209715200
end
end
describe "#total" do
it "returns the total amount of storage in the volume" do
@volume.total.should == 629145600
end
end
describe "#percentage_used" do
it "returns the percentage of storage used" do
@volume.percentage_used.should == 66.667
end
end
describe "#to_u" do
it "returns the unit conversion of a value" do
@volume.total.to_u == 600
end
end
end
| true |
813f53207ada1b48baa8c8b4d0c7e6f9c896d2b7 | Ruby | woodRock/Dots | /lib.rb | UTF-8 | 5,895 | 3.125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/ruby
require 'ruby2d'
module Lib
def board(_is_line, dims, squares, lines)
pad = 15
sq_size = 50
# Generic window properties
set title: 'Dots'
set height: pad + dims * sq_size
set width: pad + dims * sq_size
set background: 'white'
set resizable: false
# Directions map to vectors.
dir = { 'up' => 0, 'left' => 1, 'right' => 2, 'down' => 3 }
# Offset
off = 0
count = 0
# Initialize all the squares.
(0...dims).each do |y|
(0...dims).each do |x|
off = 5 if x.zero? && y.zero? # 5px padding from top and left.
_x = off + x * sq_size
_y = off + y * sq_size
squares[count] = Square.new(size: sq_size, color: 'green', x: _x, y: _y)
count += 1
end
end
# Fill in the squares.
squares.keys.each do |s|
# No squares have been won yet.
next if s == -1
lines_in_square = square_indexes(s, dims)
# Retrieve x and y coordinates (base) for the square.
_x = squares[s].x
_y = squares[s].y
off = pad / 2
# Compute envelope for each line.
l_map = {}
l_map['up'] = [_x + off, _y, sq_size - off, off]
l_map['left'] = [_x, _y + off, off, sq_size - off]
l_map['right'] = [_x + sq_size, _y + off, off, sq_size - off]
l_map['down'] = [_x + off, _y + sq_size, sq_size - off, off]
# Work out location of the lines in each direction (i.e up, left, right, down)
dir.keys.each do |d|
# A line is rectangle.
rect = Rectangle.new(
x: l_map[d][dir['up']],
y: l_map[d][dir['left']],
width: l_map[d][dir['right']],
height: l_map[d][dir['down']],
color: 'white' # By default each line is white.
)
# Store the line in the lines array.
lines[lines_in_square[dir[d]]] = rect
end
end
end
# Returns the index positions that correspond to a given square.
# Given a dims x dims board, the index positions can be derived as follows.
def square_indexes(num, dims)
# Check if the square is valid.
return - 1 if num.negative? || num > dims**2 - 1
c = num + ((num - (num % dims)) / dims) * (dims + 1)
[c, dims + c, dims + 1 + c, dims * 2 + 1 + c]
end
# Returns the index positions that correspond to a given line.
# Given the list of square indexes and direction, and direction to vector mapping.
def index_of_line(square_indexes, dir, directions)
# Retrieve the index of a line.
square_indexes[directions[dir]]
end
def add_line(line, is_line)
valid = valid_move(line, is_line)
is_line[line] = true if valid
valid # See if move was successful.
end
def draw_lines(is_line, lines)
is_line.each_with_index do |line, i|
# If line has been filled, draw it black. Otherwise, white.
color = line ? 'black' : 'white'
lines[i].color = color
end
end
def neighbour(current, dir, dims)
return current - 1 if dir.eql?('a') && left_neighbour(current, dims)
return current + 1 if dir.eql?('d') && right_neighbour(current, dims)
return current - dims if dir.eql?('w') && (current - dims >= 0)
return current + dims if dir.eql?('s') && (current + dims < dims**2)
-1 # No neighbour.
end
def make_move(current, dims, key, map, is_line, counter, p1, p2)
return 0 if current == -1
lines = square_indexes(current, dims)
line = index_of_line(lines, key, map)
valid = valid_move(line, is_line)
before = is_square?(square_indexes(current, dims), is_line)
neighbour = neighbour(current, key, dims)
before_neighbour = is_square?(square_indexes(neighbour, dims), is_line)
add_line(line, is_line)
after = is_square?(square_indexes(current, dims), is_line)
after_neighbour = is_square?(square_indexes(neighbour, dims), is_line)
scored = !before && after
neighbour_scored = !before_neighbour && after_neighbour
p1_move = p1_move(counter)
p1 << current if scored && p1_move
p1 << neighbour if neighbour_scored && p1_move
p2 << current if scored && !p1_move
p2 << neighbour if neighbour_scored && !p1_move
return 0 if scored or neighbour_scored or !valid
1 # Regular move - valid and no squares won - now next players turn.
end
def end_game(p1_col, p2_col, p1_squares, p2_squares, squares)
# Compute result of the game.
p1_won = p1_squares.length > p2_squares.length
p2_won = p1_squares.length < p2_squares.length
draw = p1_squares.length == p2_squares.length
# Result is shown as a color.
color = p1_col if p1_won
color = p2_col if p2_won
color = 'gray' if draw
# All squares turn the game result colour above.
squares.keys.each { |s| squares[s].color = color }
end
def is_square?(square_indexes, is_line)
# Handle invalid square.
return false if square_indexes == -1
res = true
# See if all the lines of a square are filled.
square_indexes.each { |i| res &= is_line[i] }
res # True if all filled, false otherwise.
end
def valid_move(line, is_line)
# Move is not valid if a line does not exist.
!is_line[line]
end
def p1_move(counter)
# Game counter starts at 0. If even, player 1's turn.
counter.even?
end
def left_neighbour(current, dims)
# Checks if a square has a left neighbour.
(square_indexes(current - 1, dims)[0] == square_indexes(current, dims)[0] - 1 && current - 1 >= 0)
end
def right_neighbour(current, dims)
# Checks if a square has a right neighbour.
(square_indexes(current + 1, dims)[0] == square_indexes(current, dims)[0] + 1 && current + 1 <= dims**2)
end
def game_over(squares_drawn, dims)
# Game over when all squares are filled.
(squares_drawn >= dims * dims)
end
def number_of_lines(dims)
# Return the total number of lines.
2 * (dims**2 + dims)
end
end
| true |
c801f056e38df8a965d3397b8ae1b698c825c07e | Ruby | MunkiPhD/bench_reloader_log | /app/models/manufacturer.rb | UTF-8 | 468 | 2.515625 | 3 | [] | no_license | class Manufacturer < ActiveRecord::Base
attr_accessible :abbreviation, :name
validates_presence_of :name
validates_length_of :name, :in => (3..35)
validates_uniqueness_of :name
validates_presence_of :abbreviation
validates_length_of :abbreviation, :in => (2..4)
validates_uniqueness_of :abbreviation
before_save :upcase_abbreviation
has_many :primers
private
def upcase_abbreviation
self.abbreviation = self.abbreviation.upcase
end
end
| true |
f6c4b6c2004d8e217097343ff133a52ed8de2b3e | Ruby | nanotechz9l/pickaxe | /blocks_iterators/fibonacci_iterators.rb | UTF-8 | 2,274 | 4.96875 | 5 | [] | no_license | #!/usr/bin/env ruby
=begin
A Ruby iterator is simply a method that can invoke a block of code.
We said that a block may appear only in the source adjacent to a method call and that the code in the block is not executed
at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current
object, and so on) and then enters the method. This is where the magic starts.
Within the method, the block may be invoked,
almost as if it were a method itself, using the yield statement.
=end
def three_times
yield # Whenever a yield is executed, it invokes the code in the block.
yield
yield
end # When the block exits, control picks back up immediately after the yield method call.
three_times {puts "Hello"}
puts
=begin
The block (the code between the braces) is associated with the call to the three_times method. Within this method, yield is called
three times in a row. Each time, it invokes the code in the block, and a cheery greeting is printed. What makes blocks interesting,
however, is that you can pass parameters to them and receive values from them.
=end
=begin
For example, we could write a simple function that returns members of the Fibonacci series up to a certain value:
=end
def fib_up_to(max)
i1, i2 = 0, 1 # parallel assignment (i1 = 0 and i2 = 1)
while i1 <= max # while i1 is less than or equal to max
yield i1 # invoke the code block
# In this example, the yield statement has a parameter. This value is passed to the associated block.
i1, i2 = i2, i1+i2
end
end
=begin
In the definition of the block, the argument list appears between vertical bars |f|. In this instance, the variable f receives the value
passed to yield, so the block prints successive members of the series. (This example also shows parallel assignment in action.
Although it is common to pass just one value to a block, this is not a requirement; a block may have any number of arguments.
=end
# By definition, the first numbers in the Fibonacci sequence are 0, and 1, and each subsequent number is the sum of the previous two.
fib_up_to(100000000) {|f| print f, " " }
puts
| true |
24de58b2ad5bb4a4dd801a9967237d7fe9cd5a97 | Ruby | OSC/ondemand | /nginx_stage/lib/nginx_stage/generators/nginx_show_generator.rb | UTF-8 | 1,399 | 2.78125 | 3 | [
"MIT"
] | permissive | module NginxStage
# This generator shows the state of the running per-user NGINX process.
class NginxShowGenerator < Generator
desc 'Show the details for a given per-user nginx process'
footer <<-EOF.gsub(/^ {4}/, '')
Examples:
To display the details of a running per-user nginx process:
nginx_stage nginx_show --user=bob
this also displays the number of active sessions connected to this PUN.
EOF
# Accepts 'user' as an option and validates user
add_user_support
# Display the chosen user
add_hook :display_user do
puts "User: #{user}"
end
# Check that pid is valid & clean up any stale files
add_hook :check_pid_is_process do
pid_file = PidFile.new pid_path
raise StalePidFile, "stale pid file: #{pid_path}" unless pid_file.running_process?
puts "Instance: #{pid_file.pid}"
end
# Check for active sessions on Unix domain socket
add_hook :check_socket_for_active_sessions do
socket = SocketFile.new socket_path
puts "Socket: #{socket}"
puts "Sessions: #{socket.sessions}"
end
private
# Path to the user's per-user NGINX pid file
def pid_path
NginxStage.pun_pid_path(user: user)
end
# Path to the user's per-user NGINX socket file
def socket_path
NginxStage.pun_socket_path(user: user)
end
end
end
| true |
954cd76228c84bd04140bdb97c335c22593373f1 | Ruby | momchianev/test | /study/82.rb | UTF-8 | 362 | 2.78125 | 3 | [] | no_license | ##
require_relative './helpers'
arr = [[1,2,3,4],[1,2,3,4],[1,2,3,4]]
arr2 = [[1,2],[1,2],[1,2],[1,2]]
arr3 = []
if arr[0].length != arr2.length
print "razlichen broi"
end
for row in 0 .. arr.length - 1 do
arr3.push []
for col in 0 .. arr2[row].length - 1 do
arr3[row].push (multiplematrices arr[row], (getColumn arr2, col))
end
end
print arr3 | true |
e49fb79c1187ae319c748933d682a670dc45f580 | Ruby | Q-Win/morse_translator | /test/morse_translator_test.rb | UTF-8 | 895 | 3.09375 | 3 | [] | no_license | require 'pry'
require 'minitest/autorun'
require 'minitest/pride'
require './lib/morse_translator'
class MorseTranslatorTest < Minitest::Test
def test_it_exists
translation = MorseTranslator.new
assert_instance_of MorseTranslator, translation
end
def test_translate
morse_translator = MorseTranslator.new
actual = morse_translator.translate("hello world")
assert_equal "......-...-..--- .-----.-..-..-..", actual
end
def test_translate_even_with_caps
morse_translator = MorseTranslator.new
actual = morse_translator.translate("There are 3 ships")
assert_equal "-......-.. .-.-.. ...-- ..........--....", actual
end
def test_it_can_translate_to_eng
morse_translator = MorseTranslator.new
actual = morse_translator.morse_to_eng(".... . .-.. .-.. --- .-- --- .-. .-.. -..")
assert_equal "hello world", actual
end
end
| true |
b83929ee7e1ee3dffdc99afb342d7874d4f07179 | Ruby | hagasatoshi/work-for-life | /app/helpers/commits_helper.rb | UTF-8 | 1,197 | 2.546875 | 3 | [] | no_license | module CommitsHelper
def circle_style(commit_count)
return 'display: none;' if @max_count == 0 || commit_count == 0
#コミット数の割合と円の面積比が一致するように割合の平方根をかける
width = Constants::CIRCLE_SIZE * ((commit_count.to_f / @max_count)**(1/2.0))
height = width
left = (-1) * (width / 2)
top = 32 - (width / 2)
"width: #{width.to_s}px; height: #{height.to_s}px; left: #{left.to_s}px; top: #{top.to_s}px;"
end
def org_picklist(orgs)
orgs.map {|org| {label: org[:name], value: org[:id].to_s}}
end
def repo_picklist(repos)
repos.map {|repo| {label: repo[:name], value: repo[:id].to_s}}
end
def from_date_picklist
last_sunday = Time.zone.today.beginning_of_week.yesterday
(0..25)
.to_a
.map {|num|
sunday = last_sunday - num.weeks
{label: sunday.strftime('%Y-%m-%d'), value: sunday.strftime('%Y-%m-%d')}
}
end
def interval_picklist
[{label: '1週間', value: 'week'}, {label: '1ヶ月', value: 'month'}]
end
def pull_request_url(org, repo, pull_request)
"https://github.com/#{org}/#{repo}/pull/#{pull_request.number}"
end
end
| true |
f8086f9d1f3ac573949f2af2e37a631e80c272d1 | Ruby | cronin101/Distributed-Systems-Coursework | /lib/input_parser.rb | UTF-8 | 471 | 2.6875 | 3 | [] | no_license | class InputParser
def self.parse_file(filename)
File.open(filename).readlines.each { |line| parse_line(line) }
end
def self.parse_line(line)
matches = line.scan /\w+/
case (object_type = matches.shift)
when 'node'
Node.new((name = matches.shift), (addresses = matches)).store
when 'link'
Link.new((endpoints = matches.take(2))).store
when 'send'
NodeCommand.new((target = matches.first), :send).enqueue
end
end
end
| true |
8d59779d65a2a20360453a42dfde079b46d9f75e | Ruby | chemcnabb/PrepTickets | /lib/page_builder.rb | UTF-8 | 1,859 | 2.703125 | 3 | [] | no_license | require 'erb'
require 'tag_helper'
class PageBuilder
include TagHelper
attr_accessor :app, :root, :page_path
def initialize(app, page_path)
@app = app
@root = app.root
@page_path = page_path
end
def assets_sources name, options={}
assets = app.sprockets.find_asset(name)
return [] if assets.blank?
extract_asset_sources_for assets
end
def stylesheet_link_tag name='app.css', options={}
sources = assets_sources(name)
links = sources.map do |s|
s = "#{s}?body=1" if app.development?
stylesheet_tag(s, options)
end
links.join("\n")
end
def javascript_link_tag name='app.js', options={}
sources = assets_sources(name)
links = sources.map do |s|
s = "#{s}?body=1" if app.development?
javascript_tag(s, options)
end
links.join("\n")
end
def render_to_string
ERB.new(File.read(page_path)).result(binding)
end
def call(env) #Rack calls this automagically
[
200,
{
'Content-Type' => 'text/html',
'Cache-Control' => 'public, max-age=86400'
},
[render_to_string]
]
end
#######
private
#######
def extract_asset_sources_for(assets)
assets_source_list = []
if app.development?
assets.to_a.each do |asset|
if (asset.to_a.size > 1)
assets_source_list + extract_asset_sources(asset)
else
assets_source_list << get_asset_source(asset)
end
end
else
assets_source_list << get_asset_source(assets)
end
assets_source_list
end
def get_asset_source(asset)
return "" if asset.blank?
asset_attr = app.sprockets.attributes_for(asset.pathname.realpath)
name = asset_attr.logical_path.to_s
path = asset.pathname.relative_path_from(root).to_s.gsub(/#{name}(.*)/, "")
"/#{path}#{name}"
end
end
| true |
871afc0c3fcbe47046436759a6f22020827c4da0 | Ruby | okcowboy80/Frogger | /power_up.rb | UTF-8 | 775 | 3.109375 | 3 | [] | no_license |
class Power_up
attr_accessor :stop
def initialize image
@has_been_eaten = false
@insect = image
@angle = 0.0
@x = Random.rand(50...500)
@y = Random.rand(30..450)
@X_OFF_SCREEN = -10
@Y_OFF_SCREEN = -10
end
# Method that randomly generates x and y values
def get_new_location
@x = Random.rand(50...500)
@y = Random.rand(30..450)
end
# Method that places the insect object outside of viewing area until next level of play
def eaten
@x = @X_OFF_SCREEN
@y = @Y_OFF_SCREEN
end
def get_y
return @y
end
def get_x
return @x
end
def draw
@insect.draw_rot(@x, @y, 2, 0, 0.5, 0.5, 0.25, 0.25, 0xff_ffffff, mode = :default)
end
def move
end
end
| true |
bd3c6815df48b3631fb729032db480770263bdd6 | Ruby | smyptl/gimmecar | /app/gimmecar/lib/spreadsheet/compiler/spreadsheet.rb | UTF-8 | 4,232 | 2.546875 | 3 | [] | no_license | class Lib::Spreadsheet::Compiler::Spreadsheet
def initialize(sheets)
@sheets = sheets
process_sheets
end
def set(args)
@row_index = args.fetch(:row_index)
@column_index = args.fetch(:column_index)
@sheet_id = args.fetch(:sheet_id)
end
def parse(args)
args[:sheet] ||= :current
sheet = ""
sheet = "'#{processed_sheets.fetch(args[:sheet]).fetch(:name)}'!" unless args.fetch(:sheet) == :current
case
when args[:cell]
cell = parse_cell(args)
raise ArgumentError, args.to_s if cell.nil?
"#{sheet}#{::Axlsx::cell_r(cell.fetch(:column_index), cell.fetch(:row_index))}"
when args[:row] && args[:column]
"#{sheet}#{::Axlsx::cell_r(parse_column(args), parse_row(args))}"
when args[:columns]
row_index = parse_row(args)
if args[:columns].is_a?(Array)
args[:columns].map do |column|
"#{sheet}#{::Axlsx::cell_r(parse_column({sheet: args[:sheet], column: column}), row_index)}"
end
else
parse_sheet(args).fetch(:column_groups).fetch(args[:columns]).map do |column_index|
"#{sheet}#{::Axlsx::cell_r(column_index, row_index)}"
end
end
when args[:rows]
column_index = parse_column(args)
if args[:rows].is_a?(Array)
args[:rows].map do |row|
"#{sheet}#{::Axlsx::cell_r(column_index, parse_row({sheet: args[:sheet], row: row}))}"
end
else
parse_sheet(args).fetch(:row_groups).fetch(args[:rows]).map do |row_index|
"#{sheet}#{::Axlsx::cell_r(column_index, row_index)}"
end
end
when args[:cells]
raise NotImplementedError
else
raise ArgumentError
end
end
private
def sheets
@sheets || (raise NotImplementedError)
end
def processed_sheets
@processed_sheets ||= {}
end
def parse_sheet(args)
if args.fetch(:sheet) == :current
sheet = processed_sheets.fetch(@sheet_id)
else
sheet = processed_sheets.fetch(args[:sheet])
end
end
def parse_cell(args)
parse_sheet(args).dig(:cells, args.fetch(:cell))
end
def parse_row(args)
row = args.fetch(:row)
case row
when Integer
row
when :current
@row_index
else
parse_sheet(args).fetch(:rows).fetch(row)
end
end
def parse_column(args)
column = args.fetch(:column)
case column
when Integer
column
when :current
@column_index
else
parse_sheet(args).fetch(:columns).fetch(column)
end
end
def process_sheets
sheets.each do |sheet|
raise ArgumentError, "#{sheet.fetch(:id)} already set" if processed_sheets.has_key?(sheet.fetch(:id))
process_sheet(sheet)
end
end
def process_sheet(sheet)
processed_sheets[sheet.fetch(:id)] = {
name: sheet.fetch(:name),
cells: {},
cell_groups: {},
rows: {},
row_groups: {},
columns: {},
column_groups: {}
}
sheet.fetch(:rows).each_with_index do |row, row_index|
add(:rows, row[:id], row_index, sheet[:id])
add_group(:row_groups, row[:group], row_index, sheet[:id])
row.fetch(:cells).each_with_index do |cell, column_index|
index = { row_index: row_index, column_index: column_index }
add(:cells, cell[:id], index, sheet[:id])
add_group(:cell_groups, cell[:group], index, sheet[:id])
end
end
sheet.fetch(:columns).each_with_index do |column, column_index|
add(:columns, column[:id], column_index, sheet[:id])
add_group(:column_groups, column[:group], column_index, sheet[:id])
end
end
def add(type, id, index, sheet_id)
return if id.blank?
if id.is_a?(Array)
id.each { |i| add_rows(type, i, index, sheet_id) }
else
sheet = processed_sheets.dig(sheet_id, type)
raise ArgumentError, "#{id} already set" if sheet.has_key?(id)
sheet[id] = index
end
end
def add_group(type, id, index, sheet_id)
return if id.blank?
if id.is_a?(Array)
id.each { |i| add_groups(type, i, index, sheet_id) }
else
sheet = processed_sheets.dig(sheet_id, type)
(sheet[id] ||= []) << index
end
end
end
| true |
1ab38094d42432a165d25ef7fa300f53fe5167a4 | Ruby | icelander/mattermost_generate_user_file | /lib/mattermost_api.rb | UTF-8 | 1,239 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'httparty'
class MattermostApi
include HTTParty
format :json
# debug_output $stdout
def initialize(mattermost_url, token)
@base_uri = mattermost_url + 'api/v4/'
@options = {
headers: {
'Content-Type' => 'application/json',
'User-Agent' => 'Mattermost-HTTParty'
},
# TODO Make this more secure
verify: false
}
@options[:headers]['Authorization'] = "Bearer #{token}"
@options[:body] = nil
end
def post_data(payload, request_url)
options = @options
options[:body] = payload.to_json
self.class.post("#{@base_uri}#{request_url}", options)
end
def get_url(url)
per_page = 200
page = 0
results = []
loop do
request_url = "#{url}?per_page=#{per_page}&page=#{page}"
request = JSON.parse(self.class.get("#{@base_uri}#{request_url}", @options).to_s)
results = results + request
if request.length < per_page then break end
end
return results
end
def get_users_by_auth(auth_method)
users = self.get_url('/users')
output_users = {}
if auth_method == 'email'
auth_method = ''
end
users.each do |user|
if user['auth_service'] == auth_method
output_users[user['email']] = user['username']
end
end
return output_users
end
end | true |
70ead78b452103090b101b45f5b90e5fb21cd4fe | Ruby | dave2walsh/mini_project | /spec/controllers/contacts_controller_spec.rb | UTF-8 | 4,385 | 2.546875 | 3 | [] | no_license | require 'spec_helper'
describe ContactsController do
let(:user) { FactoryGirl.create(:user, name: "freddy_2", email: "freddy_2@hawai.com", password: "freddyisin") }
before(:each) do
@contact = user.contacts.build(name: "Contact Freddy 2")
#Must save the contact to test all actions except new and create, since the controller only allows access to the other actions when the user is logged in and has at least one contact.
@contact.save
log_in(user)
end
describe "GET 'new'" do
before do
get 'new'
end
it "should assign new Contact object" do
assigns[:contact].should_not be_nil
assigns[:contact].should be_new_record
assigns[:contact].should be_kind_of(Contact)
end
end
describe "GET 'index'" do
before do
get 'index'
end
it 'should load all contacts for the current user' do
assigns[:contacts].should == [@contact]
end
end
describe "GET 'show'" do
it "should get the specified contact for the current user" do
get 'show', id: @contact.id
assigns[:contact].should == @contact
end
end
describe "GET 'edit'" do
before(:each) do
get 'edit', id: @contact.id
end
it "renders the specified contact for editing" do
assigns[:contact].should == @contact
end
end
describe "POST 'create'" do
context "when using a GET verb" do
it 'rejects the request' do
get :create
controller.should_not_receive(:create)
end
end
context "When creation is successful" do
before do
@contact_new = {name: "Kenny Contact"}
post :create, contact: @contact_new
end
it "should redirect to 'show'" do
response.should redirect_to(contacts_path)
end
it "assigns contact instance variable" do
assigns[:contact].should_not be_nil
assigns[:contact].should be_kind_of(Contact)
end
it "creates a record" do
lambda {
post :create, contact: @contact_new
}.should change(Contact, :count).by(1)
end
end
context "when creation fails" do
before do
@contact_new = {name: " "}
post :create, contact: @contact_new
end
it "should render 'new'" do
response.should render_template("contacts/new")
end
it "should not create a record" do
assigns[:contact].should be_new_record
lambda {
post :create, contact: @contact_new
}.should change(Contact, :count).by(0)
end
it 'assigns the contact' do
# This is important, so that when re-rendering "new", the previously entered values are already set
post :create, :contact => @contact_new
assigns[:contact].should_not be_nil
assigns[:contact].should be_kind_of(Contact)
end
end
end
describe "PUT 'update'" do
before do
put 'update', id: @contact.id
end
context "when using a GET verb" do
it 'rejects the request' do
get :update, id: @contact.id
controller.should_not_receive(:update)
end
end
context "when update succeeds" do
it "should redirect to 'show'" do
response.should redirect_to(redirect_to contacts_url)
end
it "should assign contact instance variable" do
assigns[:contact].should == @contact
assigns[:contact].should be_kind_of(Contact)
end
it "should update the record" do
lambda {
put :update, :id => @contact.to_param, :contact => {name: "BarryContact"}
}.should change {@contact.reload.name}.from("Contact Freddy 2").to("BarryContact")
end
end
context "when the update fails" do
it "should render 'edit'" do
put :update, :id => @contact.to_param, :contact => {name: ""}
response.should render_template("contacts/edit")
end
it "should not change the record" do
lambda {
put :update, :id => @contact.to_param, :contact => {name: ""}
}.should_not change {@contact.reload.name}.from("Contact Freddy 2").to("")
end
it 'assigns the person' do
# This is important, so that when re-rendering "edit", the previously entered values are already set
put :update, :id => @contact.to_param, :contact => {name: ""}
assigns[:contact].should == @contact
end
end
end
end
| true |
c8fdf5b7d6a4259c6484aaf7eae96ce6ad75e290 | Ruby | Amrutamali/training | /survey_app/lib/tasks/dump_user_data.rake | UTF-8 | 1,141 | 2.765625 | 3 | [] | no_license | =begin
desc "dump file"
task :dump_user_data, [:id, :name] =>:environment do|task, args|
puts args
puts "in task"
#user1 = User.first
user1 = User.find( args[:id] )
puts user1.name
puts user1.email
temp = user1.name.split(" ")
puts temp[0]
puts temp[1]
# input by name
str = args[:name]
user2 = User.find_by(name: str)
puts "-----------"
puts user2.name,user2.email,user2.gender,user2.age
temp = user1.name.split(" ")
puts temp[0]
puts temp[1]
end
=end
=begin
namespace :dump_user_data do
desc "dump file"
task ":dump user data by id", [:id] =>:environment do|task, args|
puts args
puts "in task"
#user1 = User.first
user1 = User.find( args[:id] )
puts user1.name
puts user1.email
temp = user1.name.split(" ")
puts temp[0]
puts temp[1]
end
end
=end
##define name space
namespace :task do
# describe task
desc "dump the user data"
#task name and optional argument
task :task1,[:arg1] => :environment do |task, args|
#default argument
args.with_defaults(arg1: 'default value')
p args[:arg1]
#allow variable number of argument
p args.extras
end
end
| true |
c3ba0bf3acc6b8fc160206206c88c8ef2f92e6e1 | Ruby | iliabylich/binding_dumper | /lib/binding_dumper/core_ext/local_binding_patch_builder.rb | UTF-8 | 2,277 | 3.25 | 3 | [
"MIT"
] | permissive | # Class responsible for building patch for local binding
#
# @example
# data = {
# file: '/path/to/file.rb',
# line: 17,
# method: 'do_something'
# }
# patch = BindingDumper::CoreExt::LocalBindingPatchBuilder.new(data).patch
# patched_binding = binding.extend(patch)
#
# patched_binding.eval('__FILE__')
# # => '/path/to/file.rb'
# patched_binding.eval('__LINE__')
# # => 17
# patched_binding.eval('__method__')
# # => 'do_something'
#
class BindingDumper::CoreExt::LocalBindingPatchBuilder
# Returns +undumped+ object passed to constructor
#
# @return [Hash]
#
attr_reader :undumped
# Takes an undumped object representation
#
# @param undumped [Hash]
#
def initialize(undumped)
@undumped = undumped
end
# Returns module that is ready for patching existing binding
#
# @return [Module]
#
def patch
deps = [
file_method_patch,
line_method_patch,
method_method_patch,
eval_method_patch
]
Module.new do
include *deps
end
end
private
# Returns a module with patch for __FILE__ evaluation
#
# @return [Module]
#
def file_method_patch
undumped = self.undumped
Module.new do
define_method(:_file) { undumped[:file] }
end
end
# Returns a module with patch for __LINE__ evaluation
#
# @return [Module]
#
def line_method_patch
undumped = self.undumped
Module.new do
define_method(:_line) { undumped[:line] }
end
end
# Returns a module with patch for __method__ evaluation
#
# @return [Module]
#
def method_method_patch
undumped = self.undumped
Module.new do
define_method(:_method) { undumped[:method] }
end
end
# Returns a module with patch of 'eval' method, so:
# 1. __FILE__ returns undumped[:file]
# 2. __LINE__ returns undumped[:line]
# 3. __method__ returns undumoed[:method]
#
# @return [Module]
#
def eval_method_patch
Module.new do
define_method :eval do |data, *args|
case data
when /__FILE__/
_file
when /__LINE__/
_line
when /__method__/
_method
else
Binding.instance_method(:eval).bind(self).call(data, *args)
end
end
end
end
end | true |
49eb787a8c6b00f233b3d99969b5988f4d30e678 | Ruby | lucasmonteiro12/tic-tac-toe | /board.rb | UTF-8 | 323 | 3.46875 | 3 | [] | no_license | class Board
attr_accessor :tiles
def initialize
@tiles = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]
end
def print_board
puts " #{@tiles[0]} | #{@tiles[1]} | #{@tiles[2]} \n===+===+===\n #{@tiles[3]} | #{@tiles[4]} | #{@tiles[5]} \n===+===+===\n #{@tiles[6]} | #{@tiles[7]} | #{@tiles[8]} \n"
end
end
| true |
e1eacc31536e002e5321bf175bacae0c2985c19d | Ruby | kazunetakahashi/atcoder | /2017/1106_ABC042/C.rb | UTF-8 | 239 | 2.78125 | 3 | [
"MIT"
] | permissive | n, k = gets.chomp.split(" ").map{|i| i.to_i}
d = gets.chomp.split(" ").map{|i| i.to_s}
for i in n...1000000
ok = true
i.to_s.chars{|c|
if d.include?(c)
ok = false
break
end
}
if ok
puts i
exit
end
end
| true |
64d5ddf88c99d2858a7c8f6d73aa1aad77c9386e | Ruby | hascong/ExerciseForRuby | /TestReadFile.rb | UTF-8 | 2,090 | 2.90625 | 3 | [
"MIT"
] | permissive | #! /usr/bin/ruby
#encoding: UTF-8
# Input File
system "printf \"The input vocabulary file is: \n\" > test_result_read_file_rb"
system "cat vocab_bank_fake_small >> test_result_read_file_rb"
# Test case 1
system "printf \"\nTest Case 1 The new word is a new head\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb boy \\\"Little boy.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb boy \"Little boy.\" >> test_result_read_file_rb"
# Test case 2
system "printf \"\nTest Case 2 The new word is behind current head\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb goddd \\\"Goddd.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb goddd \"Goddd.\" >> test_result_read_file_rb"
# Test case 3
system "printf \"\nTest Case 3 The new word is equal to certain entry\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb good \\\"Good to see you again.\\\" \\\"Good night baby.\\\" \\\"Good evening.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb good \"Good to see you again.\" \"Good night baby.\" \"Good evening.\" >> test_result_read_file_rb"
# Test case 4
system "printf \"\nTest Case 4 The new word is behind the middle\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb goooooood \\\"Goooooood.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb goooooood \"Goooooood.\" >> test_result_read_file_rb"
# Test case 5
system "printf \"\nTest Case 5 The new word is before tail\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb hi \\\"Hi there.\\\" \\\"Hi I am John.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb hi \"Hi there.\" \"Hi I am John.\" >> test_result_read_file_rb"
# Test case 6
system "printf \"\nTest Case 6 The new word is behind current tail\n\" >> test_result_read_file_rb"
system "printf \"$ ruby ReadFile.rb zip \\\"Zip!\\\" \\\"Zip up.\\\"\n\" >> test_result_read_file_rb"
system "clear && ruby ReadFile.rb zip \"Zip!\" \"Zip up.\" >> test_result_read_file_rb"
| true |
a9815adc6b2615968562b8966b0429a32180b915 | Ruby | Kole565/RubyRush | /lesson_methods/arrayCut.rb | UTF-8 | 843 | 3.734375 | 4 | [] | no_license | def cut_array (cuting_len, source_array)
if (cuting_len == nil || !cuting_len.is_a?(Numeric))
cuting_len = 3
end
if (source_array == nil || !source_array.is_a?(Array))
source_array = [1, 2, 3]
end
res = []
index = 0
while index < cuting_len
if (source_array[index])
res << source_array[index]
end
index += 1
end
return res
end
sausage_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
puts("Вот какая палка колбасы у нас есть: ")
puts(sausage_array.to_s)
puts("Сколько первых элементов вам отрезать?")
while (true)
choice_len = STDIN.gets.encode("UTF-8").chomp
choice_len = choice_len.to_i
if (choice_len != nil && choice_len.is_a?(Numeric))
break
end
end
puts("Вот ваша колбаса: ")
puts(cut_array(choice_len, sausage_array).to_s) | true |
1f1e99f7429aff8e23fc70876f06b2a9af9fd031 | Ruby | compostbrain/go-tournament-manager | /app/interactors/create_tournament_registration.rb | UTF-8 | 1,519 | 2.65625 | 3 | [
"MIT"
] | permissive | class CreateTournamentRegistration
def self.call(
tournament:,
player_attributes:,
round_statuses:,
tournament_registration_status:
)
instance = new(
tournament,
player_attributes,
round_statuses,
tournament_registration_status,
)
instance.call
end
def initialize(
tournament,
player_attributes,
round_statuses,
tournament_registration_status
)
@tournament = tournament
@player_attributes = player_attributes
@round_statuses = round_statuses
@tournament_registration_status = tournament_registration_status
end
def call
player = Player.create!(player_attributes)
create_round_statuses!(player)
TournamentRegistration.create!(
player_id: player.id,
tournament_id: tournament.id,
status: tournament_registration_status,
)
OpenStruct.new(success?: true, player: player, message: "")
rescue StandardError => e
OpenStruct.new(success?: true, player: player, message: e.message)
end
private
attr_reader :tournament,
:player_attributes,
:round_statuses,
:tournament_registration_status
def create_round_statuses!(player)
tournament.rounds.each do |round|
round_status =
RoundStatus.find_or_initialize_by(
player_id: player.id, round_id: round.id,
)
round_status.status =
(round_statuses || {}).keys.include?(round.number.to_s) ? 1 : 2
round_status.save!
end
end
end
| true |
dd915834d1940bd16faf910aa2be2292205a4a74 | Ruby | porf25/ruby_view_server | /block_example.rb | UTF-8 | 503 | 3.984375 | 4 | [] | no_license |
## functions can take in a block similar to the way Array#each can
# i.e. [1,2,3].each {|x| x + 1}
## here we are providing a function called `wrap_around_contents` when a block is passed to it, it will yield to the block
def wrap_around_contents
"hey your contents =>| #{yield} |<= have been wrapped"
end
puts wrap_around_contents { " my contents" }
## We can call the function and provide it a block it will give us this output
# => "hey your contents =>| my contents |<= have been wrapped"
| true |
473aa535125bcf73e929e56852f74c8ade193fce | Ruby | soemirno/heresy | /lib/counter.rb | UTF-8 | 259 | 3.171875 | 3 | [] | no_license | class Counter
def initialize
@count = 0
end
def render_on(html)
html.heading("Hello World: #{@count}")
html.tag("p"){html.text("this is fun!!!")}
html.link("--"){ @count -= 1 }
html.space
html.link("++"){ @count += 1 }
end
end | true |
89685428b8ca076bb710e64402dd40ba19232be8 | Ruby | niclin/ios-job-list | /app/models/job.rb | UTF-8 | 428 | 2.671875 | 3 | [] | no_license | class Job
attr_accessor :id, :title, :content, :image_url
def initialize(data)
@id = data['id']
@title = data['title']
@content = data['content']
@image_url = data['image_url']
end
def self.all(&callback)
ApiClient.client.get 'jobs' do |response|
models = []
models = response.object.map { |data| new(data) } if response.success?
callback.call(response, models)
end
end
end
| true |
b4f31f0504f8335161c83d8d34f0ba09a8cf9747 | Ruby | simonpatrick/all-about-designpattern | /data_structure/ruby/libs/macros.rb | UTF-8 | 670 | 2.859375 | 3 | [] | no_license | def fifo_stack size=1
RubyDataStructures::FifoStack.new size
end
def stack size=1
RubyDataStructures::Stack.new size
end
def multi_array(*dimensions)
RubyDataStructures::MultiDimensionalArray.new(*dimensions)
end
def max_heap(*array)
RubyDataStructures::MaxHeap.build(array.flatten)
end
def linked_list(type = :single)
case type
when :single
RubyDataStructures::SinglyLinkedList.new
when :double, :dbl
RubyDataStructures::DoublyLinkedList.new
else
raise ArgumentError, "Unknown or unsupported kind of Linked List: #{type}, must be: :single or :double"
end
end
def aqueue size
RubyDataStructures::QueueAsArray.new size
end | true |
4acc46836e9484c8341224c874daf30f8b2fa5cc | Ruby | Joeo8/Ruby | /loop/until.rb | UTF-8 | 150 | 3.203125 | 3 | [] | no_license | sum = 0
i = 1
until sum >= 50
sum += i
i += 1
end
puts sum
count = 0
a = 1
while !(count >= 50)
count += a
a+=1
end
puts count
| true |
d33302f97a76a3eea58605ef0b8ddd0674b9e798 | Ruby | vilusa/Ruby-101 | /sayilar.rb | UTF-8 | 810 | 3.75 | 4 | [] | no_license | sayi = 2**30-1
puts sayi.class
puts sayi.size # bellekte kac byte lik yer kapladigini verir
tutar = 1399.1 # para cinsinden
puts tutar.class # Float
# Rasyonel Sayilar
puts Rational(1) # 1/1
puts Rational(20/5) # 4/1
puts Rational(3,5) # 3/5
# Tip donusumleri
puts "142".to_f.class # float
puts "142".to_s.class # string
puts "142".to_i.class # integer
# Bazi operatorler
puts 14.0/2 # bolme
puts 14.div(2) # div boler
puts 15.div(2) # div boler ondalik kisma bakmaz
puts 15.fdiv(2) # fdiv boler ondalik kisma dikkat eder
puts 2**3 # us alir 2 ussu 3
print 19.divmod(4.5) # bolum ve kalani dizi dondurur
puts ""
puts 19.quo(4.5) # bolumu verir
puts "Kalan: #{19.remainder(4.5)}" # kalani verir
k = 5
puts k
puts k+=5
puts k-=4
puts k*=4
puts k%=5
a, b, c = 1, 2, 3 #paralel atama
puts a
puts b
puts c | true |
28cad3202a4b143fa2c13b78b15370f279282f25 | Ruby | chuckremes/rzmq_brokers | /lib/rzmq_brokers/broker/service.rb | UTF-8 | 2,445 | 2.8125 | 3 | [] | no_license |
module RzmqBrokers
module Broker
# Used by the Broker to maintain a list of Workers for the named Service. The Service
# knows how to iterate, add, delete and purge workers.
#
# This is meant to be subclassed to add specific support for a protocol (e.g. Consensus)
#
class Service
include Enumerable
attr_reader :name
def initialize(reactor, name, handler)
@reactor = reactor
@name = name
@handler = handler
@workers = Hash.new # key is identity, value is Worker instance
end
# It is safe to call other Service methods on the yeilded workers
# even when adding or deleting a worker. This method does the
# right thing.
#
def each
# by calling #values, we are working on a copy; any addition/deletion
# will happen on @workers
@workers.values.each { |worker| yield(worker) }
end
def add(worker)
@workers[worker.identity] = worker
@reactor.log(:debug, "#{self.class}, Service [#{name}] adding worker, [#{worker_count}] total workers.")
end
def delete(worker)
@workers.delete(worker.identity)
worker.die
@reactor.log(:debug, "#{self.class}, Service [#{name}] deleting worker, [#{worker_count}] remaining workers.")
end
def [](identity)
@workers[identity]
end
def workers?
@workers.size > 0
end
def worker_count
@workers.size
end
def purge_expired_workers
@workers.values.each do |worker|
delete(worker) if worker.expired?
end
end
# Any message from a worker is considered part of the heartbeat. Make sure
# the worker is updated so it doesn't expire.
#
# Subclasses of this class should be sure to call #super so that this operation
# is handled.
#
def process_reply(message)
worker = @workers[message.envelope_identity]
worker.process_heartbeat if worker
worker
end
# Checks message to verify this service can handle it. May be rejected due to
# incompatibility, duplicate sequence number, sequence number already marked as
# failed, etc.
#
def request_ok?(message)
true
end
def ready?
true
end
def add_request(message)
# no op
end
end # class Service
end
end
| true |
00a2a93d7d8397df9a8b3d7f9fadf5f83f433731 | Ruby | Elukoye/leetcode_challenges | /common_characters.rb | UTF-8 | 527 | 3.609375 | 4 | [] | no_license | def common_chars(a)
count_map = Hash.new(0)
result = []
a.first.chars.each {|c| count_map[c] += 1 }
a.each { |str|
count_map.each { |c, count|
count_map[c] = [count, str.count(c)].min
}
}
count_map.each { |c, count|
result += (c * count).split("") if count > 0
}
result
end
# solution that makes sense
# def common_chars(a)
# first_word = a.first
# first_word.chars.uniq.map{|char| [char] * (a.map{|word| word.count(char)}).min}.flatten
# end
puts common_chars(["bella","label","roller"]) | true |
5d23963f932c4360ba28dc97a42dcd9b6fc0ca57 | Ruby | sirinath/Terracotta | /dso/tags/2.2-stable/code/base/buildscripts/archive_tag.rb | UTF-8 | 1,885 | 2.53125 | 3 | [] | no_license | #
# All content copyright (c) 2003-2006 Terracotta, Inc.,
# except as may otherwise be noted in a separate copyright notice.
# All rights reserved
#
# Represents an 'archive tag': a family of relative paths that let you store
# archives associated with a build (build logs, build directory archive, etc.)
# in a consistently-named location.
class ArchiveTag
# Creates a new ArchiveTag. build_environment should be the current BuildEnvironment.
def initialize(build_environment)
@build_environment = build_environment
end
# Returns a FilePath object representing where you should place a product of
# the build that has base filename 'filename' and extension 'extension'. Currently,
# this returns something like:
#
# main/rev1.3092/standard-unit/rhel4/rh4mo0/2006/09/27/filename-main-standard-unit-rev1.3092-rh4mo0-2006-09-27-17-38-37.extension
def to_path(filename, extension)
user = @build_environment.build_username
host = @build_environment.build_hostname
revision = @build_environment.current_revision
version = @build_environment.specified_build_version
branch = @build_environment.current_branch
os_type = @build_environment.os_type(:nice)
monkey_label = @build_environment.monkey_label
timestamp = @build_environment.build_timestamp
year = timestamp.strftime("%Y")
month = timestamp.strftime("%m")
day = timestamp.strftime("%d")
hour = timestamp.strftime("%H")
minute = timestamp.strftime("%M")
second = timestamp.strftime("%S")
FilePath.new(branch, "rev%s" % revision, monkey_label, os_type, host, year.to_s, month.to_s, day.to_s,
[ filename, branch, monkey_label, "rev%s" % revision, host, year, month, day, hour, minute, second ].join("-") + "." + extension)
end
end
| true |
f1a70c60ca074f8f145259223601fb0cfce606c7 | Ruby | RBGeomaticsRob/takeaway-challenge | /spec/menu_spec.rb | UTF-8 | 777 | 2.96875 | 3 | [] | no_license | require 'menu'
describe Menu do
it 'can have a list of dishes stored as a hash' do
expect(subject.items).to be_a Hash
end
it 'can load dishes from a yaml file' do
yaml_file = './menu.yml'
subject.load!(yaml_file)
expect(subject.items).not_to be_empty
end
it 'accepts a menu yml as an argument' do
menu = described_class.new(menu: './menu.yml')
expect(menu.items).not_to be_empty
end
it 'can retrieve an individual item from the menu' do
dish1 = subject.items[1]['dish']
price1 = subject.items[1]['price']
item1 = { 'dish' => dish1, 'price' => price1 }
expect(subject.item(1)).to eq item1
end
it 'can cycle through each item' do
expect { subject.each_item { |_k, (d, _p)| puts d } }.to output.to_stdout
end
end | true |
efc26876e3512eb9358f5b46d252b5a042458544 | Ruby | koukimiura/cherry_book | /lib/word_synth.rb | UTF-8 | 690 | 3.640625 | 4 | [] | no_license |
# require 'logger'
class WordSynth
def initialize
@effects = []
end
def add_effect(effect) #Effectrs.newのインスタンスが渡される
#test_play_with_many_effectsメソッドをするために配列化と繰り返し
@effects << effect
end
def play(original_words)
# 配列が0個でも injectメソッドは引数の値(ここではoriginal_words)をそのまま返してくれる.
@effects.inject(original_words) do |words, effect|
#結果的に Effects.call('Ruby is fun!') #1回目はplayメソッドの引数がinjectの引数に入るが2回目以降はブロック処理の戻り値がinjectの引数に入る
effect.call(words)
end
end
end | true |
fb1259dfa223ba636f3dc62e19b4f82e8a36eeee | Ruby | kodywilson/printsly | /bin/printsly | UTF-8 | 1,170 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'printsly'
v = ARGV
case
when v.empty? == true
puts
puts bar_top.yellow
puts " "*24 + "Helps you add printers to CUPS".yellow + " "*19
puts bar_low.yellow
puts # format
puts "Selectable options will normally be enclosed in " + "[ ]".yellow + "'s."
puts # format
Menu.new.choices
when v.count > 2
help_text
exit 1 #something went wrong
when v.count == 1
help_text
exit 1 #soemthing went wrong
when v.count == 2
v.each do |dirk| #basic directory verification
if /^\//.match(dirk) #does path start at root?
unless Dir.exists?(dirk)
puts # format
puts "#{dirk} does not exist!".red
help_text
exit 1 #something went wrong
end
else
help_text
exit 1 #something went wrong
end
end
spreads = Dir.glob(File.join(v[0], '*.xls'))
if spreads.size > 0
spreads.each do |sheety|
hosty = `hostname`.strip
sheet = sheety + "." + hosty
cur_conf = fill_hash sheety, "On", "On"
unless File.exists?(sheet)
Batch.new.process(cur_conf)
system "bash", "-c", "touch #{sheet}" if $green == true
end
end
end
end
| true |
9c290b4b4375697399710150e6f78e6252b4ef16 | Ruby | lucadegasperi/vagrant-puppet | /modules/stdlib/lib/puppet/parser/functions/validate_array.rb | UTF-8 | 822 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | module Puppet::Parser::Functions
newfunction(:validate_array, :doc => <<-'ENDHEREDOC') do |args|
Validate all passed values are a Array data structure
value does not pass the check.
Example:
These values validate
$my_array = [ 'one', 'two' ]
validate_array($my_array)
These values do NOT validate
validate_array(true)
validate_array('some_string')
$undefined = undef
validate_array($undefined)
ENDHEREDOC
unless args.length > 0 then
raise Puppet::ParseError, ("validate_array(): wrong number of arguments (#{args.length}; must be > 0)")
end
args.each do |arg|
unless arg.is_a?(Array)
raise Puppet::ParseError, ("#{arg.inspect} is not an Array. It looks to be a #{arg.class}")
end
end
end
end
| true |
cd1b9411ce78f75a6841ef667497094c141f1cec | Ruby | DavidBarriga-Gomez/Sweater-Weather | /app/poros/daily_forecast.rb | UTF-8 | 645 | 3.453125 | 3 | [] | no_license | class DailyForecast
attr_reader :high, :low, :today, :tonight
def initialize(weather)
@high = weather['daily']['data'].first['temperatureHigh'].round
@low = weather['daily']['data'].first['temperatureLow'].round
@today = weather['daily']['data'].first['summary']
@tonight = night_summary(weather)
end
def night_summary(weather)
current_hour = Time.at(weather['hourly']['data'].first['time']).in_time_zone(weather['timezone']).strftime("%k").to_i
if current_hour < 20
weather['hourly']['data'][20-current_hour]['summary']
else
weather['hourly']['data'][current_hour]['summary']
end
end
end
| true |
a29caf8f2559e8e6fa01abbdac633c971bd83c7a | Ruby | antomus/problems | /lib/insertion_sort.rb | UTF-8 | 322 | 3.609375 | 4 | [] | no_license | module InsertionSort
def insertion_sort(array, &compare)
array.each_with_index do |el, i|
while i > 0 and compare.call(el, array[i - 1]) do
array[i - 1], array[i] = array[i], array[i - 1]
i -= 1
end
end
array
end
# private
# def compare(a, b)
# a < b
# end
end | true |
85b4222416baf335623e7559e159f37767edcb38 | Ruby | ngeballe/ls-intro-book | /6 arrays/exercises/ex1_is_number_in_array.rb | UTF-8 | 350 | 4.40625 | 4 | [] | no_license | # Below we have given you an array and a number. Write a program that checks to see if the number appears in the array.
def number_in_array?(array, number)
#array.include?(number)
# or with each
array.each do |item|
return true if item == number
end
false
end
arr = [1, 3, 5, 7, 9, 11]
number = 3
puts number_in_array?(arr, number) | true |
6e769fbfd93c2eba525c7cd38cf1a793a430103e | Ruby | alex707/L10 | /deck.rb | UTF-8 | 397 | 3.453125 | 3 | [] | no_license | # deck contain cards
class Deck
attr_reader :cards
def initialize
@cards = []
['♠', '♣', '♥', '♦'].product(%w[2 3 4 5 6 7 8 9 10 J Q K A]).each do |s, v|
c = if v.to_s == 'A'
11
else
v.to_i.zero? ? 10 : v.to_i
end
@cards << Card.new(s, v, c)
end
@cards.shuffle!
end
def take_card
@cards.shift
end
end
| true |
ea81d8fbd9aa0dea568260f96b95b342daeca2c0 | Ruby | Videmor/TestingRoR | /clase2/calculate.rb | UTF-8 | 553 | 3.28125 | 3 | [] | no_license | def add(*num)
# s = 0
# num.length.times do |i|
# s += num[i]
# end
# s
num.reduce(&:+)
end
def subtract(*num)
# s = num[0]
# (num.length - 1).times do |i|
# s = s - num[i + 1]
# end
# s
num.reduce(&:-)
end
# < ruby 2.0
# def calculate *num
# option = num[-1].class == Hash ? num.pop : {add: true}
#
# return add(*num) if option[:add]
# return subtract(*num) if option[:subtract]
# end
# >= ruby 2.0.0
def calculate(*num, add: true, subtract: false)
return subtract(*num) if subtract
return add(*num) if add
end
| true |
2175d42f30de322d1ec0ddbfad42f9508482073e | Ruby | wardymate/codewars-kata | /TitleCase/spec/titlecase_spec.rb | UTF-8 | 591 | 3.015625 | 3 | [] | no_license | require 'titlecase'
describe TitleCase do
tester = TitleCase.new
it 'should return an empty string when passed an empty string' do
expect(tester.title_case('')).to eq ''
end
it 'should convert the string' do
expect(tester.title_case('a clash of KINGS', 'a an the of')).to eq 'A Clash of Kings'
end
it 'should convert the string' do
expect(tester.title_case('THE WIND IN THE WILLOWS', 'The In')).to eq 'The Wind in the Willows'
end
it 'should convert the string' do
expect(tester.title_case('the quick brown fox')).to eq 'The Quick Brown Fox'
end
end | true |
026e270aa51db41e2e4dcf4bee0bf121b54981df | Ruby | Asteriskx/Ice-Chan | /lib/Ice-chan/command/cmd_update_name.rb | UTF-8 | 2,849 | 2.5625 | 3 | [
"MIT"
] | permissive | puts "Load: cmd_update_name.rb"
def cmd_update_name?(status)
text = status.text
name = status.in_reply_to_screen_name
if name == $cfg.screen_name && parser?(text, ["-n", "--update_name", "--name", "update_name", "--lock_name", "--unlock_name"])
return true
else
return false
end
end
def cmd_update_name(client, status)
name = status.user.screen_name
id = status.id
text = status.text
puts timestamp + "@" + name + " > " + text
if parser?(text, ["--lock_name"]) && !parser?(text, ["-n", "--update_name", "--name", "update_name"])
if name == $cfg.admin || name == $cfg.screen_name
$update_name_lock = true
tweet = "@" + name + " " + $cfg.bot_name + ": update_name locked."
else
tweet = "@" + name + " Error: Permission denied."
end
puts timestamp + "@" + $cfg.screen_name + " > " + tweet
client.update(tweet, :in_reply_to_status_id => id)
elsif parser?(text, ["--unlock_name"]) && !parser?(text, ["-n", "--update_name", "--name", "update_name"])
if name == $cfg.admin || name == $cfg.screen_name
$update_name_lock = false
tweet = "@" + name + " " + $cfg.bot_name + ": update_name unlocked."
else
tweet = "@" + name + " Error: Permission denied."
end
puts timestamp + "@" + $cfg.screen_name + " > " + tweet
client.update(tweet, :in_reply_to_status_id => id)
elsif !$update_name_lock && client.friendship?($cfg.screen_name, name) && client.friendship?(name, $cfg.screen_name) || name == $cfg.screen_name || name == $cfg.admin
new_name = parser(text, ["update_name", "--name", "--update_name", "-n"])
if new_name.length > 20
tweet = "@" + name + " Error: 名前が長過ぎます。"
#elsif new_name.length < 1
# client.update_profile(name: $cfg.default_name)
# tweet = "> @" + name + " " + $cfg.bot_name + ": 名前をデフォルトに変更しました。"
else
begin
client.update_profile(name: new_name)
client.retweet(id) if !status.user.protected?
tweet = "> @" + name + " " + $cfg.bot_name + ": Rename is「" + new_name + "」."
rescue
#tweet = "@" + name + " update_name でエラーが起きてます。制作者は直ちに出てこいや。"
end
end
puts timestamp + "@" + $cfg.screen_name + " > " + tweet
client.update(tweet, :in_reply_to_status_id => id)
elsif $update_name_lock
tweet = "@" + name + " Error: 名前はロックされています。"
puts timestamp + "@" + $cfg.screen_name + " > " + tweet
client.update(tweet, :in_reply_to_status_id => id)
else
tweet = "@" + name + " Error: Permission denied.\nこの機能はF/F内のユーザのみ使用できます。"
puts timestamp + "@" + $cfg.screen_name + " > " + tweet
client.update(tweet, :in_reply_to_status_id => id)
end
end
| true |
d557b620517c3f5bad38110567bcc37288d91d12 | Ruby | nithinbekal/euler-ruby | /code/euler-0006.rb | UTF-8 | 633 | 4.21875 | 4 | [] | no_license | # The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 385 = 2640.
# Find the difference between the sum of the squares of the first one hundred
# natural numbers and the square of the sum.
def sum_of_squares(n)
n * (n+1) * (2*n + 1) / 6
end
def sum_of_series(n)
n * (n+1) / 2
end
def diff(n)
(sum_of_squares(n) - sum_of_series(n)**2).abs
end
puts diff(100)
| true |
e1160f1b10c9b2675cf775a9c14c479007605a01 | Ruby | mojotech/helios2 | /app/lib/clients/create_tweet.rb | UTF-8 | 1,610 | 2.65625 | 3 | [
"MIT"
] | permissive | # Polls weather for subscribed locations
class Clients::CreateTweet
delegate :text, :media, :interactions, :status, :user, :created_at, to: :@tweet
InteractionQuery = Struct.new(:favorite_count, :retweet_count)
MediaQuery = Struct.new(:images, :link)
UserQuery = Struct.new(:name, :handle, :avatar)
def initialize(tweet)
@tweet = tweet
end
def attributes
case status
when 'retweet'
@tweet.attrs[:retweeted_status]
when 'quote'
@tweet.attrs[:quoted_status]
else
@tweet.attrs
end
end
def created_at
@tweet.created_at
end
def media
MediaQuery.new(images, link)
end
def images
attributes[:extended_entities][:media]
rescue StandardError
nil
end
def link
attributes[:entities][:urls].first[:expanded_url]
rescue StandardError
nil
end
def interactions
InteractionQuery.new(attributes[:favorite_count], attributes[:retweet_count])
end
def text
text = attributes[:full_text]
links = text.split(/\s|\n/).select { |word| word.include? "http" }
clean_text = text
links.each do |l|
clean_text = clean_text.gsub(l, "")
end
clean_text
end
def status
if @tweet.attrs[:retweeted_status]
"retweet"
elsif @tweet.attrs[:quoted_status]
"quote"
else
"normal"
end
end
def user
user = attributes[:user]
# removing '_normal' from url given returns orginal sized picture
large_profile_image_url = user[:profile_image_url].remove("_normal")
UserQuery.new(user[:name], user[:screen_name], large_profile_image_url)
end
end
| true |
301b13249fdd4b360e5e2d7679512a664cb2fe09 | Ruby | tsetsefly/launch_school-prepwork | /back_end_prep/ruby_basics_exercises/user_input/lsprint.rb | UTF-8 | 282 | 3.34375 | 3 | [] | no_license | response = nil
loop do
puts "How many output lines do you want? Enter a number >= 3:"
response = gets.chomp.to_i
if response > 2
response.times do
puts "Launch School is the best!"
end
break
else response < 3
puts "That's not enough lines."
end
end
| true |
20d24f0e7237311c14ab8a9f85fed31899ac4266 | Ruby | a2800276/des.go | /src/rb/make_test_data_cbc.rb | UTF-8 | 1,598 | 3.140625 | 3 | [] | no_license |
require "test_data_basics"
require 'openssl'
def cbcStruct
struct = <<END
type cbcTest struct {
name string
key [] byte
iv [] byte
in [] byte
out [] byte
}
END
puts struct
end
def head
puts "package des"
cbcStruct
puts "var cbcDESTests = []cbcTest {"
end
def tail
puts "}"
end
def random_key c
case c
when "des-cbc"
return make_des_key
#return [0x86,0x20,0xd3,0xda,0x3d,0x8c,0xfe,0x94]
when "des-ede-cbc"
return make_2des_key
when "des-ede3-cbc"
return make_3des_key
else
raise "unknown cipher: #{c}"
end
end
def enc (cipher, key, iv, data)
name = cipher
data = opensslkey(data)
cipher = OpenSSL::Cipher::Cipher.new name
cipher.encrypt
cipher.iv = opensslkey iv
cipher.key = opensslkey key
enc = cipher.update data
enc << cipher.final
cipher = OpenSSL::Cipher::Cipher.new name
cipher.decrypt
cipher.iv = opensslkey iv
cipher.key = opensslkey key
dec = cipher.update enc
dec << cipher.final
if dec != data
puts print_go_slice(s2b(enc))
puts print_go_slice(s2b(data))
raise "hell"
end
enc
end
def testCase c
iv = random_bytes(8)
#iv = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
key = random_key c
puts " {"
puts " \"#{c}\","
puts " #{print_go_slice iv},"
puts " #{print_go_slice key},"
data = random_bytes 128
puts " #{print_go_slice data},"
puts " #{print_go_slice s2b(enc(c, key, iv, data))},"
puts " },"
end
CIPHERS = %w{ des-cbc des-ede-cbc des-ede3-cbc }
head
CIPHERS.each {|c|
testCase(c)
}
tail
| true |
d94368cea7989902ef6f3451ae5b997eae8ca550 | Ruby | sheg/FantasyFootball | /app/helpers/leagues_helper.rb | UTF-8 | 8,768 | 2.65625 | 3 | [] | no_license | module LeaguesHelper
class WeekData
attr_accessor :week_number,
:start_date
def initialize
self.week_number = 0
end
def end_date
(start_date + 1.week - 1.day).end_of_day
end
end
class DraftInfo
attr_accessor :current_team,
:draft_round,
:draft_round_pick,
:last_pick_time,
:next_pick_time
def draft_pick_decimal
return "#{draft_round}.#{draft_round_pick}"
end
def time_left
return (next_pick_time.to_time - Time.now.utc).round(0)
end
end
def set_league_week_data
return if self.nfl_start_week
return if self.available_teams > 0
return if draft_transactions.count < self.teams_count * self.roster_count
data = get_league_week_data_for_week(1)
nfl_game = get_nfl_week_game(data)
unless nfl_game
nfl_game = NflGame.where(season_type_id: 1, week: 1).order(start_time: :desc).first
raise "The season is over" if nfl_game.start_time < data.start_date
data.start_date = nfl_game.start_time.beginning_of_week - 1.week + 2.days
end
self.nfl_start_week = nfl_game.week
self.nfl_start_week += 17 if nfl_game.season_type_id == 3
self.nfl_start_week = 1 if nfl_game.season_type_id == 2
self.start_week_date = data.start_date
self.start_week_date += (5 - nfl_game.week).weeks if nfl_game.season_type_id == 2
self.save
end
def get_league_week_data_for_week(league_week = nil)
week_data = get_league_week_data
league_week = week_data.week_number unless league_week
return nil if league_week > self.total_weeks or league_week <= 0
week_data.week_number = 1 if(week_data.week_number == 0) # 0 is returned when league hasn't started yet
week_data.start_date += (league_week - week_data.week_number).weeks
week_data.week_number = league_week
return week_data
end
def get_league_week_data(date = nil)
start_week = nil
week = WeekData.new
if(self.start_week_date)
start_week = self.start_week_date
else
transactions = draft_transactions.to_a
order = get_draft_order
end
if(start_week or transactions.count == order.count)
# Use the next upcoming Tuesday as the start of week
start_day_of_week = 2
unless(start_week)
# Get last draft pick as league start time and add 1 week if it is on start day of week or later
max_transaction = transactions.max_by { |t| t.transaction_date }.transaction_date
max_transaction += 1.week if max_transaction.wday >= start_day_of_week
start_week = max_transaction
end
start_week = (start_week.beginning_of_week.at_beginning_of_day + start_day_of_week.days).to_date
date = DateTime.now unless date
date = date.utc.at_beginning_of_day.to_date
days = (date - start_week).to_i
if(days < 0)
week.week_number = 0
week.start_date = start_week
else
week.week_number = (days / 7).floor + 1
week.start_date = start_week + (week.week_number - 1).weeks
end
end
return week
end
def get_nfl_week_game(league_week_data)
game = nil
if(league_week_data)
# Adding extra weeks to end date in case of missing weeks (i.e. skipped week before super bowl)
games = NflGame.where('start_time between ? and ?', league_week_data.start_date + 1.days, league_week_data.end_date + 2.week + 1.days).order(:start_time)
if(games.count > 0)
game = games.first
end
end
return game
end
def get_nfl_week_game_from_league_week(league_week)
week_data = get_league_week_data_for_week(league_week)
get_nfl_week_game(week_data)
end
def is_waiver_period?(now = nil)
now = Time.now unless now
now = Time.parse(now) if now.is_a? String
now = now.utc
week_data = get_league_week_data(now)
now < (week_data.start_date + 2.days)
end
def get_waiver_order(league_week)
order = []
standings = self.team_standings.where(week: league_week).order(:percent, :points_for, points_against: :desc).order("rand()").to_a
end
def test_draft()
set_draft_order
catchup_draft
while(true)
pick = auto_draft_player
break unless pick
end
end
def catchup_draft
current_draft_info = self.get_current_draft_info
while(current_draft_info and current_draft_info.time_left < 0)
pick = self.auto_draft_player(current_draft_info)
break unless pick
current_draft_info = self.get_current_draft_info
end
end
def auto_draft_player(draft_info = nil)
draft_info = self.get_current_draft_info unless draft_info
return nil unless draft_info
slots = self.league_type.get_starting_slots
round = draft_info.draft_round
slot = (round - 1) % slots.count
position = slots[slot].sample
@position_players = {} unless @position_players
unless @position_players[position]
@position_players[position] = NflPlayer.find_position(position).where("nfl_games.season_id between #{season_id} - 1 and #{season_id}")
.select("nfl_players.*, sum(nfl_game_players.points) as points").group("nfl_players.id").order("points desc").to_a
end
players = @position_players[position]
pick = nil
@retry_num = 0
while(pick.nil?)
begin
break if @retry_num >= 10
player = players.slice!(0)
# Adjust the transaction date in case this draft was made after time expired for that pick
if(draft_info.time_left < 0)
transaction_date = draft_info.next_pick_time
else
transaction_date = nil
end
pick = draft_info.current_team.draft_player(player.id, false, transaction_date)
#puts "DraftOrder #{draft_info.current_team.draft_order}: Team #{draft_info.current_team.name} drafted position #{position}: #{player.full_name}"
rescue Exception => e
if e.message.include?("already taken")
#puts "DraftOrder #{draft_info.current_team.draft_order}: Team #{draft_info.current_team.name} failed to draft position #{position}: #{player.full_name}"
#puts " #{e.message}"
@retry_num += 1
else
raise e
end
end
end
return pick
end
def set_schedule
return unless self.teams.count == self.size
return if Game.where(league_id: self.id).count > 0
league_teams = self.teams.to_a
weeks = create_schedule
weeks.each_with_index do |week, week_index|
week.each_slice(2).to_a.each do |team_game_pair|
week = (week_index + 1)
home_team = league_teams[team_game_pair.first - 1].id
away_team = league_teams[team_game_pair.last - 1].id
Game.create!(league_id: self.id, week: week, home_team_id: home_team, away_team_id: away_team)
end
end
end
def create_schedule
weeks = []
count = self.size
unique_weeks = count - 1
games_per_week = count / 2
for week in 0...unique_weeks
for i in 0...games_per_week
x = (week + i) % (count - 1)
y = (count - 1 - i + week) % (count - 1)
if i == 0
y = count - 1
end
weeks.push x + 1
weeks.push y + 1
end
end
weeks = weeks.each_slice(count).to_a
remaining_games = (self.weeks - (self.size - 1))
remaining_games.times do |remaining_week_index|
weeks.push (weeks[remaining_week_index]).reverse
end
weeks
end
def set_draft_order
return unless self.teams.count == self.size
return if self.teams.first.draft_order
order = (1..self.size).to_a.shuffle
self.teams.each_with_index { |team, i|
team.draft_order = order[i]
team.save
}
end
def get_draft_order()
draft_teams = self.teams.order(:draft_order).to_a
order = []
self.roster_count.times do
order += draft_teams
draft_teams = draft_teams.reverse
end
order
end
def get_current_draft_info()
transactions = draft_transactions.to_a
order = get_draft_order
info = nil
if(transactions.count < order.count)
info = DraftInfo.new
info.current_team = order[transactions.count]
info.draft_round = (transactions.count / self.size).floor + 1
info.draft_round_pick = (transactions.count % self.size) + 1
max_transaction = transactions.max_by { |t| t.transaction_date }
info.last_pick_time = max_transaction.transaction_date if max_transaction
info.last_pick_time = self.draft_start_date unless max_transaction
info.last_pick_time = DateTime.now.utc unless info.last_pick_time
info.next_pick_time = info.last_pick_time + self.draft_pick_time.seconds
end
return info
end
end | true |
49edcfa54ff42c95347483728d9b9bb1572a4b38 | Ruby | iamalan/arduino_plane | /Arduino.rb | UTF-8 | 2,677 | 3.328125 | 3 | [] | no_license | require 'rubygems'
require 'YAML'
require 'serialport'
require 'log'
require 'valuemapper'
class Arduino
def initialize(config_file)
begin
@CONFIG = File.open(config_file) { |f| YAML.load(f) }
Log.instance.add "Opened Arduino config #{config_file}:"
Log.instance.add @CONFIG.to_yaml
@sp = SerialPort.new(@CONFIG["serial"], @CONFIG["baud"], @CONFIG["data_bits"], @CONFIG["stop_bits"], SerialPort::NONE)
rescue Exception => e
Log.instance.add "#{e} #{e.backtrace}"
# re raise, this is a deal breaker.
raise e
end
end
def getBytes(size)
data = []
begin
Log.instance.add "#{self.class.name} #{__method__} called."
while(@sp.getbyte != 0xff)
end
Log.instance.add "Got sync byte over serial."
size.times do
got = @sp.getbyte
data << got
Log.instance.add "Got #{got} over serial."
end
checksum = (@sp.getbyte << 8 | @sp.getbyte)
Log.instance.add "Got checksum: #{checksum} over serial."
if checksum != data.inject(:+)
Log.instance.add "Checksum is not equal."
data = []
end
rescue Exception => e
Log.instance.add "#{e} #{e.backtrace}"
end
Log.instance.add "Passed checksum :)."
Log.instance.add "getBytes returning #{data.inspect}"
return data
end
def sendArray(array)
begin
Log.instance.add "#{self.class.name} #{__method__} called with #{array.inspect}."
@sp.write([255].pack('C'));
Log.instance.add "Wrote sync byte over serial."
checksum = 0;
array.each do |value|
@sp.write([value].pack('C'))
Log.instance.add "Wrote #{value} over serial."
if value > ValueMapper::BYTE_MAX_VALUE then Log.instance.add "Warning, last value written was over BYTE_MAX_VALUE of #{ValueMapper::BYTE_MAX_VALUE}." end
checksum = checksum + value
end
@sp.write([checksum].pack('s'))
Log.instance.add "Wrote #{checksum} over serial."
rescue Exception => e
Log.instance.add "#{e} #{e.backtrace}"
end
end
def sendHash(hash)
begin
Log.instance.add "#{self.class.name} #{__method__} called with #{hash.inspect}."
keys = hash.keys.sort
Log.instance.add "sendHash will create an array corresponding to keys: #{keys.inspect}"
array = []
keys.each do |k|
array = array + hash[k]
end
rescue Exception => e
Log.instance.add "#{e} #{e.backtrace}"
end
Log.instance.add "Passing to sendArray..."
sendArray(array)
end
end | true |
1352b488c7e79ca66da7faa0e5888452a806a9cb | Ruby | rscottm/ruby-ev3 | /lib/ev3/button.rb | UTF-8 | 1,335 | 3 | 3 | [
"MIT"
] | permissive | require 'ev3/actions/button'
module EV3
class Button
include EV3::Validations::Constant
include EV3::Validations::Type
include EV3::Actions::Button
attr_writer :pressed
attr_reader :name
UP = 1
ENTER = 2
DOWN = 3
RIGHT = 4
LEFT = 5
BACK = 6
def initialize(button, brick)
validate_constant!(button, 'button', self.class)
validate_type!(brick, 'brick', EV3::Brick)
@button = button
@name = self.class.constants[button-1].downcase.to_sym
@brick = brick
@pressed = false
@on_button_changed = nil
end
def self.on_button_changed
@on_button_changed
end
def self.on_button_changed=(change_proc)
@on_button_changed = change_proc
end
def on_button_changed
@on_button_changed || self.class.on_button_changed
end
def on_button_changed=(change_proc)
@on_button_changed = change_proc
end
def pressed?
brick.execute(_pressed?)
end
def pressed=(value)
(@pressed = value; on_button_changed.call(self, value)) if @pressed != value and on_button_changed
@pressed = value
end
private
attr_reader :brick, :button
# Helper for accessing the brick's layer (for daisy chaining)
def layer
brick.layer
end
end
end
| true |
4b5b4fb8e6798412a370d5bfbc997decfcfe3bb0 | Ruby | yuihyama/monkeyrock | /benchmark/subt_benchmark.rb | UTF-8 | 678 | 2.921875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'benchmark'
require './lib/subt'
Benchmark.bmbm do |x|
x.report('2.subt(1)') { 2.subt(1) }
x.report('Rational(2, 3).subt(1)') { Rational(2, 3).subt(1) }
x.report('[1, 2, 3].subt(1)') { [1, 2, 3].subt(1) }
x.report('(1..3).subt(1)') { (1..3).subt(1) }
x.report('300_000.times { 2.subt(1) }') do
300_000.times { 2.subt(1) }
end
x.report('300_000.times { Rational(2, 3).subt(1) }') do
300_000.times { Rational(2, 3).subt(1) }
end
x.report('300_000.times { [1, 2, 3].subt(1) }') do
300_000.times { [1, 2, 3].subt(1) }
end
x.report('300_000.times { (1..3).subt(1) }') do
300_000.times { (1..3).subt(1) }
end
end
| true |
62ef74b73bcdddcff90980ed71e826225f9822a4 | Ruby | tskorupa/soiree-gageure-2017 | /app/models/ticket_listing.rb | UTF-8 | 811 | 2.578125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class TicketListing
extend Memoist
include Enumerable
attr_reader :number_filter
def initialize(ticket_scope:, **options)
@ticket_scope = ticket_scope
@number_filter = options.fetch(:number_filter, nil)
end
def tickets_to_display?
tickets.any?
end
memoize :tickets_to_display?
def each
tickets.each_with_index do |ticket, index|
row_number = index + 1
yield TicketPresenter.new(ticket: ticket, row_number: row_number)
end
end
private
attr_reader :ticket_scope
def tickets
requested_tickets = ticket_scope.includes(:seller, :guest, :sponsor, :table).order(:number)
requested_tickets = requested_tickets.where(number: number_filter) if number_filter.present?
requested_tickets
end
memoize :tickets
end
| true |
8dbb23586dc526fbda9a1c68d685b614888baf20 | Ruby | GabbyMont/Ruby-Programming | /Day_6.rb | UTF-8 | 614 | 4.59375 | 5 | [] | no_license | soda_types = ["sprite", "coke", "mountain dew", "orange soda", "dr pepper", "surge"]
puts soda_types[2] #2 = mountian dew because each string is its own number i.e. "sprite" is 0, "coke" is 1, "mountain dew" is 2
puts soda_type[-2] #-2 = dr pepper because when you give a negative it starts at the end of the array, therefore "surge" is -1 and "dr pepper" is -2
soda_type = ["tab", 6, "cherry coke", 8.5225, "pepsi", 6 + 4 ]
puts soda_type
=begin
Output:
tab
6
cherry coke
8.5225
pepsi
10
=end
string_one = "Your favorite drink is "
puts string_one + soda_type[2]
puts "{soda_type[4]} tastes delicious!" | true |
6274a06d39213f167335cb36ff35bc498e3b4728 | Ruby | castle-crew/chess-group-project | /app/models/queen.rb | UTF-8 | 203 | 3.0625 | 3 | [] | no_license | class Queen < Piece
def valid_move?(x, y)
if x_space == x && y_space == y
return false
elsif diagonal_move?(x, y) == true
return true
else
return true
end
end
end
| true |
14adb31c37c62e7816b43ee3c9f71d53d816a87c | Ruby | s11rikuya/ruby-perfect-lesson | /cycle-2/2-2-1-1.rb | UTF-8 | 108 | 3.046875 | 3 | [] | no_license | greeting = "HELLO,"
people = ["Alice","Bob"]
people.each do |person|
puts greeting + person
end
outs person
| true |
c59086173090c68e865bd92fac47c5b1312ced2f | Ruby | mstmari/ttt-with-ai-project-v-000 | /lib/players/computer.rb | UTF-8 | 1,276 | 3.421875 | 3 | [] | no_license |
# require 'pry'
# module Players
# class Computer < Player
# def opponent_token
# #if the opponent token is X then type O and vise versa
# self.token == "X" ? "O" : "X"
# end
#
# def move(board)
#
#
# #turn one
# if !board.taken?(1)
# return "1"
# elsif !board.taken?(3)
# return "3"
# end
#
# idx = nil
# Game::WIN_COMBINATIONS.each do |combo|
# # binding.pry[0, 3, 9]
# if board.cells.include?(combo[0]) == token && !board.taken?(combo[1] + 1)
# idx = combo[1].to_i + 1
# return idx
# elsif board.cells.include?(combo[0]) == token && board.cells.include?(combo[1]) == current_player && !board.taken?(combo[2] + 1)
# idx = combo[2].to_i + 1
# return idx
# end
# end
#
# idx.to_s
# end
# end
# end
# #
module Players
class Computer < Player
def move(board)
if !board.taken?(9)
"9"
elsif !board.taken?(1)
"1"
elsif !board.taken?(3)
"3"
elsif !board.taken?(6)
"6"
elsif !board.taken?(2)
"2"
elsif !board.taken?(7)
"7"
elsif !board.taken?(8)
"8"
elsif !board.taken?(4)
"4"
elsif !board.taken?(5)
"5"
end
end
end
end
| true |
dbcb88dfc444643a8aa54066ecd96257f581d532 | Ruby | hide83/project-euler-multiples-3-5-e-000 | /lib/multiples.rb | UTF-8 | 403 | 3.265625 | 3 | [] | no_license | # Enter your procedural solution here!
require 'pry'
def collect_multiples(limit)
(1..limit-1).collect do |i|
if i % 3 == 0 || i % 5 == 0
i
end
end.compact
end
def sum_multiples(limit)
array = (1..limit-1).collect do |i|
if i % 3 == 0 || i % 5 == 0
i
end
end.compact
sum = 0
array.collect do |x|
sum += x
end.last
end
| true |
6d7c39bd65eaab75583f95a527c820447444783a | Ruby | coverless/peopole | /spec/platform/twitter_spec.rb | UTF-8 | 850 | 2.546875 | 3 | [] | no_license | # frozen_string_literal: true
require_relative '../../platform/twitter'
describe Platform::Twitter do
let(:twitter_platform) { described_class.new }
describe '#account_for' do
subject { twitter_platform.account_for(person) }
context 'when a verified account exists' do
let(:person) { 'Dillon Francis' }
let(:expected) { 'https://twitter.com/DILLONFRANCIS' }
it 'returns the correct account' do
expect(subject).to eq(expected)
end
end
context 'when there is no verified account' do
let(:person) { 'blueyhuey' }
let(:expected) { '' }
it 'returns an empty string' do
expect(subject).to eq(expected)
end
end
end
describe '#count_for' do
it 'returns an integer' do
expect(twitter_platform.count_for('Rick and Morty')).to be_an Integer
end
end
end
| true |
99fdc25f6853211578321db5c2760e62a9cf242a | Ruby | adrianagithub/rails-basics | /rails basics/logger.rb | UTF-8 | 507 | 3.890625 | 4 | [] | no_license | require "logger"
class BankAccount
attr_accessor :name
attr_reader :logger, :transactions
def initialize(name)
@name = name
@transactions = []
@logger = Logger.new("account.txt")
end
def deposit(amount)
logger.info "[#{name}] Deposited #{amount}"
transactions.push(amount)
end
def withdraw(amount)
logger.info("[#{name}] Withdrew #{amount}")
transactions.push(-amount)
end
end
account = BankAccount.new("Jason")
account.deposit 100
account.withdraw 50
| true |
b71a7bfc2ec2de698935bc7c4f05bb477c4d4305 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/anagram/763d557b03f74d629a38cb6670fe9954.rb | UTF-8 | 336 | 3.546875 | 4 | [] | no_license | class Anagram
attr_accessor :word
def initialize(word)
@word = word.downcase
end
def match(anagrams)
anagrams.select do |anagram|
anagrams_of(word).include? anagram.downcase
end
end
private
def anagrams_of(word)
word.chars.permutation.map(&:join).reject {|anagram| anagram.eql? word}
end
end
| true |
89c90749b367fc87512eefb8b31de78f3d9416fc | Ruby | jasminenoack/app-academy | /poker-etc-master/lib/array.rb | UTF-8 | 1,732 | 3.4375 | 3 | [] | no_license | class Array
def my_uniq
self.each_with_object([]) do |el, uniqs|
uniqs << el unless uniqs.include?(el)
end
end
def two_sum
array = []
(0...length - 1).each do |i|
(i...length).each do |j|
array << [i, j] if self[i] + self[j] == 0
end
end
array
end
def my_transpose
return self unless self[0].is_a?(Array)
rows, columns = self.length, self[0].length
new_array = Array.new(columns) { Array.new(rows) }
(0...rows).each do |row|
(0...columns).each do |column|
new_array[column][row] = self[row][column]
end
end
new_array
end
end
class Hanoi
attr_reader :board
def self.setup
Hanoi.new([[3,2,1],[],[]])
end
def initialize(board)
@board = board
end
def render
render_str = ""
2.downto(0) do |depth|
(0..2).each do |column|
render_str << " "
char = board[column][depth]
render_str << (char.nil? ? " " : char.to_s)
end
render_str << "\n"
end
render_str
end
def move(start, finish)
raise "invalid move" unless [start, finish].all? { |num| num.between?(0,2) }
raise "invalid move" if board[start].empty?
unless board[finish][0].nil?
raise "invalid move" if board[start][0] > board[finish][0]
end
board[finish] << board[start].pop
end
def won?
board[0].empty? && board[1..2].any?{ |column| column.empty? }
end
end
def stock_picker(days)
best_days = []
profit = 0
(0...days.length - 1).each do |day1|
(day1...days.length).each do |day2|
if days[day2] - days[day1] > profit
profit = days[day2] - days[day1]
best_days = [day1, day2]
end
end
end
best_days
end
| true |
74aef2e86b0d335289dda0a8418cd33f6e3f1cfa | Ruby | boesemar/exim-quotad | /exim-quotad.rb | UTF-8 | 9,091 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# Documentation:
# https://github.com/boesemar/exim-quotad
###################################################################
##################### CUSTOMIZE HERE #########################
###################################################################
DIRECTORY = '/var/exim-quotad'
EMAIL_DIRECTORY = "/var/vmail/%domain%/%local_part%/"
DEFAULT_QUOTA = 5000 * 1000 * 1000 # 5 GB
QUOTA_DIRECTORY = '/etc/exim4/quota-per-domain'
LISTEN_PORT = 2626
LISTEN_PORT_DEBUG = 2627 # if called with -d
CACHE_TIME = 300 # how long to keep quota before re-calculating
WARNING_LIMIT = 0.9 # If quota is > that availabel one this will send the warning email
# Do not apply quota if sender matches this REGEX
WHITELIST_SENDER_REGEX = /mailprovider-123.xyz$/
# Define the blocked email, telling a customer that we don't accept more email.
# You can use %used% , %limit%, %percent% and %email% placeholders
BLOCKED_EMAIL_SUBJECT = "URGENT: Quota Exceeded"
BLOCKED_EMAIL_FROM = "Email Service <noreply@mailprovider-123.xyz>"
BLOCKED_EMAIL_BODY = <<-TEND
This is an automated message by your email provider.
You have exceeded your Mailbox quote for Email %email% .
You are using %used%.
Your limit is %limit%.
Please delete old emails from the server! At this moment no new email
can be received.
We recommend to setup your email client to delete emails from the server
at least after 14 days once they are downloaded. Please refer to the
settings of your email client how this can be done.
TEND
# Define the warning email. You can use %used% , %limit%, %percent% and %email% placeholders
WARNING_EMAIL_SUBJECT = "WARNING: Low storage for your email"
WARNING_EMAIL_FROM = "Email Service <noreply@mailprovider-123.xyz>"
WARNING_EMAIL_BODY = <<-TEND
This is an automated message by the ITA email service.
You are running low on storage for your email %email% .
You are currently using %percent% of your available storage space of %limit%.
Please ugently delete old emails from the server - once the limit is reached
we will not be able to accept new email.
We recommend to setup your email client to delete emails from the server
at least after 60 days once they are downloaded. Please refer to the
settings of your email client how this can be done.
TEND
###################################################################
##################### DON'T CHANGE BELOW #########################
###################################################################
require 'socket'
$debug = ARGV.include?('-d')
def log(txt)
File.open("#{DIRECTORY}/exim-quotad.log", 'a') do |file|
file << "#{Time.now.to_s} : #{txt}\n"
end
if $debug then
STDOUT.puts(txt)
STDOUT.flush
end
end
############### Warning stuff ######################
def state_file(email, type='warning')
"#{DIRECTORY}/in_#{type}/#{email}"
end
def in_state?(email, type='warning')
return File.exist?(state_file(email, type))
end
def enter_state(email,type)
File.open(state_file(email, type),'w') do |f|
f << Time.now.to_s
end
end
def leave_state(email, type)
fn = state_file(email, type)
File.unlink(fn) if File.exist?(fn)
end
def bytes2gb(bytes)
"%.2f GB" % (bytes.to_f / (1000 * 1000 * 1000))
end
# This will deliver one email using the mail command
def send_email(to, from, subject, body, variables)
m = body
s = subject
variables.each do |k,v|
m = m.gsub("%#{k}%", v)
s = s.gsub("%#{k}%", v)
end
log "#{to} - Sending email '#{s}'\n#{m}"
IO.popen(["mail", "-s", s, "-a",
"From: #{from}", to],"r+") do |io|
io.write m
io.close_write
io.close
if $?.to_i != 0 then
log "#{to} - Error sending email - mail command failed"
end
end
end
def send_blocked_email(email, used, limit)
return if in_state?(email, 'blocked')
used = check_size(email2directory(email),1_000_000_000_000)
send_email(email, BLOCKED_EMAIL_FROM, BLOCKED_EMAIL_SUBJECT, BLOCKED_EMAIL_BODY,
{ 'limit' => bytes2gb(limit),
'used' => bytes2gb(used),
'percent' => ("%.2f" % (used.to_f/limit)),
'email' => email
})
end
# this will send the warning email
def send_warning_email(email, used, limit)
return if in_state?(email, 'warning')
rate = (used.to_f / limit)
send_email(email, WARNING_EMAIL_FROM, WARNING_EMAIL_SUBJECT, WARNING_EMAIL_BODY,
{
'limit' => bytes2gb(limit),
'used' => bytes2gb(used),
'percent' => ("%.2f%" % (rate*100)),
'email' => email
})
end
class Memcache
def initialize
@data = {}
end
def value(key, ttl = 300, &block)
v = @data[key] || {:ttl=>0,:val => nil}
if (v[:ttl] < Time.now.to_i) then
new_value = block.call
@data[key] = { :ttl=>(Time.now.to_i + ttl), :val => new_value }
end
@data[key][:val]
end
end
class QuotaError < StandardError; end
class QuotaExceeded < StandardError; end
# walking directory, checking size, until max
def check_size(directory, max, total_counted=0)
cur_size = 0
Dir.foreach(directory).each do |last_part|
next if last_part == '.'
next if last_part == '..'
f = directory + '/' + last_part
if File.directory?(f) then
cur_size += check_size(f, max, total_counted + cur_size)
else
cur_size += File.size(f)
end
if (total_counted + cur_size) > max then
raise QuotaExceeded, "Limit reached, stopped counting at: #{total_counted + cur_size}"
end
end
cur_size
end
# returns the data directory for one email account
def email2directory(email)
u, d = email.split('@').map { |x| x.downcase }
ed = EMAIL_DIRECTORY
ed = ed.gsub('%domain%', d)
ed = ed.gsub('%local_part%', u)
ed
end
# expect a file "quota-per-domain" that looks like:
# domaina.com:2000 # 2GB for domaina.com
# domainb.com:1000
def get_limit_for_domain(domain)
File.read(QUOTA_DIRECTORY).split(/\n/).each do |line|
line = line.strip
next if line.strip[0] == '#'
line = line.split('#').first # allow comments
next if line.empty?
if line =~ /^(.*):(\d+)/ then
d = $1
q = $2
if d.strip.downcase == domain.downcase then
return q.to_i * (1000 * 1000)
end
end
end
return DEFAULT_QUOTA
end
begin
if $debug then
server = TCPServer.open(LISTEN_PORT_DEBUG)
puts "Listening on #{LISTEN_PORT_DEBUG} for debug purpose"
else
server = TCPServer.open(LISTEN_PORT)
end
rescue => e
STDERR.puts " Can't open socket"
exit
end
mc = Memcache.new
loop do
Thread.fork(server.accept) do |client|
# begin
# client = server.accept
command = client.gets.strip.downcase
if command =~ /^check_quota\s(.*)/ then
email_and_sender = $1.strip
email = email_and_sender.split(' ')[0]
sender = email_and_sender.split(' ')[1]
if sender.to_s =~ WHITELIST_SENDER_REGEX then
log "#{email} Whitelist sender: #{sender}"
quota = {:defined_quota => nil, :used => 0, :result => :whitelist }
else
log "#{email} - Checking Quota"
quota = mc.value(email, CACHE_TIME) do
result = {:defined_quota => nil, :used => 0, :result => :undefined }
log "#{email} - Recalculating..."
u, d = email.split('@').map { |x| x.downcase }
defined_quota = get_limit_for_domain(d)
result[:defined_quota] = defined_quota
log "#{email} - Limit for #{d} = #{bytes2gb(defined_quota)}"
dir = email2directory(email)
log "#{email} - directory is: #{dir}"
if !File.directory?(dir) then
log "#{email} - Can't find user directory #{dir}"
next result
end
size = 0
begin
size = check_size(dir, defined_quota) # check size raises QuotaExceed if counting is above defined_quota
result[:used] = size
if (size.to_f / defined_quota) > WARNING_LIMIT then
result[:result] = :warn
else
result[:result] = :good
end
rescue QuotaExceeded => e
result[:used] = result[:defined_quota]
result[:result] = :block
end
result
end
log "#{email} - #{bytes2gb(quota[:used])}/#{bytes2gb(quota[:defined_quota])} - #{quota[:result].inspect}"
case quota[:result]
when :good then
leave_state(email, 'warning')
leave_state(email, 'blocked')
when :warn then
send_warning_email(email, quota[:used], quota[:defined_quota])
leave_state(email, 'blocked')
enter_state(email, 'warning')
when :block then
send_blocked_email(email, quota[:used], quota[:defined_quota])
enter_state(email, 'blocked')
leave_state(email, 'warning')
end
end # if whitelist
log "#{email} Result: #{quota[:result] == :block ? 'BLOCK' : 'ACCEPT'}"
client.print quota[:result] == :block ? "1" : "0" # 0 == OK, 1 = NO QUOTA
elsif command =~ /^ping/i then
client.puts "pong!"
else
client.puts "Unknown command"
end
client.close
end
end
| true |
9960497e59ded803ff4fccb02954cc497e40a9ad | Ruby | codedogfish/ruby-in-action | /meta/class/definition/attr.rb | UTF-8 | 320 | 3.78125 | 4 | [] | no_license | class MyClass
def my_attribute=(value)
@my_attribute = value
end
def my_attribute
@my_attribute
end
end
obj = MyClass.new
obj.my_attribute = 'x'
puts obj.my_attribute
class MyClass1
attr_accessor :my_attribute
end
obj2 = MyClass.new
obj2.my_attribute = 'y'
puts obj2.my_attribute
| true |
62eeb581ead32c94e1da07ca5688514305cb9bf1 | Ruby | timbot1789/ruby-project | /atom.rb | UTF-8 | 518 | 3.359375 | 3 | [] | no_license | =begin
Implements a simple atom defined by it's atomic number.
Keeps track of bonds it has to other atoms.
=end
require_relative "constants"
class Atom
def initialize(atomic_number = 6)
@number = atomic_number
end
def number
@number
end
def getAtomicSymbol
symbol = Constants::ATOMIC_SYMBOLS.key(@number)
if !symbol
raise KeyError, "No symbol found for atomic number #{@number} in ATOMIC_SYMBOLS table"
end
symbol
end
end
| true |
ab5131ee3d5edd7bbabd50fb82794508de798a17 | Ruby | steveoro/goggles_core | /lib/framework/interface_data_export.rb | UTF-8 | 4,247 | 2.78125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'common/format'
#
# = InterfaceDataExport
#
# - version: 3.00.02.20120204
# - author: Steve A.
#
# Framework "interface" Module for commonly used Data-Export methods. To be included in any
# EntityBase sibling implementation.
#
# Refactored from the original EntityBase implementation.
#
module InterfaceDataExport
# Returns attribute values as an array composed by their values, using the subset of field
# keys specified by data_symbols().
#
# Specifying a custom +export_syms+ Array allows to select a custom subset of instance columns to be exported.
#
def to_a(export_syms = self.class.data_symbols)
export_syms.collect do |sym|
value = send(sym)
fld_name = sym.to_s
# Check if it could be an association column:
idx = (fld_name =~ /_id\b/)
subentity_row = nil
if value.is_a?(ActiveRecord::Base)
subentity_row = value
elsif idx
subentity_row = send(fld_name[0..idx - 1])
end
if subentity_row # If it's an association column, search and use a value getter:
value_getter = [:name, :to_label, :get_full_name, :description].detect { |getter| subentity_row.respond_to?(getter) }
value = subentity_row.send(value_getter) if value_getter
end
value = value.to_f if value.is_a?(BigDecimal)
# If no optimal getter is rightly guessed, simply uses the default value obtained above:
if block_given?
value = yield value
else
value
end
end
end
# (Constant) Blank filler length of Floats converted to String values
#
CONVERTED_FLOAT2STRING_FIXED_LENGTH = 0 unless defined? CONVERTED_FLOAT2STRING_FIXED_LENGTH
# (Constant) precision of Floats converted to String values
#
CONVERTED_FLOAT2STRING_FIXED_PRECISION = 2 unless defined? CONVERTED_FLOAT2STRING_FIXED_PRECISION
# (Constant) Blank filler length of Floats converted to String percentages (including ' %')
#
CONVERTED_PERCENT2STRING_FIXED_LENGTH = 3 unless defined? CONVERTED_PERCENT2STRING_FIXED_LENGTH
# Similarly to +to_a()+, this returns all +data_symbols+ values as an Array, but with each
# element converted to a string.
#
# Each attribute String value is formatted where possible to avoid conflicts
# with all common CSV separators.(Mainly ';' for strings and '.' for floats.)
#
# Specifying a custom +export_syms+ Array allows to select a custom subset
# of instance columns to be exported.
#
# The date and time formats defaults used for this output are specified inside config/initializers/time_formats.rb
#
def to_a_s(export_syms = self.class.data_symbols,
precision = CONVERTED_FLOAT2STRING_FIXED_PRECISION,
rjustification = CONVERTED_FLOAT2STRING_FIXED_LENGTH,
datetime_format = Date::DATE_FORMATS[:agex_default_datetime],
date_format = Date::DATE_FORMATS[:agex_default_date],
float_pnt_char = '.')
to_a(export_syms) do |value|
Format.to_localized_string(value, precision, rjustification, datetime_format, date_format, float_pnt_char)
end
end
# Returns attribute values as a (horizontal) line of string values joined by a separator.
#
# Specifying a custom +export_syms+ Array it's possible to select a subset
# of instance columns to be exported.
#
def to_csv(separator = ';', export_syms = self.class.data_symbols)
to_a_s(export_syms).join(separator)
end
# Returns attribute values as a (vertical) form-like list of header field labels with
# their corresponding values converted to strings.
#
# Specifying a custom +export_syms+ Array it's possible to select a subset
# of instance columns to be exported.
#
def to_txt(field_separator = ': ', line_separator = "\r\n", export_syms = self.class.data_symbols)
result = export_syms.dup
values = to_a_s(export_syms)
result.each_with_index do |sym, idx|
result[idx] = "#{I18n.t(sym, scope: self.class.table_name.singularize.to_sym)}#{field_separator}#{values[idx]}"
end
result.join(line_separator)
end
#----------------------------------------------------------------------------
#++
end
#------------------------------------------------------------------------------
| true |
63a2969b631cf37e4bb782e91a8cea046beabdff | Ruby | aberant/worker-tracker | /lib/worker_tracker/server.rb | UTF-8 | 1,334 | 2.53125 | 3 | [
"MIT"
] | permissive | require 'sinatra/base'
require 'erb'
require 'worker_tracker'
module WorkerTracker
class Server < Sinatra::Base
dir = File.dirname(File.expand_path(__FILE__))
set :views, "#{dir}/server/views"
set :public, "#{dir}/server/public"
set :static, true
helpers do
include Rack::Utils
def path_prefix
request.env['SCRIPT_NAME']
end
def url(*path_parts)
[ path_prefix, path_parts ].join("/").squeeze('/')
end
alias_method :u, :url
end # helpers
def show(page, layout = true)
erb page.to_sym, {:layout => layout}
end
get "/" do
@workers = WorkerList.find
show :index
end
post "/register_worker" do
worker_data = JSON.parse(params[:worker_data])
worker_hash = {:host => worker_data["host"], :status => worker_data["status"]}
WorkerList.add_worker( worker_hash )
redirect "/"
end
post "/mark_as_busy" do
worker_data = JSON.parse(params[:worker_data])
host_ip = worker_data["host"]
WorkerList.mark_worker_as_busy( host_ip )
redirect "/"
end
post "/mark_as_available" do
worker_data = JSON.parse(params[:worker_data])
host_ip = worker_data["host"]
WorkerList.mark_worker_as_available( host_ip )
redirect "/"
end
end
end | true |
dbe05bd90936f35bb0b7ff851aea399d6f31f031 | Ruby | Kriordan/shortest_sequence | /program.rb | UTF-8 | 148 | 2.5625 | 3 | [] | no_license | require_relative 'shortest_sequence'
File.foreach(ARGV[0]) do |line|
sequence = ShortestSequence.new(line).shortest_sequence
print sequence
end | true |
03761e303201a3b3da0c6972b785788b0ea609f8 | Ruby | hoangtommy/sinatra | /web_guesser/web_guesser.rb | UTF-8 | 1,026 | 3.296875 | 3 | [] | no_license |
require 'sinatra'
require 'sinatra/reloader'
SECRET_NUMBER = rand(101)
# @@guesses_left = 5
# def reset
# @@guesses_left = 5
# message = 'new game, new number, new guesses'
# end
def check_guess(guess)
if guess === SECRET_NUMBER
message = "you guessed it! The secret number is #{SECRET_NUMBER}"
elsif guess - 5 > SECRET_NUMBER
message = 'way too high'
elsif guess > SECRET_NUMBER
message = "a little high."
elsif guess + 5 < SECRET_NUMBER
message = 'way too low'
elsif guess < SECRET_NUMBER
message = 'a little low'
end
end
def get_color(guess)
if guess === SECRET_NUMBER
color = 'green'
elsif guess + 5 < SECRET_NUMBER || guess - 5 > SECRET_NUMBER
color = 'red'
else
color = 'pink'
end
end
get '/' do
guess = params["guess"].to_i
message = check_guess(guess)
# to-fix: subtracting guesses left is only happening once here. need to create a loop?
# @@guesses_left -= 1
color = get_color(guess)
erb :index, :locals => {:message => message, :color => color}
end | true |
cdef26fa3359af4257a780551b74c828e7f4337c | Ruby | almozaz/codaisseurup | /spec/models/profile_spec.rb | UTF-8 | 1,092 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Profile, type: :model do
describe "validations" do
it { is_expected.to validate_presence_of(:first_name) }
it { is_expected.to validate_presence_of(:last_name) }
end
describe "#full_name?" do
let(:user) { create :user }
let!(:profile) {create :profile, user: user }
it "Check if returns full name in correct format" do
expect(profile.full_name).to eq("#{profile.first_name} #{profile.last_name}")
end
end
describe ".by_initial" do
subject { Profile.by_initial("S") }
let(:user1) { create :user }
let(:user2) { create :user }
let(:user3) { create :user }
let!(:sander) { create :profile, first_name: "Sander", user: user1 }
let!(:stefan) { create :profile, first_name: "Stefan", user: user2 }
let!(:wouter) { create :profile, first_name: "Wouter", user: user3 }
it "returns the profiles that match the initial" do
expect(subject).to match_array([stefan, sander])
end
it "is sorted on first_name" do
expect(subject).to eq([sander, stefan])
end
end
end
| true |
8c43550e6e32c2162c5a2f1b3408c01a402007f3 | Ruby | diegollams/LanguageAnalysis | /app/models/post.rb | UTF-8 | 3,151 | 3.25 | 3 | [] | no_license | class Post < ActiveRecord::Base
validates :body,:title,presence: true
has_and_belongs_to_many :words
before_save :evaluate
has_many :evaluated_words
HAPPY_VALUE = 1
SAD_VALUE = -1
NEGATION_WORDS = %w[ no nunca jamas]
ENHANCERS = %w[muy mucho demasiado exagerado]
REDUCERS = %w[poco nada ]
def evaluate
self.evaluated = 0
self.sum = 0
words.destroy_all
evaluate_words
end
def create_message
positive_words = self.positive_words.count
negative_words = self.negative_words.count
doubt_words = self.doubt_words.count
if self.sum > 0
rate = (positive_words * 100) / (positive_words + negative_words + doubt_words)
message = "Este post tiene una evaluacion de pensamientos positiva debido a que el rating es de #{sum}, y cuenta con #{positive_words} palabras positivas
y tan solo cuenta con #{negative_words} palabras negativas y #{doubt_words} palabras de duda"
elsif self.sum < 0
rate = (negative_words * 100) / (positive_words + negative_words + doubt_words)
message = "Este post tiene una evaluacion de pensamiento negativos debido a que el rating es de #{sum}, y cuenta con #{negative_words} palabras negativas
y tan solo cuenta con #{positive_words} palabras positivas y #{doubt_words} palabras de duda"
else
message = "Este post tiene una evaluacion de neutral debido a que el rating es de de 0, y cuenta con #{negative_words} palabras negativas
y con #{positive_words} palabras positivas y #{doubt_words} palabras de duda"
rate = 0
end
update_attribute('message', message)
update_attribute('rate', rate)
end
def positive_words
words.where(kind: Word::KIND_HAPPY)
end
def negative_words
words.where(kind: Word::KIND_SAD)
end
def doubt_words
words.where(kind: Word::KIND_DOUBT)
end
def evaluate_words
# here we save if get a negation we change the meaning of the folowing word
negation_word = false
words = self.body.split(/\s|\.|\,/) + self.title.split(/\s|\.|\,/)
words.each do |word|
if word.length < 3
if NEGATION_WORDS.include? word.downcase
negation_word = true
end
next
end
if NEGATION_WORDS.include? word.downcase
negation_word = true
end
match = Word.conjugation_search(word.downcase)
unless match.empty?
self.words << match
# if thera was a negation before the word we change the sense of
if negation_word
if match.first.happy?
self.sum += SAD_VALUE
self.sum += SAD_VALUE if word.include? '!'
else
self.sum += HAPPY_VALUE
self.sum += HAPPY_VALUE if word.include? '!'
end
else
if match.first.happy?
self.sum += HAPPY_VALUE
self.sum += HAPPY_VALUE if word.include? '!'
else
self.sum += SAD_VALUE
self.sum += SAD_VALUE if word.include? '!'
end
end
self.evaluated += 1
negation_word = false
end
end
end
end
| true |
92de97ade3dbe42e57220e31a0707c5cedfdc06a | Ruby | WSINTRA/square_array-dumbo-web-career-021819 | /square_array.rb | UTF-8 | 202 | 3.1875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def square_array(array)
# your code here
new_array =[]
array.each do |m|
output = m ** 2
new_array.push(output)
end
new_array
end
#test_array = [1,2,3,4,8]
#square_array(test_array)
| true |
eb9a8dc90924c65fc92200fad9792c26074da61d | Ruby | hampelm/grantr | /app/lib/data_importer.rb | UTF-8 | 1,192 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'csv'
class DataImporter
attr_accessor :filepath
def initialize(filepath)
self.filepath = filepath
end
def import_grants
csv_text = File.read Rails.root.join(filepath)
csv = CSV.parse(csv_text, :headers => true)
grants = []
csv.each do |row|
data = row.to_hash
ActiveRecord::Base.transaction do
granter = Organization.where(
name: data['granter']
).first_or_initialize
grantee = Organization.where(
name: data['grantee'],
city: data['grantee_city'],
state: data['grantee_state']
).first_or_initialize
grant = Grant.new(
from: granter,
to: grantee,
amount: data['amount'],
impact_area: data['impact_area'],
impact_neighborhood: data['impact_neighborhood'],
starts: Date.strptime(data['year'], "%Y"),
ends: Date.strptime(data['year'] + data['length_years'], "%Y"),
data_source: data['data_source'],
notes: data['notes']
)
granter.save!
grantee.save!
grant.save!
grants << grant
end
end
return grants
end
end
| true |
6c077888eeaf503ef2459807078baf94f4cae7ac | Ruby | fdavidcl/ruby-ten-lines | /enumerators.rb | UTF-8 | 2,026 | 4.15625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
puts <<END
# Some examples of Enumerators and Enumerable
# author: David Charte
# license: MIT
# source: https://libreim.github.io/blog/2015/08/24/ruby-enumerators/
END
################################################################################
# Primes Enumerator
################################################################################
primes = Enumerator.new do |yielder|
n = 2
loop do
yielder << n
# Find next prime
prime = false
until prime
n += 1
prime = (2..Math.sqrt(n).floor).all? do |i|
n % i != 0
end
end
end
end
puts "First 10 primes:"
puts primes.take(10).to_s
################################################################################
# Fibonacci Enumerator
################################################################################
fibonacci = Enumerator.new do |yielder|
a, b = 0, 1
loop do
yielder << a
a, b = b, a + b
end
end
puts "\nThe 200th element of the Fibonacci sequence:"
# Calculate 500 elements, retrieve last
puts fibonacci.take(200).drop(199)
################################################################################
# Enumerable Blog class
################################################################################
class Blog
include Enumerable
def initialize
# The class uses any kind of internal collection
@posts = [
{
:title => "Mean inequalities",
:author => "Mario"
},
{
:title => "Introduction to JavaScript",
:author => "David"
},
{
:title => "Genetic algorithms",
:author => "Andrés"
},
{
:title => "Introduction to Category Theory",
:author => "Mario"
}
]
end
# The each method should invoke 'yield' for every element
def each
@posts.each do |p|
yield p[:title], p[:author]
end
end
end
libreim = Blog.new
puts "\nPosts authored by Mario:"
puts libreim.select { |tit, aut| aut == "Mario" }.map &:first
| true |
174d5207f7aef3faa323896574f76167a04780c9 | Ruby | 2called-chaos/mcl | /lib/mcl/server.rb | UTF-8 | 982 | 2.546875 | 3 | [
"MIT"
] | permissive | module Mcl
class Server
attr_reader :app, :status, :players
attr_accessor :version, :boottime, :world, :datapacks
include Helper
include Getters
include IPC
include IO
def initialize app
@app = app
@version = $mcl_server_version
@boottime = $mcl_server_boottime
@world = $mcl_server_world
@datapacks = $mcl_server_datapacks
@status = $mcl_server_status || :stopped # booting, running, stalled, stopping
ipc_setup
end
def update_status status
$mcl_server_status = @status = status.to_sym
end
def died?
ipc_died?
end
def alive?
!died?
end
def invoke command = nil, &block
raise ArgumentError, "command or block must be given" if !command && !block
cmd = block ? VersionedCommand.new(app, &block).compile(@version) : command
cmd = cmd.call(app) if cmd.respond_to?(:call)
ipc_invoke(cmd[0] == "/" ? cmd[1..-1] : cmd)
end
end
end
| true |
fcd86c48afff0d6a41a6dbbda7f383af247de6e5 | Ruby | achyutdev/voice-app | /app/classes/queue_handler.rb | UTF-8 | 914 | 2.625 | 3 | [] | no_license | class QueueHandler
attr_accessor :id
def initialize(id)
@id=id
end
def make_queue
@required_id , @controller= OutboundList.find_controller(@id)
selected_contact_id=LinkOutboundContact.where(:outbound_call_id => @id)
@contact_in_queue=Queue.new
selected_contact_id.each do |for_each_one|
@contact_in_queue << ContactList.find_by(:id => for_each_one.outbound_contact_id).contact_number
end
return true
end
def make_call
until @contact_in_queue.empty?
@id=rand(10000)
number=@contact_in_queue.pop
puts number
calling_number="SIP/"+number.to_s
call_status=OutboundCallClass.new(calling_number, @required_id, @controller)
if call_status.status!=:active
puts 'calling ..'
call_status.start!
else
'try to sleep ..'
sleep(1) until call_status.status == :ended
end
end
end
end
| true |
0089a9eb6354614a367a981d0ff690ee98547d81 | Ruby | allizad/searchyll | /lib/searchyou/indexer.rb | UTF-8 | 4,494 | 2.640625 | 3 | [] | no_license | require 'json'
require 'net/http'
module Searchyou
class Indexer
BATCH_SIZE = 50
attr_accessor :indexer_thread
attr_accessor :queue
attr_accessor :timestamp
attr_accessor :uri
attr_accessor :working
def initialize(elasticsearch_url)
self.uri = URI(elasticsearch_url)
self.queue = Queue.new
self.working = true
self.timestamp = Time.now
end
# Public: Add new documents for batch indexing.
def <<(doc)
self.queue << doc
end
# Signal a stop condition for our batch indexing thread.
def working?
working || queue.length > 0
end
# A versioned index name, based on the time of the indexing run.
# Will be later added to an alias for hot reindexing.
# TODO: base index name should be configurable in the site.config.
def es_index_name
"jekyll-#{timestamp.strftime('%Y%m%d%H%M%S')}"
end
# Prepare an HTTP connection
def http_start(&block)
http = Net::HTTP.start(
uri.hostname, uri.port,
:use_ssl => (uri.scheme == 'https')
)
yield(http)
end
# Prepare our indexing run by creating a new index.
# TODO: make the number of shards configurable or variable
def prepare_index
create_index = http_post("/#{es_index_name}")
create_index.body = {
index: {
number_of_shards: 1,
number_of_replicas: 0,
refresh_interval: -1
}
}.to_json # TODO: index settings
http_start do |http|
resp = http.request(create_index)
end
# todo: mapping?
end
# Public: start the indexer and wait for documents to index.
def start
prepare_index
self.indexer_thread = Thread.new do
http_start do |http|
loop do
break unless working?
es_bulk_insert!(http, current_batch)
end
end
end
end
def http_put(path)
http_request(Net::HTTP::Put, path)
end
def http_post(path)
http_request(Net::HTTP::Post, path)
end
def http_get(path)
http_request(Net::HTTP::Post, path)
end
def http_delete(path)
http_request(Net::HTTP::Delete, path)
end
def http_request(klass, path)
req = klass.new(path)
req.content_type = 'application/json'
req.basic_auth(uri.user, uri.password)
req
end
# Given a batch (array) of documents, index them into Elasticsearch
# using its Bulk Update API.
# https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
# TODO: choose a better type name, or make it configurable?
def es_bulk_insert!(http, batch)
bulk_insert = http_post("/#{es_index_name}/post/_bulk")
bulk_insert.body = batch.map do |doc|
[ { :index => {} }.to_json, doc.to_json ].join("\n")
end.join("\n") + "\n"
puts bulk_insert.body
http.request(bulk_insert)
end
# Fetch a batch of documents from the queue. Returns a maximum of BATCH_SIZE
# documents.
def current_batch
count = 0
batch = []
while count < BATCH_SIZE && queue.length > 0
batch << queue.pop
count += 1
end
batch
end
# Public: Indicate to the indexer that no new documents are being added.
def finish
self.working = false
indexer_thread.join
finalize!
end
# Once documents are done being indexed, finalize the process by adding
# the new index into an alias for searching.
# TODO: cleanup old indices?
def finalize!
# refresh the index to make it searchable
refresh = http_post("/#{es_index_name}/_refresh")
# add replication to the new index
add_replication = http_put("/#{es_index_name}/_settings")
add_replication.body = { index: { number_of_replicas: 1 }}.to_json
# hot swap the index into the canonical alias
update_aliases = http_post("/_aliases")
update_aliases.body = {
"actions": [
{ "remove": { "index": "*", "alias": "jekyll" }},
{ "add": { "index": es_index_name, "alias": "jekyll" }}
]
}.to_json
# delete old indices
cleanup_indices = http_delete("/jekyll-*,-#{es_index_name}")
# run the prepared requests
http_start do |http|
http.request(refresh)
http.request(add_replication)
http.request(update_aliases)
http.request(cleanup_indices)
end
end
end
end
| true |
e70fed398fce45ac9ed7fc052cc48c925da2bb0c | Ruby | danherr/ar-lite | /lib/searchable.rb | UTF-8 | 381 | 2.515625 | 3 | [] | no_license | require_relative 'db_connection'
module Searchable
def where(params)
if params.is_a?(Hash)
results = DBConnection.execute(<<-SQL, params)
SELECT
*
FROM
#{self.table_name}
WHERE
#{params.map{|key, val| "#{key} = :#{key}"}.join(' AND ')}
SQL
results.map{|row_hash| self.new(row_hash)}
end
end
end
| true |
c271c0d3ab5ee528bda5427f02606c70affeb094 | Ruby | HarborEng/fortuneteller | /test/inflating_int_test.rb | UTF-8 | 2,685 | 2.671875 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class InflatingIntTest < MiniTest::Test
def test_growth
replacement_income = FortuneTeller::Utils::InflatingInt.new(
int: 1000_00,
start_date: Date.today
)
growth_rates = FortuneTeller::GrowthRateSet.new(
{ inflation: [1.02, 1.03] },
start_year: Date.today.year
)
assert_equal 1020_00, replacement_income.on(Date.today + 1.year, growth_rates: growth_rates)
assert_equal 1050_60, replacement_income.on(Date.today + 2.years, growth_rates: growth_rates)
assert_equal 1071_61, replacement_income.on(Date.today + 3.years, growth_rates: growth_rates)
assert_equal 1103_76, replacement_income.on(Date.today + 4.years, growth_rates: growth_rates)
# let's make sure the caching depends on the particular growth rates.
higher_rates = FortuneTeller::GrowthRateSet.new(
{ inflation: [1.10, 1.20] },
start_year: Date.today.year
)
assert_equal 1100_00, replacement_income.on(Date.today + 1.year, growth_rates: higher_rates)
assert_equal 1320_00, replacement_income.on(Date.today + 2.years, growth_rates: higher_rates)
assert_equal 1452_00, replacement_income.on(Date.today + 3.years, growth_rates: higher_rates)
assert_equal 1742_40, replacement_income.on(Date.today + 4.years, growth_rates: higher_rates)
end
def test_math
growth_rates = FortuneTeller::GrowthRateSet.new(
{ inflation: [1.01] }, start_year: Date.today.year
)
wages = FortuneTeller::Utils::InflatingInt.new(int: 100_00, start_date: Date.today)
one_half = wages * 0.50
div_three = wages / 3
times_two = wages + wages
just_one = wages + FortuneTeller::Utils::InflatingInt.zero
assert_equal 50_50, one_half.on(Date.today + 1.year, growth_rates: growth_rates)
assert_equal 33_66, div_three.on(Date.today + 1.year, growth_rates: growth_rates)
assert_equal 202_00, times_two.on(Date.today + 1.year, growth_rates: growth_rates)
assert_equal 101_00, just_one.on(Date.today + 1.year, growth_rates: growth_rates)
end
def test_growth_keys
inflation = FortuneTeller::Utils::InflatingInt.new(
int: 1000_00,
start_date: Date.today,
)
wage_growth = FortuneTeller::Utils::InflatingInt.new(
int: 1000_00,
start_date: Date.today,
growth_key: :wage_growth
)
growth_rates = FortuneTeller::GrowthRateSet.new(
{ inflation: [1.02, 1.03],
wage_growth: [1.10, 1.20] },
start_year: Date.today.year
)
assert_equal 1103_76, inflation.on(Date.today + 4.years, growth_rates: growth_rates)
assert_equal 1742_40, wage_growth.on(Date.today + 4.years, growth_rates: growth_rates)
end
end | true |
5ea486a62076296d8525471f63ee946e8f103a46 | Ruby | dsiefert/test | /dungeon_level.rb | UTF-8 | 12,755 | 2.65625 | 3 | [] | no_license | require 'ncurses'
require_relative 'point'
require_relative 'tile'
require_relative 'monster'
require_relative 'fov'
require_relative 'test_items'
module Roguelike
class DungeonLevel
include FOV
include Event::Capable
include Roguelike::TestItems
ROOM_RATIO_HIGH = 0.30
ROOM_RATIO_LOW = 0.20
LOOP_RATIO = 0.10
ROOM_ATTEMPTS = 500
COLUMNS = 78
ROWS = 23
attr_reader :columns, :rows, :rooms, :corridors, :offset_y, :offset_x, :map_attempts, :up_square, :place
attr_writer :depth
attr_accessor :unmarked_rooms
def self.design(&block)
Roguelike::Design.new(block)
end
def initialize(place, title = nil, map = nil, options = {})
Event::Event.new(:initialize, self)
map = map.draw if map && map.is_a?(Roguelike::Design)
@place = place
@columns = COLUMNS
@rows = ROWS
@custom_map = map
@title = title
@rooms = []
@unmarked_rooms = []
@corridors = []
@movables = []
@map_attempts = 0
@tiles = []
@columns.times do |x|
@tiles[x] = []
@rows.times do |y|
@tiles[x][y] = nil
end
end
@offset_x = ((80 - @columns) / 2).floor
@offset_y = ((25 - @rows) / 2).floor
if !@custom_map
Event::Event.new(:create_start, self)
create_map
else
create_tiles
end
unless @custom_map
listen_for(:enter, Roguelike::Player) do |me|
me.ignore(:enter)
Dispatcher.queue_message('These caves seem endless.')
end
end
self
end
def draw(display_messages = true)
calculate_fov
# clear what's there
rows.times do |row|
$window.move(row + offset_x, 0)
$window.clrtoeol
end
# actually draw it onscreen
# on every point on the map:
# draw tile if visible
# every item (inc monsters inc PC)
# draw item if item is on a visible point and is visible
@tiles.each do |col|
col.each { |tile| tile.draw if tile.visible? || tile.remembered? }
end
# draw the frame around the map
frame_symbol = "+"
if @offset_y > 0 && @offset_x > 0
$window.attron(Ncurses::COLOR_PAIR(8))
$window.mvaddstr(@offset_y - 1, @offset_x - 1, frame_symbol * (@columns + 2))
@rows.times do |row|
$window.mvaddstr(row + @offset_y, @offset_x - 1, frame_symbol)
$window.mvaddstr(row + @offset_y, @offset_x + @columns, frame_symbol)
end
$window.mvaddstr(@rows + @offset_y, @offset_x - 1, frame_symbol * (@columns + 2))
end
# and the title. note that we trim it to 72 max to allow three columns plus a space on either side
$window.mvaddstr(@offset_y - 1, 3, " #{title.slice(0, 72)} ")
$window.mvaddstr(@offset_y - 1, @offset_x + @columns - 2 - depth.to_s.length, " #{depth} ")
#items!
@movables.each do |movable|
# TODO: Ensure monsters always draw after items
if square(movable.x, movable.y).visible? || (movable.is_a?(Items::Item) && square(movable.x, movable.y).remembered?)
Event::Event.new(:see, Game.player, target: movable) if square(movable.x, movable.y).visible?
movable.draw unless movable.invisible
end
end
Game.player.draw
Dispatcher.display_messages if display_messages
# set the cursor to the player's current position
$window.move(Game.player.y + offset_y, Game.player.x + offset_x)
# all done!
$window.refresh
Event::Event.new(:draw_complete, self)
end
def depth
@depth ||= 1
end
def map
self
end
def title
@title || @place.title
end
def unoccupied?(x, y)
tile_type(x, y) == false
end
def walkable?(x, y = nil)
return false if x.nil?
x, y = x unless y
return false if Game.player && x == Game.player.x && y == Game.player.y
walkable_except_player?(x, y)
end
def empty?(x, y = nil)
return false if x.nil?
x, y = x unless y
walkable?(x, y) && movables(x, y).empty?
end
def unfilled?(x, y = nil)
return false if x.nil?
x, y = x unless y
walkable?(x, y) && movables(x, y).reject{ |m| !m.walkable? }.empty?
end
def walkable_except_player?(x, y = nil)
return false if x.nil?
x, y = x if y.nil?
@movables.each do |movable|
next if movable.walkable?
return false if movable.x == x && movable.y == y
end
!square(x, y).transit_time.nil?
end
def random_square(*options)
x = Random.rand(0 .. columns - 1)
y = Random.rand(0 .. rows - 1)
options.each do |opt|
return random_square(*options) unless send(opt, x, y)
end
[x, y]
end
def movables(x = nil, y = nil)
return @movables unless x
x, y = x unless y
@movables.select{ |m| m.x == x && m.y == y }
end
def square(x, y = nil)
x, y = x unless y
# return something that resembles a tile if given out-of-bounds values, for FOV calculation
return FakeTile.instance(x, y) unless (0 .. (columns - 1)).include?(x) && (0 .. (rows - 1)).include?(y)
@tiles[x][y]
end
def area_empty?(x1, y1, x2, y2, options = {})
exceptions = options.key?(:except) ? options.delete(:except) : []
if x2 < x1
x_range = (x2 .. x1)
else
x_range = (x1 .. x2)
end
if y2 < y1
y_range = (y2 .. y1)
else
y_range = (y1 .. y2)
end
x_range.each do |x|
y_range.each do |y|
next if exceptions.include?([x, y])
return false if tile_type(x, y)
end
end
true
end
def room_area
val = 0
rooms.each do |room|
val += room.area
end
val
end
def add_movable(movable)
@movables << movable
movable
end
def remove_movable(movable)
@movables -= [movable]
end
def reveal
columns.times do |x|
rows.times do |y|
square(x, y).reveal
end
end
end
private
def random_row(range = nil)
return Random.rand(rows / 2) * 2 + 1 unless range
odd_from_range(range)
end
def random_column(range = nil)
return Random.rand(columns / 2) * 2 + 1 unless range
odd_from_range(range)
end
def odd_from_range(range)
range.to_a.select{ |x| x.odd? }.sample
end
def random_width
Random.rand(((Room::MAX_WIDTH - Room::MIN_WIDTH) / 2) + 1) * 2 + Room::MIN_WIDTH
end
def random_height
Random.rand(((Room::MAX_HEIGHT - Room::MIN_HEIGHT) / 2) + 1) * 2 + Room::MIN_HEIGHT
end
def max_row
(rows - 2).odd? ? rows - 2 : rows - 3
end
def max_column
(columns - 2).odd? ? columns - 2 : columns - 3
end
def create_map
# wipe the map in case this isn't the first go-round
@rooms = []
@unmarked_rooms = []
@corridors = []
@tiles = []
@movables = []
@columns.times do |x|
@tiles[x] = []
@rows.times do |y|
@tiles[x][y] = nil
end
end
room_ratio = Random.rand(ROOM_RATIO_LOW .. ROOM_RATIO_HIGH)
@map_attempts += 1
# start by adding a room
add_room
ROOM_ATTEMPTS.times do
# pick a room at random, try a new one if that one's joins are all used up
room = nil
until room
room = @rooms.sample.with_joins
end
# try drawing a corridor -- rinse and repeat if it's looped
join = room.add_join
start_x, start_y, direction = join.x, join.y, join.direction
new_corridor = Corridor.new(start_x, start_y, direction, self) rescue nil
if new_corridor && new_corridor.looped && (Random.rand < LOOP_RATIO) && !room.loopy
room.loopy = true
@corridors.push(new_corridor)
end
new_corridor = nil if new_corridor && new_corridor.looped
# 50% of the time draw another corridor at the end of that -- toss this one if its looped
# we now have a guaranteed corridor with an endpoint, possibly with some looped ones as well
# try add_room_from_edge
# if false, kill the new corridor
new_corridor = nil if new_corridor && !add_room_from_edge(new_corridor.end_x, new_corridor.end_y, new_corridor.direction)
# did it work? then let's go!
if new_corridor
@corridors.push(new_corridor)
else
room.pop_join
end
if (room_area / (rows * columns).to_f) > room_ratio
create_tiles
break
end
end
# if even after ROOM_ATTEMPTS tries, we still don't have enough room area . . .
return create_map if (room_area / (rows * columns).to_f) < room_ratio
populate_map
# trigger event
return Event::Event.new(:create_complete, self)
end
def add_room(coordinates = {})
# specify four coordinates to mark the upper-left and lower-right corners of the room.
# or we'll just choose our own damn selves!
if coordinates.key?(:x1) && coordinates.key?(:y1) && coordinates.key?(:x2) && coordinates.key?(:y2)
x1, y1, x2, y2 = coordinates.keys(:x1, :y1, :x2, :y2)
return false if overlaps_room?(x1, y1, x2, y2)
else
x1 = random_column
y1 = random_row
x2 = x1 + random_width - 1
y2 = y1 + random_height - 1
if x2 > max_column
x1 -= (x2 - max_column)
x2 = max_column
end
if y2 > max_row
y1 -= (y2 - max_row)
y2 = max_row
end
return add_room if !area_empty?(x1, y1, x2, y2)
end
room = Room.new(x1, y1, x2, y2, self)
@rooms.push(room)
@unmarked_rooms.push(room)
room
end
def add_room_from_edge(x, y, direction)
# TODO: This needs to avoid making rooms adjacent to non-rock spaces excluding the edge passed to it
# if this returns false, you most likely need to pick a new starting point,
# not just try running it again.
# this is not always true, but it's true often enough that it'll be faster to
# scrap it and try something else
return false if x <= 1 || y <= 1 || x > max_column || y > max_row
# check to ensure enough room is available, according to the direction
# note that it's a bit dumb about verifying sufficient clear area -- i.e.
# it errs on the side of giving up. this should be fine, but it may be worth
# revising at some point
if direction == 0
return false if x > max_column - Room::MIN_WIDTH
return false unless area_empty?(x + 1, y - 2, x + 4, y + 2)
max_width = max_column - x
elsif direction == 1
return false if y < Room::MIN_HEIGHT + 1
return false unless area_empty?(x - 2, y - 4, x + 2, y - 1)
max_height = y - 1
elsif direction == 2
return false if x < Room::MIN_WIDTH + 1
return false unless area_empty?(x - 4, y - 2, x - 1, y + 2)
max_width = x - 1
elsif direction == 3
return false if y > max_row - Room::MIN_HEIGHT
return false unless area_empty?(x - 2, y + 4, x + 2, y + 1)
max_height = max_row - y
end
# try several times to make a room before giving up
5.times do |iteration|
if direction.odd? # up-and-down style room
width = random_width
height = odd_from_range(Room::MIN_HEIGHT .. [max_height, Room::MAX_HEIGHT].min)
x1_min = [x - width + 1, 1].max
x1 = odd_from_range(x1_min .. x)
x2 = x1 + width - 1
# try moving it if it's too far to the right
if x2 > max_column
x2 = max_column
x1 = x2 - width + 1
end
if direction == 1
y2 = y - 1
y1 = y2 - height + 1
else
y1 = y + 1
y2 = y1 + height - 1
end
else # left-and-right style room
width = odd_from_range(Room::MIN_WIDTH .. [max_width, Room::MAX_WIDTH].min)
height = random_height
y1_min = [y - height + 1, 1].max
y1 = odd_from_range(y1_min .. y)
y2 = y1 + height - 1
# try moving it if it's too far down
if y2 > max_row
y2 = max_row
y1 = y2 - height + 1
end
if direction == 0
x1 = x + 1
x2 = x1 + width - 1
else
x2 = x - 1
x1 = x2 - width + 1
end
end
if area_empty?(x1, y1, x2, y2)
room = Room.new(x1, y1, x2, y2, self)
@rooms.push(room)
@unmarked_rooms.push(room)
return room
end
end
# couldn't make a room! sad!
false
end
def create_tiles
if !@custom_map
rows.times do |y|
columns.times do |x|
if x == 0 || x == columns - 1 || y == 0 || y == rows - 1
type = :hard_rock
else
type =
case tile_type(x, y)
when true
:dirt
when 1
:obsidian
when 2
:moss
when false
:soft_rock
end
end
@tiles[x][y] = Tile.new(x, y, type)
end
end
else
rows.times do |y|
columns.times do |x|
@tiles[x][y] = Tile.new(x, y, @custom_map[x][y])
end
end
end
end
def tile_type(x, y)
# decided to check corridors first, to make it more obvious if they erroneously overlap things
corridors.each { |corridor| return true if corridor.contains?(x, y) }
# look through @rooms, ensure square is not in any of them
rooms.each{ |room| return room.contains?(x, y) if room.contains?(x, y) }
false
end
end
end
| true |
9706a433507f2f9aa2762f7a6a67f1c722b88ec0 | Ruby | sugiyamam/furima-19345 | /spec/models/item_spec.rb | UTF-8 | 2,919 | 2.515625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Item, type: :model do
describe '#create' do
before do
@item = FactoryBot.build(:item)
end
describe '商品出品機能'
context 'うまくいく場合' do
it '全て入力されていれば出品できる' do
expect(@item).to be_valid
end
end
context 'うまくいかない場合' do
it 'image:ファイル未選択' do
@item.image = nil
@item.valid?
expect(@item.errors.full_messages).to include("Image can't be blank")
end
it 'name:未入力' do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it 'description:未入力' do
@item.description = ''
@item.valid?
expect(@item.errors.full_messages).to include("Description can't be blank")
end
it 'category_id:未入力' do
@item.category_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('Category is invalid')
end
it 'status_id:未入力' do
@item.status_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('Status is invalid')
end
it 'delivery_price_id:未入力' do
@item.delivery_price_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('Delivery price is invalid')
end
it 'prefecture_id:未入力' do
@item.prefecture_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('Prefecture is invalid')
end
it 'delivery_time_id:未入力' do
@item.delivery_time_id = 1
@item.valid?
expect(@item.errors.full_messages).to include('Delivery time is invalid')
end
it 'price:金額が未入力で空白' do
@item.price = ''
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
it 'price:半角英数混合で入力' do
@item.price = 'a1'
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
it 'price:半角英語のみで入力' do
@item.price = 'aA'
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
it 'price:金額が300未満の数値入力' do
@item.price = 299
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
it 'price:金額が半角以外' do
@item.price = '299'
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
it 'price:金額が10000000以上の数値入力' do
@item.price = 10_000_000
@item.valid?
expect(@item.errors.full_messages).to include('Price is invalid')
end
end
end
end
| true |
b43bee91bbcfeaf72190893a16131cb15997468f | Ruby | iFixit/nagnagnag | /log.rb | UTF-8 | 183 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'logger'
class Log
def self.instance
@@logger ||= Logger.new(STDOUT)
end
def self.method_missing(method, *args)
instance.send(method, *args)
end
end
| true |
41bbc8a098193e8abd3caa7a82f27f2ed4911c03 | Ruby | lowentropy/more_magic | /app/helpers/application_helper.rb | UTF-8 | 406 | 2.859375 | 3 | [] | no_license | module ApplicationHelper
def emphasize_letters(text, letters)
letters = letters.split ''
text = text.split ''
str = ""
until text.empty?
letter = text.shift
if letter.upcase == letters[0].upcase
str << "<b>#{letter}</b>"
letters.shift
else
str << letter
end
break if letters.empty?
end
str.html_safe + text.join('')
end
end
| true |
680771989b2b2d0f050c1a963bb370dc0f58d173 | Ruby | wrburgess/grand-central | /app/models/weather.rb | UTF-8 | 855 | 3.328125 | 3 | [] | no_license | class Weather
def initialize(zipcode)
root_url = "http://api.openweathermap.org/data/2.5/weather"
request_url = "#{root_url}?q=#{zipcode}"
@data = ActiveSupport::JSON.decode(Nokogiri::HTML(open(request_url)))
end
def current_date
Time.now.strftime "%a, %b %e"
end
def current_time
Time.now.strftime "%l:%M %p"
end
def current_temp
temp = to_fahrenheit @data["main"]["temp"]
"#{temp} F"
end
def high_temp
temp = to_fahrenheit @data["main"]["temp_max"]
"#{temp} F"
end
def low_temp
temp = to_fahrenheit @data["main"]["temp_min"]
"#{temp} F"
end
def chance_of_rain
"30%"
end
def wind
speed = @data["wind"]["speed"]
"#{speed} mph"
end
private
def to_fahrenheit(temp)
celsius = temp - 273
converted = celsius * 1.8 + 32
converted.round
end
end | true |
6e566aa2c3038941cecffae5c4a8c2d967b0ac1e | Ruby | wagura-maurice/glowing-umbrella | /lib/api/h_mac_helper.rb | UTF-8 | 2,754 | 3.125 | 3 | [
"MIT"
] | permissive | require 'openssl'
require 'base64'
require 'uri'
require 'api/hash_helper'
class HMacHelper
def self.format_request_string(http_verb, uri, api_key, timestamp, params = nil)
clean_http_verb = self.format_http_verb(http_verb)
clean_uri = self.extract_api_endpoint_from_uri(uri)
clean_api_key = self.format_api_key(api_key)
clean_timestamp = self.format_timestamp(timestamp)
clean_params = self.format_custom_params(params)
# Put the base query together, without the optional GET/POST params for now.
formatted_query = "#{clean_http_verb}\n#{clean_uri}\n#{clean_params}\nApiKey=#{clean_api_key}\nTimestamp=#{clean_timestamp}\n"
end
def self.format_http_verb(http_verb)
http_verb.strip.upcase
end
def self.extract_api_endpoint_from_uri(uri)
clean_uri = uri.downcase.strip.chomp("/").gsub /https?:\/\//, "" # Remove protocol
clean_uri.gsub /\?.*/, "" # Remove query params. See byte order below
end
def self.format_api_key(api_key)
#Rails automatically URL decodes parameters
#Hence URL escape it again to ensure an identical signature calculation
unless api_key.include? "%20"
return URI.escape(api_key)
end
api_key
end
def self.format_timestamp(timestamp)
#Rails automatically URL decodes the timestamp or any parameter for that fact
#Hence URL escape it again to ensure an identical signature calculation
unless timestamp.include? "%20"
return URI.escape(timestamp)
end
timestamp
end
def self.format_custom_params(params)
if params && params.size > 0
sorted_params = ""
# Rails submits PUT/POST calls with nested attributes. Sample:
# params: {
# user: {
# first_name: "John",
# last_name: "Doe"
# }
# }
# We hence we recursively parse the tree and flatten the hash to format the query.
flat_hash = HashHelper.flatten_hash params
sorted_flat_hash = flat_hash.sort.to_h #Ruby sorts in ASCII byte order. Hurray
sorted_flat_hash.each do |k, v|
value = v.to_s
if v.is_a?(Array)
value = "[#{v.join(",")}]"
end
sorted_params << "#{URI.escape(k.to_s)}=#{URI.escape(value)}&"
end
sorted_params.chomp! "&" #Remove trailing ampersand
return "#{sorted_params}\n"
end
return ""
end
def self.compute_hmac_signature(request_string, api_secret)
hmac = OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), api_secret, request_string)
#Base 64 encode the HMac
base64_signature = Base64.encode64(hmac)
#Remove whitespace, new lines and trailing equal sign.
base64_signature.strip().chomp("=")
end
end
| true |
d0c9c34153587218c74033b508de7e56303c27c4 | Ruby | Trevoke/SGFParser | /lib/sgf/variation.rb | UTF-8 | 216 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class SGF::Variation
attr_reader :root, :size
def initialize
@root = SGF::Node.new
@size = 1
end
def append(node)
@root.add_children node
@size += 1
end
end
| true |
7391ecf71047dca69d0d550c586bfe2d4a24b3a5 | Ruby | shimta020/AtCoder | /beginners_selection/c3.rb | UTF-8 | 1,155 | 3.515625 | 4 | [] | no_license | # n = gets.to_i
# arr = []
# n.times{ |n| arr << gets.split.map(&:to_i) }
# ans = 'Yes'
# arr.each_with_index do |_, key|
# if key >= 1
# p _
# t = arr[key][0] - arr[key-1][0]
# distance = (arr[key][1] - arr[key][1]).abs + (arr[key][2] - arr[key][2]).abs
# if t < distance
# ans = 'No'
# break
# elsif (t.odd? && distance.even?) || (t.even? && distance.odd?)
# ans = 'No'
# end
# end
# end
# arr.each_with_index do |_, key|
# if key >= 1
# t = arr[key][0] - arr[key-1][0]
# distance = (arr[key][1] - arr[key][1]).abs + (arr[key][2] - arr[key][2]).abs
# if t < distance && ((t.odd? && distance.even?) || (t.even? && distance.odd?))
# ans = 'No'
# break
# end
# end
# end
# puts ans
n = gets.strip.to_i
t_old = x_old = y_old = 0
n.times do
t, x, y = gets.strip.split.map(&:to_i)
#移動可能時刻と最短到着時刻を計算
able = (t_old - t).abs
dist = (x_old - x).abs + (y_old - y).abs
if (t + x + y) % 2 != 0 || able < dist #<-条件追加
puts 'No'
exit
end
#今回入力された値を記録
t_old = t
x_old = x
y_old = y
end
puts 'Yes' | true |
af26a6dbe3e25da0f230283947d0695aafac2057 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/meetup/22732905eec146888db3e9cdb9b1cc13.rb | UTF-8 | 736 | 3.5 | 4 | [] | no_license | class Meetup
WDAYS = [:sunday, :monday, :tuesday, :wednesday, :thursday, :friday, :saturday]
ORDER = {:first => 0, :second => 1, :third => 2, :fourth => 3, :last => -1}
def initialize month, year
@month = month
@year = year
end
def find_day weekday
last = Date.new(@year, @month, -1).mday
(1..last).each.with_object([]) {|d, arr|
this_date = Date.new(@year, @month, d)
arr << this_date if WDAYS[this_date.wday] == weekday
}
end
def day weekday, modifier
if modifier == :teenth
(13..19).each {|x|
this_date = Date.new(@year, @month, x)
return this_date if WDAYS[this_date.wday] == weekday
}
end
return find_day(weekday)[ORDER[modifier]]
end
end
| true |
4489b01abad576f97c8707c09c43c1bc60fccdb6 | Ruby | wmavis/timeclock | /app/models/model.rb | UTF-8 | 107 | 2.65625 | 3 | [] | no_license | class Model
def initialize(attributes)
attributes.each do |k,v|
self.send("#{k}=", v)
end
end
end
| true |
5b293bed78aad8399238078eb1cb279cd3a6b7c7 | Ruby | jacksonlink/JogaPedra | /Resultados.rb | UTF-8 | 2,920 | 2.921875 | 3 | [] | no_license | #receber o array de partidas calcula as bonificacoes de cada jogada, soma as jogadas e calcula o resultado geral da partida
class Resultados
def initialize(value)
@partidas = value
end
def resultado_partida
@resultado_array = []
@partidas.each_with_index do |lines, index|
@mandante = lines[0]['partida'][0][0]['mandante']
@visitante = lines[0]['partida'][0][0]['visitante']
@mandante_pulos_j1 = lines[0]['partida'][0][0]['mandante_pulos'].to_i
@visitante_pulos_j1 = lines[0]['partida'][0][0]['visitante_pulos'].to_i
@mandante_pulos_j2 = lines[0]['partida'][1][0]['mandante_pulos'].to_i
@visitante_pulos_j2 = lines[0]['partida'][1][0]['visitante_pulos'].to_i
@mandante_pulos_j3 = lines[0]['partida'][2][0]['mandante_pulos'].to_i
@visitante_pulos_j3 = lines[0]['partida'][2][0]['visitante_pulos'].to_i
#soma pontuacao da partida
@mandante_soma_pulos_pertida = @mandante_pulos_j1 + @mandante_pulos_j2 + @mandante_pulos_j3
@visitante_soma_pulos_pertida = @visitante_pulos_j1 + @visitante_pulos_j2 + @visitante_pulos_j3
#bonificacao por pontuacao superior a 10 na partida
@mandante_bonus_1 = @mandante_soma_pulos_pertida > 10 ? 2 : 0
@visitante_bonus_1 = @visitante_soma_pulos_pertida > 10 ? 2 : 0
#bonificacao por pulos iguais nas tres jogadas
@visitante_bonus_2 = 0
@mandante_bonus_2 = 0
if (@mandante_pulos_j1 == @mandante_pulos_j2) and (@mandante_pulos_j2 == @mandante_pulos_j3)
@mandante_bonus_2 = (@mandante_soma_pulos_pertida * 1.1).round
end
if (@visitante_pulos_j1 == @visitante_pulos_j2) and (@vistante_pulos_j2 == @visitante_pulos_j3)
@visitante_bonus_2 = (@visitante_soma_pulos_pertida * 1.1).round
end
#pontuacao final
@mandante_placar_final = @mandante_soma_pulos_pertida + @mandante_bonus_1 + @mandante_bonus_2
@visitante_placar_final = @visitante_soma_pulos_pertida + @visitante_bonus_1 + @visitante_bonus_2
@vencedor = ""
if @mandante_soma_pulos_pertida != @visitante_soma_pulos_pertida
@vencedor = @mandante_soma_pulos_pertida > @visitante_soma_pulos_pertida ? @mandante : @visitante
end
@jogadores_punidos = []
if @mandante_soma_pulos_pertida < 3
@jogadores_punidos<<@mandante
end
if @visitante_soma_pulos_pertida < 3
@jogadores_punidos<<@visitante
end
@resultado = [
"mandante" => @mandante,
"visitante" => @visitante,
"mandante_placar_final" => @mandante_placar_final,
"visitante_placar_final" => @visitante_placar_final,
"vencedor" => @vencedor == "" ? "null" : @vencedor,
"punicao" => @jogadores_punidos == "" ? "null" : @jogadores_punidos,
]
@resultado_array << @resultado
end
@resultado_array
end
end | true |
cbdc80f9b57f3770b49c84a52e9b416b286abb57 | Ruby | zjwhitehead/iterable-api-client | /lib/iterable/in_app.rb | UTF-8 | 1,534 | 2.6875 | 3 | [
"MIT"
] | permissive | module Iterable
##
#
# Interact with /inApp API endpoints
#
# @example Creating in app endpoint object
# # With default config
# in_app = Iterable::InApp.new
#
# # With custom config
# conf = Iterable::Config.new(token: 'new-token')
# in_app = Iterable::InApp.new(config)
class InApp < ApiResource
##
#
# Get in-app messages for a user by email
#
# @param email [String] *required* Email of user who received the message to view. Required if no user_id present.
# @param count [Integer] Number of messages to return, defaults to 1
# @param attrs [Hash] Hash of query attributes like platform, SDKVersion, etc.
#
# @return [Iterable::Response] A response object
def messages_for_email(email, count: 1, **attrs)
attrs[:email] = email
attrs[:count] = count
messages(attrs)
end
##
#
# Get in-app messages for a user by user_id
#
# @param email [String] *required* Email of user who received the message to view. Required if no user_id present.
# @param count [Integer] Number of messages to return, defaults to 1
# @param attrs [Hash] Hash of query attributes like platform, SDKVersion, etc.
#
# @return [Iterable::Response] A response object
def messages_for_user_id(user_id, count: 1, **attrs)
attrs[:userId] = user_id
attrs[:count] = count
messages(attrs)
end
private def messages(**attrs)
Iterable.request(conf, '/inApp/getMessages', attrs).get
end
end
end
| true |
2df0976e8e4a8dd0582544838e90b53585f1c448 | Ruby | kirtmartintx/Iron_yard_day6 | /lab_redux.rb | UTF-8 | 1,972 | 3.140625 | 3 | [] | no_license | require './shipment'
puts "hai"
payment = 0
leelabonus = 0
leelatrips = 0
frybonus = 0
frytrips = 0
amybonus = 0
amytrips = 0
benderbonus = 0
bendertrips = 0
venustotal = 0
jupitertotal = 0
saturntotal = 0
neptunetotal = 0
plutototal = 0
countearth = 0
countmars = 0
counturanus = 0
leelas_deliveries = 0
open("planet_express_logs").each do |line|
values_array = line.chomp.split(",")
shipment = Shipment.new
shipment.destination = values_array[0]
shipment.item = values_array[1]
shipment.crates = values_array[2].to_i
shipment.payment = values_array[3].to_i
#puts shipment.inspect
payment += shipment.payment
case shipment.destination
when "Earth"
countearth += shipment.payment
frybonus += shipment.payment/10
frytrips += 1
when "Mars"
countmars += shipment.payment
amybonus += shipment.payment/10
amytrips += 1
when "Uranus"
counturanus += shipment.payment
benderbonus += shipment.payment/10
bendertrips += 1
else
leelas_deliveries = shipment.payment
leelabonus += shipment.payment/10
leelatrips += 1
end
case shipment.destination
when "Jupiter"
jupitertotal += shipment.payment
when "Venus"
venustotal += shipment.payment
when "Saturn"
saturntotal += shipment.payment
when "Pluto"
plutototal += shipment.payment
end
end
p "Payment of #{plutototal} from trips to Earth."
p "Payment of #{saturntotal} from trips to Earth."
p "Payment of #{venustotal} from trips to Earth."
p "Payment of #{neptunetotal} from trips to Earth."
p "Payment of #{jupitertotal} from trips to Earth."
p "Our take for this week is #{payment}."
p "Payment of #{countearth} from trips to Earth."
p "Payment of #{countmars} from trips to Mars."
p "Payment of #{counturanus} from trips to Uranus."
p "Leelas' bonus is #{leelabonus}."
p "Frys' bonus is #{frybonus}."
p "Benders' bonus is #{benderbonus}."
p "Fry made #{frytrips} trips."
p "Amy made #{amytrips} trips."
p "Bender made #{bendertrips} trips."
p "Leela made #{leelatrips} trips."
| true |
561f828665a5a407d3b26a241d92f137c1596856 | Ruby | kaganon/reverse_sentence | /lib/reverse_sentence.rb | UTF-8 | 1,199 | 3.859375 | 4 | [] | no_license | # A method to reverse the words in a sentence, in place.
def reverse_sentence(my_sentence)
return if my_sentence == nil || my_sentence == ''
i = 0
end_of_s = my_sentence.length - 1
# reverse the whole sentence
reverse_string(my_sentence, i, end_of_s)
# reverse the words
reverse_words(my_sentence)
return
raise NotImplementedError
end
def reverse_words(my_words)
i = 0
all_words_end = my_words.length
while i < all_words_end
while my_words[i] == ' ' && i < all_words_end
i += 1
end
start_of_word = i
while my_words[i] != ' ' && i < all_words_end
i += 1
end
end_of_word = i - 1
reverse_string(my_words, start_of_word, end_of_word)
end
return my_words
raise NotImplementedError
end
def reverse_string(string, start_of_word, end_of_word)
i = start_of_word
j = end_of_word
while i < j
temp = string[i]
string[i] = string[j]
string[j] = temp
i += 1
j -= 1
end
return string
end
=begin
Time complexity is linear O(3n), where n is the length of the input(my_sentence)
Space complexity is constant O(1), because the storage remains the same
even if the input (my_sentece) increases.
=end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.