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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
827cc34b6114a51236589fa72e08a260292c64cf
|
Ruby
|
bbfsdev/bbfs
|
/bin/run_in_background/daemon_wrapper
|
UTF-8
| 3,616
| 2.625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# Wrapper script, that can receive commands from Windows Service Control and run user script,
# provided as it's argument.
# NOTE This wrapper script doesn't intended to be run from command line,
# rather be started and controlled by Windows Service Control.
# For more information see documentations and examples of win32-daemon library.
# usage: $0 <abs path to Ruby> <abs path to script> [blank-separated list of script's arguments]
# example: C:\ruby.exe c:\dev\daemon_wrapper c:\ruby.exe c:\dev\test_app 1000 -dbg=true
require 'win32/daemon'
#require 'win32/process'
include Win32
begin
require 'params'
require 'log'
rescue LoadError
$:.unshift(File.join(File.dirname(File.expand_path(__FILE__)), '..', '..', 'lib'))
$:.unshift(File.join(File.dirname(File.expand_path(__FILE__)), '..', '..'))
require 'params'
require 'log'
end
Params['log_write_to_console'] = false
# On WindowsXP log can be found under:
# C:/Documents and Settings/NetworkService/.bbfs/daemon_wrapper_<pid>.log
Params['log_file_name'] = File.join(Dir.home, '.bbfs', "#{File.basename(__FILE__)}_#{Process.pid}.log")
Log.init
class WrapperDaemon < Daemon
def service_main
Log.debug1 "Wrapper starts: #{ARGV.join(' ')}"
@pid = Process.spawn ARGV.join(' ')
Log.debug1 "Wrapper inner app pid: #{@pid}"
while running?
begin
# checking whether inner application is alive
Process.kill 0, @pid
rescue Errno::ESRCH
# if inner application exited then stop the service
Log.debug1 'Inner app no more running.'
service_stop
end
sleep 0.5
end
end
# checking whether process with given pid exists
def alive? pid
begin
Process.kill 0, pid
rescue Errno::ESRCH
return false
end
true
end
# kill inner application with given signal
# default signal is 9 - mercilessly kill the application
def kill_inner_app sig = 9
if alive? @pid # checking whether inner application is alive
begin
Process.kill sig, @pid # kill the inner application
rescue Exception => e
Log.debug1 "kill inner app with #{sig} signal failed: #{e.message}"
sleep 1
Process.kill sig, @pid # second try to kill the inner application
end
if alive? @pid
Log.debug1 'inner app still alive after kill. wait till exit...'
# may be redundant. children processes on Windows look be detached.
# also can be rather dangerous to use here.
pid_exit_stat = Process.waitpid2 @pid
Log.debug1 "inner application exit status: #{pid_exit_stat}"
if alive? @pid
Log.debug1 'inner app still alive after wait'
# this exception can be raised when using win32/process
raise 'inner app still alive after wait'
else
Log.debug1 'inner app deleted after wait'
end
else
Log.debug1 'inner app was killed'
end
else
# if got here then inner application is already exit. do nothing.
Log.debug1 'inner app already deleted'
end
end
def service_stop
Log.debug1 'service should be stopped'
[1, 2, 6, 15, 22, 9].each do |sig|
begin
Log.debug1 "signal #{sig} sent to kill inner app"
kill_inner_app sig
rescue Exception => e
Log.debug1 "#{e.message}"
next
end
Log.debug1 'Wrapper was stopped'
# let log be written
Log.flush
exit!
end
Log.error 'Failed to stop service'
Log.flush
#exit!
raise 'Failed to stop service'
end
end
WrapperDaemon.mainloop
| true
|
b841090c55b7ecfbb270616d50787c434aab5ec7
|
Ruby
|
manishchaks/payback-service
|
/spec/user_spec.rb
|
UTF-8
| 1,959
| 2.953125
| 3
|
[] |
no_license
|
require 'user.rb'
describe User do
before :each do
@user = User.new('user1', 'user@gmail.com', 500)
end
context 'Initialization' do
it 'is possible to create a valid user object' do
expect(@user).to respond_to(:name)
expect(@user).to respond_to(:email)
expect(@user).to respond_to(:credit_limit)
expect(@user.name).to eq('user1')
expect(@user.email).to eq('user@gmail.com')
expect(@user.credit_limit).to eq(500)
end
end
context 'Updation' do
it 'is not possible to change the email and name' do
expect(@user).to_not respond_to(:name=)
expect(@user).to_not respond_to(:email=)
end
end
context 'Validation' do
it 'should raise error if user created with negative credit limit' do
expect{User.new('user1', 'user@gmail.com', -1)}.to raise_exception(InvalidCreditLimitException,'Credit Limit cannot be less than or equal to zero')
end
it 'should raise error if user created with empty name' do
expect{User.new('', 'user@gmail.com', 100)}.to raise_exception(InvalidNameException,'Name should be at least 1 character long')
end
it 'should raise error is user created with invalid email address' do
expect{User.new('manish', 'invalid_email', 100)}.to raise_exception(InvalidEmailException,'Please supply a valid email address with a @ character')
end
end
context 'Credit limits' do
it 'should allow user to avail credit if sufficient amount exists' do
expect(@user.at_credit_limit?).to eq(false)
expect(@user.can_avail_credit?(300)).to eq(true)
@user.avail_credit(300)
expect(@user.dues).to eql(300)
expect(@user.available_credit).to eq(200)
expect(@user.can_avail_credit?(300)).to eq(false)
expect(@user.can_avail_credit?(200)).to eq(true)
@user.avail_credit(200)
expect(@user.dues).to eql(500)
expect(@user.available_credit).to eq(0)
expect(@user.at_credit_limit?).to eq(true)
end
end
end
| true
|
10d9146484bb22f32696876ec6f46af443264a44
|
Ruby
|
kocsenc/kchung
|
/Ruby/AdvancedLevel/DietManager/LogItemUnitTest.rb
|
UTF-8
| 1,541
| 3.609375
| 4
|
[] |
no_license
|
# Kocsen Chung
# LogItem Class Unit test.
# simple unit tests that willt test for the LogItem object functionality
require "test/unit"
require "./LogItem"
require "date"
class LogItemUnitTest < Test::Unit::TestCase
def setup
#puts "LogItem Unit Test Setup"
end
# Make sure that a LogItem Object can be intantiated and that
# the correct variables are accessible.
def test_initialization
item1 = LogItem.new("FOODNAME", Date.parse("2012-10-10"), 1)
assert( item1.foodName == "FOODNAME" , "item1 foodname should = FOODNAME")
dateTest = Date.parse("2012-10-10")
assert( (item1.date).eql?(dateTest), "item1 date should be 2012-10-10 object")
assert( item1.count == 1, "item1 count should be 1")
item1.foodName = "POTATO"
assert( item1.foodName == "POTATO")
item1.count+=1
assert( item1.count == 2)
end
# test to string method
def test_to_s
item1 = LogItem.new("PEACH", Date.parse("1212-12-12"), 1)
assert( item1.to_s == "1212-12-12,PEACH" )
end
# test comparator
def test_comparator #comparator based on date
item1 = LogItem.new("PAST PEACH", Date.parse("1212-12-12"), 1)
item2 = LogItem.new("PRESENT PEACH", Date.parse("2000-12-12"), 1)
item3 = LogItem.new("FUTURE PEACH", Date.parse("2013-12-12"), 1)
assert( item1<item2, "item1 should be < item 2")
assert( item2<item3, "item2 should be < item 3")
unsorted = [item3,item1,item2]
sorted = [item1,item2,item3]
unsorted.sort!
assert( unsorted==sorted, "the sort should arrange in increasing order")
end
end #end LogITemUnitTest Class
| true
|
c0af64d08cc3291422f83f3c82fdfa62952941bb
|
Ruby
|
luprz/runa-access-control
|
/client/app/services/authentication.rb
|
UTF-8
| 675
| 2.90625
| 3
|
[] |
no_license
|
class Authentication
SIGN_IN = '/api/v1/users/sign_in'
SIGN_OUT = '/api/v1/users/sign_out'
def initialize(user = {}, headers={})
@email = user[:email]
@password = user[:password]
@headers = headers
end
def sign_in
api.post do |req|
req.url SIGN_IN
req.body = {
email: @email,
password: @password
}
end
end
def sign_out(headers)
api = api_with_headers(headers)
api.delete do |req|
req.url SIGN_OUT
end
end
private
def api
api = Api.new(headers: nil)
api.conection
end
def api_with_headers(headers)
api = Api.new(headers: headers)
api.conection
end
end
| true
|
33edc466d0f8b16ece0e0801b53874c66ab17cbb
|
Ruby
|
cstrynatka/ruby_fundamentals1
|
/p004strings.rb
|
UTF-8
| 630
| 3.609375
| 4
|
[] |
no_license
|
# Defining a constant
PI = 3.14156
puts PI
# Defining a local variable
my_string = "I love the city of Rome"
puts my_string
=begin
Conversions
.to_i, .to_f, .to_a
=end
var1 = 5;
var2 = "2"
puts var1 + var2.to_i
# << appending to a string
a = "hello"
a<<"world.
I love this world..."
puts a
=begin
<< marks the start of the string literal AND
is followed by a delimiter of your choice.
The string literal THEN starts from the NEXT
NEW line AND finishes WHEN the delimiter is repeated
again on a line on its own. This is known as
Here document syntax.
=end
a = <<END_STR
This is the string
And a second line
END_STR
puts a
| true
|
b5be2ecf6f4d60787466bd2292146aabcb70faf1
|
Ruby
|
tmaczukin/simple_backup
|
/lib/simple_backup/utils/disk_usage.rb
|
UTF-8
| 1,322
| 2.6875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module SimpleBackup
module Utils
class Disk
@@high_usage_treshold = 0.9
@@paths = []
def self.high_usage_treshold=(value)
@@high_usage_treshold = value.to_f
raise ArgumentError.new "Backuper::Utils::Disk::high_usage_treshold must be a float greater than zero" if @@high_usage_treshold <= 0.0
end
def self.high_usage_treshold
@@high_usage_treshold
end
def self.add_path(path)
@@paths << path unless @@paths.include?(path)
end
def self.usage
df = `df -m #{@@paths.join(' ')} 2>/dev/null`.split("\n")
df.shift
max_percent = 0.0;
df.map! do |row|
row = row.split(' ')
percent_usage = (row[4].gsub('%', '').to_f / 100).round(2)
row = {
mount: row[5],
fs: row[0],
size: row[1],
used: row[2],
available: row[3],
percent: percent_usage,
high_usage_exceeded: percent_usage >= @@high_usage_treshold
}
max_percent = row[:percent] if row[:percent] > max_percent
row
end
{
mounts: df.uniq,
high_usage_exceeded: max_percent >= @@high_usage_treshold,
high_usage: max_percent
}
end
end
end
end
| true
|
5597ac7b445d8dc8ea370749f32b12a9c6b567ef
|
Ruby
|
adamsanderson/palm
|
/test/waba_db_test.rb
|
UTF-8
| 4,286
| 2.5625
| 3
|
[] |
no_license
|
require File.dirname(__FILE__) + '/test_helper.rb'
class TestCollectionPointRecord < Palm::WabaRecord
class_id 072
field :corridor, :string
field :site, :string
field :direction, :byte
field :lanes, :byte
field :hov_lane, :byte
field :ramp_type, :string
field :express, :boolean
field :cp_id, :int
end
class TC_WabaDBTest < Test::Unit::TestCase
def setup
setup_paths
@pdb = Palm::WabaDB.new(TestCollectionPointRecord)
@pdb.load(open(@path))
end
def teardown
File.delete(@temp_path) if File.exist? @temp_path
end
def test_records_exist
assert @pdb.data.length > 0
end
def test_correct_class
@pdb.data.each do |record|
assert_instance_of TestCollectionPointRecord, record
end
end
def test_records_look_right
cp_ids = {}
@pdb.data.each do |record|
assert record.corridor.length > 0, "Corridor should not be empty"
assert record.site.length > 0, "Site should not be empty"
assert (1..4).include?(record.direction), "Direction should be 1-4"
assert (0..9).include?(record.lanes), "Lanes should be between 0 and 9, found #{record.lanes}"
assert (0..9).include?(record.hov_lane), "Hov Lane should be between 0 and 9, found #{record.hov_lane}"
assert !cp_ids[record.cp_id], "Each cp_id should be unique, #{cp_ids[record.cp_id].inspect} overlaps with #{record.inspect}"
cp_ids[record.cp_id] = record
end
end
def test_database_round_tripping
@pdb.write_file(@temp_path)
@loaded = Palm::WabaDB.new(TestCollectionPointRecord)
@loaded.load_file(@temp_path)
# Ensure they're two different objects
assert(@pdb != @loaded)
# Test that the loaded data is the same as the original
@pdb.data.zip(@loaded.data) do |expected, actual|
assert_equal expected.class.fields, actual.class.fields, "Records should have the same fields"
expected.class.fields.map{|f| f.name}.each do |name|
assert_equal expected.send(name), actual.send(name), "Field #{name} did not match"
end
end
end
def test_binary_equality
@pdb.write_file(@temp_path)
# Ensure the files are the same size
assert_equal File.size(@path), File.size(@temp_path)
# Ensure the files are identical
assert_equal IO.read(@path), IO.read(@temp_path)
end
def test_creating_from_scratch
@created = Palm::WabaDB.new(TestCollectionPointRecord)
@created.name = "HovData"
@created.type = "HovD"
@created.creator = "Trac"
@created.created_at = @pdb.created_at
@created.modified_at = @pdb.modified_at
@created.backed_up_at = @pdb.backed_up_at
# These are two picky bits. They don't really need to be equal
@created.version = 1
@created.modnum = 420
@pdb.data.each do |r|
n = TestCollectionPointRecord.new
# Copy each field
r.class.fields.map{|f| f.name}.each do |name|
n.send("#{name}=", r.send(name))
end
@created.data << n
end
@created.attributes = @pdb.attributes
@created.write_file(@temp_path)
# Ensure the files are the same size
assert_equal File.size(@path), File.size(@temp_path)
# First assert the headers are the same
expected_header = IO.read(@path, Palm::PDB::HEADER_LENGTH).unpack("a32 n n N N N N N N a4 a4 N")
actual_header = IO.read(@temp_path, Palm::PDB::HEADER_LENGTH).unpack("a32 n n N N N N N N a4 a4 N")
fields = [:name, :bin_attributes, :version, :created_at, :modified_at, :backed_up_at,
:modnum, :appinfo_offset, :sort_offset, :type, :creator,
:unique_id_seed]
fields.each_with_index do |field, i|
assert_equal expected_header[i], actual_header[i], "Header field #{field} should be equal"
end
# Ensure the files are identical
expected = IO.read(@path)
actual = IO.read(@temp_path)
expected.split('').zip(actual.split('')).each_with_index do |pair, i|
e,a = pair
assert_equal e,a, "At #{i}: expected '#{e}', actual'#{a}'"
end
assert_equal IO.read(@path), IO.read(@temp_path), "Bytes should be identical"
end
def test_written_records_are_binary_equivalent
@raw = Palm::PDB.new
@raw.load_file(@path)
@pdb.data.each_with_index do |r,i|
io = Palm::WabaStringIO.new(s='', "w")
r.write(io)
# The actual db will handle writing the first byte
assert_equal @raw.data[i].data[1..-1], s, "Data portion should be idential"
end
end
end
| true
|
6c1def0e1ec52e05efaad748bf65c0ad954fd655
|
Ruby
|
tebatalla/Blocks-Recursions
|
/recursion.rb
|
UTF-8
| 2,269
| 3.75
| 4
|
[] |
no_license
|
def range(start, ending)
return [] if ending < start
[start] + range(start + 1, ending)
end
def sum_recursive(array)
return array.first if array.length == 1
array.first + sum_recursive(array.drop(1))
end
def sum_iterative(array)
array = array.dup
sum = 0
until array.empty?
sum += array.shift
end
sum
end
def exp_one (base, power)
return base if power <= 1
base * exp_one(base, power - 1)
end
def exp_two (base, power)
return 1 if power == 0
return base if power == 1
if power.even?
sq_half = exp_two(base, power / 2)
sq_half * sq_half
else
sq_half = exp_two(base, (power - 1) / 2)
sq_half * sq_half
end
end
class Array
def deep_dup
return self unless self.is_a?(Array)
result = []
each do |item|
result << (item.is_a?(Array) ? item.deep_dup : item)
end
result
end
def subsets
return [[]] if self.empty?
subs = array.take(count - 1).subsets
subs += subs.map { |sub| sub + [last] }
end
def quicksort
pivot = self.sample
return self if self.length <= 1
less, greater, equal = [], [], []
self.each do |elem|
if elem < pivot
less << elem
elsif elem > pivot
greater << elem
else
equal << elem
end
end
less.quicksort + equal + greater.quicksort
end
def my_tap(&prc)
prc.call(self)
self
end
end
def fibonacci(n)
return [1] if n == 1
return [1, 1] if n == 2
previous = fibonacci(n - 1)
preprevious = fibonacci(n - 2)
previous += [previous.last + preprevious.last]
end
def bsearch(array, target)
return nil if array.empty?
half = array.length / 2
if array[half] == target
return half
elsif array[half] > target
bsearch(array[0...half], target)
else
right = bsearch(array[(half + 1)..-1], target)
half + 1 + right unless right.nil?
end
end
def merge_sort(array)
return array if array.length <= 1
half = array.length / 2
left = array.take(half)
right = array.drop(half)
merge(merge_sort(left),merge_sort(right))
end
def merge(left, right)
merged = []
until left.empty? || right.empty?
if left.first < right.first
merged << left.shift
else
merged << right.shift
end
end
merged + left + right
end
| true
|
bcb44a0f8888b517a64f5cbc7d05a81df68bc749
|
Ruby
|
blumaa/OO-mini-project-chicago-web-82619
|
/app/models/Recipe.rb
|
UTF-8
| 1,452
| 3.09375
| 3
|
[] |
no_license
|
class Recipe
attr_reader :name
@@all = []
def self.all
@@all
end
def initialize(name)
@name = name
self.class.all << self
end
def self.most_popular
recipes = RecipeCard.all.map { |card| card.recipe }
recipes.sort_by { |recipe| recipes.count(recipe) }.last
# recipes = RecipeCard.all
# recipe_hash = Hash.new(0)
# recipes.each {|recipecard| recipe_hash.store(recipecard.recipe, recipe_hash[recipecard.recipe] + 1)}
# most_popular = 0
# name_of_most_popular = nil
# recipe_hash.each do |recipecard, num|
# if num > most_popular
# most_popular = num
# name_of_most_popular = recipecard
# end
# end
# name_of_most_popular
end
def users
r = RecipeCard.all.select {|recipecard| recipecard.recipe == self}
r.map {|card| card.user}
end
def ingredients
arr = RecipeIngredient.all.select {|recipeingredient| recipeingredient.recipe == self}
arr.map {|card| card.ingredient}
end
def allergens
Allergy.all.map {|allergy| allergy.ingredient} & ingredients
end
def add_ingredients(new_ingredients)
new_ingredients.each do |ingredient|
if !self.ingredients.include?(ingredient)
RecipeIngredient.new(self, ingredient)
end
end
end
end
| true
|
0a58421a9c21a49e33ebe37f56aafa260f587a26
|
Ruby
|
HGouin/operators-onl01-seng-pt-032320
|
/lib/operations.rb
|
UTF-8
| 136
| 2.765625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def unsafe?(speed)
if speed <40 || speed>60
true
else false
end
end
def not_safe?(speed)
speed>60 || speed<40 ? true : false
end
| true
|
88144bddefa1600012ae3ee6102e646673bc5f91
|
Ruby
|
KarthikVenkatraman/artifactory-ami-build
|
/rakelib/environment/packer_copy_template.rb
|
UTF-8
| 1,956
| 2.671875
| 3
|
[] |
no_license
|
require 'json'
require 'erb'
require 'ostruct'
require 'securerandom'
require 'fileutils'
module Environment
class PackerCopyTemplate
RHEL_TEMPLATE = File.dirname(__FILE__) + '/templates/copy_rhel_template.erb'
WIN_TEMPLATE = File.dirname(__FILE__) + '/templates/copy_win_template.erb'
@os_type
def initialize(os_type)
@os_type = os_type
os_type == :rhel ? @template = File.read(RHEL_TEMPLATE) : nil
os_type == :win ? @template = File.read(WIN_TEMPLATE) : nil
end
def generate(role_arn, image_name, image_id, variables_filepath, output_filepath)
file = File.read(variables_filepath)
env_vars = JSON.parse(file)
add_assume_role_credentials!(role_arn, env_vars)
copy_vars = copy_ami_vars(env_vars)
copy_vars['ami_name'] = image_name
copy_vars['source_ami_id'] = image_id
File.open(output_filepath, 'w') do |f|
f.write UserDataRenderer.render(@template, copy_vars)
end
@os_type == :win ? FileUtils.cp_r(Dir.glob(File.dirname(__FILE__) + '/files/win_*'), File.dirname(output_filepath) ) : nil
end
def add_assume_role_credentials!(role_arn, vars)
client_factory = AwsSupport::ClientFactory.new(role_arn)
vars['aws_access_key'] = client_factory.credentials.credentials.access_key_id
vars['aws_secret_key'] = client_factory.credentials.credentials.secret_access_key
vars['aws_security_token'] = client_factory.credentials.credentials.session_token
end
def copy_ami_vars(vars)
copy_vars = vars.select{ |k,v| k.match /(_vpc_id|bakery_1_subnet_id|bakery_sg_id|aws)/}
copy_vars.keys.each { |key | if key =~ /_vpc_id/ ; copy_vars['vpc_id'] = copy_vars.delete(key) end }
copy_vars
end
end
class UserDataRenderer < OpenStruct
def self.render(t, h)
UserDataRenderer.new(h)._render(t)
end
def _render(template)
ERB.new(template).result(binding)
end
end
end
| true
|
4b9f0eca8c5a5fe3d335aa13b9de92be170ee9cd
|
Ruby
|
adamnoto/lab
|
/rb/import-app/app/models/concerns/company_informer.rb
|
UTF-8
| 1,219
| 2.984375
| 3
|
[] |
no_license
|
module CompanyInformer
class InformationFetcher
attr_reader :company
def initialize(company)
@company = company
end
def number_of_operations
company.operations.count
end
def number_of_accepted_operations
company.operations.where(status: 'accepted').count
end
def average_operation_amount
amount = company.operations.average(:amount)
amount.to_f.round(2) if amount
end
def monthly_highest_operation(date: Date.today)
start_date, end_date = date.beginning_of_month, date.end_of_month
amount = company.operations
.where(operation_date: start_date..end_date)
.maximum(:amount)
amount.to_f.round(2) if amount
end
def to_h
{
noops: number_of_operations,
opsacp: number_of_accepted_operations,
avgamt: average_operation_amount,
mohigh: monthly_highest_operation
}
end
end # InformationFetcher
def info(id)
InformationFetcher.new(id).to_h
end
def all_info
Company.select(:name, :id).includes(:operations).map do |comp|
data = {}
data[:comp] = comp.attributes
data[:comp][:op] = info(comp).to_h
data
end
end
end
| true
|
4a3bc47595192c20a871e558810a995aaa58cda4
|
Ruby
|
Mani082/RubyFiles
|
/firstClass.rb
|
UTF-8
| 351
| 3.375
| 3
|
[] |
no_license
|
class Greeter
def initialize(name = "Boss")
@nameInstance = name
end
def sayHi
puts "Hi #{@nameInstance}!!"
end
def sayBye
puts "Bye #{@nameInstance}, come back soon!!"
end
end
greeter1=Greeter.new("MAaaniii")
greeter2=Greeter.new("Mounica")
greeter1.sayHi
greeter1.sayBye
greeter2.sayHi
greeter2.sayBye
| true
|
0e20acce02e4fbbf6140dd0e944c97ffe93c4066
|
Ruby
|
fraterrisus/advent2018
|
/day18/part1.rb
|
UTF-8
| 1,271
| 3.203125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require './grid.rb'
iters = ARGV[1].to_i || raise
lines = IO.readlines(ARGV[0]).map(&:rstrip)
dim = lines[0].length
this_grid = Grid.new(dim)
next_grid = Grid.new(dim)
lines.each_with_index do |row,y|
row.split(//).each_with_index do |sq,x|
case sq
when '.'
val = :open
when '|'
val = :tree
when '#'
val = :yard
else
raise "Unknown char #{sq} at line #{y} char #{x}"
end
this_grid.set(x,y,val)
next_grid.set(x,y,val)
end
end
iters.times do
#this_grid.disp
dim.times do |y|
dim.times do |x|
i = this_grid.index(x,y)
sq = this_grid.get_index(i)
n = this_grid.nearby(x,y)
#puts "(#{x},#{y}) : #{n.inspect}"
case sq
when :open
if n[:tree] > 2
newval = :tree
else
newval = :open
end
when :tree
if n[:yard] > 2
newval = :yard
else
newval = :tree
end
when :yard
if n[:yard] > 0 && n[:tree] > 0
newval = :yard
else
newval = :open
end
end
next_grid.set_index(i,newval)
end
end
tmp = this_grid
this_grid = next_grid
next_grid = tmp
end
#this_grid.disp
puts "Score: #{this_grid.score}"
| true
|
f205f0d270d75ef82da254369f1c824b687b1646
|
Ruby
|
LinuxGit/Code
|
/ruby/Metaprogramming/object_model/alphanumberic.rb
|
UTF-8
| 579
| 2.984375
| 3
|
[] |
no_license
|
def to_alphanumberic(s)
s.gsub(/[^\w\s]/, '')
end
p to_alphanumberic('hello# ruby!')
require 'test/unit'
class ToAlphanumbericTest < Test::Unit::TestCase
def test_strip_non_alphanumberic_characters
assert_equal '3 the Magic Number', to_alphanumberic('#3 the *Magic, Number*!')
end
end
class String
def to_alphanumberic
gsub /[^\w\s]/, ''
end
end
require 'test/unit'
class StringExtensionTest < Test::Unit::TestCase
def test_strip_non_alphanumberic_characters
assert_equal '3 the Magic Number', to_alphanumberic('#3 the *Magic, Number*!')
end
end
| true
|
52987b4a55c1560d5e9d53c97ec9d6ef5c3d3193
|
Ruby
|
ymek/spree_test
|
/lib/domain_constraint.rb
|
UTF-8
| 668
| 2.8125
| 3
|
[] |
no_license
|
class DomainConstraint
def initialize(domain)
@domains = [domain].flatten
end
def matches?(request)
request.subdomain.present? ? domain_to_match = request.subdomain + "." + request.domain : domain_to_match = request.domain
@domains.include? domain_to_match
end
end
# # This class allows use of a route when a subdomain is present in the request object.
# # If the subdomain is “www,” the class will respond as if a subdomain is not present.
# class Subdomain
# def self.matches?(request)
# case request.subdomain
# when 'www', '', 'boombotix', "boombotix-staging", nil
# false
# else
# true
# end
# end
# end
| true
|
90688ce8bffaa7f144dacc79ea2e606dbc2a9b8e
|
Ruby
|
appium/ruby_lib_core
|
/lib/appium_lib_core/element.rb
|
UTF-8
| 5,219
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# frozen_string_literal: true
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Appium
module Core
# Implement useful features for element.
# Patch for Selenium Webdriver.
class Element < ::Selenium::WebDriver::Element
include ::Appium::Core::Base::SearchContext
include ::Appium::Core::Base::TakesScreenshot
# Retuns the element id.
#
# @return [String]
# @example
# e = @driver.find_element :accessibility_id, 'something'
# e.id
#
attr_reader :id
# Returns the value of attributes like below. Read each platform to know more details.
#
# uiautomator2: https://github.com/appium/appium-uiautomator2-server/blob/203cc7e57ce477f3cff5d95b135d1b3450a6033a/app/src/main/java/io/appium/uiautomator2/utils/Attribute.java#L19
# checkable, checked, class, clickable, content-desc, enabled, focusable, focused
# long-clickable, package, password, resource-id, scrollable, selection-start, selection-end
# selected, text, bounds, index
#
# XCUITest automation name supports below attributes.
# UID, accessibilityContainer, accessible, enabled, frame,
# label, name, rect, type, value, visible, wdAccessibilityContainer,
# wdAccessible, wdEnabled, wdFrame, wdLabel, wdName, wdRect, wdType,
# wdUID, wdValue, wdVisible
#
# @return [String]
#
# @example
#
# e = @driver.find_element :accessibility_id, 'something'
# e.value
# e.resource_id # call 'e.attribute "resource-id"'
#
def method_missing(method_name, *args, &block)
ignore_list = [:to_hash]
return if ignore_list.include? method_name
respond_to?(method_name) ? attribute(method_name.to_s.tr('_', '-')) : super
end
def respond_to_missing?(*)
true
end
# Alias for type
alias type send_keys
# Set the value to element directly
#
# @example
#
# element.immediate_value 'hello'
#
def immediate_value(*value)
@bridge.set_immediate_value @id, *value
end
# Replace the value to element directly
#
# @example
#
# element.replace_value 'hello'
#
def replace_value(*value)
@bridge.replace_value @id, *value
end
# For use with location_rel.
#
# @return [::Selenium::WebDriver::Point] the relative x, y in a struct. ex: { x: 0.50, y: 0.20 }
#
# @example
#
# e = @driver.find_element :accessibility_id, 'something'
# e.location_rel @driver
#
def location_rel(driver)
rect = self.rect
location_x = rect.x.to_f
location_y = rect.y.to_f
size_width = rect.width.to_f
size_height = rect.height.to_f
center_x = location_x + (size_width / 2.0)
center_y = location_y + (size_height / 2.0)
w = driver.window_size
::Selenium::WebDriver::Point.new "#{center_x} / #{w.width.to_f}", "#{center_y} / #{w.height.to_f}"
end
# Return an element screenshot as base64
#
# @return String Base 64 encoded string
#
# @example
#
# element.screenshot #=> "iVBORw0KGgoAAAANSUhEUgAABDgAAAB+CAIAAABOPDa6AAAAAX"
#
def screenshot
bridge.element_screenshot @id
end
# Return an element screenshot in the given format
#
# @param [:base64, :png] format
# @return String screenshot
#
# @example
#
# element.screenshot_as :base64 #=> "iVBORw0KGgoAAAANSUhEUgAABDgAAAB+CAIAAABOPDa6AAAAAX"
#
def screenshot_as(format)
case format
when :base64
bridge.element_screenshot @id
when :png
bridge.element_screenshot(@id).unpack('m')[0]
else
raise Core::Error::UnsupportedOperationError, "unsupported format: #{format.inspect}"
end
end
# Save an element screenshot to the given path
#
# @param [String] png_path A path to save the screenshot
# @return [File] Path to the element screenshot.
#
# @example
#
# element.save_screenshot("fine_name.png")
#
def save_screenshot(png_path)
extension = File.extname(png_path).downcase
if extension != '.png'
::Appium::Logger.warn 'name used for saved screenshot does not match file type. ' \
'It should end with .png extension'
end
File.open(png_path, 'wb') { |f| f << screenshot_as(:png) }
end
end # class Element
end # module Core
end # module Appium
| true
|
2e4822cf0f320cf175671805f04228efbcf62f46
|
Ruby
|
ckccameron/sweater_weather_api
|
/spec/facades/road_trip_facade_spec.rb
|
UTF-8
| 1,625
| 2.546875
| 3
|
[] |
no_license
|
require 'rails_helper'
describe RoadTripFacade do
it "returns road trip summary that includes forecast and travel time" do
response1 = File.read("spec/fixtures/denver_to_san_diego_mapquest_route.json")
stub_request(:get, "http://www.mapquestapi.com/directions/v2/route?from=denver,%20co&key=#{ENV["MAPQUEST_KEY"]}&to=san%20diego,%20ca")
.to_return(status: 200, body: response1)
response2 = File.read("spec/fixtures/san_diego_mapquest_geocode.json")
stub_request(:get, "http://www.mapquestapi.com/geocoding/v1/address?key=#{ENV["MAPQUEST_KEY"]}&location=san%20diego,%20ca")
.to_return(status: 200, body: response2)
response3 = File.read("spec/fixtures/san_diego_open_weather_forecast.json")
stub_request(:get, "https://api.openweathermap.org/data/2.5/onecall?appid=#{ENV["WEATHER_KEY"]}&exclude=minutely&lat=32.71576&lon=-117.163817&units=imperial")
.to_return(status: 200, body: response3)
origin = "denver, co"
destination = "san diego, ca"
road_trip = RoadTripFacade.new(origin, destination).road_trip
# binding.pry
expect(road_trip).to be_a(RoadTrip)
expect(road_trip.origin).to eq(origin)
expect(road_trip.origin).to be_a(String)
expect(road_trip.destination).to eq(destination)
expect(road_trip.destination).to be_a(String)
expect(road_trip.travel_time).to be_a(String)
expect(road_trip.travel_time).to_not include(":")
expect(road_trip.weather_at_eta).to be_a(RoadTripWeatherSummary)
expect(road_trip.weather_at_eta.temperature).to be_a(Float)
expect(road_trip.weather_at_eta.conditions).to be_a(String)
end
end
| true
|
f4f82caca5e148eaa70d0c78862d33ea8d7ef07f
|
Ruby
|
yshen901/AAClasswork
|
/W5D4/aa_questions/questions.rb
|
UTF-8
| 5,369
| 2.828125
| 3
|
[] |
no_license
|
require 'sqlite3'
require 'singleton'
class QuestionsDatabase < SQLite3::Database
include Singleton
def initialize
super('questions.db')
self.type_translation = true
self.results_as_hash = true
end
end
class Question
attr_accessor :id, :body, :author_id, :title
def self.find_by_id(id)
question = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
questions
WHERE
id = ?
SQL
return nil if question.empty?
Question.new(question.first) #selects first row of query result
end
def self.find_by_author_id(author_id)
#gives an array of hashes, where each hash is a row
questions = QuestionsDatabase.instance.execute(<<-SQL, author_id)
SELECT
*
FROM
questions
WHERE
author_id = ?
SQL
questions.map { |question| Question.new(question) }
# results = []
# questions.each do |question|
# results << Questions.new(question)
# end
# results
end
def initialize(data) #data is a hash
@id = data['id']
@body = data['body']
@author_id = data['author_id']
@title = data['title']
end
def author
User.find_by_id(@author_id)
end
def replies
Reply.find_by_question_id(@id)
end
def followers
QuestionFollow.followers_for_question_id(self.id)
end
end
class User
attr_accessor :id, :fname, :lname
def self.find_by_id(id)
user = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
return nil if user.empty?
User.new(user.first)
end
def self.find_by_name(fname, lname)
users = QuestionsDatabase.instance.execute(<<-SQL, fname, lname)
SELECT
*
FROM
users
WHERE
fname = ? AND lname = ?
SQL
users.map { |user| User.new(user) }
end
def initialize(data)
@id = data['id']
@fname = data['fname']
@lname = data['lname']
end
def authored_questions
Question.find_by_author_id(@id)
end
def authored_replies
Reply.find_by_user_id(@id)
end
def followed_questions
QuestionFollow.followed_questions_for_user_id(self.id)
end
end
class QuestionFollow
attr_accessor :id, :user_id, :question_id
def self.find_by_id(id)
data = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
question_follows
WHERE
id = ?
SQL
return nil if data.empty?
QuestionFollow.new(data.first)
end
def self.followers_for_question_id(question_id)
followers = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
users.id, users.fname, users.lname
FROM
users
JOIN
question_follows ON users.id = question_follows.user_id
WHERE
question_id = ?
SQL
followers.map { |user| User.new(user) }
end
def self.followed_questions_for_user_id(user_id)
questions = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
questions.id, questions.body, questions.author_id, questions.title
FROM
question_follows
JOIN
questions ON question_follows.question_id = questions.id
WHERE
user_id = ?
SQL
questions.map { |question| Question.new(question) }
end
def initialize(data)
@id = data['id']
@user_id = data['user_id']
@question_id = data['question_id']
end
end
class QuestionLike
attr_accessor :id, :user_id, :question_id
def self.find_by_id(id)
question_likes = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
question_likes
WHERE
id = ?
SQL
return nil if question_likes.empty?
QuestionLike.new(question_likes.first)
end
def initialize(data)
@id = data['id']
@user_id = data['user_id']
@question_id = data['question_id']
end
end
class Reply
attr_accessor :id, :user_id, :question_id, :parent_id, :body
def self.find_by_id(id)
replies = QuestionsDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
replies
WHERE
id = ?
SQL
return nil if replies.empty?
Reply.new(replies.first)
end
def self.find_by_user_id(user_id)
replies = QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
*
FROM
replies
WHERE
user_id = ?
SQL
replies.map { |reply| Reply.new(reply) }
end
def self.find_by_question_id(question_id)
replies = QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
question_id = ?
SQL
replies.map { |reply| Reply.new(reply) }
end
def initialize(data)
@id = data['id']
@user_id = data['user_id']
@question_id = data['question_id']
@parent_id = data['parent_id']
@body = data['body']
end
def author
User.find_by_id(@user_id)
end
def question
Question.find_by_id(@question_id)
end
def parent_reply
Reply.find_by_id(@parent_id)
end
def child_replies
replies = QuestionsDatabase.instance.execute(<<-SQL, @id)
SELECT
*
FROM
replies
WHERE
parent_id = ?
SQL
return nil if replies.empty?
replies.map { |reply| Reply.new(reply) }
end
end
| true
|
be7317325feabda0f5b0920ba2c967a809c6c1cc
|
Ruby
|
SoundWavesHello/bowdoin_web_crawler
|
/webCrawl.rb
|
UTF-8
| 4,010
| 2.78125
| 3
|
[] |
no_license
|
=begin
Web Crawler
Author: Kevin Lane
Last Modified: 11/22/19
=end
load "open-uri.rb" # get the URI library
class WebCrawler
attr_accessor :visited, :broken, :start, :allLinks, :badExtensions,
:noAccess, :domain
def initialize(domain)
@visited = Array.new
@broken = Array.new
@start = "http://www." + domain
@domain = domain
@allLinks = Array.new([@start])
# I was told by Systems to not crawl through these extensions on Bowdoin.edu
@badExtensions = ["/includes", "/scripts", "/alumni/pdf/",
"/chinesescrolls", "/alumni/cityguides", "/cgi-bin/",
"/visitors-friends/breakfast/",
"/news/archives/1bowdoincampus/001738.shtml", "/security/alerts/",
"/catalogue/archives/", "/polaris/degreeworks.shtml", "/digests/",
"/truman/", "/fdr/", "/atreus/", "/ZZ-Old/", "/BowdoinDirectory/",
"/calendar/", "/hoplite/", "/noindex/"]
@noAccess = []
# append the domain so we have the full link,
# and add it to @noAccess
@badExtensions.each do |link|
link = @start + link
@noAccess.push(link)
end
end
def getLinks(url)
# scan the page for links
# get a string of the content of the webpage
content = open(url).read
begin
#look for links in the content
links = content.scan(/<a\s+href="(.+?)"/i).flatten
# handle relative links by adding domain
final_links = []
links.each do |oneLink|
# if the link is relative
if not oneLink.start_with?("http")
#if it starts with /, then put bowdoin.edu is the parent url
if oneLink.start_with?("/")
final_links.push(oneLink.insert(0, "http://bowdoin.edu"))
# if it's a directory change, ignore it
elsif oneLink.start_with?("..")
# do nothing
# otherwise, the link doesn't start with /
else
# if the url ends with /
if url.end_with?("/")
# then just push it onto the parent url
final_links.push(oneLink.insert(0, url))
# if the parent url isn't a directory
elsif url.end_with?("html")
# get the parent url of the parent url
rel_link = /[a-z]*\.[s]?[h][t][m][l]/.match(url).to_s
parent = url.chomp(rel_link)
final_links.push(oneLink.insert(0, parent))
# otherwise, just insert an extra /
else
final_links.push(oneLink.insert(0, url + "/"))
end
end
else
final_links.push(oneLink)
end
end
final_links
rescue
puts("There was a UTF-8 encoding error at the
following url: #{url}")
final_links = []
end
end
def explore()
# as long as there are still links in allLinks
while @allLinks.size != 0
# set x equal to the first element of allLinks
x = @allLinks[0]
# if x is in our domain to search AND we haven't visited it yet
if /#{Regexp.quote(@domain)}/.match(x) != nil and not @visited.include?(x)
# if x is broken, add it to broken
if broken?(x)
@broken.push(x)
# check if it is one of the links in @noAccess
elsif not Regexp.union(@noAccess) === x
# if it isn't, then we can crawl the url
newLinks = getLinks(x)
# add each link to allLinks
newLinks.each do |oneLink|
# make sure the link isn't already there
if not @allLinks.include?(oneLink)
@allLinks.push(oneLink)
end
end
end
# add x to visited
@visited.push(x)
end
# remove x from allLinks
@allLinks.delete_at(0)
end
end
def broken?(link)
begin
content = open(link).read
broken = false
rescue
broken = true
end
end
end
crawler = WebCrawler.new("bowdoin.edu")
crawler.explore()
puts "There are #{crawler.broken.size} broken links"
puts "Here are the broken links: "
crawler.broken.each do |link|
puts link
end
=begin
puts
puts "These ones were visited"
crawler.visited.each do |link|
puts link
end
=end
| true
|
aabb6cdc517ae8eb0f0b797211f3232ba32b88d2
|
Ruby
|
RealEstateWebTools/property_web_scraper
|
/app/services/property_web_scraper/listing_retriever.rb
|
UTF-8
| 1,293
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
require 'nokogiri'
require 'open-uri'
require 'faraday'
module PropertyWebScraper
class ListingRetriever
# TODO - add logic to retrieve
# from db or scraper depending on expiry
attr_accessor :import_url
def initialize(import_url)
@import_url = import_url
end
def retrieve
result = OpenStruct.new(:success => false, :error_message => "not processed")
import_uri = get_import_uri
unless import_uri.is_a?(URI::HTTP) || import_uri.is_a?(URI::HTTPS)
result.error_message = "Invalid Url"
return result
end
import_host = PropertyWebScraper::ImportHost.find_by_host(import_uri.host)
unless import_host
result.error_message = "Unsupported Url"
return result
end
web_scraper = PropertyWebScraper::Scraper.new(import_host.scraper_name)
begin
retrieved_listing = web_scraper.process_url import_url, import_host
result.retrieved_listing = retrieved_listing
result.success = true
rescue Exception => e
result.error_message = e.message
end
return result
end
private
def get_import_uri
begin
uri = URI.parse import_url
rescue URI::InvalidURIError => error
uri = ""
end
end
end
end
| true
|
d6b76d42f521d8ffd00cf58dcfcb89e53f58d077
|
Ruby
|
bellycard/middleman-blog-authors
|
/lib/author.rb
|
UTF-8
| 618
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module Middleman
class BlogAuthors
class Author
attr_accessor :attributes, :articles
def initialize(name, local_data = nil)
@articles = []
@attributes = {
"name" => name,
"permalink" => BlogAuthors::AuthorPages.permalink(name)
}
if local_data.try(:authors)
@attributes.merge!(local_data.authors[@attributes["permalink"]]) if local_data.authors[@attributes["permalink"]]
end
@attributes.each do |attribute|
eval "def #{attribute[0]}; @attributes['#{attribute[0]}']; end"
end
end
end
end
end
| true
|
40ac06b15d90d4f1512628d5b417548f4dc22b42
|
Ruby
|
vic/mrT
|
/lib/mrT/rb_compat.rb
|
UTF-8
| 492
| 2.5625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
# Backport some ruby-1.9 features to ruby-1.8
module Kernel
def singleton_class
(class << self; self; end)
end unless method_defined?(:singleton_class)
def spawn(*args)
args.reject! { |item| item.instance_of? Hash }
Kernel.fork { Kernel.exec(*args) }
end unless method_defined?(:spawn)
end
class Class
def define_singleton_method(*args, &proc)
singleton_class.module_eval { define_method(*args, &proc) }
end unless method_defined?(:define_singleton_method)
end
| true
|
3f02aeb9a69ee1d50ae3767c9211fbd3ca6830a3
|
Ruby
|
kazunetakahashi/atcoder-ruby
|
/0709/ARC033_B.rb
|
UTF-8
| 337
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
n = gets.chomp.split(" ").map{|i| i.to_i}
a = []
a << gets.chomp.split(" ").map{|i| i.to_i}
a << gets.chomp.split(" ").map{|i| i.to_i}
s = {}
bunbo = 0
bunshi = 0
2.times{|i|
n[i].times{|j|
if s.has_key?(a[i][j])
bunshi += 1
else
s[a[i][j]] = 0
bunbo += 1
end
}
}
printf("%.9f\n", bunshi.to_f/bunbo)
| true
|
45355fe7540066154e500eb385129cb27544b2d3
|
Ruby
|
Neve/Pr1
|
/app/controllers/pure_ruby.rb
|
UTF-8
| 1,426
| 3.9375
| 4
|
[] |
no_license
|
class Base_class
# To change this template use File | Settings | File Templates.
def self.main
puts "hello" + " ruby version is " + `/usr/bin/ruby -v`
end
def arrays
a = [ 1, 'cat', 3.14 ] # array with three elements
a[0] # access the first element (1)
a[2] = nil # set the third element
# array now [ 1, 'cat', nil ]
## for elements in a
puts a
## end
end
def hashes
inst_section = {
:cello => 'string',
:clarinet => 'woodwind',
:drum => 'percussion',
:oboe => 'woodwind',
:trumpet => 'brass',
:violin => 'string'
}
# puts inst_section[:cello]
end
def self.greet
radiation = 3001
yield
3.times { print "Ho! " }
puts "Danger, Will Robinson" if radiation > 3000
end
def self.find_all_unpaid
self.where('paid = 0')
end
def total
sum = 0
line_items.each {|li| sum += li.total}
end
# def initialize(name)
# @name = name
#end
#Base_class end
end
class Greeter
attr_accessor :name # create reader and writer methods
attr_reader :greeting # create reader only
attr_writer :age # create writer only
def initialize(name)
@name = name
end
def name
@name
end
def name=(new_name)
@name = new_name
end
end
g = Greeter.new("Barney")
puts g.name #=> Barney
g.name = "Betty"
puts g.name #=> Betty
b1 = Base_class.new
b1.arrays
#main
#arrays
#hashes
Base_class.greet { Base_class.main }
| true
|
a7e79eaf025c37a847c3fa4bb85f05265164cdef
|
Ruby
|
PreservedKillick/Prime-Numbers-in-Ruby
|
/spec/prime_numbers_spec.rb
|
UTF-8
| 401
| 3.28125
| 3
|
[] |
no_license
|
require("rspec")
require("prime_numbers")
describe("prime_numbers") do
it ('returns the prime number 2 when given two') do
prime_numbers(2).should(eq([2]))
end
it ('returns an array of [2, 3, 5] when given 5') do
prime_numbers(5).should(eq([2, 3, 5]))
end
it ('returns an array of [2, 3, 5, 7, 11] when given twelve') do
prime_numbers(12).should(eq([2, 3, 5, 7, 11]))
end
end
| true
|
33c7fea062f9db2c0fae1b49b51bbf9ad448f814
|
Ruby
|
dougpotter/controlcenter
|
/trunk/lib/pixel_generator.rb
|
UTF-8
| 3,794
| 2.671875
| 3
|
[] |
no_license
|
module PixelGenerator
# event types hash
EVENT_TYPES = HashWithIndifferentAccess.new({
:impression => "imp",
:imp => "imp",
:engagement => "eng",
:eng => "eng",
:click => "clk",
:clk => "clk",
})
# pixel type hash
PIXEL_TYPES = HashWithIndifferentAccess.new({
:ae => "ae",
:ad_event => "ae"
})
# macros
AIS_CODE_MACRO = "$${ais_code}"
PARTNER_CODE_MACRO = "$${partner_code}"
CAMPAIGN_CODE_MACRO = "$${campaign_code}"
CREATIVE_CODE_MACRO = "$${creative_code}"
EVENT_TYPE_MACRO = "$${event_type}"
MPM_CODE_MACRO = "cpm"
PIXEL_TYPE_MACRO = "ae"
# pixel skeleton
AE_PIXEL_URL = "http://xcdn.xgraph.net/#{PARTNER_CODE_MACRO}/" +
"#{PIXEL_TYPE_MACRO}/xg.gif?type=#{PIXEL_TYPE_MACRO}&ais=#{AIS_CODE_MACRO}" +
"&pid=#{PARTNER_CODE_MACRO}&cid=#{CAMPAIGN_CODE_MACRO}&crid=" +
"#{CREATIVE_CODE_MACRO}&mpm=#{MPM_CODE_MACRO}&evt=#{EVENT_TYPE_MACRO}"
# returns array of strings (which are pixel URLs). Any unrecognized options keys
# are ignored; however, unknown values associated with known keys will result in
# an empty return array (because the method will filter out all results not
# consistent with that value)
def self.ae_pixels(creative, campaign, options = {})
# filter on aises
if options[:aises].blank?
campaign_inventory_configs = campaign.campaign_inventory_configs
else
all_campaign_inventory_configs =
campaign.campaign_inventory_configs(:include => :ad_inventory_source)
campaign_inventory_configs = all_campaign_inventory_configs.select { |cic|
cic.ad_inventory_source.ais_code.member?(options[:aises])
}
end
# filter on event types
if options[:event_types].blank?
event_types = [ :imp, :eng, :clk ]
else
event_types = [ options[:event_types] ].flatten.map { |t| EVENT_TYPES[t] }
event_types.compact!
end
# populate pixel array
pixels = []
for cic in campaign_inventory_configs
for event_type in event_types
pixels << generate_pixel(creative, event_type, cic)
end
end
return pixels
end
private
# returns a properly formatted pixel URL as a string
def self.generate_pixel(creative, event_type, campaign_inventory_config, options = {})
# type check arguments
if EVENT_TYPES[event_type].nil?
raise ArgumentError, "event_type must be a known event type"
elsif !creative.instance_of?(Creative)
raise ArgumentError, "creative argument must be an instance of Creative"
elsif !campaign_inventory_config.instance_of?(CampaignInventoryConfig)
raise ArgumentError,
"campaign_inventory_config argument must be an instance of" +
"CampaignInventoryConfig"
else
event_type = EVENT_TYPES[event_type]
end
# query db
query = CampaignInventoryConfig.find(
campaign_inventory_config,
:include => [
:ad_inventory_source,
{ :campaign => { :line_item => :partner } }
])
# gather relevant codes
ais_code = query.ad_inventory_source.ais_code
partner_code = query.campaign.line_item.partner.partner_code.to_s
campaign_code = query.campaign.campaign_code
creative_code = creative.creative_code
# inject codes into pixel URL skeleton
pixel = AE_PIXEL_URL.gsub(AIS_CODE_MACRO, ais_code)
pixel = pixel.gsub(PARTNER_CODE_MACRO, partner_code)
pixel = pixel.gsub(CAMPAIGN_CODE_MACRO, campaign_code)
pixel = pixel.gsub(CREATIVE_CODE_MACRO, creative_code)
pixel = pixel.gsub(EVENT_TYPE_MACRO, event_type)
pixel += options[:append].to_s
if event_type == EVENT_TYPES["click"] &&
landing_page_url = creative.landing_page_url
pixel += "&n=" + CGI::escape(landing_page_url)
end
return pixel
end
end
| true
|
b6b2fd1832605935ad5d7730d7b4e5880d1da686
|
Ruby
|
rsnorman/julysoundcheck
|
/app/value_objects/rating.rb
|
UTF-8
| 1,231
| 3.28125
| 3
|
[] |
no_license
|
class Rating
SCORES = {
'0-' => 0,
'0' => 1,
'0+' => 2,
'1-' => 3,
'1' => 4,
'1+' => 5,
'2-' => 6,
'2' => 7,
'2+' => 8,
'3-' => 9,
'3' => 10,
'3+' => 11
}.freeze
DESCRIPTIONS = {
0 => 'Painful',
1 => 'Unlistenable',
2 => 'Almost unlistenable',
3 => 'Barely listenable',
4 => 'Only worth a listen',
5 => 'Probably listen only once',
6 => 'Probably listen more than once',
7 => 'Listen multiple times',
8 => 'Definitely listen multiple times',
9 => 'Almost essential',
10 => 'Essential',
11 => 'AOTM contender'
}.freeze
SCORE_GROUPS = {
0 => 'Unlistenable',
1 => 'Listen Once',
2 => 'Multiple Listens',
3 => 'Essential'
}.freeze
attr_reader :value
def self.from_score(score)
new(SCORES[score])
end
def self.values_from_score(score_group)
SCORES.dup.keep_if { |score, _value| score[0] == score_group }.values
end
def initialize(value)
@value = value
end
def to_s
short_description
end
def short_description
SCORES.key(@value)
end
def description
DESCRIPTIONS[@value]
end
def ==(other_rating)
value == other_rating.value
end
end
| true
|
d654b160de9e146b423591852c826d5a66d0f110
|
Ruby
|
faiweiner/wdi-5
|
/02-web.1.0/receipt/main.rb
|
UTF-8
| 1,712
| 2.71875
| 3
|
[] |
no_license
|
require 'pry'
require 'pry-debugger'
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
get '/' do
@receipts = query_db "SELECT * FROM receipts"
erb :receipts
end
get '/new' do
erb :new_receipt
end
post '/' do
# "INSERT INTO receipts (service, cost) VALUES ('Do some service', '12')"
sql = "INSERT INTO receipts (service, cost) VALUES ('#{ params['service'] }', '#{ params['cost'] }' )"
query_db sql
redirect to "/"
end
get '/receipts/:id' do
id = params[:id]
sql = "SELECT * FROM receipts WHERE id = #{ id }"
@receipts = query_db sql
@receipt = @receipts.first #Flattening the array
erb :receipt
end
get '/receipts/:id/edit' do
id = params[:id]
end
delete '/receipts/:id' do
end
get '/stats' do
@max = query_db("SELECT MAX(cost) FROM receipts").last[0]
@min = query_db("SELECT MIN(cost) FROM receipts").last[0]
@average = query_db("SELECT AVG(cost) FROM receipts").last[0]
@count = query_db("SELECT COUNT(*) FROM receipts").last[0]
erb :stats
end
def query_db(sql)
db = SQLite3::Database.new "receipts.db"
db.results_as_hash = true
result = db.execute sql
db.close
result
end
# post '/' do
# f = File.new('receipt.txt', 'a+')
# @service = params[:service]
# @cost = params[:cost]
# f.puts("COMPANY NAME: Idiot Cousin Services")
# f.puts("Good/service provided: #{ @service }")
# f.puts("Cost: #{ @cost }")
# f.puts("Thank you for your patronage.")
# f.puts("We are missing you already.")
# f.puts("-----------------------------------")
# #when you open this form, you're going to append the form, add new items at the end
# f.close
# #Remember to CLOSE files every time you open it!!
# erb :receipt
# end
| true
|
efe403725f78dc5dc3de0303183dce81a2e30008
|
Ruby
|
PetronellaSimonsbacka/library-challenge
|
/lib/library.rb
|
UTF-8
| 762
| 2.921875
| 3
|
[] |
no_license
|
require 'yaml'
class Library
attr_accessor :jane_library, :exp_date, :lend, :title, :author, :published
def initialize
@jane_library = YAML.load_file('./lib/data.yml')
@exp_date = Date.today.next_month(1).strftime("%m/%y")
end
def lend(item, titel)
case
when book_is_not_available(available) then
{ available: false, message: 'Book is not in library' }
when subject_have_library_book_at_home then
{ available: true, message: 'Return the book you have at home first' }
else
perform_lend(item, titel, available, return_date)
{ available: true, message: 'Return the book after 30 days' }
end
end
private
def set_expiry_date
Date.today.next_month(30).strftime("%m/%y")
end
end
| true
|
bc87231a02cb305d46785c44141a4fa06ea119df
|
Ruby
|
burke/rulebook
|
/test/test_chevy.rb
|
UTF-8
| 1,633
| 2.796875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require 'helper'
class TestChevy < Test::Unit::TestCase
class Engine
attr_accessor :state
def initialize
@state = "off"
end
rules do
rule(/is_(.*)/) do |state|
@state = state.gsub(/_/, " ")
end
end
end
context 'A Chevy engine checked with #state_is?' do
setup do
@chevy = Engine.new
class << @chevy
def state_is?(state)
@state == state
end
end
end
should 'be off' do
assert @chevy.state_is?('off')
end
should 'be idling' do
@chevy.is_idling
assert @chevy.state_is?('idling')
end
should 'be broken as usual' do
@chevy.is_broken_as_usual
assert @chevy.state_is?('broken as usual')
end
end
context 'A Chevy engine checked with custom rule' do
setup do
@chevy = Engine.new
class << @chevy
rules do
rule(/is_(.*)?/) do |state|
@state == state
end
end
end
end
should 'be off' do
assert @chevy.is_off?
end
should 'be idling' do
@chevy.is_idling
assert @chevy.is_idling?
end
should 'be broken as usual' do
@chevy.is_broken_as_usual
assert @chevy.is_broken_as_usual?
end
end
end
| true
|
fb6159e28a148b9424733e51c215ab5bc55ceb1e
|
Ruby
|
ChrisQ97/ProyectoRuby
|
/src/task.rb
|
UTF-8
| 332
| 2.671875
| 3
|
[] |
no_license
|
class Task
@name = ''
@state = ''
@task ={
name: '',
state: ''
}
def create (name, state)
@name = name
@state = state
@task = {
name: @name,
state: @state
}
$manager.append(@task)
end
def show
$manager
end
end
| true
|
c5239c082f6891f50addac8ccc33ad1d1902cc34
|
Ruby
|
lewhitley/w2d3
|
/poker/spec/card_spec.rb
|
UTF-8
| 618
| 3.015625
| 3
|
[] |
no_license
|
require 'rspec'
require 'card'
describe Card do
subject(:card) { Card.new(:two, :hearts) }
let(:bad_card) { Card.new(:twelve, :yellow) }
describe "#initialize" do
it "has a value and suit" do
expect(card.value).to_not be_nil
expect(card.suit).to_not be_nil
end
it "correctly assigns the value and suit" do
expect(card.value).to eq(:two)
expect(card.suit).to eq(:hearts)
end
it "does not assign invalid values and suits" do
expect{ bad_card.value }.to raise_error (ArgumentError)
expect{ bad_card.suit }.to raise_error (ArgumentError)
end
end
end
| true
|
cac3499314a068b728ace4fdd41782dfe7af5c50
|
Ruby
|
alephtwo/screensbot
|
/lib/commands/gatherer.rb
|
UTF-8
| 1,126
| 2.53125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require_relative '../util/twitter_util'
require_relative '../util/collectable'
require 'set'
# Gather them metrics
module Gatherer
include Collectable
LOGGER = Logger.new(STDOUT)
LOGGER.level = Logger::INFO
CLIENT = TwitterUtil.client
MAX_TWEETS = Twitter::REST::Timelines::MAX_TWEETS_PER_REQUEST
BATCH_SIZE = MAX_NUM_RESULTS * (MAX_PAGE - 1)
def self.update_metrics
timeline = gather_timeline
tweets = Tweet.all
tweets_by_id = tweets.group_by(&:tweet_id)
find_updates(timeline, tweets).each do |id, v|
LOGGER.info "updating tweet with id #{id}"
tweets_by_id[id].first.update(favorites: v[:favs], retweets: v[:rts])
end
end
def self.gather_timeline
Collectable.collect_with_count(BATCH_SIZE) do |opts|
CLIENT.user_timeline(CLIENT.user.screen_name, opts)
end
end
def self.find_updates(timeline, tweets)
tweeted_ids = tweets.map(&:tweet_id).to_set
timeline
.select { |t| tweeted_ids.include?(t.id.to_s) }
.map { |t| [t.id.to_s, { favs: t.favorite_count, rts: t.retweet_count }] }
.to_h
end
end
| true
|
c31eca71dc83676bf50aee4f58821975644302e2
|
Ruby
|
avocade/nested_accessors
|
/spec/nested_accessors_spec.rb
|
UTF-8
| 6,913
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
require 'minitest/autorun'
require 'minitest/spec'
require 'simple_mock'
require_relative '../lib/nested_accessors'
# STUBBING OUT active_record "serialized" class method
class Person #< ActiveRecord::Base # must inherit from activerecord to get "serialize" class method
# Stubs out the "serialize :name, Hash" method
# So don't have to use activerecord
# Creates eg a :info hash accessor and returns hash
def self.serialize(name, klass)
attr_accessor name
define_method name do
@serialized_hash = {} if @serialized_hash.nil?
@serialized_hash
end
end
# must include module after the serialize method has been defined (it's defined in the superclass when inherited from activerecord)
include NestedAccessors
# USAGE in active_record model:
# nested_accessor :info, :phone, address: [ :street, :zipcode ]
end
# SPECS
describe NestedAccessors do
describe 'init method for hash accessors' do
it 'should init root object to Hash if blank or not a Hash' do
Person.class_eval %q{ nested_accessor :info }
Person.new.info.class.must_equal Hash
end
describe "with phone accessor" do
before(:each) do
Person.class_eval %q{ nested_accessor :info, :phone }
end
let(:person) { Person.new }
it 'should use stringified keys' do
person.phone = "12378"
person.info.keys.must_include "phone"
end
it 'should init key to nil if blank' do
person.info.keys.must_be_empty
person.phone.must_be_nil # shouldn't raise exception since it couldn't find the key
end
it 'sets up accessors for first level of nesting' do
person.phone = "123-2345"
person.phone.must_equal "123-2345"
end
it 'read accessor should return value typed to String by default (to_s)' do
person.phone = 123
person.phone.must_equal "123"
end
it 'write accessor should save value typed to String' do
person.phone = 234
person.info["phone"].must_equal "234"
end
it 'each subvalue should be nil if regular value param' do
person.info["phone"].must_be_nil
person.info["address"].must_be_nil
end
it 'can set multiple properties if first param is Array type' do
Person.class_eval %q{ nested_accessor :info, [:phone1, :phone2] }
person = Person.new
person.info["phone1"] = "2365"
person.phone1.must_equal "2365"
person.phone2 = "9090"
person.info["phone2"].must_equal "9090"
end
end
describe 'subhashes' do
it 'should init as hash if gets Array with multiple params for a property name in Hash' do
# Gives self.info["address"]["street"] and ["city"]
Person.class_eval %q{ nested_accessor :info, address: [:street, :city] }
person = Person.new
person.address.must_be_kind_of Hash
person.address["city"] = "Goteborg"
person.address["city"].must_equal "Goteborg"
end
it 'should init subhash to nil value if blank' do
Person.class_eval %q{ nested_accessor :info, address: [:street, :city] }
person = Person.new
person.address.must_be_kind_of Hash
person.address_street.must_be_nil # shouldn't raise exception since it couldn't find the key
end
it 'should init with just one param in array' do
Person.class_eval %q{ nested_accessor :info, snub: [:identifier] }
person = Person.new
person.snub.must_be_kind_of Hash
person.snub_identifier = "Achaplan"
person.snub_identifier.must_equal "Achaplan"
end
it 'should init with just one param symbol in hash as well' do
Person.class_eval %q{ nested_accessor :info, auth: :facebook }
person = Person.new
person.auth.must_be_kind_of Hash
person.auth_facebook = "12k3j"
person.auth_facebook.must_equal "12k3j"
end
it 'should create shallow accessor methods for each hash propname' do
Person.class_eval %q{ nested_accessor :bank, branch: [:designator, :account_number] }
person = Person.new
person.branch.must_be_kind_of Hash
person.branch_designator = "123"
person.branch_designator.must_equal "123"
person.branch_account_number = "999"
person.branch_account_number.must_equal "999"
end
# it 'should perhaps create accessor methods on the subroot object, for each subparam in hash' do
# Person.class_eval %q{ nested_accessor :info, address: [:street, :city] }
# person = Person.new
# person.address.must_be_kind_of Hash
# # the subroot method must thus return an object and define attr_accessor methods on it for each propname
# person.address.street = "Storgatan"
# person.address.street.must_equal "Storgatan"
# person.address.city = "Bigtown"
# person.address.city.must_equal "Bigtown"
# end
end
it 'should init subvalue with Array if type set to array for accessor' do
# nested_accessor :info, balls: Array
#=> self.info["Balls"] == []
Person.class_eval %q{ nested_accessor :things, balls: Array }
person = Person.new
person.balls.must_be_kind_of Array
person.balls << "bob"
person.balls << "alice"
person.balls.must_include "bob"
person.balls.must_include "alice"
end
describe 'second level nesting' do
it 'sets up accessors for two level deep hash' do
# nested_accessor :info, subregion: { address: [:street, :city] }
#=> foo.info[address][subregion] = {}
# Person.class_eval %q{ nested_accessor :home, subregion: { address: [:street, :city] } }
Person.class_eval %q{ nested_accessor :home, budget: { heating: [:highest, :lowest] } }
person = Person.new
person.budget_heating.must_be_kind_of Hash
person.budget.must_be_kind_of Hash
person.budget.has_key?("heating").must_equal true # can only test that hash has the key after we've used the subregion command since that instantiates the nested hash
person.budget_heating_highest = "32 C"
person.budget_heating_highest.must_equal "32 C"
person.budget_heating_lowest = "10 C"
person.budget_heating_lowest.must_equal "10 C"
end
it 'should init deep hash values to nil value if blank' do
Person.class_eval %q{ nested_accessor :place, location: { coordinate: [:lat, :lon] } }
person = Person.new
person.location_coordinate.must_be_kind_of Hash
person.location_coordinate_lat.must_be_nil # shouldn't raise exception since it couldn't find the key
end
it 'should set deep hash values and not overwrite others in the same subhash' do
# TODO: Must test so we don't just write a new hash when changing a value
end
end
end
end
| true
|
0ef0cc7f7bf0cea3e6363baa679b0b4876f0522d
|
Ruby
|
ChunAllen/sample_prog
|
/floyd_triangle.rb
|
UTF-8
| 418
| 3.640625
| 4
|
[] |
no_license
|
class FloydTriangle
attr_reader :number
def initialize(number)
@number = number
end
def run
pascal_calc(number - 1)
end
private
def pascal_calc(row_num)
if row_num == 0
return [1]
end
previous = pascal_calc(row_num - 1)
ret = []
(previous.length - 1).times do |i|
ret.push (previous[i] + previous[i + 1])
end
return [1, ret, 1].flatten
end
end
| true
|
030d01fce2ee28258859a8cba49a16010b7ba041
|
Ruby
|
pgoos/clark-app
|
/features/support/page_object/components/list.rb
|
UTF-8
| 606
| 2.5625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module Components
# This component provides methods for interactions with lists of web elements
module List
# Method asserts that a list of objects exists and (optional) contains provided entities
# DISPATCHER METHOD
# Custom method MUST be implemented. Example: def assert_documents_list(table) { }
# @param marker [String] custom method marker
# @param table [Cucumber::Ast::Table] table of entities
def assert_list(marker, table=nil)
custom_method = "assert_#{marker.tr(' ', '_')}_list"
send(custom_method, table)
end
end
end
| true
|
f8d9b71a460300b312f967debadd2236428fc4b2
|
Ruby
|
ollie/wallet
|
/app/models/search.rb
|
UTF-8
| 699
| 2.828125
| 3
|
[] |
no_license
|
class Search
attr_accessor :query, :date_from, :date_to, :page
def initialize(query: nil, date_from: nil, date_to: nil, page: nil)
self.query = query.to_s.strip
self.date_from = date_from.to_s.strip
self.date_to = date_to.to_s.strip
self.page = (page || 1).to_i || 1
end
def results
@results ||= begin
phrases = query.split('|').map(&:strip).reject(&:empty?)
if phrases.any?
date_from = Date.parse(self.date_from) if self.date_from.present?
date_to = Date.parse(self.date_to) if self.date_to.present?
GroupsList.search(phrases, date_from, date_to, page)
else
GroupsList.new
end
end
end
end
| true
|
f7eab8e8f4ee73a71f81b00ef56d300ad69963ad
|
Ruby
|
Brianpantoja33/digiramp
|
/app/classes/error_notification.rb
|
UTF-8
| 934
| 2.53125
| 3
|
[] |
no_license
|
module ErrorNotification
def errored(error, obj)
ap '--------------------------------------------'
message = "#{error}: #{obj.inspect}"
ap 'ERROR: ' + message if Rails.env.development?
Opbeat.capture_message( message )
end
def post_error(error)
ap '--------------------------------------------'
ap 'ERROR: ' + error if Rails.env.development?
Opbeat.capture_message( error )
end
def self.post_object error, obj
ap '--------------------------------------------'
message = "#{error}: #{obj.inspect}"
ap 'ERROR: ' + message if Rails.env.development?
Opbeat.capture_message( message )
end
def self.post message
ap '--------------------------------------------'
ap 'ERROR: ' + message if Rails.env.development?
Opbeat.capture_message( message )
end
end
# ErrorNotification.post 'some message'
# ErrorNotification.post_object 'some message', some_object
| true
|
bf8106e4c7003f0a24a325075d72e2846e04b060
|
Ruby
|
jtrtj/battleshift
|
/db/seeds.rb
|
UTF-8
| 1,133
| 2.65625
| 3
|
[] |
no_license
|
player_1_board = Board.new(4)
player_2_board = Board.new(4)
player_1 = User.create(email: "brickstar@gmail.com", name: 'matt', password: '123', status: 'active', user_token: ENV['BATTLESHIFT_API_KEY'])
player_2 = User.create(email: "jtr022@gmail.com", name: 'john', password: '123', status: 'active', user_token: ENV['BATTLESHIFT_OPPONENT_API_KEY'])
sm_ship = Ship.new(2)
md_ship = Ship.new(3)
# # Place Player 1 ships
# ShipPlacer.new( player_1_board,
# sm_ship,
# "A1",
# "A2").run
# ShipPlacer.new( player_1_board,
# md_ship,
# "B1",
# "D1").run
# # Place Player 2 ships
# ShipPlacer.new( player_2_board,
# sm_ship.dup,
# "A1",
# "A2").run
# ShipPlacer.new( player_2_board,
# md_ship.dup,
# "B1",
# "D1").run
game_attributes = {
player_1_board: player_1_board,
player_2_board: player_2_board,
player_1_turns: 0,
player_2_turns: 0,
current_turn: 0,
player_1_id: player_1.id,
player_2_id: player_2.id
}
game = Game.new(game_attributes)
game.save!
| true
|
cbd6bddb8c16e6efd097de8a8d38ad90f0aa00a1
|
Ruby
|
harvard-library/STLee-blacklight
|
/lib/harvard/library_cloud/collections.rb
|
UTF-8
| 2,345
| 2.515625
| 3
|
[] |
no_license
|
module Harvard::LibraryCloud::Collections
require 'faraday'
require 'json'
include Harvard::LibraryCloud
# Logic for adding an item to a collection,
def add_to_collection_action (collection, item)
api = Harvard::LibraryCloud::API.new
path = 'collections/' + collection
connection = Faraday.new(:url => api.get_base_uri + path) do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
faraday.headers['Content-Type'] = 'application/json'
faraday.headers['X-LibraryCloud-API-Key'] = ENV["LC_API_KEY"]
end
raw_response = begin
response = connection.post do |req|
req.body = '[{"item_id": "' + item + '"}]'
end
{ status: response.status.to_i, headers: response.headers, body: response.body.force_encoding('utf-8') }
rescue Errno::ECONNREFUSED, Faraday::Error => e
raise RSolr::Error::Http.new(connection, e.response)
end
end
# This is the action that displays the contents of the "Add to Collection" dialog
def add_to_collection
if request.post?
# Actually add the item to the collection
ids = request.params[:id].split(',')
ids.each do |id|
add_to_collection_action(request.params[:collection], id)
end
# Don't render the default "Add to Collection" dialog - render the "Success!" dialog contents
flash[:success] ||= "The item has been added to the collection"
render 'catalog/add_to_collection_success'
end
end
# There is probably a better way to do this. Blacklight is calling a function with this name to render
# the path for the "Add to Collection" action, but I'm not 100% sure why. According to the documentation
# we would expect this function to be named 'add_to_collection_catalog_path'.
def add_to_collection_solr_document_path (arg)
"/catalog/" << arg.id << "/add_to_collection"
end
# Helper method to get the collections that are available for adding an item to
# This does not currently do any filtering by ownership, so it shows ALL collections
def available_collections
api = API.new
params = {:limit => 9999, :preserve_original => true}
response = api.send_and_receive('collections', {:params => params})
response.map {|n| [n['title'], n['identifier']]}
end
end
| true
|
2295e0aca3c0884a4dbd6ac8f8c40cb1e1188b80
|
Ruby
|
samvaughn/courseproject
|
/new_roman.rb
|
UTF-8
| 1,169
| 3.75
| 4
|
[] |
no_license
|
def new_roman numeral
thousands = (numeral / 1000)
hundreds = (numeral % 1000 / 100)
tens = (numeral % 100 / 10)
ones = (numeral % 10)
roman = 'M' * thousands
if hundreds == 9
roman = roman + 'CM'
elsif hundreds == 4
roman = roman + 'CD'
else
roman = roman + 'D' * (numeral % 1000 / 500)
roman = roman + 'C' * (numeral % 500 / 100)
end
if tens == 9
roman = roman + 'XC'
elsif tens == 4
roman = roman + 'XL'
else
roman = roman + 'L' * (numeral % 100 / 50)
roman = roman + 'X' * (numeral % 50 / 10)
end
if ones == 9
roman = roman + 'IX'
elsif ones == 4
roman = roman + 'IV'
else
roman = roman + 'V' * (numeral % 10 / 5)
roman = roman + 'I' * (numeral % 5 / 1)
end
roman
end
# roman = roman + 'M' * (numeral / 1000)
# roman = roman + 'D' * (numeral % 1000 / 500)
# roman = roman + 'C' * (numeral % 500 / 100)
# roman = roman + 'L' * (numeral % 100 / 50)
# roman = roman + 'X' * (numeral % 50 / 10)
# roman = roman + 'V' * (numeral % 10 / 5)
# roman = roman + 'I' * (numeral % 5 / 1)
# roman
# end
puts 'Enter a number between 1 and 3000'
num = gets.chomp
puts(new_roman(num.to_i))
| true
|
6850c327f846ac524d95f62ae3d3ffddd674d47a
|
Ruby
|
NEU-DSG/tapas_rails
|
/app/models/content/concerns/filename.rb
|
UTF-8
| 443
| 2.53125
| 3
|
[] |
no_license
|
# The use of the content datastream label to store the basename of the
# file held in that stream has been historically controversial, but I keep
# doing it because so far no better solution has come along.
#
# To ease the eventual migration away from this use this filename method to
# access the filename of a content object file.
module Filename
extend ActiveSupport::Concern
def filename
return self.content.label
end
end
| true
|
34cb9ffe304910ab8db64b8407ae7ec0d46a3a58
|
Ruby
|
crayolapancake/Animal_Shelter_Project
|
/animal_shelter/models/animal.rb
|
UTF-8
| 2,223
| 3.40625
| 3
|
[] |
no_license
|
require_relative('../db/sql_runner')
class Animal
attr_accessor :image_url, :name, :species, :age, :adoptable, :owner_id
attr_reader :id
def initialize(options)
@id = options['id'].to_i if options['id']
@image_url = options['image_url']
@name = options['name']
@species = options ['species']
@age = options ['age']
@adoptable = options ['adoptable']
@owner_id = options ['owner_id'].to_i
end
def save()
sql = "INSERT INTO animals
(image_url, name, species, age, adoptable, owner_id)
VALUES
($1, $2, $3, $4, $5, $6)
RETURNING id"
values = [@image_url, @name, @species, @age, @adoptable, @owner_id]
result = SqlRunner.run(sql, values)
id = result.first['id']
@id = id
end
# return an array of Animal objects (all of them)
def self.all()
sql = "SELECT * FROM animals"
values = []
animal_hash = SqlRunner.run(sql, values)
array_of_animal_objects = animal_hash.map { |animal_hash| Animal.new(animal_hash) }
return array_of_animal_objects
end
def owner()
owner = Owner.find(@owner_id)
return owner
end
def delete()
sql = "DELETE FROM animals
WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def update()
sql = "UPDATE animals
SET
(image_url, name, species, age, adoptable, owner_id) =
($1, $2, $3, $4, $5, $6)
WHERE id = $7"
values = [@image_url, @name, @species, @age, @adoptable, @owner_id, @id]
SqlRunner.run(sql, values)
end
def self.adopt(animal_id, owner_id)
sql = "UPDATE animals
SET owner_id = $1
WHERE id = $2"
values = [owner_id, animal_id]
SqlRunner.run(sql, values)
end
def self.map_items(animal_data)
return animal_data.map { |animal| Animal.new(animal) }
end
def self.find(id)
sql = "SELECT * FROM animals
WHERE id = $1"
values = (id)
result = SqlRunner.run(sql, values).first
animal = Animal.new(result)
return animal
end
def self.find_species(species)
sql = "SELECT * FROM animals
WHERE species = $1"
values = [species]
result = SqlRunner.run(sql, values)
animal = result.map{|animal| Animal.new(animal)}
return animal
end
end
| true
|
f03ed7f83e18835d2f5c0af8f831a4b299ed8b1a
|
Ruby
|
judofyr/rcpu
|
/test/test_emulator.rb
|
UTF-8
| 7,345
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
require 'helper'
module RCPU
class TestEmulator < TestCase
def test_parse
ins = []
rcpu(false) do
block :main do
SET a, 1
ins << @ins.last
ADD [a], 0x1000
ins << @ins.last
SUB (a+1), [0x10]
ins << @ins.last
SET push, o
ins << @ins.last
SET x, pop
ins << @ins.last
SET x, peek
ins << @ins.last
SET x, pc
ins << @ins.last
JSR :crash
label :crash
SUB pc, 1
end
end
until ins.empty?
assert_equal ins.shift, @emu.next_instruction[1]
@emu.tick
end
end
def test_set
block do
SET a, 0x30
SET [0x2000], a
SET b, 0x2001
SET [b], 0x10
end
assert_equal 0x30, memory[0x2000]
assert_equal 0x10, memory[0x2001]
end
def test_add
block do
SET [0x1000], 0x5678 # low word
SET [0x1001], 0x1234 # high word
ADD [0x1000], 0xCCDD # add low words, sets O to either 0 or 1 (in this case 1)
ADD [0x1001], o # add O to the high word
ADD [0x1001], 0xAABB
ADD [0x1001], o
end
assert_equal 0x2355, memory[0x1000]
assert_equal 0xBCF0, memory[0x1001]
end
def test_sub
block do
SET [0x1000], 0x5678
SUB [0x1000], 0xCCDD
end
assert_equal 0x899B, memory[0x1000]
assert_equal 0xFFFF, register(:O)
end
def test_mul
block do
SET [0x1000], 0x5678
MUL [0x1000], 0x3
end
assert_equal 0x0368, memory[0x1000]
assert_equal 0x1, register(:O)
end
def test_div
block do
SET [0x1000], 15
DIV [0x1000], 4
end
assert_equal 3, memory[0x1000]
assert_equal 0xC000, register(:O)
block do
SET [0x1000], 15
DIV [0x1000], 0
end
assert_equal 0, memory[0x1000]
assert_equal 0, register(:O)
end
def test_mod
block do
SET [0x1000], 15
MOD [0x1000], 4
end
assert_equal 3, memory[0x1000]
block do
SET [0x1000], 15
MOD [0x1000], 0
end
assert_equal 0, memory[0x1000]
end
def test_shl
block do
SET [0x1000], 0xFFFF
SHL [0x1000], 4
end
assert_equal 0xFFF0, memory[0x1000]
assert_equal 0xF, register(:O)
end
def test_shr
block do
SET [0x1000], 0xFF
SHR [0x1000], 4
end
assert_equal 0xF, memory[0x1000]
assert_equal 0xF000, register(:O)
end
def test_and
block do
SET [0x1000], 5
AND [0x1000], 4
end
assert_equal (5 & 4), memory[0x1000]
end
def test_bor
block do
SET [0x1000], 5
BOR [0x1000], 4
end
assert_equal (5 | 4), memory[0x1000]
end
def test_xor
block do
SET [0x1000], 5
XOR [0x1000], 4
end
assert_equal (5 ^ 4), memory[0x1000]
end
def test_ife
block do
SET a, 5
IFE a, 4
SET b, 1
IFE a, 5
SET pc, :crash
SET b, 1
end
assert_equal 0, register(:B)
end
def test_ifn
block do
SET a, 5
IFN a, 5
SET b, 1
IFN a, 4
SET pc, :crash
SET b, 1
end
assert_equal 0, register(:B)
end
def test_ifg
block do
SET a, 5
IFG a, 6
SET b, 1
IFG a, 3
SET pc, :crash
SET b, 1
end
assert_equal 0, register(:B)
end
def test_ifb
block do
SET a, 5
IFB a, 2
SET b, 1
IFB a, 1
SET pc, :crash
SET b, 1
end
assert_equal 0, register(:B)
end
def test_stack
block do
SET a, sp
SET push, 2
SET push, 3
SET b, pop
SET c, pop
SET x, sp
end
# Default SP
assert_equal 0, register(:A)
# Push and pop
assert_equal 3, register(:B)
assert_equal 2, register(:C)
# Final value of SP
assert_equal 0, register(:X)
end
class VoidExtension
def initialize(array, start)
@array = array
@start = start
end
def map; yield @start end
def [](key)
0
end
def []=(key, value)
# do nothing
end
end
def test_extension
rcpu do
extension 0x1000, VoidExtension
block :main do
SET [0x1000], 5
label :crash
SET pc, :crash
end
end
assert_equal 0, memory[0x1000]
end
def test_format
rcpu(false) do
block :main do
SET a, 1
ADD [a], 0x1000
SUB [a+1], [0x10]
SET push, o
SET x, pop
SET x, peek
SET x, pc
JSR :crash
label :crash
SUB pc, 1
end
end
res = [
"SET a, 0x1",
"ADD [a], 0x1000",
"SUB [a+1], [0x10]",
"SET push, o",
"SET x, pop",
"SET x, peek",
"SET x, pc",
"JSR 0xC",
"SUB pc, 0x1"
]
until res.empty?
assert_equal res.shift, @emu.next_instruction[1].to_s
@emu.tick
end
end
def test_parse_number
rcpu do
library :parse
block :main do
SET a, 10
SET b, 3
SET c, :base10
JSR :_parse_number
SET [0x1000], x
SET [0x1001], o
SET a, 16
SET b, 3
SET c, :base16
JSR :_parse_number
SET [0x1002], x
SET [0x1003], o
SET a, 2
SET b, 3
SET c, :base2
JSR :_parse_number
SET [0x1004], x
SET [0x1005], o
SET a, 5
SET b, 3
SET c, :base16
JSR :_parse_number
SET [0x1006], o
SUB pc, 1
data :base10, "123"
data :base16, "11F"
data :base2, "101"
end
end
assert_equal 123, memory[0x1000]
assert_equal 0, memory[0x1001]
assert_equal 0x11F, memory[0x1002]
assert_equal 0, memory[0x1003]
assert_equal 0b101, memory[0x1004]
assert_equal 0, memory[0x1005]
assert_equal 1, memory[0x1006]
end
def test_sin_table
n = 16
rcpu(false) do
block :main do
extend TrigMacros
sin_lookup_table n
end
end
expected = [32767, 45307, 55937, 63040,
65535, 63040, 55937, 45307,
32767, 20227, 9597, 2494,
0, 2494, 9597, 20227]
assert_equal expected, memory.slice(0...n)
end
# Tests PC wraparound in the middle of an instruction.
def test_pc_wrap
rcpu do
block :main do
crash = 0x85c3 # SUB PC, 1
set_z = 0x7c51 # SET z, <next word>
SET y, crash
SET pc, :wrapped_instruction
data :pad, Array.new(65531, 0)
data :wrapped_instruction, [set_z]
end
end
assert_equal 0x85c3, register(:Y)
assert_equal 0x7c41, register(:Z)
end
end
end
| true
|
9d5770ade0854abe62f9c06e42740bdbbeb1317f
|
Ruby
|
04alexklink/student-directory
|
/step8exercise11.rb
|
UTF-8
| 1,551
| 4
| 4
|
[] |
no_license
|
# STEP 8 EXERCISE 11
# Once you have completed the "Asking for user input" section,
# open this file. It's Ruby code but it has some typos. Copy it
# to a local file and open it in Atom without syntax highlighting.
# To do this, select "Plain Text" in the lower right corner of the window.
# Now, find all typos in that file and correct them. Use your experience, online documentation,
# etc. to find all mistakes. Run the script in the terminal from time to time to make sure it works
# as it should. Google the errors Ruby will give you, think about what they could mean, try different things
# but don't look the answer up :)
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
# create an empty array
students = []
# get the first name
name = gets.chomp
# while the name is not empty, repeat this code
while !name.empty? do
# add the student hash to the array
students << {name: name, cohort: :november}
puts "Now we have #{students.count} students"
# get another name from the user
name = gets.chomp
end
# return the array of students
students
end
def print_header
puts "The students of my cohort at Makers Academy"
puts "-------------"
end
def print_student(students)
students.each do |student|
puts "#{student[:name]} (#{student[:cohort]} cohort)"
end
end
def print_footer(students)
puts "Overall, we have #{students.count} great students"
end
students = input_students
print_header
print_student(students)
print_footer(students)
| true
|
c10572285de5003bc46729008e73bdd7192b9848
|
Ruby
|
sdexter91/chatbot
|
/pingpong.rb
|
UTF-8
| 1,520
| 2.6875
| 3
|
[] |
no_license
|
require 'socket'
server = 'cherryh.freenode.net'
port = 6667
socket = TCPSocket.open(server, port)
nickname = 'SkillcrushBotOMG'
channel = '#turquoise1591'
socket.puts "NICK #{nickname}"
socket.puts "USER #{nickname} 0 * #{nickname}"
socket.puts "JOIN #{channel}"
socket.puts "PRIVMSG #{channel} :I am so happy to be here!"
while message = socket.gets do
puts message
if message.match('^PING :')
server = message.split(':').last
puts "PONG #{server}"
socket.puts "PONG #{server}"
elsif message.match('How are you?')
puts "PRIVMSG #{channel} :I'm great, thanks!"
socket.puts "PRIVMSG #{channel} :I'm great, thanks!"
#elsif message.match('SuperAwesomeBot who is your BFF?')
#puts "PRIVMSG #{channel} :Sam!"
#socket.puts "PRIVMSG #{channel} :Sam!"
elsif message.match('SuperAwesomeBot I want to be your BFF!')
File.write('bff.txt', "#{channel}")
puts "PRIVMSG #{channel} :Gee thanks :)"
socket.puts "PRIVMSG #{channel} :Gee thanks :)"
elsif message.match('SuperAwesomeBot who is your BFF?')
puts "PRIVMSG #{channel} :My best friend is #{File.read('bff.txt')}"
socket.puts "PRIVMSG #{channel} :My best friend is #{File.read('bff.txt')}"
elsif message.match('BFFBot I feel down, inspire me!')
puts "PRIVMSG #{channel} :It is during our darkest moments that we must focus to see the light. - Aristotle"
socket.puts "PRIVMSG #{channel} :It is during our darkest moments that we must focus to see the light. - Aristotle"
end
end
| true
|
4a89e23ae3d613064fb5654f7fcb50d5ba7ef211
|
Ruby
|
heshf/learn-to-program
|
/chap08/ex1.rb
|
UTF-8
| 477
| 3.09375
| 3
|
[] |
no_license
|
=begin
puts 'Hello there, please enter some text (one word only per line'
responses = []
while true
responses = gets.chomp
if responses ==""
break
end
responses.push
end
puts "Thank you. Now here are your words"
puts responses.sort
=end
puts 'Hello there, please enter some text (one word only per line)'
responses = []
while true
response = gets.chomp
if response ==""
break
end
responses.push response
end
puts "Thank you. Now here are your words"
puts responses.sort
| true
|
4440f6d9e1b99ed28f71ca3450414e14cdd69c63
|
Ruby
|
laurengordonfahn/phase-0-tracks
|
/ruby/santa.rb
|
UTF-8
| 3,896
| 3.859375
| 4
|
[] |
no_license
|
#Initalizeing class Santa
class Santa
attr_reader :ethnicity
attr_accessor :gender, :age
#Creating two instances of class Santa
# Instance Methods for class Santa
def speak(number_of_times)
index = 0
until number_of_times == index
puts "Ho, ho, ho!, Haaaappy holidays!"
index +=1
end
end
def eat_milk_and_cookies(type_of_cookie)
puts "That was a good #{type_of_cookie}."
end
def initialize(name, gender, ethnicity)
puts "Initializing Santa instance...#{name}, #{gender}, #{ethnicity}."
@name = name.to_s
@gender = gender.to_s
@ethnicity = ethnicity.to_s
@reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"]
@age = 0
end
#Release 2
def celebrate_birthday(age)
@age = age + 1
end
def get_mad_at(reindeer_name)
@reindeer_ranking.delete(reindeer_name)
p @reindeer_ranking.push(reindeer_name)
end
#This is noted because we added attr_ statements at the top of this code
# def gender= (new_gender)
# @gender = new_gender
# end
# def age
# @age
# end
# def ethnicity
# @ethnicity
# end
end
# driver code to test Release 0
# sarah = Santa.new("sarah")
# small_santa = Santa.new("small santa")
# sarah.speak(2)
# small_santa.eat_milk_and_cookies("Oatmeal Chocolate-Chip")
#Release 1
# an empty container for the santa instances
# santas = []
# example_names = ["Sarah", "Sting", "Sigmond", "Stella", "Stephen", "Sidney", "Singin"]
# example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"]
# example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"]
# example_names.length.times do |i|
# santas << Santa.new(example_names[i], example_genders[i], example_ethnicities[i])
# end
#Release 2
# class Reindeer
# def initialize(name)
# @name = name
# end
# end
# reindeer = Reindeer.new("Blitzen")
# reindeer.name
phil = Santa.new("Phil", "Maleish", "Caucasian")
p phil.celebrate_birthday(4)
phil.get_mad_at("Dancer")
p phil.age
p phil.ethnicity
p phil.gender= ("Transcurious")
# an empty container for the santa instances
def santa_generator(num)
@santas = []
example_names = ["Sarah", "Sting", "Sigmond", "Stella", "Stephen", "Sidney", "Singin"]
example_genders = ["agender", "female", "bigender", "male", "female", "gender fluid", "N/A"]
example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"]
num.times do |num|
new_santa = Santa.new(example_names.sample(example_names.length), example_genders.sample(example_genders.length), example_ethnicities.sample(example_ethnicities.length))
# name = example_names.rand(example_name.length)
# gender = example_genders.rand(example_genders.length)
# ethnicity = example_ethnicities.rand(example_ethnicities.length)
new_santa.age = (1..140).to_a.sample
# Emmanual said these sage words otherwise there is no variable to accept the random number
# [11:21]
# if you had another method that created age and called it before this that would work too
# [11:21]
# basically, initialize sets all of the basic information for the class. What needs to exist for this class to exist
@santas << new_santa
# index = 0 do |num|
# until num == index
# name = example_names.rand(example_name.length)
# gender = example_genders.rand(example_genders.length)
# ethnicity = example_ethnicities.rand(example_ethnicities.length)
# age = Random.rand(141)
# santas << Santa.new (name, gender,ethnicity)
# # name = example_names(rand(example_name.length)
# # gender = example_genders(rand(example_genders.length)
# # ethnicity = example_ethnicities(rand(example_ethnicities.length)
# # age = Random.rand(141)
# index += 1
end
end
santa_generator(5)
p @santas[4].age
| true
|
34ecaba67a17fc2771d01dd1c1de2fddafb79d18
|
Ruby
|
JaimeVRodriguez/RubyOnRailsIntro
|
/Week1/Debug1.rb
|
UTF-8
| 608
| 3.71875
| 4
|
[] |
no_license
|
#--------------------------------------------------------------------------
#
# Script Name: Debug1.rb
# Version: 1.3
# Author: Jaime V. Rodriguez
# Date: 10 June 2020
# Assignment #: Assignment 1.3
#
# Description: This Ruby script has purposely inserted "bugs" in order
# for fellow students to practice debuggin a program.
#
#--------------------------------------------------------------------------
print "Enter your name: "
#miss "D" should read STDIN.gets
name = STIN.gets
name.chop!
message = "Hello " + name + "! Have a great day!"
#missing "s" should read puts
put message
| true
|
87ca35104060e81ea75c3d73f8b07be0d504c354
|
Ruby
|
deltapurna/intro_to_ruby_and_sinatra
|
/code/monkey_patch.rb
|
UTF-8
| 122
| 2.65625
| 3
|
[] |
no_license
|
#!/home/delta/.rbenv/shims/ruby
class String
def shout!
"#{self.upcase}!!!"
end
end
puts "Tech Talk JDV".shout!
| true
|
20adac3e4befb1a89364fcca283a40c661f58d29
|
Ruby
|
sergewhite/faye_demo
|
/faye.rb
|
UTF-8
| 704
| 2.53125
| 3
|
[] |
no_license
|
#!/usr/env ruby
BASE_DIR = File.expand_path("../", __FILE__)
if ARGV[1]
PID="#{BASE_DIR}/pids/#{ARGV[1].match(/(\w+)(.ru)/)[1]}.pid"
COMMAND="bundle exec rackup -s thin -E production #{BASE_DIR}/#{ARGV[1]}"
case ARGV[0]
when "start"
puts ">>Starting"
pid = fork do
Dir.chdir(BASE_DIR)
exec *COMMAND.split(' ') # fails for quoted args, obviously
end
Process.detach(pid)
File.open(PID, "w+") do |f|
f.write(pid)
end
when "stop"
puts ">>Stoping"
begin
Process.kill "KILL", File.read(PID).to_i
File.delete(PID)
rescue
end
else
puts "usage: #{$0} {start|stop} {config_name}"
end
else
puts "lose config name!!!"
end
| true
|
377288eddf31f7aa94f22a99cd1bb8b6433b5d2a
|
Ruby
|
ang3lkar/pact_broker
|
/lib/pact_broker/hash_refinements.rb
|
UTF-8
| 407
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module PactBroker
module HashRefinements
refine Hash do
def deep_merge(other_hash, &block)
block_actual = Proc.new {|key, oldval, newval|
newval = block.call(key, oldval, newval) if block_given?
[oldval, newval].all? {|v| v.is_a?(Hash)} ? oldval.merge(newval, &block_actual) : newval
}
merge(other_hash, &block_actual)
end
end
end
end
| true
|
9bd6b0a01902204b82c020b9fd9875ade2952635
|
Ruby
|
hhoopes/exercism
|
/ruby/robot-name/robot_name.rb
|
UTF-8
| 545
| 3.21875
| 3
|
[] |
no_license
|
class Robot
@@name_repository = []
attr_reader :name
def initialize
@name = generate_name
end
def reset
generate_name
end
private
def generate_name
new_name = ""
2.times do
new_name << ("A".."Z").to_a.sample
end
3.times do
new_name << ("0".."9").to_a.sample
end
unique_name?(new_name) ? save_name(new_name) : generate_name
end
def save_name(name)
@@name_repository << name
@name = name
end
def unique_name?(name)
!@@name_repository.include?(name)
end
end
| true
|
f5e8b51ce80f422d5a1ebe8d153e3e622b7764ca
|
Ruby
|
KGan/appacc
|
/algo/euler/integer partition.rb
|
UTF-8
| 946
| 3.4375
| 3
|
[] |
no_license
|
require 'colorize'
def integer_partition(set)
set
set_sum = set.inject(:+)
mat = DpArray.new(set.length + 1) { DpArray.new(set_sum / 2 + 1) }
mat[0].map! { 0 }
mat.each do |row|
row[0] = 0
end
mat[0][0] = 1
mat[1..-1].each_with_index do |row, ri|
row.each_with_index do |sum, si|
prev_sum = mat[0..ri].inject(0) { |acc, row| si - set[ri] < 0 ? 0 : acc + row[si - set[ri]] }
row[si] = prev_sum
end
end
print ' ' + ('0'..(set_sum / 2).to_s).to_a.map { |n| "%3s" % n }.join('') + "\n"
mat.each_with_index do |row, r|
if r == 0
print ' '
else
print "%2s" % set[r-1].to_s + ' '
end
row.each_with_index do |val, c|
print " " + (val == 0 ? '0' : val.to_s.colorize(color: :red)) + " "
end
print "\n"
end
nil
end
class DpArray < Array
# def [](i)
# i < 0 ? 0 : super(i)
# end
end
integer_partition([7,8,5,4,6,3,2,1])
integer_partition([1,8,10])
| true
|
44ad6997b9aefcac6fbe76fe738384e570fea3f5
|
Ruby
|
ppawel/openstreetmap-watch-list
|
/lib/tiler/test/utils_test.rb
|
UTF-8
| 836
| 2.78125
| 3
|
[] |
no_license
|
$:.unshift File.absolute_path(File.dirname(__FILE__) + '/../lib/')
require 'test/unit'
require 'utils'
class UtilsTest < Test::Unit::TestCase
def test_bbox_to_tiles
tiles = bbox_to_tiles(18, [-95.2174366, 18.4330814, -95.2174366, 18.4330814])
assert_equal(61736, tiles.to_a[0][0])
assert_equal(117411, tiles.to_a[0][1])
tiles = bbox_to_tiles(12, [-95.2143046, 18.450548, -95.2143046, 18.450548])
assert_equal(964, tiles.to_a[0][0])
assert_equal(1834, tiles.to_a[0][1])
end
def test_box2d_to_bbox
bbox = box2d_to_bbox('BOX(5.8243191 45.1378079,5.8243191 45.1378079)')
assert_equal(5.8243191, bbox[0])
assert_equal(45.1378079, bbox[1])
assert_equal(5.8243191, bbox[2])
assert_equal(45.1378079, bbox[3])
end
def test_south_pole_tile
puts latlon2tile(-90.0, 0.0, 18)
end
end
| true
|
19148dbbe52b0e9bc77434d03dbe82034f36615d
|
Ruby
|
at90/flatlane-app-rails
|
/app/helpers/application_helper.rb
|
UTF-8
| 860
| 2.515625
| 3
|
[] |
no_license
|
module ApplicationHelper
def numeralify (val)
if val <=9000000
val=val/100000
numer="#{val} lacs"
end
if val >=9000000.0
val=val/10000000.0
fl_val=number_with_precision(val, :precision => 1)
numer="#{fl_val} Cr"
end
return numer
end
def curr_city
curr_city=@city
end
def home_icon (cat)
if cat == 1
cat_icon ="home"
end
if cat == 2
cat_icon ="building"
end
if cat == 3
cat_icon ="tree"
end
return cat_icon
end
def similarHomes(cityID,homeID)
project = Home.all
filter=[]
id = cityID
project.each do |project|
if project.c_id==id && project.id!=homeID
filter.push(project)
end
end
return filter
end
def builderName(builderID)
builder=Builder.find(builderID).b_name
return builder
end
end
| true
|
e2640ce3a92d7aa9043cbf3234e76aa365f1daa3
|
Ruby
|
Kkelly22/pokemon-scraper-v-000
|
/lib/pokemon.rb
|
UTF-8
| 669
| 3.234375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Pokemon
attr_accessor :name, :type, :db, :id, :hp
@@all = []
def initialize(name: name, type: type, db: db, id: id, hp: hp)
@name = name
@type = type
@db = db
@id = id
@hp = hp
@@all << self
end
def self.all
@@all
end
def self.save(name, type, db)
db.execute("INSERT INTO pokemon (name, type) VALUES (?, ?)",name, type)
end
def self.find(x, db)
array = db.execute("SELECT * FROM pokemon WHERE ? = id", x)[0]
Pokemon.new(id: array[0], name: array[1], type: array[2], db: db, hp: array[3])
end
def alter_hp(h, db)
db.execute("UPDATE pokemon SET hp = ? WHERE name = ?", h, self.name)
end
end
| true
|
348ceec79ef3f054fca9d14d846670dfb7c085b5
|
Ruby
|
brunofaboci/Rails_TimeToAnswer
|
/app/models/user_statistic.rb
|
UTF-8
| 552
| 2.734375
| 3
|
[] |
no_license
|
class UserStatistic < ApplicationRecord
belongs_to :user
def total_questions
self.right_question + self.wrong_question
end
def self.set_statistic(answer, current_user)
if !!current_user # ! é negação | uma ! nega a resposta, que seria true, transformando em um New, e a segunda ! nega novamente, voltando a ser true
user_statistic = UserStatistic.find_or_create_by(user: current_user)
answer.correct? ? user_statistic.right_question += 1 : user_statistic.wrong_question += 1
user_statistic.save
end
end
end
| true
|
56b6a1a894284b94f5fe4831df1f40975833e83f
|
Ruby
|
superr4y/hacks
|
/spotify/spotify_ad_blocker_linux.rb
|
UTF-8
| 3,352
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'pty'
# This script scans the output from 'strace spotify' and search for ads
# If it finds one it will mute the master channel and umute it if the ad is over.
# The script was developed for the Spotify Linux Client.
#
#
# Usage: sudo ./spotify_ad_blocker_linux.rb
class SpotifyAdBlocker
def initialize cmd
@volume = 0
@mute = false
@ad_chooser = false
@debug = false
exec_and_scan cmd do |line|
puts "### #{line}" if @debug
if line.match /ad_chooser.*adclass = ''/
# ads with no adclass are the badboys
# next track will be probably an ad
# Example: [ad_chooser.cpp:1150] Found ad (time = 663, adclass = '', time left = 30, length = 22)
@ad_chooser = true
puts 'ad_chooser found'
end
if line.match /index=/
# lines with 'index=' indecates a new track
if @mute
# the last track was muted, this track is porbably not an ad.
# TODO: what if spotify decides to play more then one ad.
unmute_sound()
end
if @ad_chooser
# ad_chooser was executed this is probably an ad.
# Lets mute this sucker :P
mute_sound()
@ad_chooser = false
end
end
end
end
def exec_and_scan(cmd, &block)
#http://stackoverflow.com/questions/1154846/continuously-read-from-stdout-of-external-process-in-ruby#answer-1162850
begin
PTY.spawn( cmd ) do |stdin, stdout, pid|
begin
stdin.each { |line| block.call(line)}
rescue Errno::EIO
end
end
rescue PTY::ChildExited
puts 'The child process exited!'
end
end
def mute_sound()
output = `amixer get Master`
match = output.match(/Mono: Playback (\d+) /)
if match
@volume = match[1].to_i
`amixer set Master 0`
@mute = true
end
puts 'mute'
end
def unmute_sound()
`amixer set Master #{@volume}`
@mute = false
puts 'unmute'
end
end
# group => blockify:x:1003:user
# gshadow => blockify:!::user
#
# EDIT to your own group
gid = 'blockify'
# delete old rules
#`iptables -D OUTPUT -m owner --gid-owner #{gid} -p udp --dport 53 -j ACCEPT`
#`iptables -D OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 4070 -j ACCEPT`
#`iptables -D OUTPUT -m owner --gid-owner #{gid} -j DROP`
#
## add rules to block all unnecessary communication
#`iptables -A OUTPUT -m owner --gid-owner #{gid} -p udp --dport 53 -j ACCEPT`
#`iptables -A OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 4070 -j ACCEPT`
#`iptables -A OUTPUT -m owner --gid-owner #{gid} -j DROP`
`iptables -D OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 80 -j DROP`
`iptables -D OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 443 -j DROP`
`iptables -A OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 80 -j DROP`
`iptables -A OUTPUT -m owner --gid-owner #{gid} -p tcp --dport 443 -j DROP`
#SpotifyAdBlocker.new "sg #{gid} -c 'su #{user} -c spotify'"
SpotifyAdBlocker.new "./spotify_wrapper"
| true
|
4956a9fd8b0b38ba0700367eb58ee2c537c33c3b
|
Ruby
|
michelsmonthe/ruby-test
|
/tests-ruby/lib/02_calculator.rb
|
UTF-8
| 154
| 3.109375
| 3
|
[] |
no_license
|
def add(x, y)
return x + y
end
#add(a, b)
#def subtract(a, b)
puts a - b
end
#subtract(a, b)
#a = gets.chomp.to_i
#b = gets.chomp.to_i
#def (a)
| true
|
2463dab25981a9f57472b449fad2f2130d537b31
|
Ruby
|
roselynemakena/RB
|
/logger/log.rb
|
UTF-8
| 323
| 2.734375
| 3
|
[] |
no_license
|
require 'logger'
$LOG = Logger.new($stderr)
def run_me
begin
eval(3/0)
rescue Exception => e
$LOG.warn "Caught something:: #{e}"
$LOG.info "Caught something:: #{e}"
$LOG.fatal "Caught something:: #{e}"
$LOG.error "Caught something:: #{e}"
$LOG.debug "Caught something:: #{e}"
end
end
run_me
| true
|
3859cdb6173be65a5e55985b83a60b9b96cb4555
|
Ruby
|
twrodriguez/duct_tape
|
/spec/ext/hash_spec.rb
|
UTF-8
| 2,638
| 2.765625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
require File.join(File.dirname(__FILE__), "..", "spec_helper.rb")
#
# Hash#deep_merge
#
describe Hash, "#deep_merge" do
it "should have the method defined" do
expect(Hash.method_defined?(:deep_merge)).to be(true)
end
pending "More tests"
end
#
# Hash#deep_merge!
#
describe Hash, "#deep_merge!" do
it "should have the method defined" do
expect(Hash.method_defined?(:deep_merge!)).to be(true)
end
pending "More tests"
end
#
# Hash#chunk
#
describe Hash, "#chunk" do
it "should have the method defined" do
expect(Hash.method_defined?(:chunk)).to be(true)
end
pending "More tests"
end
#
# Hash#not_empty?
#
describe Hash, "#not_empty?" do
it "should have the method defined" do
expect(Hash.method_defined?(:not_empty?)).to be(true)
end
pending "More tests"
end
#
# Hash#select_keys
#
describe Hash, "#select_keys" do
it "should have the method defined" do
expect(Hash.method_defined?(:select_keys)).to be(true)
end
pending "More tests"
end
#
# Hash#select_keys!
#
describe Hash, "#select_keys!" do
it "should have the method defined" do
expect(Hash.method_defined?(:select_keys!)).to be(true)
end
pending "More tests"
end
#
# Hash#reject_keys
#
describe Hash, "#reject_keys" do
it "should have the method defined" do
expect(Hash.method_defined?(:reject_keys)).to be(true)
end
pending "More tests"
end
#
# Hash#reject_keys!
#
describe Hash, "#reject_keys!" do
it "should have the method defined" do
expect(Hash.method_defined?(:reject_keys!)).to be(true)
end
pending "More tests"
end
#
# Hash#to_h
#
describe Hash, "#to_h" do
it "should have the method defined" do
expect(Hash.method_defined?(:to_h)).to be(true)
end
it "should not create a new instance" do
a = {1=>2}
b = a.to_h
b[2] = 3
expect(a).to eq(b)
end
end
#
# Hash#flatten_nested
#
describe Hash, "#flatten_nested" do
it "should have the method defined" do
expect(Hash.method_defined?(:flatten_nested)).to be(true)
end
pending "More tests"
end
#
# Hash#flatten_nested!
#
describe Hash, "#flatten_nested!" do
it "should have the method defined" do
expect(Hash.method_defined?(:flatten_nested!)).to be(true)
end
pending "More tests"
end
#
# Hash#expand_nested
#
describe Hash, "#expand_nested" do
it "should have the method defined" do
expect(Hash.method_defined?(:expand_nested)).to be(true)
end
pending "More tests"
end
#
# Hash#expand_nested!
#
describe Hash, "#expand_nested!" do
it "should have the method defined" do
expect(Hash.method_defined?(:expand_nested!)).to be(true)
end
pending "More tests"
end
| true
|
ca69ca4e50390b0941373275f6c59f81e00349d6
|
Ruby
|
Marcus893/W1D4-minesweeper
|
/tile.rb
|
UTF-8
| 372
| 3.5625
| 4
|
[] |
no_license
|
class Tile
attr_reader :val
def initialize(bomb = false)
@bomb = bomb
@revealed = false
@val = nil
end
def self.make_bomb
Tile.new(true)
end
def reveal
@revealed = true
end
def set_val(num)
@val = num
end
def revealed?
@revealed
end
def is_bomb?
@bomb
end
def to_s
revealed? ? val.to_s : " "
end
end
| true
|
0d1b7e4e9996da0b23a152212cdc09e48f8abb5a
|
Ruby
|
bytheway875/shakespeare_analyzer
|
/macbeth_analyzer.rb
|
UTF-8
| 1,185
| 3.5
| 4
|
[] |
no_license
|
#There are many speeches. Each speech has a speaker. Each speech has many lines.
class MacbethAnalyzer
require 'nokogiri'
require 'open-uri'
require 'active_support/inflector'
attr_accessor :macbeth
# Initializing a MacbethAnalyzer object will load the document
def initialize
@macbeth = Nokogiri::XML(open("http://www.ibiblio.org/xml/examples/shakespeare/macbeth.xml"))
end
# Friendlier name for running the analyzer
def analyze
format_results
end
# Find all speech nodes
def speeches
macbeth.xpath("//SPEECH")
end
# Loop through speech nodes to find the speakers and assign the corresponding lines within
# the speech node to that speaker.
def speakers_hash
speeches.inject(Hash.new(0)) do |speakers, speech|
speaker = speech.xpath("SPEAKER").text
speakers[speaker] += speech.xpath("LINE").count
speakers
end
end
# Format the results into a something more readable. Titleize the names to ensure they're
# all consistent
def format_results
speakers_hash.each_pair do |speaker, lines|
puts "#{speaker.titleize}: #{lines}"
end
end
end
analyzer = MacbethAnalyzer.new
analyzer.analyze
| true
|
eb45bfb70dcaf4162b50e0368b30bf83d4535ecf
|
Ruby
|
nzmoore/BillsRuby
|
/logic.rb
|
UTF-8
| 346
| 3.640625
| 4
|
[] |
no_license
|
number = rand(1..6)
puts "You rolled a #{number}"
puts "You are a winner rolling the highest number" if number == 6
puts "You are a loser rolling the lowest number" if number == 1
if (number != 1 and number != 6) then puts "You are not a winner but you did not roll the lowest number" end
if ( number < 5 ) then puts "You rolled less than 5" end
| true
|
41c6981d4354fca49fbe41e569d9101a92f85979
|
Ruby
|
dcastroeyss/wikirate
|
/mod/csv_import/lib/csv_row/normalizer.rb
|
UTF-8
| 250
| 2.53125
| 3
|
[] |
no_license
|
class CSVRow
# common methods to be used to normalize values
module Normalizer
def comma_list_to_pointer str
str.split(",").map(&:strip).to_pointer_content
end
def to_html value
value.gsub "\n", "<br\>"
end
end
end
| true
|
7cbb17cfbc540311558943a757598034387818df
|
Ruby
|
wordtreefoundation/bomdb
|
/lib/bomdb/import/verses.rb
|
UTF-8
| 1,459
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
require 'json'
require 'bomdb/models/verse'
module BomDB
module Import
class Verses < Import::Base
tables :books, :verses
# Expected data format is:
# [
# {
# "range_id": Int, # the mericope range ID
# "book": String, # the name of the book, e.g. 1 Nephi
# "chapter": Int, # the chapter number
# "verse": Int # the verse number
# },
# ...
# ]
def import_json(data, **args)
book, chapter = nil, nil
verse_model = Models::Verse.new(@db)
data.each do |r|
if r['chapter'] != chapter || r['book'] != book
# Create a heading per chapter
Models::Verse.new(@db).find_or_create(
chapter: r['chapter'],
verse: nil,
book_name: r['book'],
heading: true
)
chapter = r['chapter']
end
if r['book'] != book
puts "Importing chapters & verses for '#{r['book']}'"
book = r['book']
end
verse_model.find_or_create(
chapter: r['chapter'],
verse: r['verse'],
book_name: r['book'],
range_id: r['range_id']
)
end
Import::Result.new(success: true)
rescue Sequel::UniqueConstraintViolation => e
Import::Result.new(success: false, error: e)
end
end
end
end
| true
|
a5e5ee59402bbdc9e5faecc202a5e4225e184772
|
Ruby
|
himdel/warciv
|
/ruby/Unit.rb
|
UTF-8
| 3,886
| 2.96875
| 3
|
[] |
no_license
|
require './AttackMapItem.rb'
require './Map.rb'
require './Player.rb'
require './UI.rb'
require './buildings.rb'
require './enums.rb'
# not ruby yet!
class Unit < AttackMapItem
Unit(popis, p) : AttackMapItem(popis, p) {
self.stop()
end
bool move(x, y)
virtual bool gather(x, y)
virtual bool build(x, y, b)
void damage(hitpoints)
bool attack(x, y)
void stop()
void queueAction(ActionType at = at_None, int x = -1, int y = -1, BuildingType bt = bt_Any)
virtual const set<ActionType> availActions() = 0
virtual bool actionPending()
virtual bool performAction()
virtual string getPopis()
virtual string getDetail()
end
def move(x, y)
if (x == @x && y == @y)
return true
auto f = [x, y] (mi, px, py) { return (x == px) && (y == py); }
list< pair<int, int> > path = @map.closest(f, @x, @y)
if (path.empty()) {
UI::logAction(self, "move", "target not found", make_pair(x, y))
return false
end
int px = path.front().first
int py = path.front().second
if (@map.get(px, py)) {
UI::logAction(self, "move", "position occupied", make_pair(px, py), @map.get(px, py))
return false
end
self.remove()
self.place(px, py)
bool was_pending = false
if (px == @pending_x && py == @pending_y && @pending == at_Move) {
@pending = at_None
was_pending = true
end
UI::logAction(self, "move", was_pending ? "OK, unqueued" : "OK", make_pair(px, py))
return true
end
def gather(x, y)
UI::logAction(self, "gather", "not supported", make_pair(x, y))
return false; # done, overidden in Peon
end
def build(x, y, b)
UI::logAction(self, "gather", "not supported", make_pair(x, y))
return false; # done, overidden in Peon
end
# do not use self afterwards
def damage(hitpoints)
AttackMapItem::damage(hitpoints)
if (@hitpoints == 0) {
UI::logAction(self, "damage", "unit dead")
@owner.delUnit(self)
} else {
os << "lost " << hitpoints << " hp, remaining " << @hitpoints
UI::logAction(self, "damage", os.str())
end
end
def attack(x, y)
# if not in range, attack anything or move
if (self.distance(x, y) > @attack_range) {
if (@AttackMapItem::attack()) {
UI::logAction(self, "attack", "enemy around", make_pair(@x, @y))
return true
end
return self.move(x, y)
end
UI::logAction(self, "attack", "enemy at position", make_pair(x, y), @map.get(x, y))
bool r = AttackMapItem::attack(x, y)
if (x == @pending_x && y == @pending_y && r == false && @pending == at_Attack)
@pending = at_None
return r
end
def stop()
self.queueAction()
end
def queueAction(at, x, y, bt)
@pending = at
@pending_build = bt
@pending_x = x
@pending_y = y
end
def actionPending()
return @pending != at_None
end
# nevolat pokud byl tah udelan rucne
def performAction()
if (!self.actionPending())
return false
if (@pending == at_Move)
return self.move(@pending_x, @pending_y)
if (@pending == at_Attack)
return self.attack(@pending_x, @pending_y)
if (@pending == at_Gather)
return self.gather(@pending_x, @pending_y)
if (@pending == at_Build)
return self.build(@pending_x, @pending_y, @pending_build)
return false
end
def getPopis()
out << "_" << @owner.getName()[0] << @owner.getName()[1] << "_" << @popis << " (" << @hitpoints << ")"
return out.str()
end
def getDetail()
out << @popis << " (hp: " << @hitpoints
switch (@pending) {
case at_Move:
out << ", action: " << "move(" << @pending_x << ", " << @pending_y << ")"
break
case at_Attack:
out << ", action: " << "attack(" << @pending_x << ", " << @pending_y << ")"
break
case at_Gather:
out << ", action: " << "gather(" << @pending_x << ", " << @pending_y << ")"
break
case at_Build:
out << ", action: " << "build(" << @pending_x << ", " << @pending_y << ", " << buildings[@pending_build - 1].name << ")"
break
case at_None:
out << ", no action"
end
out << ", @[ " << @x << " " << @y << " ]"
out << ")"
return out.str()
end
| true
|
0af0865bbabd36cd0f9d2895fd74314352a773c1
|
Ruby
|
WeWantEdTR/MineField
|
/lib/mine_field/score.rb
|
UTF-8
| 169
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
module MineField
class Score
attr_reader :total
def initialize
@total = 0
end
def increment(score = 1)
@total += score
end
end
end
| true
|
22846862b94fb980e5e8d98be2afba3173a577ec
|
Ruby
|
Adrian5918/weather.rb
|
/weather.rb
|
UTF-8
| 276
| 2.828125
| 3
|
[] |
no_license
|
require 'http'
response = HTTP.get("http://api.openweathermap.org/data/2.5/weather?q=chicago&appid=#{ENV['OPEN_WEATHER_API_KEY']}&units=imperial")
data = response.parse(:json)
p data
city_name = data['name']
p city_name
temperature = data['main']['temp']
p temperature
| true
|
8174aeb5cff68d8dc4728da9fc4c9cd88878527b
|
Ruby
|
gion-1192/ftp_time
|
/lib/ftp_time/timer.rb
|
UTF-8
| 427
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
module FtpTime
class Timer
attr_accessor :exe_time
def start
raise "undefined exe_time" if @exe_time.nil?
differ = min_conversion(@exe_time - time_now)
sleep differ unless differ <= 0
if block_given?
yield
else
"execute method #{differ} ago"
end
end
private
def min_conversion(time)
(time * 24 * 60 * 60).to_i
end
def time_now
@time_now ||= DateTime.now
end
end
end
| true
|
eb29fefae33d272271b06f9aa608504462296497
|
Ruby
|
SaturdayAM/mass-assignment-dc-web-031218
|
/lib/person.rb
|
UTF-8
| 311
| 2.84375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Person
#your code here
attr_accessor :name, :birthday, :eye_color, :height, :weight,
:handed, :complexion, :t_shirt_size,
:wrist_size, :glove_size, :pant_length,
:pant_width, :hair_color
def initialize(attr_hash)
attr_hash.each{|key, val| self.send(("#{key}="), val)}
end
end
| true
|
52fee0c840e49dc73b98bda0fe8b7dbba05bc2b5
|
Ruby
|
anthonygiuliano/launch-school
|
/120-object-oriented-programming/oo-book/classes-and-objects-2/ex3.rb
|
UTF-8
| 252
| 3.1875
| 3
|
[] |
no_license
|
class Person
attr_accessor :name
def initialize(name)
@name = name
end
end
bob = Person.new("Steve")
bob.name = "Bob" # => undefined method `name='
#error occurs because there's no setter method
# change attr_reader to attr_accessor to fix
| true
|
a447735eb09df10c46e48183d0e97470e1c79886
|
Ruby
|
androidgrl/exercism
|
/ruby/hamming/hamming.rb
|
UTF-8
| 138
| 3.3125
| 3
|
[] |
no_license
|
class Hamming
def self.compute(strand1, strand2)
pairs = strand1.chars.zip(strand2.chars)
pairs.count { |x,y| x!=y }
end
end
| true
|
c95cbce13ec76b6f61a47abd074203d0815bc04c
|
Ruby
|
rkpop/upcoming-releases-widget
|
/database.rb
|
UTF-8
| 737
| 3.03125
| 3
|
[
"Unlicense"
] |
permissive
|
# frozen_string_literal: true
require 'sqlite3'
# Database class
# Entry checking, and inserting is done in this class
class Database
def initialize(database_name)
@instance = SQLite3::Database.new database_name
end
def check_entry(artist_name, release_time)
result = nil
@instance.execute('select * from entries where artist = ? AND release_time = ? LIMIT 1',
artist_name, release_time) do |row|
result = row[0] unless row.nil?
end
result
end
def add_entry(entry)
@instance.execute('insert into entries (cal_id, artist, release_time) VALUES (?, ?, ?)',
[entry[:cal_id], entry[:artist], entry[:mon_y]])
end
end
| true
|
c69aefe054145bbcb4acdc06b8461790d85b3171
|
Ruby
|
prasann/twza-training
|
/Steven/romanKata/roman.rb
|
UTF-8
| 252
| 4.03125
| 4
|
[] |
no_license
|
class Roman
def convert number
#return "I" #Testing for 1
#number == 2? "II" : "I" #Testing for both 1 and 2
#Used to test 1,2 and 3
array = ""
count = number
while count > 0
array = array + "I"
count -= 1
end
array
end
end
| true
|
a15a755a7b57fbb8409cdf30f0acf8d650e44e54
|
Ruby
|
Kimrowoon/coderbyte
|
/ArrayAdditionI.rb
|
UTF-8
| 265
| 3.171875
| 3
|
[] |
no_license
|
def ArrayAdditionI(arr)
a=arr.max
sum = arr.reduce (:+)
if a=sum
return "true"
else
return "false"
end
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
ArrayAdditionI(STDIN.gets)
| true
|
0402d7a46f0a0880132b0077848e0e1c4f1f31d0
|
Ruby
|
TravisGriffiths/ITR-BOS-01
|
/mhondoart/HW1.rb
|
UTF-8
| 1,915
| 4.1875
| 4
|
[] |
no_license
|
# HW 01
#
# Purpose:
#
# Read the taks below and complete the exercises in this file. We will start
# to write the beginnings of our "Secret Number Game" using what we've
# learned in Ruby Lesson 01.
#
###############################################################################
#
# 1. Read an Interview with the Creator of Ruby
# http://linuxdevcenter.com/pub/a/linux/2001/11/29/ruby.html
#
# 2. Read this Introduction to Programming
# http://en.wikiversity.org/wiki/Introduction_to_Programming/About_Programming
#
# 3. In this file under "Student Solution," print the welcome text of your Secret
# Number Game
#
# (i.e.) "Welcome to the Secret Number Game!"
#
# 4. Above your welcome message, write a comment to other coders introducing yourself.
# .
#
#
# 5. Create two new variables, one for your last name, one for your first name
# and enter your first and last name as strings.
#
# first_name = ""
# last_name = ""
#
# 6. Print to the screen that your game was created by you by concating the
# first and last name variables.
#
# (i.e.) "Created by " + first_name + " " + last_name
#
# 7. Feel free to add more lines of text or add comments to remind you of what
# you've learned.
#
###############################################################################
#
# Student Solution
#
###############################################################################
# this is the first assignment in Ruby on Rails class
puts "Hello and Welcome to the Secret Number Game!"
first_name = ""
last_name = "Hondo"
puts "this game was created by" + first_name + " " + last_name + " "
print "to play the game, pick a number between 1 & 20 and hit enter "
#this is where we get the number
iguess = gets.to_i
rnum = [1...20]
newrandom = rand (20)
#this is where we compare the two
if ( rnum[newrandom] != iguess)
puts "wrong number try again!"
else
puts "you got it!"
end
puts "the end"
| true
|
656111460df33defdac4e45dc8c0759a0ac77449
|
Ruby
|
oourfali/pre-ruby-course
|
/string_ext.rb
|
UTF-8
| 183
| 3.296875
| 3
|
[] |
no_license
|
class StringExt
def initialize (left, right)
@left = left
@right = right
end
def concat
@left + @right
end
def substract
@left.gsub(@right, '')
end
end
| true
|
49d322f4e303e42972bc1a0cff9ba70994a4ade4
|
Ruby
|
patrykwozinski/deployer
|
/deployer.rb
|
UTF-8
| 549
| 2.78125
| 3
|
[] |
no_license
|
class Deployer
attr_accessor :service, :env, :branch
def initialize(service, env, branch)
@service = service
@env = env
@branch = branch
end
def start
if service_exists?
Object.const_get(@service).new(env, branch).deploy
else
{ message: 'Wrong service name.', status_code: 404 }
end
rescue ArgumentError => error
return { message: error.message, status_code: 404 }
end
def service_exists?
return Module.const_get(@service.to_s).is_a?(Class)
rescue NameError
return false
end
end
| true
|
7fe50743a141ba35112d4e705d86196fa189d8ab
|
Ruby
|
gatgui/fbpg
|
/tests/ruby/flow.rb
|
UTF-8
| 237
| 3.671875
| 4
|
[] |
no_license
|
i = 0
while i < 20 do
puts i
i = i + 1
if i >= 10 then
puts "early exit"
break
end
end
x = 4
y = 4
if x == y then
puts "x equals y"
else
puts "x does not equal y"
end
y = 5
if x != y then
puts "As expected"
end
| true
|
8f9781efc5a770e0c38f84cc65d0ebd74187f901
|
Ruby
|
rmagick/rmagick
|
/spec/rmagick/draw/annotate_spec.rb
|
UTF-8
| 1,650
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
RSpec.describe Magick::Draw, '#annotate' do
it 'works' do
draw = described_class.new
image = Magick::Image.new(10, 10)
draw.annotate(image, 0, 0, 0, 20, 'Hello world')
yield_obj = nil
draw.annotate(image, 100, 100, 20, 20, 'Hello world 2') do |draw2|
yield_obj = draw2
end
expect(yield_obj).to be_instance_of(described_class)
expect do
image = Magick::Image.new(10, 10)
draw.annotate(image, 0, 0, 0, 20, nil)
end.to raise_error(TypeError)
expect { draw.annotate('x', 0, 0, 0, 20, 'Hello world') }.to raise_error(NoMethodError)
end
it 'works with string started with @ (issue 38)', unsupported_before('6.9.0') do
draw = described_class.new
image = Magick::Image.new(10, 10)
expect { draw.annotate(image, 0, 0, 0, 20, '@Hello world') }.not_to raise_error
yield_obj = nil
draw.annotate(image, 100, 100, 20, 20, '@Hello world 2') do |draw2|
yield_obj = draw2
end
expect(yield_obj).to be_instance_of(described_class)
end
it 'accepts an ImageList argument' do
draw = described_class.new
image_list = Magick::ImageList.new
image_list.new_image(10, 10)
expect { draw.annotate(image_list, 0, 0, 0, 20, 'Hello world') }.not_to raise_error
end
it 'does not trigger a buffer overflow' do
draw = described_class.new
expect do
if 1.size == 8
# 64-bit environment can use larger value for Integer and it can cause
# a stack buffer overflow.
image = Magick::Image.new(10, 10)
draw.annotate(image, 2**63, 2**63, 2**62, 2**62, 'Hello world')
end
end.not_to raise_error
end
end
| true
|
aa047917bd3c65519e1054ac2daef72503b5a795
|
Ruby
|
meganft/event-reporter
|
/test/container_test.rb
|
UTF-8
| 3,488
| 2.875
| 3
|
[] |
no_license
|
require_relative 'test_helper'
require './lib/container'
class ContainerTest < Minitest::Test
def test_it_returns_queue_in_an_array
q = Container.new
assert_instance_of Array, q.queue
end
def test_count_returns_number_of_members_in_queue
q = Container.new
expected = {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
assert_equal 0, q.count
q.insert(expected)
assert_equal 1, q.count
end
def test_queue_will_print
q = Container.new
expected = {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
assert_equal 0, q.count
q.insert(expected)
assert_equal [{"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}], q.queue_print
end
def test_it_will_print_by_certain_attribute
q = Container.new
expected = {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000", "street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
expected2 = {"first_name"=>"Sarah", "last_name"=>"Bankins", "email_address"=>"pinalevitsky@jumpstartlab.com", "homephone"=>"4145205000","street"=>"2022 15th Street NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20090"}
q.insert(expected)
q.insert(expected2)
assert_equal [{"first_name"=>"Sarah", "last_name"=>"Bankins", "email_address"=>"pinalevitsky@jumpstartlab.com", "homephone"=>"4145205000", "street"=>"2022 15th Street NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20090"}, {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000", "street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}], q.print_by("last_name")
end
def test_it_will_populate_district_number_by_zipcode
q = Container.new
assert_equal 1, q.district_info("80210")
end
def test_queue_district_will_add_district_info_to_attendee
q = Container.new
expected = {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
q.insert(expected)
assert_equal [{"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010", "district" =>0}], q.queue_district
end
def test_it_will_save_to_csv
q = Container.new
expected = {"first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
assert_equal 0, q.count
q.insert(expected)
assert "event_attendees.csv"
end
def test_it_will_export_to_html
q = Container.new
expected = { "first_name"=>"Allison", "last_name"=>"Nguyen", "email_address"=>"arannon@jumpstartlab.com", "homephone"=>"6154385000","street"=>"3155 19th St NW", "city"=>"Washington", "state"=>"DC", "zipcode"=>"20010"}
assert_equal 0, q.count
q.insert(expected)
assert "output_table4.html"
end
end
| true
|
87101a4774a379440cc3e7d42b6f30ea95c2a312
|
Ruby
|
pootsbook/elm-log
|
/app/services/url_cleaner.rb
|
UTF-8
| 625
| 2.859375
| 3
|
[] |
no_license
|
class UrlCleaner
BLACKLIST = %w(
utm_
)
attr_reader :uri
class << self
def clean(url)
self.new(url).clean
end
end
def initialize(url)
@uri = URI(url)
end
def clean
uri.query = clean_encoded_query_params.presence if uri.query
uri.to_s
end
private
def decoded_query_params
URI.decode_www_form(uri.query)
end
def clean_encoded_query_params
URI.encode_www_form(clean_query_params)
end
def clean_query_params
decoded_query_params.reject do |key, value|
BLACKLIST.each do |prefix|
key.start_with?(prefix)
end.any?
end
end
end
| true
|
d251050032470a21a9d69b43abfab11bbb080189
|
Ruby
|
mihotakeyama/ruby_game
|
/brave.rb
|
UTF-8
| 324
| 3.359375
| 3
|
[] |
no_license
|
require './character'
class Brave < Character
def attack(monster)
puts "勇者が攻撃をした!"
damage = @offense - monster.defense
monster.hp -= damage
puts "モンスターに#{damage}のダメージを与えた!"
puts "モンスターの残りのHPは#{monster.hp}になった!"
end
end
| true
|
51b2e4b27f8f96ff8ccee49a82fe6f533151da21
|
Ruby
|
jcwimer/wrestlingApp
|
/app/services/tournament_services/double_elimination_match_generation.rb
|
UTF-8
| 500
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
class DoubleEliminationMatchGeneration
def initialize( tournament )
@tournament = tournament
end
def generate_matches
@tournament.weights.each do |weight|
SixteenManDoubleEliminationMatchGeneration.new(weight).generate_matches_for_weight if weight.wrestlers.size >= 9 and weight.wrestlers.size <= 16
EightManDoubleEliminationMatchGeneration.new(weight).generate_matches_for_weight if weight.wrestlers.size >= 4 and weight.wrestlers.size <= 8
end
end
end
| true
|
c79e6f465d60fd6e54847d3f5ef52a312d49cd02
|
Ruby
|
Vladiid/ruby_on_rails
|
/Projects/MyApp/test.rb
|
UTF-8
| 966
| 3.9375
| 4
|
[] |
no_license
|
print "(R)rock, (S)scissors, (P)paper? "
s = gets.strip.capitalize
if s == "R"
user_choice = :rock
elsif s == "S"
user_choice = :scissors
elsif s == "P"
user_choice = :paper
else
puts "Can't understand what you want? Sorry."
exit
end
arr = [:rock, :scissors, :paper]
computer_choice = arr[rand(0..2)]
puts "User Choice #{user_choice}."
puts "Computer Choice #{computer_choice}."
matrix = [
[:rock, :rock, :draw],
[:scissors, :scissors, :draw],
[:paper, :paper, :draw],
[:rock, :scissors, :first_win],
[:rock, :paper, :second_win],
[:scissors, :rock, :second_win],
[:scissors, :paper, :first_win],
[:paper, :rock, :first_win],
[:paper, :scissors, :second_win]
]
matrix.each do |item|
if item [0] == user_choice && item[1] == computer_choice
if item [2] == :first_win
puts "User Wins"
elsif item [2] == :second_win
puts "Computer Wins"
else
puts "Draw!"
end
exit
end
end
| true
|
53f54e6fa69b44529af8d990f7f51041628a2bb6
|
Ruby
|
TIMBERings/easy_bowling_brackets
|
/server/app/models/event.rb
|
UTF-8
| 951
| 2.625
| 3
|
[] |
no_license
|
class Event < ApplicationRecord
belongs_to :user
has_many :bracket_groups
validates :name, presence: true
validates :event_date, presence: true
validates :user, presence: true
validates :winner_cut, presence: true, numericality: true
validates :runner_up_cut, presence: true, numericality: true
validates :organizer_cut, presence: true, numericality: true
validates :entry_cost, presence: true, numericality: true
before_validation :ensure_date_format
private
def ensure_date_format
return if event_date.is_a? Date
raise StandardError unless event_date.is_a?(String) || event_date.is_a?(DateTime)
self.event_date = Date.parse(event_date) if event_date.is_a? String
self.event_date = event_date.to_date if event_date.is_a? DateTime
rescue StandardError => ex
raise StandardError, "#{event_date} could not be coerced into a date." unless event_date.is_a?(String) || event_date.is_a?(DateTime)
end
end
| true
|
739fe70edae16c2e31a6acec5ce419597b9ad40a
|
Ruby
|
Gudarien/WIP-Gudarien
|
/day5_1.rb
|
UTF-8
| 378
| 4.28125
| 4
|
[] |
no_license
|
x = 3 # 1
y = "hello" # 2
if x > 10 # 3
x = x + 1
y = y - x
else # 4
x = x - 1 # 5
y = y * x # 6
end # 7
p x # 8
p y # 9
# 1: x is 3
# 2: x is 3, y is "hello"
# 3: Condition not met
# 4: condition is met
# 5: x is 2
# 6: x is 2, y "hellohello"
# 7: condition ends
# 8: displays 2
# 9: displays "hellohello"
| true
|
c6213cdb940e42761298a04b3b327093f4b2eea1
|
Ruby
|
davepodgorski/Monday-19th
|
/shopping cart.rb
|
UTF-8
| 540
| 3.265625
| 3
|
[] |
no_license
|
require '.product.rb'
class ShoppingCart
@@shoppingcart = []
def add_to_cart(product)
@@shoppingcart << product
return @@shoppingcart
end
def remove_from_cart(product)
@@shopping_cart.delete(product)
return @@shoppingcart
end
def add_total
counter = 0
@@shoppingcart.each do |product|
counter += product.price
end
return counter
end
def add_with_tax
counter = 0
@@shoppingcart.each do |product|
counter += product.total_price
end
return counter
end
end
| true
|
59121d089936144ec4b7bb1589ae2cf47df5ccc9
|
Ruby
|
ktlacaelel/ix
|
/bin/ix-json-append
|
UTF-8
| 204
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'json'
key = ARGV[0]
value = ARGV[1]
STDIN.each_line do |line|
begin
hash = JSON.parse(line)
hash[key] = value
puts hash.to_json
rescue => error
end
end
| true
|
7ecee98cb0896c00cb264a70417236cb33f3f413
|
Ruby
|
jeffwilliams/Torrentflow
|
/daemon/config.rb
|
UTF-8
| 11,063
| 2.703125
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
require 'yaml'
require 'logging'
class BaseConfig
# This function searches the RUBY loadpath to try and find the standard config file.
# If it's not found in the load path, the current directory, ../etc, etc/, and /etc/ are searched.
# If found it returns the full path, if not it returns nil.
def self.findConfigFile
$:.reverse.each{ |e|
path = "#{e}/#{configFileName}"
return path if File.exists? path
}
if File.exists?(configFileName)
return configFileName
elsif File.exists?("../etc/#{configFileName}")
return Dir.pwd + "/../etc/#{configFileName}"
elsif File.exists?("etc/#{configFileName}")
return Dir.pwd + "/etc/#{configFileName}"
elsif File.exists?("/etc/#{configFileName}")
return "/etc/#{configFileName}"
end
nil
end
# If dontValidateDirs is set, then the directories are not checked to
# see if they exist, etc. This should be set to true by non-daemon code that
# is reading the config file.
def load(filename, dontValidateDirs = false)
rc = true
if File.exists?(filename)
File.open(filename){ |fh|
yaml = YAML::load(fh)
return handleYaml(yaml, dontValidateDirs)
}
else
$logger.info "Loading config file failed: file '#{filename}' doesn't exist."
end
rc
end
protected
# Subclasses must override
def self.configFileName
"config.conf"
end
def handleYaml(yaml, dontValidateDirs)
true
end
def validateDir(dir, settingName)
dir.untaint
if ! dir
$logger.error "The directory '#{dir}' specified by the #{settingName} configuration file setting is blank."
return false;
elsif ! File.exists?(dir)
$logger.error "The directory '#{dir}' specified by the #{settingName} configuration file setting does not exist."
return false;
elsif ! File.directory?(dir)
$logger.error "The directory '#{dir}' specified by the #{settingName} configuration file setting is not a directory."
return false;
elsif ! File.writable?(dir)
$logger.error "The directory '#{dir}' specified by the #{settingName} configuration file setting is not writable by #{ENV['USER']}."
return false;
elsif ! File.readable?(dir)
$logger.error "The directory '#{dir}' specified by the #{settingName} configuration file setting is not readable by #{ENV['USER']}."
return false;
end
true
end
def validateAndConvertEncPolicy(policy)
if policy == 'forced'
return :forced
elsif policy == 'enabled'
return :enabled
elsif policy == 'disabled'
return :disabled
else
return nil
end
end
def validateAndConvertEncLevel(level)
if level == 'plaintext'
return :plaintext
elsif level == 'rc4'
return :rc4
elsif level == 'both'
return :both
else
return nil
end
end
def validateInteger(s, settingName)
if s.is_a?(Integer)
true
else
$logger.error "#{settingName} must be an integer but is '#{s}'"
false
end
end
def validateBoolean(s, settingName)
if s.is_a?(TrueClass) || s.is_a?(FalseClass)
true
else
$logger.error "#{settingName} must be a boolean value (true/false) but is '#{s}'"
false
end
end
def validateAndConvertLogType(type, settingName)
if type == 'file'
return :file
elsif type == 'syslog'
return :syslog
else
$logger.error "#{settingName} must be 'file' or 'syslog'"
return nil
end
end
def validateAndConvertLogLevel(level, settingName)
if level == "debug"
Logger::DEBUG
elsif level == "info"
Logger::INFO
elsif level == "warn"
Logger::WARN
elsif level == "error"
Logger::ERROR
elsif level == "fatal"
Logger::FATAL
else
$logger.error "#{settingName} must be debug, info, warn, error, or fatal"
nil
end
end
end
class TorrentflowConfig < BaseConfig
TorrentConfigFilename = "torrentflowdaemon.conf"
def initialize
@listenPort = 3000
@seedingTime = 3600
end
def self.configFileName
TorrentConfigFilename
end
# Port to listen on
attr_accessor :listenPort
# Directory in which to store .torrent files
attr_accessor :torrentFileDir
# Directory in which to store torrent content
attr_accessor :dataDir
# Password file path
attr_accessor :passwordFile
# Port range to listen for torrent connections on
attr_accessor :torrentPortLow
attr_accessor :torrentPortHigh
# Encryption settings
attr_accessor :outEncPolicy
attr_accessor :inEncPolicy
attr_accessor :allowedEncLevel
# Upload ratio
attr_accessor :ratio
attr_accessor :seedingTime
attr_accessor :maxConnectionsPerTorrent
attr_accessor :maxUploadsPerTorrent
attr_accessor :downloadRateLimitPerTorrent
attr_accessor :uploadRateLimitPerTorrent
# Whether or not to enable the TV show summary in the UI
attr_accessor :displayTvShowSummary
# Usage tracking parameters
attr_accessor :usageMonthlyResetDay
attr_accessor :enableUsageTracking
attr_accessor :dailyLimit
attr_accessor :monthlyLimit
# Mongo connection information
attr_accessor :mongoDb
attr_accessor :mongoUser
attr_accessor :mongoPass
attr_accessor :mongoHost
attr_accessor :mongoPort
# Logging
attr_accessor :logType
attr_accessor :logLevel
attr_accessor :logFile
attr_accessor :logLevel
attr_accessor :logSize
attr_accessor :logCount
attr_accessor :logFacility
protected
def handleYaml(yaml, dontValidateDirs = false)
@listenPort = yaml['port'].to_i
@torrentFileDir = yaml['torrent_file_dir']
return false if ! dontValidateDirs && ! validateDir(@torrentFileDir, 'torrent_file_dir')
@dataDir = yaml['data_dir']
return false if ! dontValidateDirs && ! validateDir(@dataDir, 'data_dir')
@passwordFile = yaml['password_file']
if ! @passwordFile
$logger.error "The configuration file had no 'password_file' setting."
return false
end
@torrentPortLow = yaml['torrent_port_low'].to_i
@torrentPortHigh = yaml['torrent_port_high'].to_i
if ! @torrentPortLow || ! @torrentPortHigh
$logger.error "The configuration file torrent_port_low and/or torrent_port_high settings are missing."
return false
end
if @torrentPortLow > @torrentPortHigh
$logger.error "The configuration file torrent_port_low is > torrent_port_high."
return false
end
if @torrentPortLow == 0 || @torrentPortHigh == 0
$logger.error "The configuration file torrent_port_low and/or torrent_port_high settings are invalid."
return false
end
@outEncPolicy = yaml['out_enc_policy']
@inEncPolicy = yaml['in_enc_policy']
@allowedEncLevel = yaml['allowed_enc_level']
@outEncPolicy = validateAndConvertEncPolicy(@outEncPolicy)
if ! @outEncPolicy
$logger.error "The configuration file out_enc_policy setting is invalid"
return false
end
@inEncPolicy = validateAndConvertEncPolicy(@inEncPolicy)
if ! @inEncPolicy
$logger.error "The configuration file in_enc_policy setting is invalid"
return false
end
@allowedEncLevel = validateAndConvertEncLevel(@allowedEncLevel)
if ! @allowedEncLevel
$logger.error "The configuration file allowed_enc_level setting is invalid"
return false
end
@ratio = yaml['ratio']
if @ratio
f = @ratio.to_f
if f != 0.0 && f < 1.0
$logger.error "The configuration file ratio setting is invalid. Ratio must be 0, or a number >= 1.0"
return false
end
else
@ratio = 0
end
@seedingTime = yaml['seedingtime']
if ! @seedingTime.is_a?(Integer)
$logger.error "The configuration file seedingtime setting is invalid. It must be an integer"
return false
end
@maxConnectionsPerTorrent = yaml['max_connections_per_torrent']
if @maxConnectionsPerTorrent
return false if ! validateInteger(@maxConnectionsPerTorrent, 'max_connections_per_torrent')
end
@maxUploadsPerTorrent = yaml['max_uploads_per_torrent']
if @maxUploadsPerTorrent
return false if ! validateInteger(@maxUploadsPerTorrent, 'max_uploads_per_torrent')
end
@downloadRateLimitPerTorrent = yaml['download_rate_limit_per_torrent']
if @downloadRateLimitPerTorrent
return false if ! validateInteger(@downloadRateLimitPerTorrent, 'download_rate_limit_per_torrent')
end
@uploadRateLimitPerTorrent = yaml['upload_rate_limit_per_torrent']
if @uploadRateLimitPerTorrent
return false if ! validateInteger(@uploadRateLimitPerTorrent, 'upload_rate_limit_per_torrent')
end
@displayTvShowSummary = yaml['display_tv_show_summary']
if @displayTvShowSummary
return false if ! validateBoolean(@displayTvShowSummary, 'display_tv_show_summary')
end
@enableUsageTracking = yaml['enable_usage_tracking']
if @enableUsageTracking
return false if ! validateBoolean(@enableUsageTracking, 'enable_usage_tracking')
end
@usageMonthlyResetDay = yaml['usage_monthly_reset_day']
if @usageMonthlyResetDay
return false if ! validateInteger(@usageMonthlyResetDay, 'usage_monthly_reset_day')
end
@dailyLimit = yaml['daily_limit']
if @dailyLimit
return false if ! validateInteger(@dailyLimit, 'daily_limit')
end
@monthlyLimit = yaml['monthly_limit']
if @monthlyLimit
return false if ! validateInteger(@monthlyLimit, 'monthly_limit')
end
@mongoDb = yaml['mongo_db']
@mongoUser = yaml['mongo_user']
@mongoPass = yaml['mongo_pass']
@mongoHost = yaml['mongo_host']
@mongoPort = yaml['mongo_port']
if @mongoPort
return false if ! validateInteger(@mongoPort, 'monthly_port')
end
@logType = validateAndConvertLogType(yaml['log_type'], 'log_type')
return false if ! @logType
if @logType == :file
@logFile = yaml['log_file']
if ! @logFile
$logger.error "The configuration file log_file setting is missing"
return false
end
@logLevel = validateAndConvertLogLevel(yaml['log_level'], 'log_level')
return false if ! @logLevel
@logSize = yaml['log_size']
if @logSize
return false if ! validateInteger(@logSize, 'log_size')
else
$logger.error "The configuration file log_size setting is missing"
return false
end
@logCount = yaml['log_size']
if @logCount
return false if ! validateInteger(@logCount, 'log_size')
else
$logger.error "The configuration file log_size setting is missing"
return false
end
elsif @logType == :syslog
@logFacility = SyslogWrapper.facilityNameToConst(yaml['log_facility'])
if ! @logFacility
$logger.error "The configuration file log_facility setting is set to an invalid value: #{yaml['log_facility']} "
end
else
$logger.error "Unknown log type #{yaml['log_type']}"
return false
end
true
end
end
| true
|
4e1e93cd9e79526c887f906ff7bc48b26a39f439
|
Ruby
|
megamsys/nilavu
|
/lib/email.rb
|
UTF-8
| 638
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
require 'mail'
module Email
def self.is_valid?(email)
return false unless String === email
parsed = Mail::Address.new(email)
# Don't allow for a TLD by itself list (sam@localhost)
# The Grammar is: (local_part "@" domain) / local_part ... need to discard latter
parsed.address == email && parsed.local != parsed.address && parsed.domain && parsed.domain.split(".").length > 1
rescue Mail::Field::ParseError
false
end
def self.downcase(email)
return email unless Email.is_valid?(email)
email.downcase
end
def self.cleanup_alias(name)
name ? name.gsub(/[:<>,]/, '') : name
end
end
| true
|
ae8ae190777574dc3c8283296b0c8496cf72db5e
|
Ruby
|
railsninja/Smartthumbs
|
/lib/smartthumbs/thumbable.rb
|
UTF-8
| 5,220
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
module Smartthumbs
module Thumbable
require 'RMagick'
include Magick
# return the rmagick instance
def rmagick_img
return @rmagick_img unless @rmagick_img.blank?
if self.class.st_config[:blob].present?
@rmagick_img ||= Magick::ImageList.new.from_blob(
self.send(self.class.st_config[:blob])
).first
elsif self.class.st_config[:file].present?
@rmagick_img ||= Magick::ImageList.new.from_blob(
File.read(self.send(self.class.st_config[:file]))
).first
else
raise "No thumb source defined. You have to define neither :blob or :file"
end
if self.class.st_config[:before_resize].present? && self.respond_to?(self.class.st_config[:before_resize].to_sym)
self.send(self.class.st_config[:before_resize].to_sym)
end
@rmagick_img
end
# returns the specific format-array for the key f
# e.g. ["100x200", :cut]
# The config value for formats can be a hash or sth that responds to +call+
# e.g. a lambda.
def st_format(f)
if self.class.st_config[:formats].respond_to?(:call)
self.class.st_config[:formats].call(f.to_sym)
else
if self.class.st_config[:formats][f].is_a?(Symbol)
self.send(self.class.st_config[:formats][f])
else
self.class.st_config[:formats][f]
end
end
end
# returns the file extension for the current image
def st_extension
return "jpg" unless self.class.st_config[:extension].present?
if self.class.st_config[:extension].is_a?(String)
self.class.st_config[:extension]
else
self.send(self.class.st_config[:extension])
end
end
# creates the directory for a certain @format if it doesn't exist
def create_directory
dest = File.dirname(thumb_path_for(@format))
FileUtils.mkdir_p(dest) unless File.exists?(dest)
end
# Creates the thumb for a certain @format
def create_thumb_for(format)
@format = format
return if st_format(@format).blank?
create_directory
method = st_format(@format)[1] || :cut
@x, @y = st_format(@format).first.split("x").map(&:to_i)
if self.respond_to?(method)
self.send(method)
end
rounding_error
quality = self.class.st_config[:quality]
quality ||= 80
rmagick_img.write(thumb_path_for(@format)) { self.quality = quality }
if self.class.st_config[:after_resize].present? && self.respond_to?(self.class.st_config[:after_resize].to_sym)
self.send(self.class.st_config[:after_resize].to_sym, thumb_path_for(@format))
end
nil
end
# returns the gravity for the current resizing process and
# provides some shrotcuts
def gravity
@gravity ||= {
:new => Magick::NorthWestGravity,
:n => Magick::NorthGravity,
:ne => Magick::NorthEastGravity,
:w => Magick::WestGravity,
:c => Magick::CenterGravity,
:e => Magick::EastGravity,
:sw => Magick::SouthWestGravity,
:s => Magick::SouthGravity,
:se => Magick::SouthEastGravity
}[st_format(@format).last]
@gravity ||= Magick::CenterGravity
end
# Does a thumb already exist?
def thumb_exists_for?(format)
File.exists?(self.thumb_path_for(format))
end
# returns the cache-path for a certain image
def thumb_path_for(format)
"#{Rails.root}/public#{thumb_url_for(format)}"
end
# return the http url to the resized image
# this one has to be route from which the image is
# availabe - otherwise the caching benefit is gone
def thumb_url_for(format)
if Smartthumbs::Config.get_option(:assume_klass).to_s == self.class.to_s
"/th/#{format.to_s}/#{self.id}.#{st_extension}"
else
"/th/#{self.class.to_s.underscore.parameterize}/#{format.to_s}/#{self.id}.#{st_extension}"
end
end
# resizes the image in a manner that both edges fit the needs.
# usually one of the edges is smaller than the needs afterwards
def fit
if self.needs_to_be_resized?
rmagick_img.resize_to_fit!(@x, @y)
else
rmagick_img.resize_to_fit(@x, @y)
end
end
# the same as +fit+, except the fact that the image
# get's filled up with a border
def fill
fit
rounding_error
border_x = (@x - rmagick_img.columns)/2
border_y = (@y - rmagick_img.rows)/2
rmagick_img.border!(border_x,border_y,"white")
end
# resizes and cuts the image, so it that it fits exactly
def cut
rmagick_img.crop_resized!(@x, @y, gravity)
end
# if there's just a small difference between the needs and the result,
# we'll make it fit exaclty
def rounding_error
dif = (@y-rmagick_img.rows) + (@x-rmagick_img.columns)
if dif > 0 && dif < 10 then
rmagick_img.resize!(@x, @y)
end
end
# checks whether the image needs to be resized to fit the current @format or not
def needs_to_be_resized?
rmagick_img.rows > @y || rmagick_img.columns > @x
end
end
end
| true
|
0b8a23c13f15cde32323aa084e8fb4b8d1a46e2f
|
Ruby
|
koukisakata/MS2Import
|
/app/models/wallpaper.rb
|
UTF-8
| 543
| 2.5625
| 3
|
[] |
no_license
|
class Wallpaper < ApplicationRecord
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
# IDが見つかれば、レコードを呼び出し、見つかれなければ、新しく作成
wallpaper = find_by(id: row["id"]) || new
# CSVからデータを取得し、設定する
wallpaper.attributes = row.to_hash.slice(*updatable_attributes)
# 保存する
wallpaper.save
end
end
# 更新を許可するカラムを定義
def self.updatable_attributes
["code"]
end
end
| true
|
cf969c0bf839ccd16f13a49726c449289baa52e6
|
Ruby
|
BigBeardy/name-and-calulator
|
/calulatormath.rb
|
UTF-8
| 306
| 3.09375
| 3
|
[] |
no_license
|
def math(group,num1,num2)
if group == "addition"
answer = num1.to_i + num2.to_i
elsif group == "subtraction"
num1.to_i - num2.to_i = answer
elsif group == "division"
num1.to_i / num2.to_i = answer
else group == "multiply"
num1.to_i * num2.to_i = answer
end
answer.to_s
end
| true
|
bfce1c2af38fce2664e77f782846ade0dea51ea9
|
Ruby
|
Easoncyx/Ruby_and_SoftwareEngineering
|
/w3c_ruby/w3c_ruby variable.rb
|
UTF-8
| 560
| 4.03125
| 4
|
[] |
no_license
|
# Golbal variable
$global_variable = 10
class Class1
def print_global
puts "Global variable in Class1 is #$global_variable"
end
end
class Class2
def print_global
puts "Global variable in Class2 is #$global_variable"
end
end
class1obj = Class1.new
class1obj.print_global
class2obj = Class2.new
class2obj.print_global
# Constant
class Example
VAR1 = 100
VAR2 = 200
def show
puts "Value of first Constant is #{VAR1}"
puts "Value of second Constant is #{VAR2}"
end
end
# 创建对象
object=Example.new()
object.show
| true
|
d2aaedf373a3c9db51d1393d5acb45d70487f497
|
Ruby
|
iHiD/threaded_in_memory_queue
|
/test/threaded_in_memory_queue/worker_test.rb
|
UTF-8
| 777
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
require 'test_helper'
class WorkerTest < Test::Unit::TestCase
def setup
@worker = ThreadedInMemoryQueue::Worker.new(Queue.new, timeout: 1)
@worker.start
end
def teardown
end
def test_calls_contents_of_blocks
Dummy.expects(:process).with(1).once
Dummy.expects(:process).with(2).once
job = Proc.new {|x| Dummy.process(x) }
@worker.queue << [job, 1]
@worker.queue << [job, 2]
@worker.poison
@worker.join
end
def test_calls_context_of_klass
Dummy.expects(:process).with(1).once
Dummy.expects(:process).with(2).once
job = Class.new do
def self.call(num)
Dummy.process(num)
end
end
@worker.queue << [job, 1]
@worker.queue << [job, 2]
@worker.poison
@worker.join
end
end
| true
|
ab3969bd69d9229d16e70614150ef25d7578caa4
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/src/2503.rb
|
UTF-8
| 208
| 3.21875
| 3
|
[] |
no_license
|
def compute(foo, bar)
foo, bar = bar, foo if bar.size < foo.size
difference = 0
foo.each_char.with_index do |char, index|
difference += 1 if char != bar[index]
end
difference
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.