# Extend Numeric with time constants
class Numeric # :nodoc:
# Time constants
#
# TODO: Use RichUnits instead (?)
#
module Times # :nodoc:
MINUTES = 60
HOURS = 60 * MINUTES
DAYS = 24 * HOURS
WEEKS = 7 * DAYS
MONTHS = 30 * DAYS
YEARS = 365.25 * DAYS
# Number of seconds (returns receiver unmodified)
def seconds
return self
end
alias_method :second, :seconds
# Returns number of seconds in <receiver> minutes
def minutes
MINUTES
end
alias_method :minute, :minutes
# Returns the number of seconds in <receiver> hours
def hours
HOURS
end
alias_method :hour, :hours
# Returns the number of seconds in <receiver> days
def days
DAYS
end
alias_method :day, :days
# Return the number of seconds in <receiver> weeks
def weeks
WEEKS
end
alias_method :week, :weeks
# Returns the number of seconds in <receiver> fortnights
def fortnights
return self * 2.weeks
end
alias_method :fortnight, :fortnights
# Returns the number of seconds in <receiver> months (approximate)
def months
MONTHS
end
alias_method :month, :months
# Returns the number of seconds in <receiver> years (approximate)
def years
YEARS #return (self * 365.25.days).to_i
end
alias_method :year, :years
# Returns the Time <receiver> number of seconds before the
# specified +time+. E.g., 2.hours.before( header.expiration )
def before( time )
return time - self
end
# Returns the Time <receiver> number of seconds ago. (e.g.,
# expiration > 2.hours.ago )
def ago
return self.before( ::Time.now )
end
# Returns the Time <receiver> number of seconds after the given +time+.
# E.g., 10.minutes.after( header.expiration )
def after( time )
return time + self
end
# Reads best without arguments: 10.minutes.from_now
def from_now
return self.after( ::Time.now )
end
# Return a string describing the amount of time in the given number of
# seconds in terms a human can understand easily.
def time_delta_string
seconds = self
return 'less than a minute' if seconds < MINUTES
return (seconds / MINUTES).to_s + ' minute' + (seconds/60 == 1 ? '' : 's') if seconds < (50 * MINUTES)
return 'about one hour' if seconds < (90 * MINUTES)
return (seconds / HOURS).to_s + ' hours' if seconds < (18 * HOURS)
return 'one day' if seconds < DAYS
return 'about one day' if seconds < (2 * DAYS)
return (seconds / DAYS).to_s + ' days' if seconds < WEEKS
return 'about one week' if seconds < (2 * WEEKS)
return (seconds / WEEKS).to_s + ' weeks' if seconds < (3 * MONTHS)
return (seconds / MONTHS).to_s + ' months' if seconds < YEARS
return (seconds / YEARS).to_s + ' years'
end
end # module TimeConstantMethods
include Times
end
true
f2685a8663d700159eac2357e5b877d1bc78a8f1
Ruby
dlbirch/rubyPOS
/spec/right_t_padder_spec.rb
UTF-8
657
2.703125
3
[]
no_license
require 'rspec'
require 'right_t_padder'
describe RightTPadder do
before(:each) do
@rtp = RightTPadder.new()
end
it 'should return an instance' do
expect(@rtp).to be_truthy
end
it 'should handle data longer than max length without throwing an exception' do
expect(@rtp.pad("1234567890123456789", 10)).to eq("1234567890")
end
it 'should handle data that requires padding' do
expect(@rtp.pad("12345678901234567890", 25)).to eq("12345678901234567890 ")
end
it 'should handle data that requires no padding and no truncation' do
expect(@rtp.pad("12345678901234567890", 20)).to eq("12345678901234567890")
end
end
true
d5e68b52cbccdc46c64e86b23335652caceddd04
Ruby
mlyubarskyy/leetcode
/362_design_hit_counter.rb
UTF-8
984
3.875
4
[]
no_license
class HitCounter
=begin
Initialize your data structure here.
=end
def initialize()
@q = [[0, 0]] * 300
end
=begin
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: Integer
:rtype: Void
=end
def hit(timestamp)
idx = timestamp % 300
time, hits = @q[idx]
@q[idx] = if time != timestamp
[timestamp, 1]
else
[time, hits + 1]
end
end
=begin
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
:type timestamp: Integer
:rtype: Integer
=end
def get_hits(timestamp)
ans = 0
300.times do |i|
time, hit = @q[i]
ans += hit if timestamp - time < 300
end
ans
end
end
# Your HitCounter object will be instantiated and called as such:
# obj = HitCounter.new()
# obj.hit(timestamp)
# param_2 = obj.get_hits(timestamp)
true
9c39bfa9b8d125738c859c1a01629d49a305d4c6
Ruby
h4hany/yeet-the-leet
/algorithms/Medium/62.unique-paths.rb
UTF-8
1,177
3.515625
4
[]
no_license
#
# @lc app=leetcode id=62 lang=ruby
#
# [62] Unique Paths
#
# https://leetcode.com/problems/unique-paths/description/
#
# algorithms
# Medium (54.32%)
# Total Accepted: 514.5K
# Total Submissions: 947.2K
# Testcase Example: '3\n2'
#
# A robot is located at the top-left corner of a m x n grid (marked 'Start' in
# the diagram below).
#
# The robot can only move either down or right at any point in time. The robot
# is trying to reach the bottom-right corner of the grid (marked 'Finish' in
# the diagram below).
#
# How many possible unique paths are there?
#
#
# Above is a 7 x 3 grid. How many possible unique paths are there?
#
#
# Example 1:
#
#
# Input: m = 3, n = 2
# Output: 3
# Explanation:
# From the top-left corner, there are a total of 3 ways to reach the
# bottom-right corner:
# 1. Right -> Right -> Down
# 2. Right -> Down -> Right
# 3. Down -> Right -> Right
#
#
# Example 2:
#
#
# Input: m = 7, n = 3
# Output: 28
#
#
#
# Constraints:
#
#
# 1 <= m, n <= 100
# It's guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.
#
#
#
# @param {Integer} m
# @param {Integer} n
# @return {Integer}
def unique_paths(m, n)
end
true
22efedbebd5394d900d6aba08047d758718c7a2a
Ruby
oshou/procon
/AC/ARC/arc014a.rb
UTF-8
64
3.28125
3
[]
no_license
n = gets.to_i
if n % 2 == 0
puts "Blue"
else
puts "Red"
end
true
49fbe07d8e92b01d61a2ef1e517eae2735cfde2f
Ruby
martom87/workshops_tennis
/spec/tennis/player_spec.rb
UTF-8
390
2.5625
3
[]
no_license
# frozen_string_literal: true
require_relative '../../lib/tennis/player.rb'
RSpec.describe Player do
subject { described_class.new(points_amount, name)}
let(:points_amount) {15}
let(:name){'Edek'}
it 'returns players points amount' do
expect(subject.points_amount).to eq(points_amount)
end
it 'returns player\'s name' do
expect(subject.name).to eq(name)
end
end
module YouGotListed
class Response
attr_accessor :ygl_response
def initialize(response, raise_error = true)
rash = Hashie::Rash.new(response)
self.ygl_response = rash.ygl_response
raise Error.new(self.ygl_response.response_code, self.ygl_response.error) if !success? && raise_error
end
def success?
self.ygl_response && self.ygl_response.respond_to?(:response_code) && self.ygl_response.response_code.to_i < 300
end
def method_missing(method_name, *args)
if self.ygl_response.respond_to?(method_name)
self.ygl_response.send(method_name)
else
super
end
end
end
end
true
5a0d571f30ce7de852d7ba05e260256f15d46eb7
Ruby
SocialCentivPublic/cheftacular
/lib/cheftacular/stateless_actions/cloud.rb
UTF-8
7,804
2.640625
3
[
"MIT"
]
permissive
class Cheftacular
class StatelessActionDocumentation
def cloud
@config['documentation']['stateless_action'][__method__] ||= {}
@config['documentation']['stateless_action'][__method__]['long_description'] = [
"`cft cloud <FIRST_LEVEL_ARG> [<SECOND_LEVEL_ARG>[:<SECOND_LEVEL_ARG_QUERY>]*] ` this command handles talking to various cloud APIs. " +
"If no args are passed nothing will happen.",
[
" 1. `domain` first level argument for interacting with cloud domains",
" 1. `list` default behavior",
" 2. `read:TOP_LEVEL_DOMAIN` returns detailed information about all subdomains attached to the TOP_LEVEL_DOMAIN",
" 3. `read_record:TOP_LEVEL_DOMAIN:QUERY_STRING` queries the top level domain for all subdomains that have the QUERY_STRING in them.",
" 4. `create:TOP_LEVEL_DOMAIN` creates the top level domain on rackspace",
" 5. `create_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME:IP_ADDRESS[:RECORD_TYPE[:TTL]]` " +
"IE: `cft cloud domain create:mydomain.com:myfirstserver:1.2.3.4` will create the subdomain 'myfirstserver' on the mydomain.com domain.",
" 6. `destroy:TOP_LEVEL_DOMAIN` destroys the top level domain and all of its subdomains",
" 7. `destroy_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME` deletes the subdomain record for TOP_LEVEL_DOMAIN if it exists.",
" 8. `update:TOP_LEVEL_DOMAIN` takes the value of the email in the authentication data bag for your specified cloud and updates the TLD.",
" 9. `update_record:TOP_LEVEL_DOMAIN:SUBDOMAIN_NAME:IP_ADDRESS[:RECORD_TYPE[:TTL]]` similar to `create_record`.",
" 2. `server` first level argument for interacting with cloud servers, " +
"if no additional args are passed the command will return a list of all servers on the preferred cloud.",
" 1. `list` default behavior",
" 2. `read:SERVER_NAME` returns all servers that have SERVER_NAME in them (you want to be as specific as possible for single matches)",
" 3. `create:SERVER_NAME:FLAVOR_ALIAS` IE: `cft cloud server \"create:myserver:1 GB Performance\"` " +
"will create a server with the name myserver and the flavor \"1 GB Performance\". Please see flavors section.",
" 1. NOTE! If you forget to pass in a flavor alias the script will not error! It will attempt to create a 512MB Standard Instance!",
" 2. NOTE! Most flavors have spaces in them, you must use quotes at the command line to utilize them!",
" 4. `destroy:SERVER_NAME` destroys the server on the cloud. This must be an exact match of the server's actual name or the script will error.",
" 5. `poll:SERVER_NAME` polls the cloud's server for the status of the SERVER_NAME. This command " +
"will stop polling if / when the status of the server is ACTIVE and its build progress is 100%.",
" 6. `attach_volume:SERVER_NAME:VOLUME_NAME[:VOLUME_SIZE[:DEVICE_LOCATION]]` " +
"If VOLUME_NAME exists it will attach it if it is unattached otherwise it will create it",
" 1. NOTE! If the system creates a volume the default size is 100 GB!",
" 2. DEVICE_LOCATION refers to the place the volume will be mounted on, a place like `/dev/xvdb`, " +
"from here it must be added to the filesystem to be used.",
" 3. If you want to specify a location, you must specify a size, if the volume already exists it wont be resized but will be attached at that location!",
" 4. If DEVICE_LOCATION is blank the volume will be attached to the first available slot.",
" 7. `detach_volume:SERVER_NAME:VOLUME_NAME` Removes the volume from the server if it is attached. " +
"If this operation is performed while the volume is mounted it could corrupt the volume! Do not do this unless you know exactly what you're doing!",
" 8. `list_volumes:SERVER_NAME` lists all volumes attached to a server",
" 9. `read_volume:SERVER_NAME:VOLUME_NAME` returns the data of VOLUME_NAME if it is attached to the server.",
" 3. `volume` first level argument for interacting with cloud storage volumes, if no additional args are passed the command will return a list of all cloud storage containers.",
" 1. `list` default behavior",
" 2. `read:VOLUME_NAME` returns the details for a specific volume.",
" 3. `create:VOLUME_NAME:VOLUME_SIZE` IE `cft rax volume create:staging_db:256`",
" 4. `destroy:VOLUME_NAME` destroys the volume. This operation will not work if the volume is attached to a server.",
" 4. `flavor` first level argument for listing the flavors available on the cloud service",
" 1. `list` default behavior",
" 2. `read:FLAVOR SIZE` behaves the same as list unless a flavor size is supplied.",
" 1. Standard servers are listed as XGB with no spaces in their size, performance servers are listed as X GB with " +
"a space in their size. If you are about to create a server and are unsure, query flavors first.",
" 5. `image` first level argument for listing the images available on the cloud service",
" 1. `list` default behavior",
" 2. `read:NAME` behaves the same as list unless a specific image name is supplied",
" 6. `region` first level argument for listing the regions available on the cloud service (only supported by DigitalOcean)",
" 1. `list` default behavior",
" 2. `read:REGION` behaves the same as list unless a specific region name is supplied",
" 7. `sshkey` first level argument for listing the sshkeys added to the cloud service (only supported by DigitalOcean)",
" 1. `list` default behavior",
" 2. `read:KEY_NAME` behaves the same as list unless a specific sshkey name is supplied",
" 3. `\"create:KEY_NAME:KEY_STRING\"` creates an sshkey object. KEY_STRING must contain the entire value of the ssh public key file. " +
"The command must be enclosed in quotes.",
" 4. `destroy:KEY_NAME` destroys the sshkey object",
" 5. `bootstrap` captures the current computer's hostname and checks to see if a key matching this hostname exists on the cloud service. " +
"If the key does not exist, the command attempts to read the contents of the ~/.ssh/id_rsa.pub file and create a new key with that data and the " +
"hostname of the current computer. Run automatically when creating DigitalOcean servers. It's worth noting that if the computer's key already " +
"exists on DigitalOcean under a different name, this specific command will fail with a generic error. Please check your keys."
]
]
@config['documentation']['stateless_action'][__method__]['short_description'] = 'Retrieves useful information about cloud services being used'
end
end
class StatelessAction
def cloud *args
raise "This action can only be performed if the mode is set to devops" if !@config['helper'].running_in_mode?('devops') && !@options['in_scaling']
args = ARGV[1..ARGV.length] if args.empty?
@config['cloud_interactor'] ||= CloudInteractor.new(@config['cheftacular'], @options)
@config['cloud_interactor'].run args
end
alias_method :aws, :cloud
alias_method :rax, :cloud
end
end
true
99146c4bc4b64653b3822888c77848f5046503ee
Ruby
golovanov1512/golovanov1512.github.io
/ruby_practice/ruby.rb
UTF-8
684
3.671875
4
[]
no_license
class PasswordGen
def initialize(count_symbol)
@count_symbol = count_symbol
@vowel = %w(a e i y o u)
@consonant = %w(q w r t p s d f g h j k l m n b v c x z)
end
def vowel_or_consonant(index)
if index.even?
to_large_letter(@vowel[rand(@vowel.size)], index)
else
@consonant[rand(@consonant.size)]
end
end
def generate
password = ""
@count_symbol.times{ |index| password << vowel_or_consonant(index) }
password
end
def to_large_letter(letter, index)
index > 5 ? letter.upcase : letter
end
end
p 'Enter password length'
password_gen = PasswordGen.new(gets.chomp.to_i)
p "Your password : #{ password_gen.generate }"
true
fc99120ceae42dad870f23ab836aea3c7515e294
Ruby
KarlaRobinson/Learning_Ruby_basics
/TablasDeMultiplicar.rb
UTF-8
273
3.34375
3
[]
no_license
def multiplication_tables(num)
arr = Array(1..num)
range = Array(1..10)
arr.each do |arrElem|
range.each do |rangeElem|
value = arrElem * rangeElem
print "#{value}\t"
end
print "\n"
end
end
multiplication_tables(5)
multiplication_tables(7)
true
6f737db76ae1aa152f008f92748f78227cf709c4
Ruby
thelazyfox/euler
/p023/solution.rb
UTF-8
1,337
3.875
4
[]
no_license
class Array
def sum
self.inject {|a,b| a+b}
end
end
def factor(n)
if n == 0
[0]
elsif n == 1
[1]
else
i = 2
while n % i > 0
i += 1
end
if i == n
[n]
else
factor(i) + factor(n/i)
end
end
end
def divisors(n)
primes = Hash.new(0)
factor(n).each do |value|
primes[value] += 1
end
factors = [1]
primes.each do |prime,count|
factors.collect! do |factor|
list = []
(count+1).times do |power|
list << factor * (prime**power)
end
list
end
factors.flatten!
end
factors.flatten
end
abundant_numbers = []
puts "Checking Abundant Numbers..."
(1..28123).each do |n|
puts n if n % 100 == 0
divs = divisors(n)
divs.sort!
divs.pop
if divs.uniq.sum > n
abundant_numbers << n
end
end
puts "Done. Found #{abundant_numbers.size} numbers"
puts abundant_numbers
puts ""
abundant_sums = Hash.new(false)
puts "Finding abundant number sums..."
abundant_numbers.each_index do |i|
puts i if i % 100 == 0
(i..(abundant_numbers.size-1)).each do |j|
sum = abundant_numbers[i] + abundant_numbers[j]
abundant_sums[sum] = true unless sum > 28123
end
end
puts "Done."
puts "Summing up the result"
sum = 0
(1..28123).each do |n|
sum += n unless abundant_sums[n]
end
puts "Done"
puts "Solution: #{sum}"
true
ea0265e2cdc8c93a05feb1a30614b6d39f6a5d95
Ruby
ahawkins/chassis-example
/app/utils.rb
UTF-8
523
2.625
3
[]
no_license
class PhoneNumbersValidator
include ActiveModel::Validations
include Enumerable
validate do |phone_numbers|
phone_numbers.each do |number|
begin
UserRepo.find_by_phone_number! number
rescue UserRepo::UnknownPhoneNumber => ex
phone_numbers.errors.add :phone_numbers, ex.message
end
end
end
def initialize(numbers)
@numbers = numbers
end
def validate!
raise ValidationError, errors unless valid?
end
def each(&block)
@numbers.each(&block)
end
end
true
13ea2ff883d92ce54ddf96396ae60a71b35ba372
Ruby
AnyPresence/do_sqlserver-tinytds
/lib/do_sqlserver_tinytds/tiny_tds_extension.rb
UTF-8
3,168
3.0625
3
[
"MIT"
]
permissive
require 'tiny_tds'
module TinyTds
class Client
#raw_execute - freetds does not support dynamic sql so
#we're going to translate dynamic sql statements into a plain
#sql statement
def raw_execute(text , *var_list)
dynamic_sql = text.clone
flat_sql = var_list.empty? ? dynamic_sql : process_questioned_sql(dynamic_sql , *var_list)
execute(flat_sql)
end
:private
def process_questioned_sql(sql , *vars)
sql_type = classify_sql(sql)
result = substitute_quoted_questions(sql)
_sql = result[:sql]
vars.each do |var|
_sql.sub!("?" , convert_type_to_s(var , sql_type))
end
#place back strings in the sql that contained "?"
result[:container].each do |k,v|
_sql.gsub!(k , v)
end
_sql
end
def substitute_quoted_questions(sql)
container = {}
#collect strings in the sql that contains a question_mark
qstrings = sql.scan(/"[^"]*"/).select{|s| s.include?("?")}
#temporarily replace quoted values
counter = 0
qstrings.each do |qstring|
key = "(((####{counter}###)))"
sql.gsub!(qstring, key)
container[key] = qstring
counter += 1
end
{:sql => sql, :container => container}
end
#convert_type_to_s - convert Ruby collection objects fed into the query into
#sql strings
def convert_type_to_s(arg , sql_type)
case sql_type
when :between
case arg
when Range , Array
"#{sql_stringify_value(arg.first)} AND #{sql_stringify_value(arg.last)}"
else
raise "Type not found..."
end
when :in
case arg
when Range , Array
" (#{arg.collect{|e| "#{sql_stringify_value(e)}"}.join(" , ")}) "
else
raise "Type not found..."
end
else
case arg
when Range , Array
arg.collect{|e| "#{sql_stringify_value(e)}"}.join(" , ")
else
sql_stringify_value(arg)
end
end
end
#convert_type_to_s - convert Ruby object fed into the query into
#sql string
def sql_stringify_value(value)
case
when value.is_a?(String)
"N'#{value.gsub(/\'/, "''")}'"
when value.is_a?(Numeric)
value.to_s
when value.is_a?(NilClass)
"NULL"
when value.is_a?(DateTime)
value.strftime("'%m/%d/%Y %I:%M:%S %p'")
when value.is_a?(Time)
DateTime.new(value.year, value.month, value.day,
value.hour, value.min, value.sec,
Rational(value.gmt_offset / 3600, 24)).strftime("'%m/%d/%Y %I:%M:%S %p'")
else
"N'#{value.to_s}'"
end
end
#classify_sql - determine if this sql has a between or in
def classify_sql(sql)
case
when sql[/between.+\?/i] #var should be an array
:between
when sql[/\sin\s+\?/i]
:in
end
end
end
class Error
alias :to_str :to_s
def errstr
@errstr ||= []
@errstr
end
end
end
module Codebreaker
class Game
attr_reader :secret, :player, :attempts, :hints
SECRET_SIZE = 4
MAX_ATTEMPTS = 4
def initialize(player)
@player = player
@secret = ""
@attempts = 0
@hints = 0
generate_secret
end
def generate_secret
SECRET_SIZE.times do
@secret << (Random.rand(6)+1).to_s
end
end
def guess(suspect)
result = ""
SECRET_SIZE.times do |i|
if @secret[i] == suspect.value[i]
result << "+"
elsif @secret.include? suspect.value[i]
result << "-"
else
result << "X"
end
end
result
end
def can_use_hint?
@hints < 1? true : false
end
def take_hint
if can_use_hint?
position = rand(3)
@hints += 1
"в этом числе присутствует цифра #{uncover(position).chr} "
end
end
def uncover(position)
secret[position]
end
def result(suspect)
@attempts += 1
string = guess(suspect)
if string == "++++"
p "Поздравляю #{@player.name} Вы угадали число!!!"
save_game_result("../../tmp/results.txt")
elsif @attempts < MAX_ATTEMPTS
p "Вы использовали #{@attempts} из #{MAX_ATTEMPTS} попыток"
elsif @attempts == MAX_ATTEMPTS
p "игра закончена загаданое число #{@secret}"
end
end
def save_game_result(file)
File.open(file, 'a') { |f| f.puts("#{@player.name} угадал число.\n за #{@attempts} попытки\n подсказок использованно: #{@hints}\n-------") }
end
def answer
p @secret
end
end
end
true
fd1975c2fb770019f2d71886f8cc9bc1def2eac8
Ruby
Scott2bReal/intro-to-programming-with-ruby
/the-basics/4.rb
UTF-8
272
3.875
4
[]
no_license
=begin
Use the dates from the previous example and store them in an array. Then
make your program output the same thing as exercise 3.
=end
movies = {"Jurassic Park" => 1995, "Forrest Gump" => 1992}
dates = []
movies.each { |k, v| dates.push(v) }
dates.each { |date| puts date }
true
975641d1484ae3d61f9dd23d0d7762fe21c65011
Ruby
jaswanthJeenu/Ruby-to-MIPS-Compiler
/project/test/pointer2.rb
UTF-8
32
2.703125
3
[]
no_license
a = []
a[1]=2
b = a+4
puts b[0]
true
e983ea42be36d6713b012ab81411405881ae3fc6
Ruby
goldstar/blackbeard
/lib/blackbeard/metric_date.rb
UTF-8
376
2.625
3
[
"MIT"
]
permissive
module Blackbeard
class MetricDate
#TODO refactor with MetricHour to be compaosed
attr_reader :date, :result
def initialize(date, result)
@date = date
@result = result
end
def results_for(segments)
segments.map{|s| result[s].to_f }
end
def result_rows(segments)
[@date.to_s] + results_for(segments)
end
end
end
true
9333388773173d9b3d6f89fc31ec9f9a63e30672
Ruby
SiCuellar/Code_Wars
/Ruby/decode_morse/algo.rb
UTF-8
240
3.0625
3
[]
no_license
require 'pry'
#test/Hash Provided
class Algo
morse_letters = morseCode.split
morse_letters.map do |let|
MORSE_CODE[let]
end
end
# morseCode.strip.split(" ").map { |w| w.split(" ").map { |c| MORSE_CODE[c] }.join }.join(" ")
true
7805b4ac1ac858a049a9a170c059cb545f4e640a
Ruby
MadayAlcala/Ruby-Training
/Slide4/flight/boarding.rb
UTF-8
1,719
3.953125
4
[]
no_license
require './flight'
require './passenger'
class Boarding
def passenger_data
puts "What is your name:"
name = gets.chomp
puts "What is your lastname:"
lastname = gets.chomp
puts "What is your address:"
address = gets.chomp
puts "What is your phone:"
phone = gets.chomp
puts "What is your age:"
years = gets.chomp
return name, lastname, address, phone, years
end
def boarding_passengers
flight1 = Flight.new("La Paz", "Oruro", 123)
flight2 = Flight.new("Oruro", "Cochabamba", 345)
flight3 = Flight.new("Potosí", "Tarija", 89)
flights = {flight1 => 0, flight2 => 0, flight3 => 0}
puts flights.values
puts "¿What type of flight did you need?"
puts "1: Flight1 \n2: Flight2 \n3: Flight3 "
flight_type = gets.chomp.to_i
if flight_type == 1
unless flight1.passengers_number >= 3
flights[flight1] = flight1.passengers_number += 1
name, lastname, address, phone, years = passenger_data
passenger = Passenger.new(name, lastname, address, phone, years)
end
elsif flight_type == 2
unless flight2.passengers_number >= 3
flights[flight2] = flight2.passengers_number += 1
name, lastname, address, phone, years = passenger_data
passenger = Passenger.new(name, lastname, address, phone, years)
end
elsif flight_type == 3
if flight3.passengers_number < 3
flights[flight3] = flight3.passengers_number +=1
name, lastname, address, phone, years = passenger_data
passenger = Passenger.new(name, lastname, address, phone, years)
end
else
"That type of flight does not exist."
end
end
end
Boarding.new.boarding_passengers
true
5309a40f02e9830afe718a639562a2a57784b914
Ruby
olistik/website-template
/app/models/cell_registry.rb
UTF-8
1,504
2.625
3
[
"MIT"
]
permissive
# cell_class = Cell::Base::class_from_cell_name(cell)
# use cell_class.instance_methods(false)
# to obtain the cell's list of available actions
class CellRegistry
@@registry = []
def self.registry
register_all if @@registry.empty?
@@registry
end
def self.registry=(r)
@@registry = r
end
def self.register(cell)
@@registry.push(cell)
end
def self.unregister(cell = nil)
return @@registry.pop unless cell
@@registry.delete(cell)
end
def self.actions_by_cell(cell)
Cell::Base::class_from_cell_name(cell).instance_methods(false)
end
def self.register_all
cells_paths = RAILS_ROOT + "/app/cells"
@possible_cells = []
paths = cells_paths.select { |path| File.directory?(path) && path != "." }
seen_paths = Hash.new {|h, k| h[k] = true; false}
ActionController::Routing::normalize_paths(paths).each do |load_path|
Dir["#{load_path}/**/*_cell.rb"].collect do |path|
next if seen_paths[path.gsub(%r{^\.[/\\]}, "")]
cell_name = path[(load_path.length + 1)..-1]
cell_name.gsub!(/_cell\.rb\Z/, '')
@possible_cells << cell_name
end
end
@possible_cells.uniq!
#TODO register only some kind of cells
for cell in @possible_cells do
# cell_class = Cell::Base::class_from_cell_name(cell)
register(cell)
end
end
end
true
dafe6a7c4c703637a3bd095c9ffff4e52d26edf3
Ruby
nax2uk/decorating-command-line
/lib/example_lolize.rb
UTF-8
1,889
3.484375
3
[]
no_license
# shows how to use lolize to selectively display rainbow coloured fonts.
require 'lolize'
colorizer = Lolize::Colorizer.new
puts "
████████╗██╗░█████╗░ ████████╗░█████╗░░█████╗░ ████████╗░█████╗░███████╗
╚══██╔══╝██║██╔══██╗ ╚══██╔══╝██╔══██╗██╔══██╗ ╚══██╔══╝██╔══██╗██╔════╝
░░░██║░░░██║██║░░╚═╝ ░░░██║░░░███████║██║░░╚═╝ ░░░██║░░░██║░░██║█████╗░░
░░░██║░░░██║██║░░██╗ ░░░██║░░░██╔══██║██║░░██╗ ░░░██║░░░██║░░██║██╔══╝░░
░░░██║░░░██║╚█████╔╝ ░░░██║░░░██║░░██║╚█████╔╝ ░░░██║░░░╚█████╔╝███████╗
░░░╚═╝░░░╚═╝░╚════╝░ ░░░╚═╝░░░╚═╝░░╚═╝░╚════╝░ ░░░╚═╝░░░░╚════╝░╚══════╝\n\n"
colorizer.write " Welcome to Tic Tac Toe!\n\n"
colorizer.write "Instructions:\n\nThe game is played on a 3x3 grid.\nYou are X, your opponent is O. Players take turns putting their marks in empty squares.\nThe first player to get 3 of their marks in a row (up, down, across, or diagonally) is the winner.\nIf all 9 squares are full and no player has 3 marks in a row, the game is over.\n\n\n"
true
b8f01eaca138d1b613db2351f0e4aef00243f977
Ruby
steinuil/yubiyubi
/vtuber_handler.rb
UTF-8
679
2.609375
3
[
"Unlicense"
]
permissive
require 'yaml'
require_relative 'lib/irc'
class VtuberHandler
def initialize file
@file = file
reload_list
end
def reload_list
@list = YAML.safe_load(File.read @file)
@last_mtime = File.mtime(@file)
end
def handle msg
return unless msg.command == "PRIVMSG" && msg.params[1].strip == "'chuuba"
if File.mtime(@file) != @last_mtime
reload_list
end
vtuber = @list.sample
IRC::Protocol.privmsg(
msg.params[0],
if vtuber["agency"]
"#{msg.prefix.nick}, your vtuber is #{vtuber["name"]} (#{vtuber["agency"]})"
else
"#{msg.prefix.nick}, your vtuber is #{vtuber["name"]}"
end
)
end
end
true
f9a7fa2d333e6d807009212ea8a0eae32c8adf10
Ruby
radu-constantin/small-problems
/easy7/swap_case.rb
UTF-8
426
3.59375
4
[]
no_license
UPPERCASE = ('A'..'Z').to_a
LOWERCASE = ('a'..'z').to_a
def swapcase (string)
new_string = ''
string.each_char do |char|
if UPPERCASE.include?(char)
new_string << char.downcase
elsif LOWERCASE.include?(char)
new_string << char.upcase
else
new_string << char
end
end
new_string
end
puts swapcase('CamelCase') == 'cAMELcASE'
puts swapcase('Tonight on XYZ-TV') == 'tONIGHT ON xyz-tv'
x = 5
i = 3
sum = x + i
subtraction = x - i
multiplication = x * i
division = (x.to_f / i.to_f).round(2)
puts sum
puts subtraction
puts multiplication
puts division
true
f9ebbc7600073dd48d1d489d148b9006bfe6f9f7
Ruby
naathyn/workspace_management
/app/models/folder.rb
UTF-8
584
2.515625
3
[]
no_license
class Folder < ActiveRecord::Base
attr_accessible :name, :directory_id, :subfolder_id
belongs_to :directory
belongs_to :subfolder, foreign_key: "subfolder_id", class_name: "Folder"
has_many :documents, dependent: :destroy
has_many :subfolders, foreign_key: "subfolder_id", class_name: "Folder", dependent: :destroy
validates_presence_of :name
def path
begin
File.join(directory.name, name).gsub(/\s/, '_').downcase
rescue NoMethodError
File.join(subfolder.directory.name, subfolder.name, name).
gsub(/\s/, '_').downcase
end
end
end
true
6169acb5a550f238064b3d508c1c0416de6b770e
Ruby
liyijie/huanct
/app/models/comment.rb
UTF-8
1,917
2.703125
3
[]
no_license
class Comment < ActiveRecord::Base
attr_accessible :dianping, :gongxian, :last_time, :member, :name, :qiandao, :reg_time
# 分页显示的默认值
self.per_page = 10
def self.create_by_member member
comment = Comment.new
comment.member = member
url = "http://www.dianping.com/member/#{member}"
params = {
:headers => {
"User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36"
}
}
response = HTTParty.get(url, params)
# puts response.body
nodes = Nokogiri::XML(response.body).xpath("//h2")
nodes.each do |node|
text = node.get_attribute "class"
next if text.nil?
if (text == "name")
comment.name = node.text
end
end
nodes = Nokogiri::XML(response.body).xpath("//a")
nodes.each do |node|
text = node.text
next if text.nil?
if (text.start_with? "点评(")
comment.dianping = text.sub("点评(","").sub(")","")
elsif (text.start_with? "签到(")
comment.qiandao = text.sub("签到(","").sub(")","")
end
end
nodes = Nokogiri::XML(response.body).xpath("//span")
nodes.each do |node|
text = node.get_attribute "title"
if text
if (text.start_with? "贡献值")
comment.gongxian = text.sub("贡献值","")
end
elsif (node.text.start_with? "注册时间")
comment.reg_time = node.parent.text.sub("注册时间:","")
elsif (node.text.start_with? "最后登录")
comment.last_time = node.parent.text.sub("最后登录:","")
end
end
comment
end
def merge other
@member = other.member
@name = other.name
@dianping = other.dianping
@gongxian = other.gongxian
@qiandao = other.qiandao
@reg_time = other.reg_time
@last_time = other.last_time
end
end
true
ec51717a567eaa7196298caa45045348010e5eb6
Ruby
emarcha/scuba_shop_app
/app/models/tour.rb
UTF-8
1,078
2.84375
3
[]
no_license
class Tour < ActiveRecord::Base
has_many :bookings,
before_add: :check_available_seats,
dependent: :destroy
before_create :populate_available_seats
before_create :parse_time_input
validates :title,
presence: true,
length: { maximum: 100 }
validates :tour_date,
presence: true
validates :total_seats,
presence: true,
numericality: { only_integer: true,
greater_than_or_equal_to: 1 }
validates :price_cents,
presence: true,
numericality: { only_integer: true,
greater_than_or_equal_to: 0}
validates :duration_before_typecast,
presence: true
private
def populate_available_seats
self.available_seats = self.total_seats
end
def parse_time_input
self.duration = ChronicDuration.parse(self.duration_before_typecast)
end
def check_available_seats(booking)
if self.available_seats <= 0
raise 'No seats available'
end
end
end
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
min_key = nil
start_zero_compare_value = 0
name_hash.each do |key, value|
if start_zero_compare_value == 0 || value < start_zero_compare_value
start_zero_compare_value = value
min_key = key
end
end
min_key
end
true
ff53c895da85ee18364cff388c06413a3533f5bd
Ruby
kkchu791/coding-challenge-kkchu791
/pop_growth/app/services/csv_parser.rb
UTF-8
1,866
2.984375
3
[]
no_license
require 'csv'
class CSVParser
attr_reader :file, :type
def initialize(file, type)
@file = file
@type = type
end
def process_file
if type == "zip_codes"
process_zip_codes
else
process_core_based_stat_areas_file
end
end
def process_zip_codes
CSV.foreach(file, headers: true) do |row|
zip_code = row.to_h
zip_attr = zip_code.keys[0]
ZipCode.find_or_create_by!(
zip_code: zip_code[zip_attr],
cbsa: zip_code["CBSA"]
)
end
end
def process_core_based_stat_areas_file
CSV.foreach(file, headers: true, encoding:'iso-8859-1:utf-8') do |row|
data = row.to_h
cbsa_attr = data.keys[0]
cbsa_record = create_cbsa_record(data, cbsa_attr)
population_stat_record = create_population_stat_record(data, cbsa_record)
create_population_estimate_records(data, population_stat_record)
end
end
private
def create_cbsa_record(data, cbsa_attr)
CoreBasedStatArea.find_or_create_by!(
cbsa: data[cbsa_attr],
mdiv: data["MDIV"]
)
end
def create_population_stat_record(data, cbsa_record)
PopulationStat.find_or_create_by!(
name: data["NAME"],
lsad: data["LSAD"],
core_based_stat_area_id: cbsa_record.id
)
end
def create_population_estimate_records(data, population_stat_record)
data.each do |attr, value|
if attr.include?("POPESTIMATE") && value.present?
year = attr[-4..-1]
PopulationEstimate.find_or_create_by!(year: year, estimate: value.to_i, population_stat_id: population_stat_record.id)
end
end
end
end
def square_array(array)
# your code here
new_array = []
array.each { |n| new_array.push(n * n )}
new_array
end
true
79a95adc93347a5505ec2ae33a6ab1a87c9b1ae3
Ruby
rabbitz/TryRuby
/test/unit/output_test.rb
UTF-8
1,497
2.734375
3
[]
no_license
require 'test_helper'
# tests if the TryRubyOutput translation, for use with mouseapp_2.js and similar
# is working correctly
class OutputTest < Test::Unit::TestCase
def test_simple_result
t = TryRuby::Output.standard(result: [12,24])
assert_equal("=> \033[1;20m[12, 24]", t.format)
end
def test_result_and_output
t = TryRuby::Output.standard(result: 333, output: "hello")
assert_equal("hello=> \033[1;20m333", t.format)
end
def test_error
begin
40.reverse
rescue Exception => e
t = TryRuby::Output.error(error: e)
end
assert_equal("\033[1;33mNoMethodError: undefined method `reverse' for 40:Fixnum",
t.format)
end
def test_error_with_output
begin
40.reverse
rescue Exception => e
t = TryRuby::Output.error(error: e, output: "hello\nworld")
end
assert_equal("hello\nworld\033[1;33mNoMethodError: undefined method `reverse' for 40:Fixnum",
t.format)
end
def test_illegal
t = TryRuby::Output.illegal
assert_equal("\033[1;33mYou aren't allowed to run that command!",
t.format)
end
def test_line_continuation
t = TryRuby::Output.line_continuation(3)
assert_equal(".." * 3, t.format)
end
def xtest_javascript
t = TryRuby::Output.javascript(javascript: 'alert("hello")')
# expected ends in a space to stop a visual problem in mouseapp
assert_equal("\033[1;JSmalert(\"hello\")\033[m ", t.format)
end
end
true
5ad69a1732ec39a48e25e1609b0c19ad86054171
Ruby
ghostlambdax/recognizeapp
/app/queries/streamable_recognitions.rb
UTF-8
3,418
2.640625
3
[]
no_license
class StreamableRecognitions
# Order of badge is important because it is referenced in some places.
BADGE_FILTERS = %w[anniversary recognition]
attr_reader :current_user, :network, :company, :team_id, :filter_by
def self.call(args)
new(args).query
end
def initialize(args)
extract_args args
end
def query
scoped = filter_by_network_and_parameters
scoped = scoped.approved.not_private
scoped = scoped.includes(:badge)
if company.settings.hide_disabled_users_from_recognitions?
# When both recipients_active and sender_active scope applied, it fetched the recognitions having sender
# active and at least one recipient active.
scoped = scoped.recipients_active.sender_active
end
scoped.distinct
end
private
def extract_args(args)
@current_user = args[:user]
@network = args[:network]
@company = args[:company]
@team_id = args[:team_id]
@filter_by = (Array(args[:filter_by]) & badge_filters) || []
end
def filter_by_network_and_parameters
# special handling for Recognize network or admins
# there is a quirk when you view stream page as a non admin user on recognizeapp.com domain
# we enter this conditional and will see all the system recognitions sent by the system user
# to have consistency, and to not freak me out in the future when i log in as another recognizeapp
# user, have a special condition for this
records = recognitions_for_recognize_network_or_admins if is_admin_or_recognize_network?
filter_by_parameters records
end
def filter_by_parameters(default_records)
records = if team_id_present_and_valid?
find_by_team_id
else
default_records || default_recognitions
end
records = find_by_badge(records) if filter_by.any?
records
end
def find_by_team_id
find_team&.recognitions
end
def find_by_badge(records)
return records if filter_by.length == badge_filters.length
records = records.includes(:badge)
is_anniversary_query = filter_by.include?(badge_filters.first)
records.where(badges: { is_anniversary: is_anniversary_query })
end
def recognitions_for_recognize_network_or_admins
return find_by_user_company if is_same_network?
find_by_network
end
# FIXME: Admin or Director can type any network in url and access the stream page but all the rendered links
# on that page point to the different company. Network verification has to be done to fix it.
# Note: This query is used for recognize_network_or_admins only
def find_by_network
Company.where(domain: network).first.recognitions
end
# Note: This query is used for recognize_network_or_admins only
def find_by_user_company
current_user.company.recognitions
end
def is_admin_or_recognize_network?
current_user && (current_user.admin? || network == "recognizeapp.com")
end
def is_same_network?
network.casecmp?(current_user.network)
end
def default_recognitions
Recognition.for_company(company) || Recognition.none
end
# FIXME: team_id could be any company's team. Need special handeling for team verification
# so that to fetch recognitions from authoritative company's team only.
def team_id_present_and_valid?
team_id.present?
end
def find_team
Team.find_from_recognize_hashid(team_id)
end
def badge_filters
self.class::BADGE_FILTERS
end
end
true
44312f2669ca82b411ebd4affc6923254d100f01
Ruby
petejkim/skeleton
/spec/support/fixture_saver.rb
UTF-8
1,996
2.515625
3
[]
no_license
module FixtureSaver
# Saves the markup to a fixture file using the given name
def save_fixture(markup, name)
fixture_path = File.join(Rails.root, '/tmp/js_dom_fixtures')
Dir.mkdir(fixture_path) unless File.exists?(fixture_path)
fixture_file = File.join(fixture_path, "#{name}.fixture.html")
File.open(fixture_file, 'w') do |file|
file.puts(markup)
end
end
def all_html
response.body
end
# From the controller spec response body, extracts html identified
# by the css selector.
def html_for(selector = 'body')
doc = Nokogiri::HTML(response.body)
prepare_html(doc)
content = doc.css(selector).first.to_s
convert_body_tag_to_div(content)
end
def prepare_html(doc)
set_sources_to_nothing(doc)
remove_third_party_scripts(doc)
remove_iframes(doc)
end
def set_sources_to_nothing(doc)
blank_png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAIAAAA7ljmRAAAAGElEQVQIW2P4DwcMDAxAfBvMAhEQMYgcACEHG8ELxtbPAAAAAElFTkSuQmCC'
images = doc.search('img')
images.each{ |img| img['src'] = blank_png }
images = doc.search('*[style*="background"]')
images.each do |el|
el['style'] = el['style'].gsub(/url\([^\)]*\)/,"url(#{blank_png})")
end
end
def remove_third_party_scripts(doc)
scripts = doc.search('.third_party_script') +
doc.search('script[src]') +
doc.search('script:contains("fbAsyncInit")')
scripts.remove if scripts
end
def remove_iframes(doc)
iframes = doc.search('iframe')
iframes.remove if iframes
end
# Many of our css and jQuery selectors rely on a class attribute we
# normally embed in the <body>. For example:
#
# <body class="workspaces show">
#
# Here we convert the body tag to a div so that we can load it into
# the document running js specs without embedding a <body> within a <body>.
def convert_body_tag_to_div(markup)
markup.gsub("<body", '<div').gsub("</body>", "</div>")
end
end
true
01435bb4522fd104e51e381dbcb4a08d56a75688
Ruby
appwrite/sdk-for-ruby
/lib/appwrite/models/database_list.rb
UTF-8
766
2.515625
3
[
"BSD-3-Clause"
]
permissive
#frozen_string_literal: true
module Appwrite
module Models
class DatabaseList
attr_reader :total
attr_reader :databases
def initialize(
total:,
databases:
)
@total = total
@databases = databases
end
def self.from(map:)
DatabaseList.new(
total: map["total"],
databases: map["databases"].map { |it| Database.from(map: it) }
)
end
def to_map
{
"total": @total,
"databases": @databases.map { |it| it.to_map }
}
end
end
end
end
true
c1aea7d6320a4ceb29aac46cf41026bb7e0fe64d
Ruby
thomgray/trot
/lib/trot/builder.rb
UTF-8
2,399
2.515625
3
[
"MIT"
]
permissive
require 'fileutils'
module Trot
class Builder
def initialize(target)
@target = target
end
def build
puts 'target', @target
object_files = []
source_files_to_compile = []
puts '.>>>>> sources', source_files
source_files.each { |source_file|
file_name = File.basename(source_file, '.c')
object_file = File.join(object_files_directory, "#{file_name}.o")
object_files << object_file
if Make.should_update_target(source_file, object_file)
source_files_to_compile << source_file
end
}
compile_objects(source_files_to_compile)
copy_header_files
link_object_files(object_files)
end
def copy_header_files
puts "copying header files", @target
end
def compile_objects(source_files_to_compile)
$fs.ensure_dir object_files_directory
$compiler.compile(source_files_to_compile, object_files_directory) unless source_files_to_compile.empty?
end
def link_object_files(object_files)
return if object_files.empty?
return unless Make.should_update_target(object_files, target_path)
$fs.ensure_dir target_dir
if is_static_lib?
$compiler.link_static_lib(object_files, target_path)
else
$compiler.link(object_files, target_path)
end
end
private
def is_static_lib?
@is_static_lib ||= @target.is_static_lib
end
def object_files_directory
@object_files_directory ||= File.join($trot_build_dir, @target.is_default ? '' : @target.name, 'objectFiles')
end
def source_files
@source_files ||= Proc.new() {
includes = @target.src[:include]
excludes = @target.src[:exclude] || []
puts '>>>> including', includes
puts '>>>>>> excluding', excludes
src_files = Set.new;
includes.each { |f| src_files += $fs.files_recursive(f) }
excludes.each { |x| src_files -= $fs.files_recursive(x) }
src_files.to_a.select { |f| f =~ /\.c$/ }
}.call
end
def header_files
# @header_files ||= $fs.h_files_recursive(@target[:sourceDir])
end
def target_path
@target_path ||= $fs.absolute_path @target.dest
end
def target_name
@target_name ||= File.basename(target_path)
end
def target_dir
@target_dir ||= File.dirname(target_path)
end
end
end
true
4cc3f8f36afeaa02b71ab20b85ef9751768d79b1
Ruby
codyruby/cursus_thp
/week2/scrapping/lib/dark_trader.rb
UTF-8
2,602
3.71875
4
[]
no_license
# Il est possible de faire le programme en n'allant que sur une seule URL. C'est un bon moyen pour faire un programme rapide car ne chargeant pas 2000 pages HTML.
# Tout se jouera sur la rédaction d'un XPath pertinent et précis qui extrait juste ce qu'il faut d'éléments HTML. Puis un bon traitement de ces éléments pour en extraire les 2 infos dont tu as besoin : le nom des crypto et leur cours.
# Un programme qui scrappe sans rien te dire, c'est non seulement nul mais en plus, tu ne sais pas s'il marche, s'il tourne en boucle ou s’il attend que ton wifi fonctionne. Mets des puts dans ton code pour que ton terminal affiche quelque chose à chaque fois qu'il a pu récupérer une donnée. Comme ça tu vois ton scrappeur qui fonctionne et avec des mots qui apparaissent tout seul sur ton terminal, tu vas donner l'impression que t'es un hacker. Stylaï.
# Pense à bien nommer tes variables pour ne pas te perdre ! Par exemple, quand tu as un array, nomme-le crypto_name_array ou à minima mets son nom au pluriel crypto_nameS. Sinon tu vas oublier que c'est un array et tu vas tenter des .text dessus alors qu'il faut bosser avec un .each.
# Rappel: un hash s’initialise avec result = Hash.new et on y stocke des infos avec result['ta_key'] = 'ta_value'
# N'hésite pas à découper ton programme en plusieurs étapes simples et dont le fonctionnement est facile à vérifier. Par exemple : 1) Isoler les éléments HTML qui vont bien, 2) En extraire le texte et mettre ça dans un hash, 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé.
# Même si ça n'est pas le chemin le plus court, l'essentiel est que chaque petite étape te fasse avancer et qu'à chaque fois tu te dises "ok, étape 1), ça fonctionne nickel - pas de bug. Passons à la suite".
require 'open-uri'
require 'nokogiri'
def crypto_price
doc = Nokogiri::HTML(open("https://coinmarketcap.com/all/views/all/"))
list_crypto_and_price = []
# 1) Isoler les éléments HTML qui vont bien,
# Nom : [:href].split("/")[2]
# Cours : xpath("//a[@class=\"price\"]")
# 2) En extraire le texte et mettre ça dans un hash
doc.xpath("//a[@class=\"price\"]").each do |node|
list_crypto_and_price << {name: node[:href].split("/")[2], price: node.text}
end
# 3) Réorganiser ce hash dans un array de plusieurs mini-hash comme demandé.
crypto_price_view = {}
list_crypto_and_price.each do |value|
crypto_price_view[value[:name]] = value[:price]
end
p crypto_price_view
end
crypto_price
true
739e5d9b68e24eb2e8342b07e288ce2e1bc7d52b
Ruby
lipanski/hexagonly
/lib/hexagonly/polygon.rb
UTF-8
3,210
3.1875
3
[
"MIT"
]
permissive
module Hexagonly
class Polygon
# Adds Polygon methods to an object. The Polygon corners are read via
# the #poly_points method. You can override this method or use the
# #poly_points_method class method to set a method name for reading
# polygon corners.
#
# @example
# class MyPolygon
#
# include Hexagonly::Polygon::Methods
# poly_points_method :corners
#
# attr_reader :corners
# def initialize(corners); @corners = corners; end
#
# end
module Methods
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
attr_accessor :poly_points_method_name
def poly_points_method(points_method)
self.poly_points_method_name = points_method.to_sym
end
end
attr_accessor :collected_points, :rejected_points
def poly_points
raise NoMethodError if self.class.poly_points_method_name.nil?
send(self.class.poly_points_method_name)
end
# Crossing count algorithm for determining whether a point lies within a
# polygon. Ported from http://www.visibone.com/inpoly/inpoly.c.txt
# (original C code by Bob Stein & Craig Yap).
def contains?(point)
raise "Not a valid polygon!" if poly_points.nil? || poly_points.size < 3
is_inside = false
old_p = poly_points.last
poly_points.each do |new_p|
if new_p.x_coord > old_p.x_coord
first_p = old_p
second_p = new_p
else
first_p = new_p
second_p = old_p
end
if ((new_p.x_coord < point.x_coord) == (point.x_coord <= old_p.x_coord)) && ((point.y_coord - first_p.y_coord) * (second_p.x_coord - first_p.x_coord) < (second_p.y_coord - first_p.y_coord) * (point.x_coord - first_p.x_coord))
is_inside = ! is_inside
end
old_p = new_p
end
is_inside
end
# Grabs all points within the polygon boundries from an array of Points
# and appends them to @collected_points. All rejected Points are stored
# under @rejected_points (if you want to pass the to other objects).
#
# @param points [Array<Hexagonly::Point>]
#
# @return [Array<Hexagonly::Point] the grabed points
def grab(points)
parts = points.partition{ |p| contains?(p) }
@collected_points ||= []
@collected_points += parts[0]
@rejected_points = parts[1]
parts[0]
end
attr_accessor :geo_properties
attr_accessor :geo_style
def to_geojson
points = poly_points.map{ |p| [p.x_coord, p.y_coord] }
points << points.last
{
:type => "Feature",
:geometry => {
:type => "Polygon",
:coordinates => [points]
},
:style => geo_style,
:properties => geo_properties
}
end
end
include Methods
attr_accessor :poly_points
# @param [Array<Hexagonly::Point>] poly_points the points that make up the polygon
def initialize(poly_points)
@poly_points = poly_points
end
end
end
true
f57c32cc91e84ca130fe042ad0295673acc1b6da
Ruby
neilkelty/programming-ruby
/chapter_2/arrays_and_hashes.rb
UTF-8
515
3.21875
3
[]
no_license
a = [1, 'cat', 3.14] # array with three elements
puts "The first element is #{a[0]}"
# set the third element
a[2] = nil
puts "The array is now #{a.inspect}"
inst_section = {
'cello' => 'string',
'clarinet' => 'woodwind',
'drum' => 'percussion',
'oboe' => 'woodwind',
'trumpet' => 'brass',
'violin' => 'string'
}
p inst_section['oboe']
p inst_section['cello']
p inst_section['bassoon']
histogram = Hash.new(0)
histogram['ruby'] # => 0
histogram['ruby'] = histogram['ruby'] + 1
histogram['ruby'] # => 1
# Write your code here.
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def badge_maker(name) do
puts "Hello, my name is #{name}"
end
def batch_badge_maker
#attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
attendees.each do |name|
puts "Hello, my name is #{name}"
end
end
def assign_rooms
attendees.each_with_index { |name, index| puts "Hello, #{name}! You'll be assigned to room #{index}!" }
end
true
7eb689f0b6dc4e819e985b029674a4338cbe0a33
Ruby
emielhagen/convoyer
/app/services/location_service.rb
UTF-8
1,582
2.828125
3
[]
no_license
class LocationService
attr_reader :from_location, :to_location, :base_url, :api_key
attr_accessor :params
def initialize(params)
@from_location = params.dig('convoy', 'from_location')
@to_location = params.dig('convoy', 'to_location')
@base_url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'
@api_key = ENV['MAPBOX_API_KEY']
@params = params
end
def create_location_hash
return if from_location.empty? || to_location.empty?
from_id = find_or_create_location(from_location)
to_id = find_or_create_location(to_location)
params = update_params_hash(from_id, to_id)
params
end
def find_or_create_location(location)
db_location = Location.find_by(name: location.capitalize)
return db_location.id if db_location
coordinates = get_mapbox_details(location)
return if coordinates.nil?
new_location = create_new_location(location, coordinates)
new_location.id
end
def update_params_hash(from, to)
params['convoy']['from_location_id'] = from
params['convoy']['to_location_id'] = to
end
def get_mapbox_details(location_name)
response = JSON.parse(HTTParty.get("#{base_url}#{location_name.gsub(/ /, '+')}.json?access_token=#{api_key}"))
return if response.nil? || response.dig('features').empty?
features = response.dig('features')&.first
return if features.empty?
features.dig('geometry', 'coordinates')
end
def create_new_location(name, coordinates)
Location.create(name: name.capitalize, longitude: coordinates[0], latitude: coordinates[1])
end
end
true
ecaff361c4d36023aa63db8598b973fadab76d7a
Ruby
justinsteele/coveragetrends
/lib/coveragetrends.rb
UTF-8
385
2.578125
3
[]
no_license
require './lib/circleci'
require 'csv'
class CoverageTrends
def initialize(username, project)
@username = username
@project = project
end
def run
ci = CircleCI.new(@username, @project)
stats = ci.get_stats
save_stats(stats)
return 1
end
def save_stats(array)
open('output/data.json', 'wb') do |f|
f.puts array.to_json
end
end
end
true
ad303f4648f2f1a6777612cb890b5cad578c9364
Ruby
masayasviel/algorithmAndDataStructure
/OtherContests/zone2021/mainA.rb
UTF-8
124
2.984375
3
[]
no_license
s = gets.chomp
ans = 0
9.times do |i|
tmp = s[i..(i+3)]
if tmp == "ZONe" then
ans += 1
end
end
puts ans
true
8be9ef85d7c0a93338c4b0d7c307096cbf57091f
Ruby
lvzhongwen/pms
/pms-server/app/models/enum/base_type.rb
UTF-8
913
2.9375
3
[]
no_license
class BaseType<BaseClass
def self.method_missing(method_name, *args, &block)
mn=method_name.to_s.sub(/\?/, '')
if /\w+\?/.match(method_name.to_s)
begin
self.const_get(mn.upcase)==args[0].to_i
rescue
super
end
else
super
end
end
class<<self
define_method(:has_value?) { |s| self.constants.map { |c| self.const_get(c.to_s) }.include?(s) }
end
def self.get_type(type)
const_get(type.upcase)
end
def self.display(v)
constant_by_value(v)
end
def self.include_value?(v)
constants.collect{|c|const_get(c.to_s)}.include?(v.to_i)
end
def self.key(v)
constant_by_value(v).downcase
end
def self.to_select
select_options = []
constants.each do |c|
v = const_get(c.to_s)
select_options << SelectOption.new(display: self.display(v), value: v, key: self.key(v))
end
select_options
end
end
true
8d31576108cf12c70df5f17b43b77ba4654f8212
Ruby
broad-well/aoc2016
/day5.rb
UTF-8
815
3.0625
3
[
"Unlicense"
]
permissive
# Day 5 of Advent Of Code, 2016
INPUT = 'ojvtpuvg'
require 'digest'
require 'set'
part2 = ARGV.include? 'part2'
fast = ARGV.include? 'fast'
i = 0
$c = Set.new if part2
pwd = part2 ? '00000000' : ''
loop do
md5 = Digest::MD5.hexdigest INPUT + i.to_s
if !fast && i % 50 == 0 then print "Fresh MD5: #{md5}\r" end
#print "#{INPUT + i.to_s} => #{md5}\r"
if md5.start_with? '00000'
if part2 && md5[5].to_i < 8 && md5[5].to_i.to_s == md5[5] && !$c.include?(md5[5].to_i)
pwd[md5[5].to_i] = md5[6]
puts "\e[2KPassword now: #{pwd}"
if part2 then $c << md5[5].to_i end
else
unless part2
pwd += md5[5]
puts "\e[2KFound one! @ #{i}, md5=#{md5}"
end
end
end
break if part2 ? $c.length == 8 : pwd.length == 8
i+=1
end
puts "\e[1mpassword: #{pwd}\e[0m"
true
67bca19a9af6b558856e1e41533d40e7ebb62ef7
Ruby
kaiks/unobot
/lib/misc.rb
UTF-8
1,188
2.5625
3
[]
no_license
# TODO: separate logger from the rest
# require 'extend_logger.rb'
require 'logger'
$logger = Logger.new('logs/unobot.log', 'daily', 10)
$logger_queue = Queue.new
$logger.datetime_format = '%H:%M:%S'
$logger_thread = Thread.new do
loop do
while $DEBUG == true && $bot && $bot.config.engine.busy == false
$logger.add(Logger::INFO, $logger_queue.pop)
end
sleep(0.5)
end
end
def log(text)
$logger_queue << ('\n' << text)
end
def bot_debug(text, detail = 1)
log(text)
if $DEBUG_LEVEL >= detail
puts "#{detail >= 3 ? '' : caller[0]} #{text}"
end
end
def set_debug(level)
$DEBUG = true
$DEBUG_LEVEL = level.to_i
end
def unset_debug
$DEBUG = false
$DEBUG_LEVEL = 0
end
class Array
# array exists and has nth element (1=array start) not null
def exists_and_has(n)
size >= n && !at(n - 1).nil?
end
def equal_partial?(array)
each_with_index.all? { |a, i| a == :_ || array[i] == :_ || a == array[i] }
end
end
class NilClass
def exists_and_has(_n)
false
end
end
module Misc
NICK_REGEX = /([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]{1,15})'s/i
NICK_REGEX_PURE = /([a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]{1,15})/i
end
true
f058f9161f4811e53e651d66fdcc132612299588
Ruby
pelensky/lrthw
/ex34.rb
UTF-8
471
4.03125
4
[]
no_license
animals = ["bear", "ruby", "peacock", "kangaroo", "whale", "platypus"]
puts "The animal at 1 is ruby"
puts animals[1]
puts "The third animal is peacock"
puts animals[3-1]
puts "The first animal is bear"
puts animals[0]
puts "The animal at 3 is kangaroo"
puts animals[3]
puts "The fifth animal whale"
puts animals[5-1]
puts "The animal at 2 is peacock"
puts animals[2]
puts "The sixth animal is platypus"
puts animals[6-1]
puts "the animal at 4 is whale"
puts animals[4]
true
80878e5d6076dca59107ace39240663a11ee1ac8
Ruby
shumShum/libgdx-tanks
/bin/src/config/sound_storage.rb
UTF-8
451
2.5625
3
[]
no_license
class SoundStorage
SOUND_PATH_BASE = {
fire: 'res/sounds/fire.wav',
damage: 'res/sounds/damage.wav',
explosion: 'res/sounds/explosion1.wav',
}
attr_reader :sound_base
def initialize
@sound_base = {}
SOUND_PATH_BASE.each_pair do |name, path|
@sound_base[name] = Gdx.audio.newSound(Gdx.files.internal(RELATIVE_ROOT + path))
end
end
def get_by_name(sound_name)
@sound_base[sound_name.to_sym]
end
end
true
e0876c35e82f5f6cb841924662bc35f3a818849d
Ruby
alexgh123/ruby_projects
/sorting.rb
UTF-8
395
3.9375
4
[]
no_license
def bubble_sort(array)
n = array.length
p "hey n = #{n}"
loop do
swapped = false
(n-1).times do |i|
p "hey i is changing... it is: #{i}"
p "swapped is: #{swapped}"
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i]
swapped = true
end
end
break if not swapped
end
array
end
p bubble_sort([1,99,20,13,4,566,11])
# A class used to read text files
# Author:: Youssef Benlemlih
# Author:: Jonas Krukenberg
class TextEditor
attr_reader :content
# Initialize a new instance of *TextEditor*
# with String @content
# @param path: The path to the text file
def initialize(path)
File.open(path) { |f| @content = f.read }
end
# Returns an array of each word in @param
def words_to_array
words = @content.split
word_list = []
# filter the words list
words.each do |word|
# replace all upcase characters with downcase ones
w = word.downcase
# remove all non-letters characters
w.gsub!(/\W/, '')
# remove all whitespaces
w.gsub!(/\s+/, '')
# only all non-empty word to the filtered list
word_list.push(w) unless w.empty?
end
@content = word_list
nil
end
# Returns the words list as an array, where each word is inverted
def reverse_words
reversed_word_list = []
@content.each { |word| reversed_word_list.push(word.reverse) }
# return the reversed word list
@content = reversed_word_list
nil
end
# Saves the given wordlist in a file in the given path wit one word per line
def to_file(filepath)
text = @content.join("\n")
File.open(filepath, 'w') { |f| f.write text }
nil
end
# Returns a Hash where:
# * *key* is the word
# * *value* is the occurrence of the usage of the word in the words list
def words_occurrences
# the default value of the occurrence of a word is 0
word_count = Hash.new(0)
@content.each { |word| word_count[word] += 1 }
word_count
end
end
true
6ff71a3aadac96fef685e6c47fb1597b57bd7ab1
Ruby
ranjanisrini/guvi
/compare.rb
UTF-8
79
3.28125
3
[]
no_license
def helo
n = gets.chomp
y = gets.chomp
if (n==y)
true
else
false
end
end
require 'core_extensions'
module MailServer
class IMAP
# Mail::IMAP
#
# Description:
# Wrapper around Net::IMAP
#
require 'net/imap'
attr_accessor :settings, :connection, :query, :authenticated, :messages
attr_reader :access, :folder, :before, :body, :cc, :from, :on, :since, :subject, :to
# Initialize an IMAP object.
#
# Options:
# :address # string, server's address
# :username # string, user mail account to connect with
# :password # string, user password
# :authentication # string, authentication protocol, options {'login', 'cram-md5'}
# :enable_ssl # boolean, default false
#
# Example:
# imap = Mail::IMAP.new(:address => '<mailserver>',:username => '<username>',:password => '<password>',:authentication => 'CRAM-MD5')
#
def initialize(values = {})
self.settings = {
:address => 'localhost',
:port => 143,
:username => nil,
:password => nil,
:authentication => 'LOGIN',
:enable_ssl => false,
:folder => nil,
:access => nil
}.merge!(values)
@authenticated = false
@query = []
end
# Open IMAP session.
#
# Accepts a hash of options.
# Options:
# :folder # string, default 'inbox'
# :access # string, options: {'read-only', 'read-write'}, default 'read-only'
#
# Example:
# imap.open :folder => 'Sent Messages' do |mailbox|
# mailbox.search(['from', 'some user').each do |msg_id|
# puts msg_id
# end
# end
#
def open(args = {:folder => 'INBOX', :access => 'read-only'})
self.settings.merge!(args)
connect
if settings[:access] == 'read-write'
@connection.select(settings[:folder])
else
@connection.examine(settings[:folder])
end
yield(self) if block_given?
end
def connect
@connection ||= Net::IMAP.new(settings[:address])
begin
@connection.authenticate(settings[:authentication],settings[:username],settings[:password]) unless authenticated
@authenticated = true
rescue Net::IMAP::NoResponseError
"Failed to authenticate"
end
at_exit {
begin
disconnect
rescue Exception => e
"Error closing connection: #{e.class}: #{e.message}."
end
}
end
def disconnect
@connection.disconnect
@connection = nil
@authenticated = false
end
def connected?
! connection.nil? && ! connection.disconnected?
end
def access(access = 'read-only')
@access = access
self
end
def folder(folder = 'INBOX')
@folder = folder
end
def before(date = Date.today)
query.push('BEFORE',date.to_imap)
self
end
def body(string)
query.push('BODY',string)
self
end
def cc(string)
query.push('CC',string)
self
end
def from(string)
query.push('FROM',string)
self
end
def update
self
end
def on(date = Date.today)
query.push('ON',date.to_imap)
self
end
def since(date = Date.today - 14)
query.push('SINCE',date.to_imap)
self
end
def subject(string)
query.push('SUBJECT',string)
self
end
def to(string)
query.push('TO',string)
self
end
def search(criteria = nil)
scratch = criteria.nil? ? query.clone : criteria
clear_query
connection.search(scratch)
end
def clear_query
@query = []
end
def fetch(seq_nos = [],attributes = 'BODY')
@messages = connection.fetch(seq_nos,attributes) unless seq_nos.empty?
end
def uid_fetch(arr = [])
end
end
end
true
7ba612ede0baf65d596ecbaa27293ddb047251d9
Ruby
arvidnilber/standard-biblioteket
/lib/power.rb
UTF-8
134
3.1875
3
[]
no_license
def power(num1,up)
i = 0
output = 1
while i < up
output *= num1
i += 1
end
return output
end
true
a1cbb184cdf6a1b80139e28fb575699de359feb1
Ruby
anners/ruby
/reverse-string
UTF-8
360
3.59375
4
[]
no_license
#!/usr/bin/env ruby
string = "beer"
puts string
puts string.reverse
array = ["b", "e", "e", "r"]
array.reverse.each do |a|
print a
end
yarra = Array.new
yarra << array.pop until array.empty?
print yarra
array = ["b", "e", "e", "r"]
def rev(array)
x = array.pop
rev(array) if array.length > 0
array.unshift x
end
puts rev(array).inspect
true
9b053de63a29dde735ff362986c2605dc97703aa
Ruby
alexharv074/puppet-strings
/lib/puppet-strings/yard/util.rb
UTF-8
1,265
2.546875
3
[
"Apache-2.0"
]
permissive
require 'puppet/util'
# The module for various puppet-strings utility helpers.
module PuppetStrings::Yard::Util
# Trims indentation from trailing whitespace and removes ruby literal quotation
# syntax `%Q{}` and `%{q}` from parsed strings.
# @param [String] str The string to scrub.
# @return [String] A scrubbed string.
def self.scrub_string(str)
match = str.match(/^%[Qq]{(.*)}$/m)
if match
return Puppet::Util::Docs.scrub(match[1])
end
Puppet::Util::Docs.scrub(str)
end
# hacksville, usa
# YARD creates ids in the html with with the style of "label-Module+description", where the markdown
# we use in the README involves the GitHub-style, which is #module-description. This takes our GitHub-style
# links and converts them to reference the YARD-style ids.
# @see https://github.com/octokit/octokit.rb/blob/0f13944e8dbb0210d1e266addd3335c6dc9fe36a/yard/default/layout/html/setup.rb#L5-L14
# @param [String] data HTML document to convert
# @return [String] HTML document with links converted
def self.github_to_yard_links(data)
data.scan(/href\=\"\#(.+)\"/).each do |bad_link|
data.gsub!("=\"##{bad_link.first}\"", "=\"#label-#{bad_link.first.capitalize.gsub('-', '+')}\"")
end
data
end
end
true
f4b9571473abeb92a0888911b7929c6e44c8f417
Ruby
asiandcs/baseballbot_discord
/baseball_discord/commands/links.rb
UTF-8
847
2.515625
3
[
"MIT"
]
permissive
# frozen_string_literal: true
module BaseballDiscord
module Commands
# Basic debug commands that should log to the output file
module Links
extend Discordrb::Commands::CommandContainer
command(:bbref, help_available: false) do |event, *args|
LinksCommand.new(event, *args).bbref
end
command(:fangraphs, help_available: false) do |event, *args|
LinksCommand.new(event, *args).fangraphs
end
# Prints some basic info to the log file
class LinksCommand < Command
def bbref
'https://www.baseball-reference.com/search/search.fcgi?search=' +
CGI.escape(args.join(' '))
end
def fangraphs
'https://www.fangraphs.com/players.aspx?new=y&lastname=' +
CGI.escape(args.join(' '))
end
end
end
end
end
true
a1a97dff36f7bc6a6f21e474242bbc46da973d40
Ruby
kmbhuvanprasad/ruby_set4
/modules/1.rb
UTF-8
211
3.390625
3
[]
no_license
module W4
def z1
puts "I am number 1"
end
def z3
puts "I am number 3"
end
def nUMBER_4
puts "I am number 4"
end
end
class Q4
include W4
end
number = Q4.new
number.z1
number.z3
number.nUMBER_4
true
f7f5a843c92857a0a41cdbf62c91496cfb9c7c10
Ruby
anukin/game_of_life-9_07
/spec/gameoflife/board_spec.rb
UTF-8
686
2.671875
3
[]
no_license
require 'spec_helper'
module Gameoflife
describe "Cell" do
it "should generate the next generation" do
board = Board.new(3, 4)
curr_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
nex_gen = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
board.set_current_generation(curr_gen)
expect(board.next_generation).to eq(nex_gen)
end
it "should generate the next generation based on current generation" do
board = Board.new(3, 3)
curr_gen = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
nex_gen = [[0, 1, 0], [0, 1, 1], [1, 0, 0]]
board.set_current_generation(curr_gen)
expect(board.next_generation).to eq(nex_gen)
end
end
end
true
033355d4596a85c44409c9b1a2c837dda5c3c0b3
Ruby
JRSoftware92/Android-Class-Generator
/AXMLGenerator/src/main/android_sqlite_reader.rb
UTF-8
4,269
3.015625
3
[]
no_license
require_relative 'sqlite_reader.rb'
require_relative 'sqlite_model.rb'
#Class for reading DDL and DML SQLite files
#TODO Rewrite to export generic xml data for template generation and utilize generic regex parser
#CAN BE DONE FOR BOTH DDL AND DML
class ASqliteReader# < SqliteParser
include Sqlite
#DDL_REGEX = /[a-zA-Z0-9_]+\({1}(?:[\s\,]*[a-zA-Z]+\s*)+(?:\)\;){1}/
TABLE_REGEX = /(?<name>[a-zA-Z0-9_]+)\({1}(?<parameters>(?:[\s\,]*[a-zA-Z]+\s*)+)(?:\)\;){1}/
def initialize
#super
@select_queries = []
@insert_queries = []
@update_queries = []
@delete_queries = []
@tables = []
end
#Reads in queries
def read_ddl_file(filename)
File.foreach(filename) do |line|
extract_table_from line
end
end
#Reads in queries
def read_dml_file(filename)
File.foreach(filename) do |line|
extract_query_from line
end
end
#Extracts table declarations from the given line and extracts the data as table objects into the local table array
def extract_table_from(line)
matchdata = line.scan(TABLE_REGEX)
matchdata.each do |name, param_str|
parameters = extract_table_parameters_from param_str
table = Sqlite::Table.new(name, parameters)
@tables << table
end
end
#Extracts the table parameters from a given string and outputs them as an array
def extract_table_parameters_from(str)
if str.nil? || str.size < 1 then
return []
end
if !str.include? ',' then
return str
else
return str.split ','
end
end
#Extracts a Sqlite Query object from the sql string
def extract_query_from(line)
#Remove leading and trailing whitespace
temp = line.upcase.strip
#Retrieve the index of the name-query delimiter
index = temp.index(':')
if !index.nil? && index > -1 then
#Function name of the query
name = line[0,index]
#SQLite query
statement = line[index + 1, temp.length]
#Parametric arguments of the query
args = extract_parameters_from statement
if statement.include? 'SELECT' then
@select_queries << Sqlite::Query.new(name, statement, args, 'SELECT')
end
if statement.include? 'INSERT' then
@insert_queries << Sqlite::Query.new(name, statement, args, 'INSERT')
end
if statement.include? 'UPDATE' then
@update_queries << Sqlite::Query.new(name, statement, args, 'UPDATE')
end
if statement.include? 'DELETE' then
@delete_queries << Sqlite::Query.new(name, statement, args, 'DELETE')
end
end
end
def queries
return select_queries + insert_queries + update_queries + delete_queries
end
def select_queries
return @select_queries
end
def select_queries_sql
return objects_to_sql @select_queries
end
def select_queries_xml
return objects_to_xml @select_queries
end
def insert_queries
return @insert_queries
end
def insert_queries_sql
return objects_to_sql @insert_queries
end
def insert_queries_xml
return objects_to_xml @insert_queries
end
def update_queries
return @update_queries
end
def update_queries_sql
return objects_to_sql @update_queries
end
def update_queries_xml
return objects_to_xml @update_queries
end
def delete_queries
return @delete_queries
end
def delete_queries_sql
return objects_to_sql @delete_queries
end
def delete_queries_xml
return objects_to_xml @delete_queries
end
def tables
return @tables
end
def table_statements_sql
return objects_to_sql @tables
end
def table_statements_xml
return objects_to_xml @tables
end
#Converts an array of query objects to an array of sql strings
def objects_to_sql(objects)
if objects.nil? || objects.size < 1 then
return []
end
objects.each do |object|
output << object.to_sql
end
return output
end
#Converts an array of query objects to an array of android xml string resources
def objects_to_xml(objects)
if objects.nil? || objects.size < 1 then
return []
end
output = []
objects.each do |object|
output << object.to_xml
end
return output
end
def print_debug
puts 'Tables: '
temp = @tables
if !temp.nil? then
temp.each do |table|
table.print_debug
end
end
puts 'Queries: '
temp = queries
if !temp.nil? then
temp.each do |query|
query.print_debug
end
end
end
end
# Your code goes here!
class Anagram
@@all=[]
attr_accessor
def initialize(word)
@word = word
@@all << self
end
def self.all
@@all
end
def sort_word(word)
word.chars.sort!.to_s
end
def match(anagram)
anagram.each.select{ |word| sort_word(word) == sort_word(@word) }
end
end
true
326e7c03b5c2b4c9ecdd6aacc7bf20329cc18896
Ruby
xababafr/RubyPFE
/implementation/resl_compiler.rb
UTF-8
2,976
3.015625
3
[
"MIT"
]
permissive
# the compiler takes ruby code as an input, and can :
# - add probes
# - generate the ast
# - simulate the code to infer types
# - do all those 3 and create a systemC code
require "./resl_data"
require "./resl_objects"
require "./resl_objectifier"
require "./resl_dsl"
require "./resl_simulator"
require "./visitors/systemc"
require "./visitors/prettyprinter"
require "./visitors/addprobes"
module RubyESL
class Compiler
def initialize
end
def get_ast filename, convert = false
objectifier = Objectifier.new filename, convert
ret = objectifier.methods_objects
ret[:sys] = objectifier.sys_ast
puts "\n\n"
pp ret[[:Sourcer,:source]]
ret
# .methods_ast would give the original non objectified ast
end
def add_probes filename
add_probes = AddProbes.new filename
add_probes.generate_file
end
def eval_dsl filename
rcode=IO.read(filename)
eval(rcode)
end
def deep_copy(o)
Marshal.load(Marshal.dump(o))
end
def simulate sys
sys.ordered_actors.each do |actor|
actor_threads = Actor.get_threads[actor.class.get_klass()]
actor_threads.each do |thread|
fiber = Fiber.new do
actor.method(thread).call
end
DATA.simulator.add_fiber("#{actor.class.get_klass}.#{thread}" , fiber)
end
end
DATA.simulator.run
end
def get_init_params sys
initParams = {}
sys.ordered_actors.each do |actor|
key = [actor.class.get_klass(), actor.name]
initParams[key] = actor.method(:initialize).parameters
if actor.initArgs.size > 0
actor.initArgs.each_with_index do |argHash, i|
initParams[key][i+1] << argHash
end
end
end
initParams
end
def generate_systemc filename
puts "\n\n\n"
puts "[STEP 1 : GET INPUT'S CODE AST]".center(80,"=")
puts "\n\n\n"
ast = get_ast filename
s_ast = get_ast filename, true
puts "\n\n\n"
puts "[STEP 2 :ADD PROBES TO THE CODE]".center(80,"=")
puts "\n\n\n"
root = Root.new ast, {}, Actor.get_threads() # + it collects the data from DATA
root.accept AddProbes.new
File.open("P_#{filename}",'w'){|f| f.puts(root.sourceCode)}
sys = eval_dsl ( "P_" + filename )
puts "\n\n\n"
puts "[STEP 3 : SIMULATE THE CODE TO INFER TYPES]".center(80,"=")
puts "\n\n\n"
simulate sys
puts "\n\n"
pp DATA.instance_vars
puts "\n\n"
pp DATA.local_vars
puts "\n\n"
initParams = get_init_params sys
puts "\n\n\n"
puts "[STEP 4 : GENERATE THE SYSTEMC CODE]".center(80,"=")
puts "\n\n\n"
root = Root.new s_ast, initParams, Actor.get_threads()
root.accept SystemC.new
end
end #Compiler
end #MTS
if $PROGRAM_NAME == __FILE__
compiler = RubyESL::Compiler.new
compiler.generate_systemc "#{ARGV[0]}"
end
true
f8f56633de925adf7bf5615ee7191495e5b55e43
Ruby
viing937/codeforces
/src/400B.rb
UTF-8
223
2.953125
3
[
"MIT"
]
permissive
n, m = gets.split.collect{|i| i.to_i}
ans = Array.new(n)
n.times do |i|
s = gets.chomp
d = s.index("G")
c = s.index("S")
if d > c
puts -1
exit
end
ans[i] = c-d
end
puts ans.uniq.size
true
f6531a107f9053c1e75a359c8917322bf5c90a82
Ruby
somalipirat3/GameTracker
/lib/modules/consume_api/tracker_data_only.rb
UTF-8
1,615
2.640625
3
[]
no_license
# Tracker.gg api
# Full profile requests
class ConsumeApi::TrackerDataOnly
include HTTParty
def initialize(options = {})
@data = options
@api_key = Rails.application.credentials.api_keys[:tracker_gg][:key]
endpoint = Rails.application.credentials.api_keys[:tracker_gg][:endpoint]
@endpoint = "#{endpoint}apex/standard/profile/#{@data[:platform]}/#{@data[:username]}"
@response = self.class.get(@endpoint, headers: {"TRN-Api-Key": @api_key})
end
def player
return @response['data']['platformInfo']
end
def segments
segments = []
@response['data']['segments'].each do |segment|
if segment['type'] == "legend"
segments << {
legendName: legend(segment),
stat: stats(segment)
}
end
end
return segments
end
private
def stats(stats)
new_stats = []
stats['stats'].each do |stat|
new_stats.push({
rank: stat[1]['rank'],
percentile: stat[1]['percentile'],
displayName: stat[1]['displayName'],
displayCategory: stat[1]['displayCategory'],
category: stat[1]['category'],
metadata: stat[1]['metadata'],
value: stat[1]['value'],
displayValue: stat[1]['displayValue'],
displayType: stat[1]['displayType']
})
end
return new_stats
end
def legend (segment)
segment['metadata']['name']
end
end
true
738af5499acde1463b603abd941ef9d77787dd23
Ruby
omajul85/oystercard
/spec/journey_spec.rb
UTF-8
991
2.65625
3
[]
no_license
require "journey"
describe Journey do
subject(:journey) { described_class.new }
let(:station) { double :station, zone: 1 }
it "journey should not be completed" do
expect(journey).not_to be_completed
end
it 'has a penalty fare by default' do
expect(subject.fare).to eq described_class::PENALTY_FEE
end
context "given an entry station" do
before do
journey.start(station)
end
it "has an entry station" do
expect(journey.entry_station).to eq station
end
it "returns a penalty fee if no exit station given" do
expect(journey.fare).to eq described_class::PENALTY_FEE
end
context "and an exit station" do
let(:exit_station) { double :station, zone: 1 }
before do
journey.finish(exit_station)
end
it "calculates a fare" do
expect(journey.fare).to eq described_class::MINIMUM_FARE
end
it "knows if a journey is completed" do
expect(journey).to be_completed
end
end
end
end
true
f6622987eefcd67dfc0fb13290b667f403aa48ab
Ruby
tetetratra/contest
/leetcode/6_16/3.rb
UTF-8
237
3.328125
3
[]
no_license
# https://leetcode.com/problems/rotate-function/
def max_rotate_function(nums)
nums.size.times.map { |n| nums.rotate(n) }.map { |arr|
arr.map.with_index { |a, i| a * i }.sum
}.max
end
nums = [4,3,2,6]
max_rotate_function(nums)
true
2e23550093914cb6290721de13f2f996a0c514cd
Ruby
milesstanfield/whats-for-lunch
/spec/services/time_formatter_spec.rb
UTF-8
646
2.5625
3
[]
no_license
require 'spec_helper'
describe TimeFormatter do
describe '.visit_time(time)' do
it 'formats time' do
expect(TimeFormatter.visit_time(now_time)).to eq '02/09/2016'
end
end
describe '.days_ago(formatted_time)' do
it 'returns days since time argument' do
control_time = Time.parse('2016-02-11 08:53:34 -0500')
expect(TimeFormatter.days_ago('02/05/2016', control_time)).to eq 6
end
end
describe '.parsed_visit_time(visited_time)' do
it 'returns time object from strftime string' do
expect(TimeFormatter.parsed_visit_time('02/05/2016').to_s).to eq '2016-02-05 00:00:00 -0500'
end
end
end
true
713714e42caa50fe0c0d22b1e6661582214e88a1
Ruby
Bielfla27/gerenciamento-servicos
/test/models/usuario_test.rb
UTF-8
1,502
2.625
3
[]
no_license
require "test_helper"
class UsuarioTest < ActiveSupport::TestCase
test "deve salvar Usuario criado corretamente" do
usuario = Usuario.new nome: 'Usuario Teste',
cpf: '39775387485',
funcao: 'Confeiteiro',
password: 'password1'
assert usuario.save
end
test "nao deve salvar Usuario com password menor que 8 caracteres" do
usuario = Usuario.new nome: 'Usuario Teste',
cpf: '39775387485',
funcao: 'Confeiteiro',
password: 'passw'
assert_not usuario.save
end
test "nao deve salvar Usuario criado com cpf com letras" do
usuario = Usuario.new nome: 'Usuario Teste',
cpf: 'sda397753aa',
funcao: 'Confeiteiro',
password: 'password01'
assert_not usuario.save
end
#terceira iteração---------------------------------------------
test "nao deve salvar Usuario criado com cpf invalido" do
usuario = Usuario.new nome: 'Usuario Teste',
cpf: '00000000000',
funcao: 'Confeiteiro',
password: 'password01'
assert_not usuario.save
end
test "nao deve salvar Usuario sem funcao" do
usuario = Usuario.new nome: 'Usuario Teste',
cpf: '39775387485',
funcao: '',
password: 'password01'
assert_not usuario.save
end
test "nao deve salvar Usuario com nome maior que 35 caracteres" do
usuario = Usuario.new nome: 'Maria Raphaela Gonzaga da Rocha e Silva',
cpf: '39775387485',
funcao: 'Vendedora',
password: 'password01'
assert_not usuario.save
end
end
class User
attr_reader :name
@@all = []
def self.all
@@all
end
def initialize(name)
@name = name
@@all << self
end
def make_pledge(project, amount)
Pledge.new(self, project, amount)
end
def make_project(project_name, goal_amount)
Project.new(project_name, self, goal_amount)
end
def pledges
Pledge.all.select {|pledge| pledge.user == self}
end
def pledges_count
pledges.count
end
def projects_made
Pledge.all.select {|pledge| pledge.project.created_by == self}
end
def projects_made_count
Pledge.all.select {|pledge| pledge.project.created_by == self}.count
end
def self.all_pledge_amounts_sort
highest = Pledge.all.map {|pledge| pledge.amount}.sort!
highest.last
end
def self.highest_pledge
Pledge.all.find {|pledge| pledge.amount == all_pledge_amounts_sort}.user.name
end
def self.pledger_names
Pledge.all.map {|pledge| pledge.user.name}
end
def self.multi_pledger
# returns all users who have pledged to multiple projects
@@all.select {|user_instance| user_instance.pledges_count > 1}
end
def self.project_creator
@@all.select{|user_instance| user_instance.projects_made_count > 0}
#returns all users who have created a project
end
end
true
0173a501f107144afd808149940aa2f7d2d113f8
Ruby
bethanyr/RubyFall2013
/week4/exercises/timer_spec.rb
UTF-8
663
2.96875
3
[
"Apache-2.0"
]
permissive
require './code_timer.rb'
describe CodeTimer do
it "should run our code" do
flag = false
CodeTimer.time_code do
flag = true
end
flag.should eq true
end
it "should time our code" do
Time.stub(:now).and_return(0,3)
run_time = CodeTimer.time_code do
end
run_time.should be_within(0.1).of(3.0)
end
it "should run our code multiple times " do
i = 0
CodeTimer.time_code(10){ i+=1 }
i.should eq 10
end
it "should give us the average time" do
Time.stub(:now).and_return(0,10)
run_time = CodeTimer.time_code(10) {
}
run_time.should be_within(0.1).of(1.0)
end
end
# Create the files that PSL will use.
# Processing:
# - Copy over the id mapping files (not necessary, but convenient).
# - Convert all ids in triple files from string identifiers to int identifiers.
# - List out all the possible targets (test triples and their corruptions).
# - Compute and output all the energy of all triples (targets).
#
# To save space (since there are typically > 400M targets), we will only write out energies
# that are less than some threshold.
# To signify an energy value that should not be included, the respective tripleEnergy() methods
# will return first return a value of false and then the actual energy value.
# We still return the actual energy so we can log it for later statistics.
#
# We make no strides to be overly efficient here, just keeping it simple.
# We will check to see if a file exists before creating it and skip that step.
# If you want a full re-run, just delete the offending directory.
require_relative '../../lib/constants'
require_relative '../../lib/embedding/energies'
require_relative '../../lib/embedding/load'
require_relative '../../lib/load'
require 'etc'
require 'fileutils'
require 'set'
# gem install thread
require 'thread/channel'
require 'thread/pool'
NUM_THREADS = Etc.nprocessors - 1
SKIP_BAD_ENERGY = false
MIN_WORK_PER_THREAD = 50
WORK_DONE_MSG = '__DONE__'
TARGETS_FILE = 'targets.txt'
ENERGY_FILE = 'energies.txt'
ENERGY_STATS_FILE = 'energyStats.txt'
def copyMappings(datasetDir, outDir)
if (!File.exists?(File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME)))
FileUtils.cp(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME), File.join(outDir, Constants::RAW_ENTITY_MAPPING_FILENAME))
end
if (!File.exists?(File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME)))
FileUtils.cp(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME), File.join(outDir, Constants::RAW_RELATION_MAPPING_FILENAME))
end
end
def loadIdTriples(path)
triples = []
File.open(path, 'r'){|file|
file.each{|line|
triples << line.split("\t").map{|part| part.strip().to_i()}
}
}
return triples
end
def convertIdFile(inPath, outPath, entityMapping, relationMapping)
if (File.exists?(outPath))
return
end
triples = []
File.open(inPath, 'r'){|file|
file.each{|line|
parts = line.split("\t").map{|part| part.strip()}
parts[Constants::HEAD] = entityMapping[parts[Constants::HEAD]]
parts[Constants::RELATION] = relationMapping[parts[Constants::RELATION]]
parts[Constants::TAIL] = entityMapping[parts[Constants::TAIL]]
triples << parts
}
}
File.open(outPath, 'w'){|file|
file.puts(triples.map{|triple| triple.join("\t")}.join("\n"))
}
end
def convertIds(datasetDir, outDir, entityMapping, relationMapping)
convertIdFile(File.join(datasetDir, Constants::RAW_TEST_FILENAME), File.join(outDir, Constants::RAW_TEST_FILENAME), entityMapping, relationMapping)
convertIdFile(File.join(datasetDir, Constants::RAW_TRAIN_FILENAME), File.join(outDir, Constants::RAW_TRAIN_FILENAME), entityMapping, relationMapping)
convertIdFile(File.join(datasetDir, Constants::RAW_VALID_FILENAME), File.join(outDir, Constants::RAW_VALID_FILENAME), entityMapping, relationMapping)
end
# Generate each target and compute the energy for each target.
# We do target generation and energy computation in the same step so we do not urite
# targets that have too high energy.
def computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping)
if (File.exists?(File.join(outDir, ENERGY_FILE)))
return
end
targetsOutFile = File.open(File.join(outDir, TARGETS_FILE), 'w')
energyOutFile = File.open(File.join(outDir, ENERGY_FILE), 'w')
entityEmbeddings, relationEmbeddings = LoadEmbedding.vectors(embeddingDir)
targets = loadIdTriples(File.join(outDir, Constants::RAW_TEST_FILENAME))
# The number of corruptions written to disk.
# We need to keep track so we can assign surrogate keys.
targetsWritten = 0
# All the corruptions we have seen for a specific relation.
# This is to avoid recomputation.
# This will hold the cantor pairing of the head and tail.
seenCorruptions = Set.new()
# To reduce memory consumption, we will only look at one relation at a time.
relations = targets.map{|target| target[Constants::RELATION]}.uniq()
# The entities (and relations) have already been assigned surrogate keys that start at 0 and have
# no holes.
# So, instead of looking at actual entities, we can just start and zero and count up.
numEntities = entityMapping.size()
# [[id, energy], ...]
energies = []
corruptions = []
# We will keep track of all the calculated energies so that we can analyze it later.
# {energy.round(2) => count, ...}
energyHistogram = Hash.new{|hash, key| hash[key] = 0}
relations.each_index{|relationIndex|
relation = relations[relationIndex]
seenCorruptions.clear()
seenCorruptions = Set.new()
GC.start()
# Only triples that are using the current relation.
validTargets = targets.select(){|target| target[Constants::RELATION] == relation}
validTargets.each{|target|
# These are already cleared, but I want to make it explicit that we
# are batching every valid target.
energies.clear()
corruptions.clear()
# Corrupt the head and tail for each triple.
[Constants::HEAD, Constants::TAIL].each{|corruptionTarget|
for i in 0...numEntities
if (corruptionTarget == Constants::HEAD)
head = i
tail = target[Constants::TAIL]
else
head = target[Constants::HEAD]
tail = i
end
id = MathUtils.cantorPairing(head, tail)
if (seenCorruptions.include?(id))
next
end
seenCorruptions << id
corruption = Array.new(3, 0)
corruption[Constants::HEAD] = head
corruption[Constants::TAIL] = tail
corruption[Constants::RELATION] = relation
corruptions << corruption
end
}
energies = Energies.computeEnergies(
corruptions,
nil, nil,
entityEmbeddings, relationEmbeddings, energyMethod,
false, true
)
corruptions.clear()
# Log all the energies in the histogram.
energies.values().each{|energy|
energyHistogram[energy.round(2)] += 1
}
# Remove all energies over the threshold.
energies.delete_if{|id, energy|
energy > maxEnergy
}
# Right now the energies are in a map with string key, turn into a list with a surrogate key.
# [[index, [head, tail, relation], energy], ...]
# No need to convert the keys to ints now, since we will just write them out.
energies = energies.to_a().each_with_index().map{|mapEntry, index|
head, tail = mapEntry[0].split(':')
[index + targetsWritten, [head, tail, relation], mapEntry[1]]
}
targetsWritten += energies.size()
if (energies.size() > 0)
targetsOutFile.puts(energies.map{|energy| "#{energy[0]}\t#{energy[1].join("\t")}"}.join("\n"))
energyOutFile.puts(energies.map{|energy| "#{energy[0]}\t#{energy[2]}"}.join("\n"))
end
energies.clear()
}
}
energyOutFile.close()
targetsOutFile.close()
writeEnergyStats(energyHistogram, outDir)
end
def writeEnergyStats(energyHistogram, outDir)
tripleCount = energyHistogram.values().reduce(0, :+)
mean = energyHistogram.each_pair().map{|energy, count| energy * count}.reduce(0, :+) / tripleCount.to_f()
variance = energyHistogram.each_pair().map{|energy, count| count * ((energy - mean) ** 2)}.reduce(0, :+) / tripleCount.to_f()
stdDev = Math.sqrt(variance)
min = energyHistogram.keys().min()
max = energyHistogram.keys().max()
range = max - min
# Keep track of the counts in each quartile.
quartileCounts = [0, 0, 0, 0]
energyHistogram.each_pair().each{|energy, count|
# The small subtraction is to offset the max.
quartile = (((energy - min - 0.0000001).to_f() / range) * 100).to_i() / 25
quartileCounts[quartile] += count
}
# Calculate the median.
# HACK(eriq): This is slighty off if there is an even number of triples and the
# two median values are on a break, but it is not worth the extra effort.
median = -1
totalCount = 0
energyHistogram.each_pair().sort().each{|energy, count|
totalCount += count
if (totalCount >= (tripleCount / 2))
median = energy
break
end
}
File.open(File.join(outDir, ENERGY_STATS_FILE), 'w'){|file|
file.puts "Num Triples: #{energyHistogram.size()}"
file.puts "Num Unique Energies: #{tripleCount}"
file.puts "Min Energy: #{energyHistogram.keys().min()}"
file.puts "Max Energy: #{energyHistogram.keys().max()}"
file.puts "Quartile Counts: #{quartileCounts}"
file.puts "Quartile Percentages: #{quartileCounts.map{|count| (count / tripleCount.to_f()).round(2)}}"
file.puts "Mean Energy: #{mean}"
file.puts "Median Energy: #{median}"
file.puts "Energy Variance: #{variance}"
file.puts "Energy StdDev: #{stdDev}"
file.puts "---"
file.puts energyHistogram.each_pair().sort().map{|pair| pair.join("\t")}.join("\n")
}
end
def parseArgs(args)
embeddingDir = nil
outDir = nil
datasetDir = nil
embeddingMethod = nil
distanceType = nil
if (args.size() < 1 || args.size() > 5 || args.map{|arg| arg.downcase().gsub('-', '')}.include?('help'))
puts "USAGE: ruby #{$0} embedding dir [output dir [dataset dir [embedding method [distance type]]]]"
puts "Defaults:"
puts " output dir = inferred"
puts " dataset dir = inferred"
puts " embedding method = inferred"
puts " distance type = inferred"
puts ""
puts "All the inferred aguments relies on the emebedding directory"
puts "being formatted by the scripts/embeddings/computeEmbeddings.rb script."
puts "The directory that the inferred output directory will be put in is: #{Constants::PSL_DATA_PATH}."
exit(2)
end
if (args.size() > 0)
embeddingDir = args[0]
end
if (args.size() > 1)
outDir = args[1]
else
outDir = File.join(Constants::PSL_DATA_PATH, File.basename(embeddingDir))
end
if (args.size() > 2)
datasetDir = args[2]
else
dataset = File.basename(embeddingDir).match(/^[^_]+_(\S+)_\[size:/)[1]
datasetDir = File.join(Constants::RAW_DATA_PATH, File.join(dataset))
end
if (args.size() > 3)
embeddingMethod = args[3]
else
embeddingMethod = File.basename(embeddingDir).match(/^([^_]+)_/)[1]
end
if (args.size() > 4)
distanceType = args[4]
else
# TODO(eriq): This may be a little off for TransR.
if (embeddingDir.include?("distance:#{Distance::L1_ID_INT}"))
distanceType = Distance::L1_ID_STRING
elsif (embeddingDir.include?("distance:#{Distance::L2_ID_INT}"))
distanceType = Distance::L2_ID_STRING
end
end
energyMethod = Energies.getEnergyMethod(embeddingMethod, distanceType, embeddingDir)
maxEnergy = Energies.getMaxEnergy(embeddingMethod, distanceType, embeddingDir)
return datasetDir, embeddingDir, outDir, energyMethod, maxEnergy
end
def prepForPSL(args)
datasetDir, embeddingDir, outDir, energyMethod, maxEnergy = parseArgs(args)
FileUtils.mkdir_p(outDir)
entityMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_ENTITY_MAPPING_FILENAME))
relationMapping = Load.idMapping(File.join(datasetDir, Constants::RAW_RELATION_MAPPING_FILENAME))
copyMappings(datasetDir, outDir)
convertIds(datasetDir, outDir, entityMapping, relationMapping)
computeTargetEnergies(datasetDir, embeddingDir, outDir, energyMethod, maxEnergy, entityMapping, relationMapping)
end
if (__FILE__ == $0)
prepForPSL(ARGV)
end
true
1b8ef115b9d9f9894628ddf6d8c4866acfaf962c
Ruby
mcruger/HW2office_directory
/s3uploadfile.rb
UTF-8
823
2.703125
3
[]
no_license
require File.expand_path(File.dirname(__FILE__) + '/proj_config')
(bucket_name, file_name) = ARGV
unless bucket_name
puts "Usage: s3uploadfile.rb <BUCKET_NAME> <FILE_NAME>"
exit 1
end
# get an instance of the S3 interface using the default configuration
s3 = AWS::S3.new
#init bucket object
bucket = s3.buckets[bucket_name]
#check if file exists
if !File.exist?(file_name)
puts "File '#{file_name}' does not exist. Please correct file path."
else
if bucket.exists?
# upload a file
basename = File.basename(file_name)
o = bucket.objects[basename]
o.write(:file => file_name)
puts "Uploaded #{file_name} to:"
puts o.public_url
#generate a presigned URL
puts "\nURL to download the file:"
puts o.url_for(:read)
else
puts "Bucket '#{bucket_name}' does not exist. Cannot upload file."
end
end
# @param {Integer[]} nums
# @return {Integer[]}
def find_disappeared_numbers(nums)
obj = nums.to_h{|c| [c,0]}
result = []
i = 1
nums.length.times do
result.push(i) if !obj[i]
i += 1
end
result
end
true
8eab21a69b5bba49a4119a1f166d04ee77a40ef8
Ruby
mesh1nek0x0/resolve-yukicoder
/no296/snooze.rb
UTF-8
210
3.046875
3
[]
no_license
#!/bin/ruby
input = gets.chomp.split(' ')
N = input[0].to_i
H = input[1].to_i
M = input[2].to_i
T = input[3].to_i
add_minutes = T * (N - 1)
tmp = M + add_minutes + (H * 60)
puts tmp / 60 % 24
puts tmp % 60
true
27b96c25fe9cc8806ed47ae8464bc1e60effa58d
Ruby
hanami/view
/spec/integration/helpers_spec.rb
UTF-8
1,543
2.640625
3
[
"MIT"
]
permissive
# frozen_string_literal: true
RSpec.describe "helpers" do
let(:dir) { make_tmp_directory }
describe "in templates" do
before do
with_directory(dir) do
write "template.html.erb", <<~ERB
<%= format_number(number) %>
ERB
end
end
let(:view) {
dir = self.dir
scope_class = self.scope_class
Class.new(Hanami::View) do
config.paths = dir
config.template = "template"
config.scope_class = scope_class
expose :number
end.new
}
let(:scope_class) {
Class.new(Hanami::View::Scope) {
include Hanami::View::Helpers::NumberFormattingHelper
}
}
specify do
expect(view.(number: 12_300).to_s.strip).to eq "12,300"
end
end
describe "in parts" do
before do
with_directory(dir) do
write "template.html.erb", <<~ERB
<%= city.population_text %>
ERB
end
end
let(:part_class) {
Class.new(Hanami::View::Part) {
include Hanami::View::Helpers::NumberFormattingHelper
def population_text
format_number(population)
end
}
}
let(:view) {
dir = self.dir
part_class = self.part_class
Class.new(Hanami::View) {
config.paths = dir
config.template = "template"
expose :city, as: part_class
}.new
}
specify do
canberra = Struct.new(:population).new(463_000)
expect(view.(city: canberra).to_s.strip).to eq "463,000"
end
end
end
true
237d01e22dc69e0e5524e10205aaeefd341595fc
Ruby
MrRogerino/dbc-whiteboarding
/August_9/example_solutions/two_sum.rb
UTF-8
602
3.421875
3
[
"MIT"
]
permissive
def two_sum(array, target) #returns true or false
map = {}
i = 0
while i < array.length
difference = target - array[i]
if map[difference]
return true
end
map[array[i]] = 1
i += 1
end
return false
end
def two_sum_positions(array, target) #returns the position of the two numbers
map = {}
found = false
i = 0
while i < array.length
difference = target - array[i]
if map[difference]
position1 = array.find_index(difference)
position2 = i
return [position1, position2]
end
map[array[i]] = 1
i += 1
end
return false
end
true
2cf0ee197dbe7397b073e444bab51ca96641a5cd
Ruby
svallero/vaf-storage
/bin/af-create-deps.rb
UTF-8
3,669
2.9375
3
[]
no_license
#!/usr/bin/ruby
#
# af-create-deps.rb -- by Dario Berzano <[email protected]>
#
# Creates the dependency file for AliRoot versions. The following environment
# variables are needed:
#
# AF_DEP_URL => HTTP URL containing the list of AliEn packages for ALICE
# AF_DEP_FILE => destination file on the local filesystem
# AF_PACK_DIR => local AliEn Packman repository
#
require 'net/http'
require 'pp'
require 'optparse'
def get_ali_packages(url, pack_dir)
if (url.kind_of?(URI::HTTP) === false)
raise URI::InvalidURIError.new('Invalid URL: only http URLs are supported')
end
packages = []
Net::HTTP.start(url.host, url.port) do |http|
http.request_get(url.request_uri) do |resp|
# Generic HTTP error
if (resp.code.to_i != 200)
raise Exception.new("Invalid HTTP response: #{resp.code}")
return false
end
resp.body.split("\n").each do |line|
# 0=>pkg.tar.gz, 1=>type, 2=>rev, 3=>platf, 4=>name, 5=>deps
ary = line.split(" ")
# Consider only AliRoot packages
next unless (ary[1] == 'AliRoot')
# Get the VO name (like VO_ALICE, for instance)
vo_name = ary[4].split('@').first
# Check integrity of line format
deps = ary[5].split(',')
dep_root = nil
dep_geant3 = nil
deps.each do |d|
if (d.include?('@ROOT::'))
dep_root = d
elsif (d.include?('@GEANT3'))
dep_geant3 = d
end
end
next unless (dep_root && dep_geant3)
# Check if package is installed for real
if (pack_dir &&
!File.exists?("#{pack_dir}/#{vo_name}/AliRoot/#{ary[2]}/#{ary[2]}"))
next
end
# Push package hash
packages << {
:aliroot => ary[4],
:root => dep_root,
:geant3 => dep_geant3,
}
end # |line|
end # |resp|
end # |http|
return packages
end
def main
# Check if envvars are set
begin
dep_url = URI(ENV['AF_DEP_URL'])
rescue URI::InvalidURIError => e
warn 'Environment variable AF_DEP_URL should be set to a valid URL'
exit 3
end
if ((dep_file = ENV['AF_DEP_FILE']) == nil)
warn 'Environment variable AF_DEP_FILE should be set to a local filename'
exit 3
end
if ((pack_dir = ENV['AF_PACK_DIR']) == nil)
warn 'Environment variable AF_PACK_DIR should be set to a local directory'
exit 3
end
# Options
opts = {
:checkexists => true,
}
# Define and parse options
OptionParser.new do |op|
op.on('-h', '--help', 'shows usage') do
puts op
exit 4
end
op.on('-c', '--[no-]check-exists',
"include only installed packages (default: #{opts[:checkexists]})") do |v|
opts[:checkexists] = v
end
# Custom banner
prog = File.basename($0)
op.banner = "#{prog} -- by Dario Berzano <[email protected]>\n" +
"Creates a dependency file for AliRoot packages\n\n" +
"Usage: #{prog} [options]"
begin
op.parse!
rescue OptionParser::ParseError => e
warn "#{prog}: arguments error: #{e.message}"
exit 5
end
end
begin
packages = get_ali_packages(dep_url, opts[:checkexists] ? pack_dir : nil)
begin
File.open(dep_file, 'w') do |f|
packages.each do |pack|
f << pack[:aliroot] << '|' << pack[:root] << '|' <<
pack[:geant3] << "\n"
end
end
rescue Exception => e
warn "Can not write #{dep_file}: #{e.message}"
exit 2
end
rescue Exception => e
warn "Error fetching dependencies: #{e.message}"
exit 1
end
warn "#{dep_file} written"
exit 0
end
#
# Entry point
#
main
true
73fec8add9f7fc3b3f90d635deeab38f8f8ce2fb
Ruby
plapicola/enigma
/test/key_test.rb
UTF-8
954
2.859375
3
[]
no_license
require_relative 'test_helper'
class KeyTest < Minitest::Test
def setup
@key = Key.new("02715")
end
def test_it_exists
# skip
assert_instance_of Key, @key
end
def test_it_can_return_the_key_as_a_string
# skip
assert_equal "02715", @key.key
end
def test_it_can_generate_a_random_key
# skip
random_key = Key.random
assert_instance_of Key, random_key
assert_equal 5, random_key.key.length
end
def test_it_can_return_the_next_sequential_key
# skip
assert_equal "02716", @key.next_key
assert_equal "02717", @key.next_key
end
def test_it_can_return_the_array_of_keys
# skip
assert_equal [2, 27, 71, 15], @key.parse_keys
end
def test_it_can_generate_date_offsets
# skip
assert_equal [1, 0, 2, 5], @key.generate_offsets("040895")
end
def test_it_can_return_shifts_if_given_a_date
# skip
assert_equal [3, 27, 73, 20], @key.shifts("040895")
end
end
true
c84950ef5553d61ae6abaac695b46429810d6e38
Ruby
pshussain/Backup
/unlock.rb
UTF-8
541
2.640625
3
[]
no_license
require 'time'
for i in 0..100 do
puts i.to_s
start_time=Time.now
(file = File.new('shared_file','r')).flock(File::LOCK_EX)
end_time=Time.now
diff=end_time-start_time
puts diff
lines = file.readlines
#if(lines[0]!="line1\\n")
puts lines
if lines != nil and lines != "" and !lines.empty?
puts lines.inspect
for i in 0..10
puts "Read Mode :: Data is #{lines[0]}"
end
end
sleep(ARGV[0].to_i)
#exit
#end
file.flock(File::LOCK_UN)
file.close
end
true
236c175cc2d7245974204337cb1a9c0ae341dd2f
Ruby
amosjyng/UAS-Website
/app/models/event.rb
UTF-8
1,944
2.890625
3
[]
no_license
class Event < ActiveRecord::Base
attr_accessible :content, :time, :title, :date, :day_time
validates :title, :date, :day_time, :content, :presence => true
validates :content, :length => {:minimum => 5}
validate :date_valid
validate :time_valid
def date
if time.nil?
return Time.now.strftime('%m/%d/%Y')
else
time.strftime('%m/%d/%Y')
end
end
def date=(day)
begin
current_time = Time.now.to_datetime
unless time.nil?
current_time = time
end
d = Date.strptime(day, '%m/%d/%Y')
self.time = DateTime.new(d.year, d.month, d.day, current_time.hour,
current_time.min, current_time.sec,
current_time.zone).strftime '%Y-%m-%d %H:%M'
@date_success = true
rescue
@date_success = false
end
end
def day_time
if time.nil?
return Time.now.beginning_of_hour.strftime('%I:%M %p')
else
return time.strftime('%I:%M %p')
end
end
def day_time=(dt)
begin
current_time = Time.now.to_datetime
unless time.nil?
current_time = time
end
t = DateTime.strptime(current_time.strftime('%Y %m %d ') + dt, '%Y %m %d %I:%M %p')
self.time = DateTime.new(current_time.year, current_time.month,
current_time.day, t.hour, t.min, 0,
current_time.zone).strftime '%Y-%m-%d %H:%M'
@time_success = true
rescue
@time_success = false
end
end
def summary
max_length = 300
if content.length > max_length
return content[0..max_length] + '...'
else
return content
end
end
def human_time
time.strftime('%A, %B %e at %l:%M %p')
end
private
def date_valid
errors.add(:date, 'format not valid!') unless @date_success
end
def time_valid
errors.add(:day_time, 'format not valid!') unless @time_success
end
end
true
3b15db27fd5fd3aca4620217f2e5c04372312895
Ruby
alejandro-medici/retrospectiva
/extensions/retro_wiki/ext/project.rb
UTF-8
1,241
2.53125
3
[
"MIT"
]
permissive
Project.class_eval do
has_many :wiki_pages, :dependent => :destroy do
def find_or_build(title)
record = find_by_title(title)
unless record
record = build
record.title = title
end
record
end
end
has_many :wiki_files, :dependent => :destroy do
def find_readable(title)
file = find_by_wiki_title(title)
file and file.readable? ? file : nil
end
def find_readable_image(title)
file = find_readable(title)
file and file.image? ? file : nil
end
end
serialize :existing_wiki_page_titles, Array
before_update :update_main_wiki_page_title
def wiki_title(name = self.name)
name.gsub(/[\.\?\/;,]/, '-').gsub(/-{2,}/, '-')
end
def existing_wiki_page_titles
value = read_attribute(:existing_wiki_page_titles)
value.is_a?(Array) ? value : []
end
def reset_existing_wiki_page_titles!
update_attribute :existing_wiki_page_titles, wiki_pages.map(&:title)
end
protected
def update_main_wiki_page_title
if name_changed?
page = wiki_pages.find_by_title(wiki_title(name_was))
page.update_attribute(:title, wiki_title) if page
end
true
end
end
true
f5347127a5641b42dc75136a45e2bb514ab9fbb0
Ruby
siwS/theysaidsocli
/lib/quote_terminal_printer.rb
UTF-8
542
3.203125
3
[
"MIT"
]
permissive
require 'hirb'
class QuoteTerminalPrinter
def initialize(quote)
@quote = quote
@print_text = "#{@quote.author} said: \"#{@quote.quote}\""
@width = @print_text.size
end
def print
puts
print_separator
print_quote
print_separator
puts
end
private
def print_quote
puts "~ #{@print_text} ~"
end
def print_separator
puts "*" * separator_width
end
def separator_width
[@width + 4, terminal_width].min
end
def terminal_width
Hirb::Util.detect_terminal_size[0]
end
end
true
9cc6e2334547b5b9d1323c688d7b94efc9045855
Ruby
seanwbrooks/blackjack
/spec/lib/hand_spec.rb
UTF-8
1,204
3.15625
3
[]
no_license
require "spec_helper"
RSpec.describe Hand do
let(:hand) { Hand.new }
let(:card) { Card.new("♦", "2") }
let(:ace) { Card.new("A", "♦") }
let(:four_ace) { [Card.new("A", "♦"), Card.new("A", "♥"), Card.new("A","♦"), Card.new("A","♥")] }
describe '#initialize' do
it 'should take no arguments and create an instance of Hand' do
expect(hand).to be_a(Hand)
end
it 'is an empty array of cards' do
expect(hand.hand_of_cards).to eq([])
end
end
describe '#add_card' do
it 'should add another card to hand' do
hand.add_card(card)
expect(hand.hand_of_cards).to include(card)
end
end
describe "#calculate_hand" do
context "with some cards" do
it "should add these cards" do
expect(hand.calculate).to eq(0)
end
end
context "with two aces" do
it "should return a score of 12" do
hand.add_card(ace)
hand.add_card(ace)
expect(hand.calculate).to eq(12)
end
end
context "with four aces" do
it "should return a score of 14" do
4.times do
hand.add_card(ace)
end
expect(hand.calculate).to eq(14)
end
end
end
end
class Artist
extend Concerns::Findable
attr_accessor :name, :songs
@@all = []
def initialize(name)
@name = name
@songs = []
@@all << self
end
def name
@name
end
def self.all
@@all
end
def self.destroy_all
@@all.clear
end
def save
@@all << self
end
def self.create(name)
new_artist = self.new(name)
new_artist.save
new_artist
end
def songs
@songs
end
def add_song(song)
song.artist = self unless song.artist
songs << song unless songs.include?(song)
end
def genres
songs.map{|song| song.genre}.uniq
end
end
true
af9a8a9417a8cbff7f48db3a093a3827283d16a7
Ruby
achiurizo/boson
/lib/boson/inspector.rb
UTF-8
3,687
2.703125
3
[
"MIT"
]
permissive
module Boson
# Scrapes and processes method attributes with the inspectors (MethodInspector, CommentInspector
# and ArgumentInspector) and hands off the data to FileLibrary objects.
#
# === Method Attributes
# Method attributes refer to (commented) Module methods placed before a command's method
# in a FileLibrary module:
# module SomeMod
# # @render_options :fields=>%w{one two}
# # @config :alias=>'so'
# options :verbose=>:boolean
# # Something descriptive perhaps
# def some_method(opts)
# # ...
# end
# end
#
# Method attributes serve as configuration for a method's command. Available method attributes:
# * config: Hash to define any command attributes (see Command.new).
# * desc: String to define a command's description for a command. Defaults to first commented line above a method.
# * options: Hash to define an OptionParser object for a command's options.
# * render_options: Hash to define an OptionParser object for a command's local/global render options (see View).
#
# When deciding whether to use commented or normal Module methods, remember that commented Module methods allow
# independence from Boson (useful for testing). See CommentInspector for more about commented method attributes.
module Inspector
extend self
attr_reader :enabled
# Enable scraping by overridding method_added to snoop on a library while it's
# loading its methods.
def enable
@enabled = true
body = MethodInspector::METHODS.map {|e|
%[def #{e}(val)
Boson::MethodInspector.#{e}(self, val)
end]
}.join("\n") +
%[
def new_method_added(method)
Boson::MethodInspector.new_method_added(self, method)
end
alias_method :_old_method_added, :method_added
alias_method :method_added, :new_method_added
]
::Module.module_eval body
end
# Disable scraping method data.
def disable
::Module.module_eval %[
Boson::MethodInspector::METHODS.each {|e| remove_method e }
alias_method :method_added, :_old_method_added
]
@enabled = false
end
# Adds method attributes scraped for the library's module to the library's commands.
def add_method_data_to_library(library)
@commands_hash = library.commands_hash
@library_file = library.library_file
MethodInspector.current_module = library.module
@store = MethodInspector.store
add_method_scraped_data
add_comment_scraped_data
end
#:stopdoc:
def add_method_scraped_data
(MethodInspector::METHODS + [:args]).each do |key|
(@store[key] || []).each do |cmd, val|
@commands_hash[cmd] ||= {}
add_scraped_data_to_config(key, val, cmd)
end
end
end
def add_scraped_data_to_config(key, value, cmd)
if value.is_a?(Hash)
if key == :config
@commands_hash[cmd] = Util.recursive_hash_merge value, @commands_hash[cmd]
else
@commands_hash[cmd][key] = Util.recursive_hash_merge value, @commands_hash[cmd][key] || {}
end
else
@commands_hash[cmd][key] ||= value
end
end
def add_comment_scraped_data
(@store[:method_locations] || []).select {|k,(f,l)| f == @library_file }.each do |cmd, (file, lineno)|
scraped = CommentInspector.scrape(FileLibrary.read_library_file(file), lineno, MethodInspector.current_module)
@commands_hash[cmd] ||= {}
MethodInspector::METHODS.each do |e|
add_scraped_data_to_config(e, scraped[e], cmd)
end
end
end
#:startdoc:
end
end
true
571521803896c418306191cafeeeb3f89307ace3
Ruby
MuhammadTamzid/framgia_crb_v2
/app/validators/name_validator.rb
UTF-8
608
2.953125
3
[]
no_license
class NameValidator < ActiveModel::Validator
def validate record
# name may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen
if !(record.name =~ /^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$/i)
record.errors[:name] << "may only contain alphanumeric characters or single hyphens, and cannot begin or end with a hyphen"
elsif record.name.length > 39
record.errors[:name] << "is too long (maximum is 39 characters)"
elsif record.new_record? && Person.names.include?(record.name)
record.errors[:name] << "is already taken"
end
end
end
true
ca567f6ac7bc9ac5ce370db9c43c015bd867c5d5
Ruby
mdixon47/Codewars-Ruby
/8-kyu/Basic Fizz Buzz.rb
UTF-8
649
4.6875
5
[]
no_license
#Description:
#FizzBuzz is probably the second most popular way to introduce beginners to the art of coding
#(the first probably being the ancient Fibonacci sequence, the grandfather of all the algorithm theory).
#In this very basic kata you will have to create a function that
#returns the same numbers that is given as a parameter, with the following exceptions:
#If number divides evenly with 3 - returns string "fizz"
#If number divides evenly with 5 - returns string "buzz"
#If number divides evenly with 3 and 5 - returns string "fizz buzz"
def fizzbuzz(n)
n % 3 == 0 ? (n % 5 == 0 ? "fizz buzz" : "fizz") : (n % 5 == 0 ? "buzz" : n)
end
true
49bfaf32b0b1dbf85829fa22fbe3a7ca4eff7b00
Ruby
sebatapiaoviedo/dibujandoasteriscosypuntos
/asteriscos_y_puntos.rb
UTF-8
145
3.015625
3
[]
no_license
aux = ""
numero = ARGV[0].to_i
for i in (1..numero)
#i%2 == 0
if i.even?
aux += "."
else
aux += "*"
end
end
puts aux
true
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.