blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 4
137
| path
stringlengths 2
355
| src_encoding
stringclasses 31
values | length_bytes
int64 11
3.9M
| score
float64 2.52
5.47
| int_score
int64 3
5
| detected_licenses
listlengths 0
49
| license_type
stringclasses 2
values | text
stringlengths 11
3.93M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
d527aba3161eb694389376f7c7908b9c8a58b779
|
Ruby
|
jtlemkin/chess
|
/Desktop/odin/chess/lib/board.rb
|
UTF-8
| 1,268
| 3.796875
| 4
|
[] |
no_license
|
require './lib/piece'
class Board
attr_accessor :coord
def initialize
@coord = Hash.new
add_pieces
end
def add_pieces
build_king_row(8, :black)
build_pawn_row(7, :black)
build_pawn_row(2, :white)
build_king_row(1, :white)
end
def build_pawn_row(row, color)
(1..8).each do |s|
@coord[[s, row]] = Pawn.new(color)
end
end
def build_king_row(row, color)
@coord[[1, row]] = Rook.new(color)
@coord[[8, row]] = Rook.new(color)
@coord[[2, row]] = Knight.new(color)
@coord[[7, row]] = Knight.new(color)
@coord[[3, row]] = Bishop.new(color)
@coord[[6, row]] = Bishop.new(color)
@coord[[4, row]] = King.new(color)
@coord[[5, row]] = Queen.new(color)
end
def to_s
s = " abcdefgh\n"
cur = :black
nxt = :white
(1..8).each do |y|
cur, nxt = nxt, cur
s += "#{9 - y}"
(1..8).each do |x|
if @coord[[x, y]]
icon = @coord[[x, y]].to_s
else
icon = " "
end
s += colorize(icon, cur)
cur, nxt = nxt, cur
end
s += "\n"
end
s
end
def colorize(text, color)
case color
when :black then colored_string(text, "1;42")
when :white then colored_string(text, "1;47")
end
end
def colored_string(text, color_code)
"\033[#{color_code}m#{text}\033[0m"
end
end
puts Board.new
| true
|
ff7b4e9c0b9d8a3c84e2165df0f12e103b552ffb
|
Ruby
|
RobertDober/lab42_streams
|
/lib/lab42/stream/empty.rb
|
UTF-8
| 1,614
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
require 'forwarder'
module Lab42
class Stream
class Empty < Stream
extend Forwarder
# It is the nature of the EmptyStream instance to return itself for a plethora of methods
# this can be expressed as follows:
forward_all :combine, :__combine__,
:drop, :drop_unitl, :drop_while,
:flatmap, :__flatmap__, :filter, :__filter__,
:inject_stream, :__inject__,
:lazy_take, :lazy_take_until, :lazy_take_while,
:make_cyclic, :map, :__map__,
:reduce,
:segment, :__segment__, :__scan__, :split_by, :split_by_value,
:zip, :__zip__,
to_object: :self, as: :itself
def append other
raise ArgumentError, "not a stream #{other}" unless self.class.superclass === other
# ??? Is the to_stream message a good idea
other.to_stream
end
alias_method :+, :append
def empty?; true end
def head; raise StopIteration, "head called on empty stream" end
def tail; raise StopIteration, "tail called on empty stream" end
def inject *args; args.first end
alias_method :__inject__, :inject
def itself *; self end
def scan( initial, * )
[initial]
end
def scan1( * )
[]
end
def self.new
@__instance__ ||= allocate
end
end # class Empty
module ::Kernel
def empty_stream; Empty.new end
Lab42::Stream::EmptyStream = empty_stream
end # module ::Kernel
end # class Stream
end # module Lab42
| true
|
ebc78ce306488ea03eed141dd38f287639457339
|
Ruby
|
sykaeh/wikipedia_wrapper
|
/lib/wikipedia_wrapper/page.rb
|
UTF-8
| 3,756
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require 'wikipedia_wrapper/exception'
require 'wikipedia_wrapper/image'
require 'wikipedia_wrapper/util'
module WikipediaWrapper
class Page
attr_reader :title, :revision_time, :url, :extract
def initialize(term, redirect: true)
@term = term
@redirect = redirect
@images = nil
@img_width = WikipediaWrapper.config.img_width
@img_height = WikipediaWrapper.config.img_height
# FIXME: Deal with continuation
# FIXME: deal with redirect false!
load_page
end
def to_s
"Wikipedia Page: #{@title} (#{@url}), revid: #{@revision_id}, revtime: #{@revision_time}"
end
def categories
# FIXME: Implement!
end
# Retrieve image info for all given image filenames, except for the images in the whitelist
# See {http://www.mediawiki.org/wiki/API:Imageinfo}
#
# @param width [Integer] optional width of the smaller image (in px)
# @param height [Integer] optional height of the smaller image (in px)
# @note Only one of width and height can be used at the same time. If both are defined, only width is used.
# @return [Array<WikipediaWrapper::WikiImage>] list of images
def images(width: nil, height: nil)
# if we haven't retrieved any images or the width or height have changed, re-fetch
if @images.nil? || (!width.nil? && @img_width != width) || (!width.nil? && @img_width != width)
unless width.nil?
@img_width = width
end
unless height.nil?
@img_height = height
end
@images = []
# deal with the case that a page has no images
if @raw['images'].nil?
return @images
end
filenames = @raw['images'].map {|img_info| img_info['title']}.compact
if filenames.empty? # there are no filenames, return an empty array
return @images
end
# exclude whitelisted filenames
filenames = filenames.map { |f| WikipediaWrapper.config.image_allowed?(f) ? f : nil }.compact
query_parameters = {
'titles': filenames.join('|'),
'redirects': '',
'prop': 'imageinfo',
'iiprop': 'url|size|mime',
}
if (!@img_width.nil?)
query_parameters[:iiurlwidth] = @img_width.to_s
elsif (!@img_height.nil?)
query_parameters[:iiurlheight] = @img_height.to_s
end
raw_results = WikipediaWrapper.fetch(query_parameters)
# check if the proper format is there
if raw_results.key?('query') && raw_results['query'].key?('pages')
raw_results['query']['pages'].each do |k, main_info|
begin
wi = WikiImage.new(main_info)
@images.push(wi)
rescue WikipediaWrapper::FormatError => e
puts e.message
end
end
end
end
return @images
end
private
def load_page
query_parameters = {
'prop': 'revisions|info|extracts|images|pageprops',
'titles': @term,
'redirects': '',
'rvprop': 'content',
'inprop': 'url',
'exintro': '',
'ppprop': 'disambiguation',
}
raw_results = WikipediaWrapper.fetch(query_parameters)
WikipediaWrapper.check_results(@term, raw_results)
key, page_info = raw_results['query']['pages'].first
@raw = page_info
@page_id = page_info['pageid']
@title = page_info['title']
@revision_time = page_info['touched'] #FIXME: parse in to date & time, format: 2015-04-23T07:20:47Z
@revision_id = page_info['lastrevid']
@url = page_info['fullurl']
@extract = (page_info.key? 'extract') ? page_info['extract'] : ''
end
end
end
| true
|
55b755c60368c5bc1890316b5e9ceb988f96e715
|
Ruby
|
yvesdu/check-in
|
/app/serializers/api/standup_serializer.rb
|
UTF-8
| 896
| 2.546875
| 3
|
[] |
no_license
|
module Api
class StandupSerializer
def initialize(standup)
@standup = standup
end
def as_json
full_standup
end
private
def full_standup
{
id: standup.id,
standup_date: standup.standup_date,
user: {
name: standup.user.name,
id: standup.user.id
},
todos: standup.todos.map do |todo|
{
id: todo.id,
title: todo.title
}
end,
dids: standup.dids.map do |did|
{
id: did.id,
title: did.title
}
end,
blockers: standup.blockers.map do |blocker|
{
id: blocker.id,
title: blocker.title
}
end
}
end
attr_reader :standup
end
end
| true
|
4a9affb9a06d79efdbdba74575b05328ace28c8e
|
Ruby
|
plonk/100knock
|
/q58.rb
|
UTF-8
| 1,276
| 3.421875
| 3
|
[] |
no_license
|
=begin
58. タプルの抽出
Stanford Core NLPの係り受け解析の結果(collapsed-dependencies)に基づき,
「主語 述語 目的語」の組をタブ区切り形式で出力せよ.ただし,主語,述語,
目的語の定義は以下を参考にせよ.
述語: nsubj関係とdobj関係の子(dependant)を持つ単語
主語: 述語からnsubj関係にある子(dependent)
目的語: 述語からdobj関係にある子(dependent)
=end
require_relative 'q57'
# 文を表わすグラフから「主語-動詞-直接目的語」の例を抽出する。
def svo_instances(edges)
object = {}
subject = {}
edges.each do |edge|
case edge.type
when 'nsubj'
subject[edge.from] = edge.to
when 'dobj'
object[edge.from] = edge.to
end
end
# 主語と目的語が揃っている場合のみを対象とする。
verbs = (subject.keys & object.keys)
verbs.map do |v|
_idx, text = v
[subject[v][1], text, object[v][1]]
end
end
def output(table)
table.each do |row|
puts row.join("\t")
end
end
def main
doc = File.open('nlp.txt.xml', &Nokogiri.method(:XML))
gs = to_graphs(doc)
table = gs.flat_map { |g| svo_instances(g) }
output table
end
main if __FILE__ == $0
| true
|
1c90ecf04c1a21f7fd05e4012a9fbfdff510993f
|
Ruby
|
nataliecodes/phase-0
|
/week-4/calculate-grade/my_solution.rb
|
UTF-8
| 1,160
| 4.28125
| 4
|
[
"MIT"
] |
permissive
|
# Calculate a Grade
# I worked on this challenge by with Bernice.
# Your Solution Below
=begin
pseudocode
1. get a number (input)
2. relate that number to a letter grade
2.a. a = 90-100
2.b. b = 80-89
2.c. c = 70-79
2.d. d = 60-69
2.e. f = <60
3. output the letter grade (output)
=end
def get_grade(avg)
if avg.to_i >= 90
return "A"
elsif avg.to_i >= 80
return "B"
elsif avg.to_i >= 70
return "C"
elsif avg.to_i >= 60
return "D"
elsif avg.to_i < 60
return "F"
else
return "Error. Please enter a number grade from 0-100."
end
end
# refactored code
def get_grade(avg)
return "A" if avg.to_i >= 90
return "B" if avg.to_i >= 80
return "C" if avg.to_i >= 70
return "D" if avg.to_i >= 60
return "F" if avg.to_i < 60
return "Error. Please enter a number grade from 0-100." if avg.to_i > 100
end
# re-refactored code
def get_grade(avg)
case avg.to_i
when 90..100
return "A"
when 80..89
return "B"
when 70..79
return "C"
when 60..69
return "D"
when 0..60
return "F"
else
return "Error. Please enter a number grade from 0-100."
end
end
| true
|
e2166bee12758b327f463da62ea29f753b63f680
|
Ruby
|
yaobao5354/ruby-objects-has-many-lab-online-web-sp-000
|
/lib/artist.rb
|
UTF-8
| 448
| 3.328125
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'pry'
class Artist
attr_accessor :name, :songs
@@AllArtists = []
def initialize(name)
@name = name
@songs = []
@@AllArtists << self
end
def add_song(song)
song.artist = self
end
def add_song_by_name(title)
title = Song.new(title)
title.artist = self
end
def self.song_count
counter = 0
@@AllArtists.each {|artist| counter += artist.songs.length}
counter
end
end
| true
|
384827519f0e967058c564fdd8a4fe6f852048ed
|
Ruby
|
Narnach/data247
|
/lib/data247.rb
|
UTF-8
| 3,262
| 2.8125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'open-uri'
require 'timeout'
require 'active_support'
class Data247
attr_accessor :operator_name, :operator_code, :msisdn, :status
def initialize(attributes={})
attributes.each do |key, value|
self.send("#{key}=", value)
end
end
class << self
attr_accessor :username, :password, :timeout, :retries
def timeout
@timeout ||= 2
end
def retries
@retries ||= 2
end
def password
@password || raise("No password set for Data24-7")
end
def username
@username || raise("No username set for Data24-7")
end
# Attempt an operator lookup based on msisdn.
def detect(msisdn)
attempts = 0
while attempts <= self.retries
attempts += 1
begin
Timeout::timeout(self.timeout) do
data=Hash.from_xml(open("http://api.data24-7.com/carrier.php?username=#{self.username}&password=#{self.password}&p1=#{msisdn}").read)["response"]["results"]["result"]
status=data["status"].to_s.strip
operator_name=data["carrier_name"].to_s.strip
operator_code=data["carrier_id"].to_s.strip
unless status != "OK"
return new(:operator_name=> operator_name, :operator_code => operator_code, :msisdn => msisdn, :status=>status)
else
return new(:operator_code => nil, :msisdn => msisdn, :status=>status)
end
end
rescue Timeout::Error, SystemCallError => e
# ignore
end
end
new(:status=>"Timeout from Data24-7")
end
# When using FakeWeb for testing (which you should), use this to setup a fake response that returns the data you want.
#
# Required parameters:
# * :msisdn
#
# Optional parameters:
# * :status (defaults to "OK")
# * :username (defaults to Data247.username)
# * :password (defaults to Data247.password)
# * :operator (defaults to "T-Mobile")
# * :result (operator code, defaults to "123345", the T-Mobile operator code)
def setup_fakeweb_response(options={})
raise "FakeWeb is not defined. Please require 'fakeweb' and make sure the fakeweb rubygem is installed." unless defined?(FakeWeb)
raise ArgumentError.new("Option missing: :msisdn") unless options[:msisdn]
options[:status] ||= "OK"
options[:username]||= self.username
options[:password]||= self.password
options[:operator] ||= "T-Mobile"
options[:result] ||= "123345"
FakeWeb.register_uri :get, "http://api.data24-7.com/carrier.php?username=#{options[:username]}&password=#{options[:password]}&p1=#{options[:msisdn]}", :body=> <<-MSG
<?xml version="1.0"?><response><results><result item="1"><status>#{options[:status]}</status><number>#{options[:msisdn]}</number><wless>y</wless><carrier_name>#{options[:operator]}</carrier_name><carrier_id>#{options[:result]}</carrier_id><sms_address>#{options[:msisdn]}@tmomail.net</sms_address><mms_address>#{options[:msisdn]}@tmomail.net</mms_address></result></results><balance>21.5000</balance></response>
MSG
end
end
def ==(other)
[:operator_code, :msisdn, :status].each do |attribute|
return false unless self.send(attribute) == other.send(attribute)
end
true
end
end
| true
|
7d04db0a29363055f2f544889219200a10669d25
|
Ruby
|
lambyy/projects
|
/week2/w2d4/time_differences.rb
|
UTF-8
| 935
| 3.5
| 4
|
[] |
no_license
|
require 'byebug'
class Array
#time complexity O(n**2)
def my_min
each do |el1|
min = true
each do |el2|
if el2 < el1
min = false
end
end
return el1 if min == true
end
end
#time complexity O(n)
def my_better_min
min = first
each do |el|
min = min < el ? min : el
end
min
end
#time complexity O(n**4)
def sub_sum
sub_arrays = []
each_index do |ind1|
each_index do |ind2|
if ind1 <= ind2
sub_arrays << self[ind1..ind2]
end
end
end
sub_arrays.map {|sub| sub.reduce(:+)}.max
end
#time completity 0(n)
def better_sub_sum
return max if all? {|x| x < 0}
ult_sum = 0
sum = 0
each_with_index do |el, idx|
if el > 0
sum += el
ult_sum = sum if sum > ult_sum
else
sum + el < 0 ? sum = 0 : sum += el
end
end
ult_sum
end
end
| true
|
254280fea0e730093ada384af8c4e1330aee85f0
|
Ruby
|
theRingleman/schoolProjects
|
/learnToProgram/exampleName.rb
|
UTF-8
| 450
| 3.984375
| 4
|
[] |
no_license
|
puts "Hi there, what is your first name?"
firstName = gets.chomp
puts "Great! Now what is your middle name?"
middleName = gets.chomp
puts "Awesome! Now last one I promise! What is your last name?"
lastName = gets.chomp
fnLength = firstName.length
mnLength = middleName.length
lnLength = lastName.length
fullNameLength = (fnLength + mnLength + lnLength)
puts "Did you know that all of your names have " + fullNameLength.to_s + " characters in it?"
| true
|
012d4d6dd097881a75c2d21a391e49ece721da1e
|
Ruby
|
iijijii/pazzles
|
/3-2.rb
|
UTF-8
| 145
| 2.96875
| 3
|
[] |
no_license
|
data = [1,4,2,4,5,6,10,6,5,4,3,8,7,9,4,6,2,4]
count = []
(1..10).each do |n|
count[n - 1] = data.count(n)
end
puts count.index(count.max) + 1
| true
|
78a7baa07391d89b8178645cb4a789a82a955b74
|
Ruby
|
RobertDober/lab42_core
|
/spec/memoization/memoize_no_params_spec.rb
|
UTF-8
| 1,105
| 2.78125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"MIT"
] |
permissive
|
require 'spec_helper'
describe Module do
context 'undefined methods remain undefined' do
let :klass do
Class.new do
memoize :beta
end
end
it 'raises a NoMethod error' do
expect{ klass.new.beta }.to raise_error NameError, %r{undefined method .beta.}
end
end # context 'undefined methods remain undefined'
context 'memoized, parameterless methods' do
let :klass do
Class.new do
attr_reader :x
memoize def alpha; @x||=0; @x+=1; 'alpha' end
end
end
let( :instance ){ klass.new }
it 'x returns always the same result' do
expect( 3.times.map{ instance.alpha }.join ).to eq 'alpha' * 3
end
it 'x is initially nil' do
expect( instance.x ).to be_nil
end
it 'is 1 after a memoized call' do
instance.alpha
expect( instance.x ).to eq 1
end
it 'is 1 after many memoized calls' do
3.times{ instance.alpha }
expect( instance.x ).to eq 1
end
end # context 'memoized, parameterless methods'
end # describe Module
# SPDX-License-Identifier: Apache-2.0
| true
|
40f1b495dacfd1bed328251af95d0db84639f924
|
Ruby
|
jguyet/piscine-ruby-on-rails
|
/j01/ex01/croissant.rb
|
UTF-8
| 372
| 3.203125
| 3
|
[] |
no_license
|
#! /usr/bin/ruby -W0
def read_file(file_name)
if File.exist?(file_name) == false
return ""
end
file = File.open(file_name, "r")
data = file.read
file.close
return data
end
def ___MAIN()
data = read_file("./numbers.txt")
split = data.split(",")
split = data.split(",\n")
split = split.sort_by! {|s| s[/\d+/].to_i}
split.each {|c| puts c.to_s }
end
___MAIN()
| true
|
4265650664c9056ac2da2dc2faa005738c36c6c1
|
Ruby
|
s3844286/QuizPlus
|
/app/controllers/quizs_controller.rb
|
UTF-8
| 5,721
| 2.9375
| 3
|
[] |
no_license
|
class QuizsController < ApplicationController
require 'json'
def new
params[:numOfQuestions] != nil ? @numOfQuestions = params[:numOfQuestions].to_i : @numOfQuestions = 4
# array stores Question objects
@questionsForQuiz = Array.new
if params[:questions] != nil
# drops fist element it finds as this is a blank space
paramQuestions = params[:questions].split("q_").drop(1)
# read the written to file, in order to get previous questions
quizFile = File.read('quiz.json')
quizQuestions = JSON.parse(quizFile)
quizQuestions.each do |question|
@questionsForQuiz.push(question) if paramQuestions.include? (question['id'].to_s)
end
else
potentialCategories = ['Linux', 'DevOps', 'SQL', 'BASH']
@LinuxPresent, @DevOpsPresent, @SQLPresent, @BASHPresent = false;
categoryString = nil
if params[:Linux] == 'true'
@LinuxPresent = true
categoryString == nil ? categoryString = '-d category=Linux ' : categoryString += '-d category=Linux '
end
if params[:DevOps] == 'true'
@DevOpsPresent = true
categoryString == nil ? categoryString = '-d category=DevOps ' : categoryString += '-d category=DevOps '
end
if params[:SQL] == 'true'
@SQLPresent = true
categoryString == nil ? categoryString = '-d category=SQL ' : categoryString += '-d category=SQL '
end
if params[:BASH] == 'true'
@BASHPresent = true
categoryString == nil ? categoryString = '-d category=BASH ' : categoryString += '-d category=BASH '
end
if params[:difficulty] == 'Medium'
@difficulty = 'Medium'
categoryString == nil ? categoryString = '-d difficulty=Medium ' : categoryString += '-d difficulty=Medium '
elsif params[:difficulty] == 'Hard'
@difficulty = 'Hard'
categoryString == nil ? categoryString = '-d difficulty=Hard ' : categoryString += '-d difficulty=Hard '
else
@difficulty = 'Easy'
categoryString == nil ? categoryString = '-d difficulty=Easy ' : categoryString += '-d difficulty=Easy '
end
quizQuestions = loadJSON(categoryString)
while (@questionsForQuiz.length() != @numOfQuestions)
randomQuestionIndex = rand(0 ... quizQuestions.length())
individualEntry = quizQuestions[randomQuestionIndex]
@questionsForQuiz.push(individualEntry) if !@questionsForQuiz.include?(individualEntry)
end
end
end
def results
@score = 0;
quizFile = File.read('quiz.json')
quizQuestions = JSON.parse(quizFile)
@questionsAnswered = ''
@questionCount = 0
params.each do |questionParam, questionAnswer|
if questionParam.start_with?('q_')
@questionsAnswered += questionParam
@questionCount += 1
questionNum = questionParam.sub('q_', '')
quizQuestions.each do |question|
if question['id'] == questionNum.to_i
# iterates through correct answers hash
# note: correct_answer field is ocassional null hence the need for this loop
question['correct_answers'].each do |ansKey, boolVal|
@score += 1 if ansKey.start_with?(questionAnswer) && boolVal == 'true'
end
end
end
end
end
reversedOrder = cookieOperations(@score, @questionCount)
@listOfScores = Array.new
count = 0;
reversedOrder.each do |i|
splitEntry = i.split('#')
@listOfScores.push('At ' + splitEntry[0] + ' you answered ' + splitEntry[1] + ' questions correctly') unless count > 4
count += 1
end
@numOfQuestions = params[:numOfQuestions]
@difficulty = params[:difficulty]
@LinuxPresent = params[:LinuxPres]
@DevOpsPresent = params[:DevOpsPres]
@SQLPresent = params[:SQLPres]
@BASHPresent = params[:BASHPres]
end
def cookieOperations(score, questionCount)
currentTime = Time.new
# as time is default UTC (Melbourne +10)
hour = currentTime.hour + 10
hourStr = ''
hour > 12 ? hourStr = (hour - 12).to_s + "pm" : hourStr = hour.to_s + "am"
day = currentTime.day
month = currentTime.month
year = currentTime.year
strForCookie = hourStr + ',' + day.to_s + '-' + month.to_s + '-' + year.to_s + ',#' + score.to_s + '/' + questionCount.to_s
scoreCookie = cookies["usrScores"]
if scoreCookie
scoreCookie += "$" + strForCookie
else
scoreCookie = strForCookie
end
# expires after 5 days
cookies["usrScores"] = {value: scoreCookie, expires: 120.hour.from_now}
scoresFromCookie = scoreCookie.split('$')
# reversed so in order of most recent entries
reversedOrder = scoresFromCookie.reverse()
end
def loadJSON(stringOfCategories)
quizFile = File.read('quiz.json')
if stringOfCategories != nil
apiCall = `curl https://quizapi.io/api/v1/questions -G -d apiKey=RByCcRWApJ10wtRYYIKs1mf6VLo5Og22xINigoCU -d limit=15 #{stringOfCategories}`
else
apiCall = `curl https://quizapi.io/api/v1/questions -G -d apiKey=RByCcRWApJ10wtRYYIKs1mf6VLo5Og22xINigoCU -d limit=15 -d category=Linux -d difficulty=Easy`
end
if apiCall == nil
quizQuestions = JSON.parse(quizFile)
else
quizQuestions = JSON.parse(apiCall)
# writes to the file so that the quiz can be redone
File.write('quiz.json', JSON.dump(quizQuestions))
end
return quizQuestions
end
end
| true
|
425e63a4ac3c39f5ef17920dca6dffefa495f1f6
|
Ruby
|
shameem356/illuminati
|
/scripts/lims_fc_info.rb
|
UTF-8
| 2,121
| 2.8125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# fetch data from lims
require 'optparse'
require 'net/http'
require 'uri'
require 'json'
API_TOKEN = '1c5b55787c806548'
NGS_LIMS = "http://limskc01/zanmodules/molbio/api/ngs/"
getFlowcell = NGS_LIMS + 'flowcells/getFlowcell'
getSamples = NGS_LIMS + 'flowcells/getSamples'
def get_connection(uri, api_token)
url = URI.parse(uri)
req = Net::HTTP::Post.new(url.path, initheader = {'Content-Type' => 'application/json'})
req.basic_auth 'apitoken', api_token
return url, req
end
def json_data_for url, auth_req, fc_id
params = { "fcIdent" => fc_id}
auth_req.body = params.to_json
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(auth_req) }
resp.body
end
def query_connection url, connection, flowcell_ids
fc_id_n = flowcell_ids.split(',').map(&:strip)
output_array = []
fc_id_n.each do |req_fc_id|
lims_results = json_data_for(url, connection, req_fc_id)
# handle inconsistency in lims api
if lims_results != 'false'
json_lims = JSON.parse(lims_results)
unless json_lims["message"] =~ /Invalid/
output_array.push(json_lims)
end
end
end
return JSON.dump(output_array)
end
def print data
data.each do |sample|
output_array = []
output_array << sample
puts output_array.join("\t")
end
end
def run_query query_url, args
# optional comma-delimited orders
url_path = query_url
url, connection = get_connection(url_path, API_TOKEN)
puts query_connection url, connection, args
end
HELP = <<-HELP
Usage: lims_fc_info [COMMAND] <OPTIONS>
lims_fc_info Commands:
version - Print version number and exit
help - Print this help and exit
* Multiple requests can be packaged by seperating args with a comma (,)
* i.e. FC1,FC2
samples - Return JSON data from LIMS for sample data from flowcells
flowcell - Return JSON data from LIMS for flowcells meta-data
HELP
command = ARGV.shift
case command
when "samples"
# run samples query
run_query getSamples, ARGV[0]
when "flowcell"
# run flowcell query
run_query getFlowcell, ARGV[0]
else
puts HELP
end
| true
|
723214af52bbaaed9a9b42733caafa11c047677d
|
Ruby
|
Alux77/Ruby-3
|
/1_linear-search.rb
|
UTF-8
| 1,249
| 4.5625
| 5
|
[] |
no_license
|
# Escribe un método llamado linear_search que tome como argumento un número y un arreglo.
# Este método debe regresar el índice del primer elemento que sea igual al valor del número,
# revisando dentro del arreglo cada valor secuencialmente.
# En caso de no encontrar el número debe regresar nil.
# No podrás utilizar métodos de Array ni sus enumerables (each, map, etc ),
# si no que debes de utilizar iteradores como for while o until.
# El único método que puedes utilizar es: Array#[]
def linear_search(number, random_numbers)
i = 0
while i < random_numbers.length
if random_numbers[i] == number
return i
else
nil
end
i += 1
end
end
random_numbers = [ 4, 3, 2, 20, 5, 64, 78, 11, 43 ]
p linear_search(20, random_numbers)
# # # => 3
p linear_search(29, random_numbers)
# #=> nil
# Después deberás crear un método que regrese un array con los indices donde encuentre el objeto y un array vació si no existe,
# llama este método global_linear_search.
def global_linear_search(objeto, arr)
new_arr = []
i = 0
while i < arr.length
if arr[i] == objeto
new_arr << i
end
i += 1
end
new_arr
end
arr = "entretenerse".split('')
p global_linear_search("e", arr)
# => [0, 4, 6, 8, 11]
| true
|
a4ea00fe49affc88d1fa882546084dc9f0bea512
|
Ruby
|
cnorm35/InterviewExercises
|
/difference-of-squares/difference_of_squares.rb
|
UTF-8
| 120
| 2.546875
| 3
|
[] |
no_license
|
class Squares
def initialize(n); end
def sum_of_squares; end
def difference; end
def square_of_sums; end
end
| true
|
92dde66ba7ee535b295b88872def6b64f564d80a
|
Ruby
|
onthespotqa/seed_list
|
/lib/seed_list/cli.rb
|
UTF-8
| 3,335
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
require 'thor'
module SeedList
class CLI < Thor
namespace :seed_list
desc 'edit TOURNAMENT_ID', 'Reposition seeds using EDITOR (interactive)'
def edit(tournament_id)
@tournament_id = tournament_id
trap_signals
say "Using #{ENV['EDITOR']} (set $EDITOR to change)", :green
say 'Loading environment...', :green
say 'Exporting seed list...', :green
old_list = players.map { |p| p.login }
new_list = editor "tournament-#{tournament.id}-edit-seeds" do
buffer = "# Seed list for \"#{tournament.title}\" (##{tournament.id})\n\n"
buffer << "# Organize the players below by skill from best to worst.\n"
buffer << "# Save and quit to replace the seed list for this tournament.\n\n"
buffer << old_list.join("\n")
end.split("\n")
system('clear')
if new_list == old_list
say 'Nothing changed.', :yellow
else
say 'Seed list updated, saving...', :green
replace_seed_list new_list
end
end
desc 'import TOURNAMENT_ID', 'Import line-separated seeds from STDIN'
def import(tournament_id)
@tournament_id = tournament_id
trap_signals
replace_seed_list STDIN.read.split("\n")
end
desc 'export TOURNAMENT_ID', 'Export line-separated seeds to STDOUT'
def export(tournament_id)
@tournament_id = tournament_id
trap_signals
players.each { |p| puts p.login }
end
no_tasks do
def tournament
begin
@tournament ||= SeedList.tournament_class_name.constantize.find @tournament_id
rescue ActiveRecord::RecordNotFound => e
say e, :red
end
end
def players
eval("tournament.#{SeedList.player_class_name.tableize}")
.sort_by { |tp| tp.seed }
end
def get_player_id(login)
players.select { |p| p.login == login }.first.id
end
def replace_seed_list(logins)
@list = SeedList::List.new
logins.each do |login|
begin
@list.push get_player_id(login)
rescue ActiveRecord::RecordNotFound => e
say e, :red
end
end
tournament.tournament_players_seed_list = @list
tournament.save
end
# Terminate the program on SIGINT without printing a trace
def trap_signals
Signal.trap('INT') do
say "\nQuitting...", :red
Kernel.exit
end
end
# Interactively manipulate data in a text editor.
# @param [String] 'edit' Prefix for the tempfile
# @param [Block] A block returning a text string for the buffer
# @return [String] The updated text string (stripped of #comments and empty lines)
# @example Change "hello" to "goodbye"
# editor 'edit-greeting' do
# "# This line is a comment\n\nhello"
# end => "goodbye"
def editor(buffer_name = 'edit', &block)
require 'tempfile'
buffer = Tempfile.new(buffer_name + '-')
buffer << yield
buffer.flush
system("$EDITOR #{buffer.path}")
buffer.rewind
output = buffer.read.split("\n")
.reject { |line| line =~ /^\s*#.*$/ }
.reject { |line| line.empty? }
buffer.unlink
output.join("\n")
end
end
end
end
| true
|
b9e43e843631cd36d0318ca5851fb1c84f9b3692
|
Ruby
|
Jose-N/Launch-Academy-Week-1
|
/emergency-brussels-sprouts/lib/ingredient.rb
|
UTF-8
| 273
| 3.5
| 4
|
[] |
no_license
|
class Ingredient
attr_reader :name, :weight
def initialize(name, weight)
@name = name
@weight = weight
end
def self.create_from_grams(name, weight_in_grams)
weight_in_kilos = weight_in_grams / 1000
Ingredient.new(name, weight_in_kilos)
end
end
| true
|
9ec17e5e62f2211eddc5580e1ed286ae147a55ac
|
Ruby
|
hmaarek/assign-deployment
|
/app/models/fiberstrand.rb
|
UTF-8
| 3,561
| 2.59375
| 3
|
[] |
no_license
|
class Fiberstrand < ActiveRecord::Base
belongs_to :cable
validates_presence_of :name, :porta, :portb, :cable_id
after_save :set_devport_fiber_id
#run a query to build a list of all availbale ports in the
#location of the Point A of the cable...
#addition (23 June): build only the free ports list
#adjustment (25 June): porta goes into fiber_out only, and portb goes into fiber_in only
def list_ports_a
loca = Cable.find_by_id(cable_id).location_a_id
Devport.where("location_id = " + loca.to_s + " AND (fiber_out_id = 0 )") # OR fiber_out_id = 0)") -(25 June)
end
def list_ports_b
locb = Cable.find_by_id(cable_id).location_b_id
Devport.where("location_id = " + locb.to_s + " AND (fiber_in_id = 0)") # OR fiber_out_id = 0)")
end
protected
#this sets Devport either fiber_in_id or fiber_out_id
#it will first look which one is zero, and sets that to the current fiber id
#if both are not zeros, it will yeild to fiber_in_id to set (had to pick one)
def set_devport_fiber_id
#binding.pry
#get the devport assigned
dvprt = Devport.find_by_id(porta) #cannot be nill...user chose already a valid port
#june-25 adjustments:
dvprt.fiber_out_id = id #(porta)
dvprt.save
dvprt = Devport.find_by_id(portb)
dvprt.fiber_in_id = id #(portb)
dvprt.save
#this is commented-out by adjustment in June-25. Porta->fiber_out, Portb->fiber_in
#if dvprt.fiber_in_id == 0
# dvprt.fiber_in_id = id
#elsif dvprt.fiber_out_id == 0
# dvprt.fiber_out_id = id
#else
# dvprt.fiber_in_id = id #overwrite it then
#end
#save that one devport
dvprt.save
#now do the same for portb...
#dvprt = Devport.find_by_id(portb) #cannot be nill...use chose already a valid port
#if dvprt.fiber_in_id == 0
# dvprt.fiber_in_id = id
#elsif dvprt.fiber_out_id == 0
# dvprt.fiber_out_id = id
#else
# dvprt.fiber_in_id = id #overwrite it then
#end
#save that one too...
#dvprt.save
end
#----------------------------------------------
def self.import_fiber(fibername, portA, portB, cableID, connID)
#binding.pry
#+ " AND porta = '" + portA.to_s + "'" + " AND portb = '" + portB.to_s + "'"
fbr = Fiberstrand.where("cable_id = '" + cableID.to_s + "' AND name LIKE '" + fibername.to_s + "'" ).first
if fbr.nil?
fbr = create ([name: fibername.to_s, cable_id: cableID, porta: portA, portb: portB, connection_id: connID]).first
fbrID = fbr.id
#if fbr.nil? || fbrID <= 0
# binding.pry
#end
else
#24Aug2016: you cannot have dublicate fiberstrands...and you cannot overwrite...
# return an error so that backhaul/feeder will be deleted.
# If user needs to update old data in a feeder/backhauil, he has to delete it first
fbr.name = fibername.to_s
fbr.cable_id = cableID
fbr.porta= portA
fbr.portb= portB
fbr.connection_id = connID
fbr.save
#fbrID =0
fbrID = fbr.id
#binding.pry
end
fbrID #return rack id
end
#-----------------------------------------------
def self.list_connection_fibers (connID)
flist = Fiberstrand.where ("connection_id = " + connID.to_s)
end
def self.list_cable_fibers (cableID)
flist = Fiberstrand.where ("cable_id = " + cableID.to_s)
end
end
| true
|
7d3b5377bc026ad6397f502db7a9dec179ef74d0
|
Ruby
|
technohippy/Kaleidoscope.rb
|
/src/compat.rb
|
UTF-8
| 369
| 3.140625
| 3
|
[] |
no_license
|
EOF = nil
$buf = []
def getchar
$buf += ($stdin.gets || '').split('') if $buf.empty?
$buf.shift
end
def isspace c; c =~ /^\s$/ end
def isalpha c; c =~ /^[a-zA-Z]$/ end
def isalnum c; c =~ /^[a-zA-Z0-9]$/ end
def isdigit c; c =~ /^[0-9]$/ end
def isascii c
if c.is_a? String
code = c.bytes.to_a.first
0 <= code and code <= 0x7f
else
false
end
end
| true
|
76f0459758822ec9fba03f72e5bfafea567fb03c
|
Ruby
|
Matoone/THP_S2_J2
|
/spec/find_multiples_spec.rb
|
UTF-8
| 1,172
| 3.5625
| 4
|
[] |
no_license
|
require_relative '../lib/find_multiples.rb'
describe "the is_multiple_of_3_or_5? method" do
it "should return TRUE when an integer is a multiple of 3 or 5" do
expect(is_multiple_of_3_or_5?(3)).to eq(true)
expect(is_multiple_of_3_or_5?(5)).to eq(true)
expect(is_multiple_of_3_or_5?(51)).to eq(true)
expect(is_multiple_of_3_or_5?(45)).to eq(true)
end
it "should return FALSE when an integer is NOT a multiple of 3 or 5" do
expect(is_multiple_of_3_or_5?(2)).to eq(false)
expect(is_multiple_of_3_or_5?(14)).to eq(false)
expect(is_multiple_of_3_or_5?(127)).to eq(false)
expect(is_multiple_of_3_or_5?(169)).to eq(false)
end
end
describe "the sum_of_3_or_5_multiples method" do
it "should return Il faut entrer un entier naturel! when the number is not an integer and not positive" do
expect(sum_of_3_or_5_multiples(-1)).to eq("Il faut entrer un entier naturel!")
expect(sum_of_3_or_5_multiples("abcde")).to eq("Il faut entrer un entier naturel!")
expect(sum_of_3_or_5_multiples(-60)).to eq("Il faut entrer un entier naturel!")
expect(sum_of_3_or_5_multiples("ooomph")).to eq("Il faut entrer un entier naturel!")
end
end
| true
|
451313e968a475e70f9616a37c936ec4219adf4d
|
Ruby
|
danieltoppin/appliances
|
/lib/dishwasher.rb
|
UTF-8
| 359
| 2.953125
| 3
|
[] |
no_license
|
require './lib/appliances.rb'
class Dishwasher < Appliances
#instance methods
def initialize(door:, power:)
super(door: door, power: power)
end
def start
if (door_closed? && power_on?)
'Dishwasher is starting...'
else
'Dishwasher could not start'
end
end
def self.create(door:, power:)
Dishwasher.new(door: door, power: power)
end
end
| true
|
86c11c66f3e45e54a215182c9c7ef7dd8cf9e1f4
|
Ruby
|
ryerayne/oo-my-pets-v-000
|
/lib/owner.rb
|
UTF-8
| 1,437
| 3.71875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Owner
attr_accessor :pets, :name, :mood
attr_reader :species, :fishes, :cats, :dogs
attr_writer
@@owner = []
def initialize(name)
@name = name
@pets = {:fishes => [], :cats => [], :dogs => []}
@@owner << self
@species = "human"
end
def self.all
@@owner
end
def self.reset_all
@@owner = []
end
def self.count
@@owner.count
end
def buy_fish(name)
fish = Fish.new(name)
@pets[:fishes] << fish
@mood = "happy"
end
def buy_cat(name)
cat = Cat.new(name)
@pets[:cats] << cat
@mood = "happy"
end
def buy_dog(name)
dog = Dog.new(name)
@pets[:dogs] << dog
@mood = "the most happy!"
end
def say_species
return "I am a human."
end
def walk_dogs
@pets[:dogs].each do |dog|
dog.mood = "happy"
end
end
def play_with_cats
@pets[:cats].each do |cat|
cat.mood = "happy"
end
end
def feed_fish
@pets[:fishes].each do |fish|
fish.mood = "happy"
end
end
def sell_pets
sad_pets = @pets.values.flatten
@pets = {:fishes => [], :cats => [], :dogs => []}
sad_pets.each do |pet|
pet.mood = "nervous"
end
@mood = "sad"
end
def list_pets
fish = @pets[:fishes].count
dog = @pets[:dogs].count
cat = @pets[:cats].count
return "I have #{fish} fish, #{dog} dog(s), and #{cat} cat(s)."
end
end
| true
|
c566d1529fb7227f98722272c7873dc54812abd0
|
Ruby
|
ncalibey/Launch_School
|
/130_ruby_foundations/lesson_01/select.rb
|
UTF-8
| 369
| 3.953125
| 4
|
[] |
no_license
|
# select.rb
def select(arr)
counter = 0
return_arr = []
while counter < arr.size do
value = yield(arr[counter])
if value
return_arr << arr[counter]
end
counter += 1
end
return_arr
end
array = [1, 2, 3, 4, 5]
p select(array) { |num| num.odd? }
p select(array) { |num| puts num }
p select(array) { |num| num + 1 }
| true
|
147289beb01eb9777551a42b14fefdbf08f8fa23
|
Ruby
|
makotz/CodeCore-Exercises
|
/4week/10JuneDay20/a1_student_class/student.rb
|
UTF-8
| 341
| 3.375
| 3
|
[] |
no_license
|
class Student
attr_accessor :first_name, :last_name, :score
def initialize(first_name, last_name, score)
@first_name = first_name
@last_name = last_name
@score = score
end
def full_name
"#{@first_name} #{@last_name}"
end
def grade
if @score.to_i > 90
"A"
else
"F"
end
end
end
| true
|
6306efabd37cef809eb0dec39e18302b52b096f7
|
Ruby
|
netguru-hackathon/bandicoot
|
/lib/bandicoot/processor.rb
|
UTF-8
| 1,259
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module Bandicoot
module Processor
attr_accessor :browser, :content
def boot_browser
self.browser = Watir::Browser.new
self.browser.goto config.url
parse_content
end
def crawl
boot_browser
result = Hash.new
loop do
config.scopes.each do |scope|
result[scope.name] ||= []
result[scope.name] << process_scope(scope)
end
go_to_the_next_page
parse_content
end
rescue Watir::Exception::UnknownObjectException => e
result
end
def go_to_the_next_page
browser.a(css:config.next_page_css_path).click
end
# private
def config
self.class.config
end
def process_scope(scope)
scoped_contents(scope.css).each_with_object([]) do |scoped_content, scoped_data|
scoped_data << scope.attributes.each_with_object({}) do |attr, data|
data[attr.name] = scoped_content.at_css(attr.css_path).text.strip.chomp
end
end
end
def exists?(element_path)
content.at_css(element_path).present?
end
def parse_content
self.content = Nokogiri::HTML.parse(browser.html)
end
def scoped_contents(css_path)
content.css(css_path)
end
end
end
| true
|
0a6bdc9098a2f16bdf942e2b389fff310d236153
|
Ruby
|
thekompanee/chamber
|
/lib/chamber/file_set.rb
|
UTF-8
| 8,259
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'pathname'
require 'chamber/namespace_set'
require 'chamber/file'
require 'chamber/settings'
###
# Internal: Represents a set of settings files that should be considered for
# processing. Whether they actually *are* processed depends on their extension
# (only *.yml and *.yml.erb files are processed unless explicitly specified),
# and whether their namespace matches one of the namespaces passed to the
# FileSet (text after a dash '-' but before the extension is considered the
# namespace for the file).
#
# When converted to settings, files are always processed in the order of least
# specific to most specific. So if there are two files:
#
# * /tmp/settings.yml
# * /tmp/settings-blue.yml
#
# Then '/tmp/settings.yml' will be processed first and '/tmp/settings-blue.yml'
# will be processed second (assuming a namespace with the value 'blue' was
# passed in).
#
# If there are multiple namespaces, they will be process in the order that they
# appear in the passed in hash. So assuming two files:
#
# * /tmp/settings-blue.yml
# * /tmp/settings-green.yml
#
# Then:
#
# ```ruby
# FileSet.new files: '/tmp/settings*.yml',
# namespaces: ['blue', 'green']
# ```
#
# will process in this order:
#
# * /tmp/settings-blue.yml
# * /tmp/settings-green.yml
#
# Whereas:
#
# ```ruby
# FileSet.new files: '/tmp/settings*.yml',
# namespaces: ['green', 'blue']
# ```
#
# will process in this order:
#
# * /tmp/settings-green.yml
# * /tmp/settings-blue.yml
#
# Examples:
#
# ###
# # Assuming the following files exist:
# #
# # /tmp/settings.yml
# # /tmp/settings-blue.yml
# # /tmp/settings-green.yml
# # /tmp/settings/another.yml
# # /tmp/settings/another.json
# # /tmp/settings/yet_another-blue.yml.erb
# # /tmp/settings/yet_another-green.yml
# #
#
# ###
# # This will *consider* all files listed but will only process 'settings.yml'
# # and 'another.yml'
# #
# FileSet.new files: ['/tmp/settings.yml',
# '/tmp/settings']
#
# ###
# # This will all files in the 'settings' directory but will only process
# # 'another.yml' and 'yet_another-blue.yml.erb'
# #
# FileSet.new(files: '/tmp/settings',
# namespaces: {
# favorite_color: 'blue' } )
#
# ###
# # Passed in namespaces do not have to be hashes. Hash keys are used only for
# # human readability.
# #
# # This results in the same outcome as the example above.
# #
# FileSet.new(files: '/tmp/settings',
# namespaces: ['blue'])
#
# ###
# # This will process all files listed:
# #
# FileSet.new(files: [
# '/tmp/settings*.yml',
# '/tmp/settings',
# ],
# namespaces: %w{blue green})
#
# ###
# # This is the only way to explicitly specify files which do not end in
# # a 'yml' extension.
# #
# # This is the only example thus far which will process
# # '/tmp/settings/another.json'
# #
# FileSet.new(files: '/tmp/settings/*.json',
# namespaces: %w{blue green})
#
module Chamber
class FileSet
attr_accessor :decryption_keys,
:encryption_keys,
:basepath,
:signature_name
attr_reader :namespaces,
:paths
# rubocop:disable Metrics/ParameterLists
def initialize(files:,
basepath: nil,
decryption_keys: nil,
encryption_keys: nil,
namespaces: {},
signature_name: nil)
self.basepath = basepath
self.decryption_keys = decryption_keys
self.encryption_keys = encryption_keys
self.namespaces = namespaces
self.paths = files
self.signature_name = signature_name
end
# rubocop:enable Metrics/ParameterLists
###
# Internal: Returns an Array of the ordered list of files that was processed
# by Chamber in order to get the resulting settings values. This is useful
# for debugging if a given settings value isn't quite what you anticipated it
# should be.
#
# Returns an Array of file path strings
#
def filenames
@filenames ||= files.map(&:to_s)
end
###
# Internal: Converts the FileSet into a Settings object which represents all
# the settings specified in all of the files in the FileSet.
#
# This can be used in one of two ways. You may either specify a block which
# will be passed each file's settings as they are converted, or you can choose
# not to pass a block, in which case it will pass back a single completed
# Settings object to the caller.
#
# The reason the block version is used in Chamber.settings is because we want
# to be able to load each settings file as it's processed so that we can use
# those already-processed settings in subsequently processed settings files.
#
# Examples:
#
# ###
# # Specifying a Block
# #
# file_set = FileSet.new files: [ '/path/to/my/settings.yml' ]
#
# file_set.to_settings do |settings|
# # do stuff with each settings
# end
#
#
# ###
# # No Block Specified
# #
# file_set = FileSet.new files: [ '/path/to/my/settings.yml' ]
# file_set.to_settings
#
# # => <Chamber::Settings>
#
def to_settings
files.inject(Settings.new) do |settings, file|
settings.merge(file.to_settings).tap do |merged|
yield merged if block_given?
end
end
end
def secure
files.each(&:secure)
end
def unsecure
files.each(&:decrypt)
end
def sign
files.each(&:sign)
end
def verify
files.each_with_object({}) do |file, memo|
relative_filepath = Pathname.new(file.to_s).relative_path_from(basepath).to_s
memo[relative_filepath] = file.verify
end
end
protected
###
# Internal: Allows the paths for the FileSet to be set. It can either be an
# object that responds to `#each` like an Array or one that doesn't. In which
# case it will be considered a single path.
#
# All paths will be converted to Pathnames.
#
def paths=(raw_paths)
raw_paths = [raw_paths] unless raw_paths.respond_to? :each
@paths = raw_paths.map { |path| Pathname.new(path) }
end
###
# Internal: Allows the namespaces for the FileSet to be set. An Array or Hash
# can be passed; in both cases it will be converted to a NamespaceSet.
#
def namespaces=(raw_namespaces)
@namespaces = NamespaceSet.new(raw_namespaces)
end
###
# Internal: The set of files which are considered to be relevant, but with any
# duplicates removed.
#
def files
@files ||= lambda {
sorted_relevant_files = []
file_globs.each do |glob|
current_glob_files = Pathname.glob(glob)
relevant_glob_files = relevant_files & current_glob_files
relevant_glob_files.map! do |file|
File.new(path: file,
namespaces: namespaces,
decryption_keys: decryption_keys,
encryption_keys: encryption_keys,
signature_name: signature_name)
end
sorted_relevant_files += relevant_glob_files
end
sorted_relevant_files.uniq
}.call
end
private
def all_files
@all_files ||= file_globs
.map { |fg| Pathname.glob(fg) }
.flatten
.uniq
.sort
end
def non_namespaced_files
@non_namespaced_files ||= all_files - namespaced_files
end
def relevant_files
@relevant_files ||= non_namespaced_files + relevant_namespaced_files
end
def file_globs
@file_globs ||= paths.map do |path|
if path.directory?
path + '*.{yml,yml.erb}'
else
path
end
end
end
def namespaced_files
@namespaced_files ||= all_files.select do |file|
file.basename.fnmatch? '*-*'
end
end
def relevant_namespaced_files
file_holder = []
namespaces.each do |namespace|
file_holder << namespaced_files.select do |file|
file.basename.fnmatch? "*-#{namespace}.???"
end
end
file_holder.flatten
end
end
end
| true
|
af964c968bbf27a9d6217e6eca780e366d80b71e
|
Ruby
|
whatcodehaveyougit/10th_dec_sinatra_homework
|
/models/films.rb
|
UTF-8
| 1,514
| 3.203125
| 3
|
[] |
no_license
|
require_relative('../db/sql_runner')
class Film
attr_reader :id
attr_accessor :title, :price
def initialize ( options )
@id = options['id'].to_i if options ['id']
@title = options['title']
@price = options['price']
end
# =========== CREATE =============
def save()
sql="INSERT INTO films
(title, price)
VALUES ($1, $2)
RETURNING id"
values = [@title, @price]
film_save = SqlRunner.run(sql, values).first
@id = film_save['id'].to_i
end
# ============ READ ===============
def self.read_all()
sql = "SELECT * FROM films"
films_showing = SqlRunner.run(sql)
return films_showing.map {|films_hash| Film.new(films_hash)}
end
def self.find_film_by_id(id)
sql = "SELECT * FROM films WHERE id = $1"
values = [id]
film = SqlRunner.run(sql, values)
return Film.new(film.first)
end
# ========== UPDATE ===========
def update
sql = "UPDATE films SET (title, price) = ($1, $2)
WHERE id = $3"
values = [@title, @price, @id]
SqlRunner.run(sql, values)
return values
end
# ============== DELETE ===============
def self.delete_all()
sql = "DELETE FROM films"
SqlRunner.run(sql)
end
# Why is it returning the film data rather than the customer data?
def customers_at_film()
sql = "SELECT * FROM customers INNER JOIN tickets
ON customers.id = tickets.customer_id WHERE film_id = $1"
values = [@id]
customers = SqlRunner.run(sql, values)
result = customers.map {|customer_hash| Customer.new(customer_hash)}
end
end
| true
|
f4ff00a017b949ec998f040844d2fe017e5161d0
|
Ruby
|
i8hamburgrz/bewd_homework
|
/homework-04/pants/pants.rb
|
UTF-8
| 984
| 2.84375
| 3
|
[] |
no_license
|
require 'sinatra'
require 'httparty'
forcast_url = 'https://api.forecast.io/forecast/8deef2835fd7736a6afd302168019c4c/'
get '/' do
erb :home
end
post '/results' do
# zip code parsing
zip_code = params['zip_code']
zip_url = "http://api.zippopotam.us/us/#{ zip_code }"
zip = HTTParty.get( zip_url )
parsed_zip = zip.parsed_response
long = parsed_zip['places'][0]['longitude']
lat = parsed_zip['places'][0]['latitude']
#forecast parsing
forcast_url = "https://api.forecast.io/forecast/8deef2835fd7736a6afd302168019c4c/#{ lat },#{ long }"
forecast = HTTParty.get( forcast_url )
parsed_forecast = forecast.parsed_response
@temp_hi = parsed_forecast['daily']['data'][0]['temperatureMax']
@temp_low = parsed_forecast['daily']['data'][0]['temperatureMin']
if @temp_hi > 74
@message = "<span style='color:red'> Today is Shorts Day!!! YAY!!!</span>"
else
@message = "<span style='color:blue'> Today is Pants Day!!! BRRRRRR!!!</span>"
end
erb :results
end
| true
|
0be2011b40666004702799eaf45e9549514fe55c
|
Ruby
|
azet/http_sec_headers
|
/headers.rb
|
UTF-8
| 2,440
| 2.53125
| 3
|
[
"CC0-1.0"
] |
permissive
|
#!/usr/bin/env ruby -W0
#
# check for HTTP security headers
#
require 'open-uri'
def scan_headers field, page
field.map! &:downcase
case
when field.first == "strict-transport-security"
puts "[+] #{page} supports HSTS."
when field.first == "public-key-pins"
puts "[+] #{page} supports HPKP."
when field == ['x-frame-options', 'deny']
puts "[+] #{page} provides 'Clickjacking Protection' (X-Frame-Options: deny)."
when field == ['x-frame-options', 'sameorigin']
puts "[+] #{page} set X-Frame-Options to SAMEORIGIN."
when field == ['x-content-type-options', 'nosniff']
puts "[+] #{page} set X-Content-Type-Options to nosniff."
when field == ['x-xss-protection', '1; mode=block']
puts "[+] #{page} provides XSS Protection (X-Xss-Protection: 1; mode=block)."
when field.first == "content-security-policy"
when field.first == "content-security-policy-report-only"
puts "[+] #{page} sets Content-Security-Policy."
when field == ['content-security-policy', 'upgrade-insecure-requests']
puts "[+] #{page} upgrades resource requests (CSP):"
when field.first == "content-encoding"
puts "[-] #{page} uses HTTP compression (BREACH)!"
end
end
unless ARGV.first
puts " usage: ruby headers.rb http://example.com [...]"
exit 1
end
pages = []
loop do
pages << ARGV.first and ARGV.shift
break unless ARGV.first
end
pages.each do |page|
puts "::: scanning #{page}:"
begin
open(page).meta.each do |field|
scan_headers field, page
end
rescue => e
case
when e.message =~ /No such file/
puts "!!! error: not a valid URL\n\n"
usage
when e.message =~ /verify failed/
puts "[-] #{page} has no valid TLS certificate!"
# when overriding this constant, ruby will - correctly - issue a warning
# we supress the warning with the parameter -W0, since we still want to
# run the remaining checks that the script offers without being bothered
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
retry
when e.message =~ /redirection\s+forbidden:\s+http:\S+\s+->\s+https:/i
puts "[+] #{page} redirects to HTTPS."
page = page.gsub("http", "https")
retry
when e.message =~ /redirection\s+forbidden:\s+https:\S+\s+->\s+http:/i
puts "[-] #{page} downgrades HTTPS to HTTP!"
page = page.gsub("https", "http")
retry
else
puts "!!! error: #{e}"
next
end
end
end
| true
|
0b50e1e9adb45cc41d53542a1ad8b761a928324b
|
Ruby
|
yalanin/201902_rspec_practice
|
/spec/array_spec.rb
|
UTF-8
| 249
| 2.546875
| 3
|
[] |
no_license
|
RSpec.describe Array do
it 'should be empty after created' do
puts subject
puts subject.class
expect(subject.length).to eq(0)
subject.push 'hello world'
end
it 'length of array' do
expect(subject.length).to eq(1)
end
end
| true
|
b24d950fd500d6b17889c82b54145ccf5016ad2d
|
Ruby
|
fraterrisus/advent2018
|
/day02/part1.rb
|
UTF-8
| 271
| 3.359375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
lines = IO.readlines(ARGV[0])
num2 = 0
num3 = 0
lines.map(&:strip).each do |l|
freq = l.chars.inject(Hash.new(0)) { |p,v| p[v] += 1; p }
counts = freq.values
num2 += 1 if counts.include? 2
num3 += 1 if counts.include? 3
end
puts num2 * num3
| true
|
c53dcfa69ce6eadc8726a080981d6d3961d864e2
|
Ruby
|
ofrost617/Bank
|
/lib/transaction_log.rb
|
UTF-8
| 381
| 2.765625
| 3
|
[] |
no_license
|
require_relative './transaction_formatter.rb'
class TransactionLog
attr_reader :transaction_log
def initialize(transaction = TransactionFormatter.new)
@transaction = transaction
@transaction_log = []
end
def add_transaction(type, amount, balance)
new_transaction = @transaction.add(type, amount, balance)
@transaction_log << new_transaction
end
end
| true
|
5e7a227e99fba5b3842075d25e4ed4fde72c9185
|
Ruby
|
linhdangduy/ruby-learning
|
/wednesday/redflag.rb
|
UTF-8
| 284
| 2.90625
| 3
|
[] |
no_license
|
# solution
# save block passed to setup in a place
# then when event is call, it will call those object
@setups = []
def setup(&setting)
@setups << setting
end
def event(description)
@setups.each { |setting| setting.call }
puts description if yield
end
load 'setup_event.rb'
| true
|
b6c0e02e477f4b885829ce031cff2c71581a3ab8
|
Ruby
|
vlasisPit/ruby-training
|
/chapter_2/constants.rb
|
UTF-8
| 386
| 3.390625
| 3
|
[] |
no_license
|
=begin
Named using all uppercase letters
=end
# constant
MAX_SCORE = 100
# variable
max_score = 50
puts MAX_SCORE.class
puts MAX_SCORE == max_score
# Ruby lets you to change the value of a constant. But gives you a warning
MAX_SCORE = 50
puts MAX_SCORE == max_score
# If the first letter is capital, then Ruby consider this as a constant
Max_score = 50
Max_score = 150 #warning !!!
| true
|
4b0b000aa0ef211cafa2a231bab11b77cf58954a
|
Ruby
|
lintci/laundromat
|
/app/models/access_token.rb
|
UTF-8
| 1,015
| 2.59375
| 3
|
[] |
no_license
|
# API Token
class AccessToken < ActiveRecord::Base
belongs_to :user, required: true
validates :access_token, presence: true, uniqueness: true
validates :expires_at, presence: true
before_validation :set_access_token, :set_expires_at, on: :create
default_scope{order(:created_at)}
scope :active, ->{where('expires_at >= ?', Time.zone.now)}
class << self
def from_authorization(authorization)
return if authorization.blank?
access_token = authorization.gsub(/\ABearer /, '')
active.find_by(access_token: access_token)
end
end
def expires_in
seconds_remaining = (expires_at - Time.zone.now).round
seconds_remaining > 0 ? seconds_remaining : 0
end
private
def set_access_token
return if access_token.present?
loop do
self.access_token = SecureRandom.hex
break unless self.class.exists?(access_token: access_token)
end
end
def set_expires_at
return if expires_at.present?
self.expires_at = 30.days.from_now
end
end
| true
|
ad4f00a71fccc04922e84de68d3a4839ead02785
|
Ruby
|
seif-allaya/ASC-ReportParsingLib
|
/ASC-StatsReport.rb
|
UTF-8
| 2,155
| 2.875
| 3
|
[] |
no_license
|
require './ASC-CSVParselib'
require 'optparse'
require 'sqlite3'
#########################################################
# By: seif.allaya@gmail.com
#########################################################
# Connect to sqlite3 database
#
# NOt Ready Yet
#
# Print the stats
#########################################################
# Main
def main
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage: ruby excel_to_json.rb [options]"
opts.on('-i', '--database PATH', 'Input a valid Database name') { |folder| options[:inputdatabase] = folder }
opts.on('-o', '--output filename', 'Output filename') { |output| options[:outputfile] = output }
end
begin
optparse.parse!
#Chech on Input Database name
if options[:inputdatabase].nil?
raise OptionParser::MissingArgument
end
#Chech on Output file name
if options[:outputfile].nil?
options[:outputfile] = "Stats-#{Time.now.strftime("%d-%m-%Y_%H%M")}.csv"
end
#ERROR
rescue OptionParser::ParseError => e
puts "[OH] No file PATH, Noting to do!!".colorize(:red)
puts optparse
exit
end
#Starting
begin
db = SQLite3::Database.open(options[:inputdatabase])
table_name = options[:inputdatabase].to_s.downcase
stm = db.prepare "SELECT * FROM Cars LIMIT 5"
vulns_count = db.prepare("SELECT DISTINCT(Name) FROM #{table_name};").execute
hosts = db.prepare("SELECT DISTINCT(Host) FROM #{Table_name};").execute
hosts_stat = Array.new
hosts.each{ |host|
host_count = db.prepare("SELECT Count(Name) FROM #{Table_name}; WHERE Host = #{host}").execute
hosts_stat << [host, host_count]
}
hosts_stat.sort! { |x,y| x[2] <=> y[2] }
rescue SQLite3::Exception => e
puts "Exception occurred"
puts e
ensure
stm.close if stm
db.close if db
# Save the results
log("Total Vulnerabilities Count:",vulns_count)
log("Affected Hosts Count:",hosts.count)
log("Most vulnerable Host is#{hosts_stat[1]}:",hosts_stat[2])
log("Second Most vulnerable Host is #{hosts_stat[1]}:",hosts_stat[2])
log("Third Most vulnerable Host is #{hosts_stat[1]}:",hosts_stat[2])
end
end
# Starting Point
main()
| true
|
38da0f401cc60e6680ee23a0dc0abb0ff4975c7f
|
Ruby
|
jessegan/collections_practice-onl01-seng-ft-052620
|
/collections_practice.rb
|
UTF-8
| 919
| 3.8125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def sort_array_asc(arr)
arr.sort do |a,b|
a <=> b
end
end
def sort_array_desc(arr)
arr.sort do |a,b|
b<=>a
end
end
def sort_array_char_count(arr)
arr.sort do |a,b|
a.length <=> b.length
end
end
def swap_elements(arr)
if arr.length >= 3
arr[1],arr[2] = arr[2],arr[1]
end
arr
end
def reverse_array(arr)
rtn = []
arr.each do |x|
rtn.unshift(x)
end
rtn
end
def kesha_maker(arr)
rtn = []
arr.each do |str|
str[2] = "$"
rtn << str
end
rtn
end
def find_a(arr)
arr.select do |str|
str.start_with?("a")
end
end
def sum_array(arr)
# arr.inject do |sum,x|
# sum+x
# end
arr.reduce(:+)
end
def add_s(arr)
arr.each_with_index.collect do |str,i|
if i != 1
str<<"s"
else
str
end
end
end
| true
|
943b7fd5b24eab9267d9e67915f329acaef8d5e4
|
Ruby
|
thomasrogers03/thomas_utils
|
/spec/shared_examples/key_comparison.rb
|
UTF-8
| 1,295
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
shared_examples_for 'a method comparing two keys' do |method|
describe "##{method}" do
let(:key) { Faker::Lorem.word }
let(:value) { Faker::Lorem.word }
let(:lhs) { klass.new(key, value) }
let(:rhs) { klass.new(key, value) }
subject { lhs.public_send(method, rhs) }
it { is_expected.to eq(true) }
context 'when the value of one is different from the other' do
let(:rhs) { klass.new(key, Faker::Lorem.sentence) }
it { is_expected.to eq(false) }
end
context 'when the key of one is different from the other' do
let(:rhs) { klass.new(Faker::Lorem.sentence, value) }
it { is_expected.to eq(false) }
end
context 'when the right side is of the wrong type' do
let(:rhs) { String }
it { is_expected.to eq(false) }
end
end
end
shared_examples_for 'a method delegating #hash to the hash of #to_s' do
describe '#hash' do
let(:key) { klass.new(Faker::Lorem.word, Faker::Lorem.word) }
subject { key }
its(:hash) { is_expected.to eq(key.to_s.hash) }
end
end
shared_examples_for 'defining hashing methods for a key' do
it_behaves_like 'a method comparing two keys', :==
it_behaves_like 'a method comparing two keys', :eql?
it_behaves_like 'a method delegating #hash to the hash of #to_s'
end
| true
|
a268e7afac3e089de1b0fccbe95110decd688bd1
|
Ruby
|
adeshjohnson/MX3
|
/app/models/tax.rb
|
UTF-8
| 11,569
| 2.609375
| 3
|
[] |
no_license
|
# -*- encoding : utf-8 -*-
class Tax < ActiveRecord::Base
has_one :user
has_one :cardgroup
has_one :invoice
before_save :tax_before_save
=begin rdoc
Validates tax.
=end
def initialise(params = nil)
super(params)
self.compound ||= 1
end
def tax_before_save()
self.total_tax_name = "TAX" if self.total_tax_name.blank?
self.tax1_name = self.total_tax_name if self.tax1_name.blank?
end
=begin rdoc
Returns couns of enabled taxes.
=end
def get_tax_count
self.tax1_enabled.to_i+self.tax2_enabled.to_i+self.tax3_enabled.to_i+self.tax4_enabled.to_i
end
def sum_tax
sum =tax1_value.to_d
sum += tax2_value.to_d if tax2_enabled.to_i == 1
sum += tax3_value.to_d if tax3_enabled.to_i == 1
sum += tax4_value.to_d if tax4_enabled.to_i == 1
sum
end
def assign_default_tax(tax={}, opt ={})
options = {
:save => true,
}.merge(opt)
if !tax or tax == {}
tax ={
:tax1_enabled => 1,
:tax2_enabled => Confline.get_value2("Tax_2", 0).to_i,
:tax3_enabled => Confline.get_value2("Tax_3", 0).to_i,
:tax4_enabled => Confline.get_value2("Tax_4", 0).to_i,
:tax1_name => Confline.get_value("Tax_1", 0),
:tax2_name => Confline.get_value("Tax_2", 0),
:tax3_name => Confline.get_value("Tax_3", 0),
:tax4_name => Confline.get_value("Tax_4", 0),
:total_tax_name => Confline.get_value("Total_tax_name", 0),
:tax1_value => Confline.get_value("Tax_1_Value", 0).to_d,
:tax2_value => Confline.get_value("Tax_2_Value", 0).to_d,
:tax3_value => Confline.get_value("Tax_3_Value", 0).to_d,
:tax4_value => Confline.get_value("Tax_4_Value", 0).to_d,
:compound_tax => Confline.get_value("Tax_compound", 0).to_i
}
end
self.attributes = tax
self.save if options[:save] == true
end
=begin rdoc
Generates aaray of arrays [tax_name, tax_value] of all active taxes.
=end
def to_active_array
array = []
array << [self.tax1_name, self.tax1_value] if self.tax1_enabled.to_i == 1
array << [self.tax2_name, self.tax2_value] if self.tax2_enabled.to_i == 1
array << [self.tax3_name, self.tax3_value] if self.tax3_enabled.to_i == 1
array << [self.tax4_name, self.tax4_value] if self.tax4_enabled.to_i == 1
array
end
=begin rdoc
Dummy method to fake tax1_enabled option. Method always return 1.
*Returns*
1 - tax1 is always enabled.
=end
def tax1_enabled
return 1
end
=begin rdoc
Dummy method to cover fact that tax1 is always enabled
=end
def tax1_enabled=(*args)
end
=begin rdoc
Calculates amount with taxes applied.
*Params*
+amount+
*Returns*
+amount+ - float value representing the amount after taxes have been applied.
=end
def apply_tax(amount, options = {})
opts = {}.merge(options)
amount = amount.to_d
if self.compound_tax.to_i == 1
if opts[:precision]
amount += format("%.#{opts[:precision].to_i}f", (amount* tax1_value/100.0)).to_d if tax1_enabled.to_i == 1
amount += format("%.#{opts[:precision].to_i}f", (amount* tax2_value/100.0)).to_d if tax2_enabled.to_i == 1
amount += format("%.#{opts[:precision].to_i}f", (amount* tax3_value/100.0)).to_d if tax3_enabled.to_i == 1
amount += format("%.#{opts[:precision].to_i}f", (amount* tax4_value/100.0)).to_d if tax4_enabled.to_i == 1
else
amount += (amount* tax1_value/100.0) if tax1_enabled.to_i == 1
amount += (amount* tax2_value/100.0) if tax2_enabled.to_i == 1
amount += (amount* tax3_value/100.0) if tax3_enabled.to_i == 1
amount += (amount* tax4_value/100.0) if tax4_enabled.to_i == 1
end
else
tax = 0
if opts[:precision]
tax += format("%.#{opts[:precision].to_i}f", (amount* tax1_value/100.0)).to_d if tax1_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (amount* tax2_value/100.0)).to_d if tax2_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (amount* tax3_value/100.0)).to_d if tax3_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (amount* tax4_value/100.0)).to_d if tax4_enabled.to_i == 1
else
tax += (amount* tax1_value/100.0) if tax1_enabled.to_i == 1
tax += (amount* tax2_value/100.0) if tax2_enabled.to_i == 1
tax += (amount* tax3_value/100.0) if tax3_enabled.to_i == 1
tax += (amount* tax4_value/100.0) if tax4_enabled.to_i == 1
end
amount += tax
end
amount
end
=begin rdoc
Calculates amount of tax to be appliet do given amount.
*Params*
+amount+
*Returns*
+amount+ - float value representing the tax.
=end
def count_tax_amount(amount, options = {})
opts = {}.merge(options)
amount = amount.to_d
tax = amount
if self.compound_tax.to_i == 1
if opts[:precision]
tax += format("%.#{opts[:precision].to_i}f", (tax* tax1_value/100.0)).to_d if tax1_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (tax* tax2_value/100.0)).to_d if tax2_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (tax* tax3_value/100.0)).to_d if tax3_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (tax* tax4_value/100.0)).to_d if tax4_enabled.to_i == 1
else
tax += (tax* tax1_value/100.0) if tax1_enabled.to_i == 1
tax += (tax* tax2_value/100.0) if tax2_enabled.to_i == 1
tax += (tax* tax3_value/100.0) if tax3_enabled.to_i == 1
tax += (tax* tax4_value/100.0) if tax4_enabled.to_i == 1
end
return tax - amount
else
if opts[:precision]
tax = format("%.#{opts[:precision].to_i}f", (amount* tax1_value/100.0)).to_d
tax += format("%.#{opts[:precision].to_i}f", (amount* tax2_value/100.0)).to_d if tax2_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (amount* tax3_value/100.0)).to_d if tax3_enabled.to_i == 1
tax += format("%.#{opts[:precision].to_i}f", (amount* tax4_value/100.0)).to_d if tax4_enabled.to_i == 1
else
tax = amount* tax1_value/100.0
tax += (amount* tax2_value/100.0) if tax2_enabled.to_i == 1
tax += (amount* tax3_value/100.0) if tax3_enabled.to_i == 1
tax += (amount* tax4_value/100.0) if tax4_enabled.to_i == 1
end
return tax
end
end
=begin rdoc
Calculates amount after applying all taxes in tax object.
*Params*
+amount+ - amount with vat.
*Returns*
+amount+ - float value representing the amount with taxes substracted.
=end
def count_amount_without_tax(amount, options = {})
opts = {}.merge(options)
amount = amount.to_d
if self.compound_tax.to_i == 1
if opts[:precision]
amount = format("%.#{opts[:precision].to_i}f", (amount/(tax4_value.to_d+100)*100)).to_d if tax4_enabled.to_i == 1
amount = format("%.#{opts[:precision].to_i}f", (amount/(tax3_value.to_d+100)*100)).to_d if tax3_enabled.to_i == 1
amount = format("%.#{opts[:precision].to_i}f", (amount/(tax2_value.to_d+100)*100)).to_d if tax2_enabled.to_i == 1
amount = format("%.#{opts[:precision].to_i}f", (amount/(tax1_value.to_d+100)*100)).to_d if tax1_enabled.to_i == 1
else
amount = (amount/(tax4_value.to_d+100)*100) if tax4_enabled.to_i == 1
amount = (amount/(tax3_value.to_d+100)*100) if tax3_enabled.to_i == 1
amount = (amount/(tax2_value.to_d+100)*100) if tax2_enabled.to_i == 1
amount = (amount/(tax1_value.to_d+100)*100) if tax1_enabled.to_i == 1
end
else
amount = amount.to_d/((sum_tax.to_d/100.0)+1.0).to_d
amount = format("%.#{opts[:precision].to_i}f", amount) if opts[:precision]
end
amount
end
=begin rdoc
Returns list with taxes applied to given amount.
=end
def applied_tax_list(amount, options = {})
opts = {}.merge(options)
amount = amount.to_d
list = []
if self.compound_tax.to_i == 1
if opts[:precision]
list << {:name => tax1_name.to_s, :value => tax1_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax1_value).to_d/100.0), :amount => amount += format("%.#{opts[:precision].to_i}f", (amount*tax1_value).to_d/100.0).to_d} if tax1_enabled.to_i == 1
list << {:name => tax2_name.to_s, :value => tax2_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax2_value).to_d/100.0), :amount => amount += format("%.#{opts[:precision].to_i}f", (amount*tax2_value).to_d/100.0).to_d} if tax2_enabled.to_i == 1
list << {:name => tax3_name.to_s, :value => tax3_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax3_value).to_d/100.0), :amount => amount += format("%.#{opts[:precision].to_i}f", (amount*tax3_value).to_d/100.0).to_d} if tax3_enabled.to_i == 1
list << {:name => tax4_name.to_s, :value => tax4_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax4_value).to_d/100.0), :amount => amount += format("%.#{opts[:precision].to_i}f", (amount*tax4_value).to_d/100.0).to_d} if tax4_enabled.to_i == 1
else
list << {:name => tax1_name.to_s, :value => tax1_value.to_d, :tax => amount*tax1_value/100.0, :amount => amount += amount*tax1_value/100.0} if tax1_enabled.to_i == 1
list << {:name => tax2_name.to_s, :value => tax2_value.to_d, :tax => amount*tax2_value/100.0, :amount => amount += amount*tax2_value/100.0} if tax2_enabled.to_i == 1
list << {:name => tax3_name.to_s, :value => tax3_value.to_d, :tax => amount*tax3_value/100.0, :amount => amount += amount*tax3_value/100.0} if tax3_enabled.to_i == 1
list << {:name => tax4_name.to_s, :value => tax4_value.to_d, :tax => amount*tax4_value/100.0, :amount => amount += amount*tax4_value/100.0} if tax4_enabled.to_i == 1
end
else
if opts[:precision]
list << {:name => tax1_name.to_s, :value => tax1_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax1_value).to_d/100.0), :amount => format("%.#{opts[:precision].to_i}f", (amount*tax1_value).to_d/100.0).to_d} if tax1_enabled.to_i == 1
list << {:name => tax2_name.to_s, :value => tax2_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax2_value).to_d/100.0), :amount => format("%.#{opts[:precision].to_i}f", (amount*tax2_value).to_d/100.0).to_d} if tax2_enabled.to_i == 1
list << {:name => tax3_name.to_s, :value => tax3_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax3_value).to_d/100.0), :amount => format("%.#{opts[:precision].to_i}f", (amount*tax3_value).to_d/100.0).to_d} if tax3_enabled.to_i == 1
list << {:name => tax4_name.to_s, :value => tax4_value.to_d, :tax => format("%.#{opts[:precision].to_i}f", (amount*tax4_value).to_d/100.0), :amount => format("%.#{opts[:precision].to_i}f", (amount*tax4_value).to_d/100.0).to_d} if tax4_enabled.to_i == 1
else
list << {:name => tax1_name.to_s, :value => tax1_value.to_d, :tax => amount*tax1_value/100.0, :amount => amount*tax1_value/100.0} if tax1_enabled.to_i == 1
list << {:name => tax2_name.to_s, :value => tax2_value.to_d, :tax => amount*tax2_value/100.0, :amount => amount*tax2_value/100.0} if tax2_enabled.to_i == 1
list << {:name => tax3_name.to_s, :value => tax3_value.to_d, :tax => amount*tax3_value/100.0, :amount => amount*tax3_value/100.0} if tax3_enabled.to_i == 1
list << {:name => tax4_name.to_s, :value => tax4_value.to_d, :tax => amount*tax4_value/100.0, :amount => amount*tax4_value/100.0} if tax4_enabled.to_i == 1
end
end
list
end
end
| true
|
69a4b47cf970f7070c41f1e54209824ac1a84bd1
|
Ruby
|
anitaf/classrubyproject
|
/ibs_to_kg.rb
|
UTF-8
| 87
| 2.84375
| 3
|
[] |
no_license
|
# 1 lb = 0.453592 kg
puts " How much does that duck weigh?"
weight = gets.chomp.to_i
| true
|
a24cbe1238e6816b2e6841be50286bf5257329d9
|
Ruby
|
Mloweedgar/eloquent_ruby_code
|
/19/ex_2_doc_with_on_save_spec.rb
|
UTF-8
| 1,451
| 3.28125
| 3
|
[] |
no_license
|
require '../code/doc3'
require '../utils/rspec_utils'
class Document ##(main
# Most of the class omitted...
def load( path )
@content = File.read( path )
on_load(path)
end
def save( path )
File.open( path, 'w') { |f| f.print( @content ) }
on_save(path)
end
def on_load( path )
end
def on_save( path )
end
end
class ChattyDocument < Document
def on_load( path )
puts "Hey, I've been loaded from #{path}!"
end
def on_save( path )
puts "Hey, I've been saved to #{path}!"
end
end ##main)
describe Document do
before :each do
File.delete("example.txt") if File.exist?("example.txt")
end
it 'should save and load without problems' do
doc = Document.new( 'example', 'russ', 'the rain in spain')
doc.save( 'example.txt' )
new_doc = Document.new( 'example', 'russ', 'hello' )
new_doc.load( 'example.txt')
new_doc.content.should == doc.content
end
end
describe ChattyDocument do
it 'should comment on what is going on' do
doc = ChattyDocument.new( 'example', 'russ', 'the rain in spain')
out = output_of { doc.save( 'example.txt' ) }
out.should match(/Hey.*saved.*example.txt/m)
new_doc = ChattyDocument.new( 'example', 'russ', 'hello' )
out = output_of { new_doc.load( 'example.txt') }
out.should match(/Hey.*loaded.*example/m)
new_doc.content.should == doc.content
end
end
| true
|
38bf4b431318faa0fb5350d1d953e0623738f248
|
Ruby
|
stevehook/checkout-kata
|
/spec/checkout_spec.rb
|
UTF-8
| 1,551
| 2.671875
| 3
|
[] |
no_license
|
require_relative '../lib/checkout'
require 'bigdecimal'
RSpec.describe Checkout do
let(:rules) { {} }
subject { Checkout.new(rules) }
it 'initial total is zero' do
expect(subject.total).to eql BigDecimal('0.0')
end
context 'without rules' do
it 'can scan items' do
subject.scan('001')
expect(subject.total).to eql BigDecimal('9.25')
end
it 'can scan multiple items' do
subject.scan('001')
subject.scan('002')
subject.scan('003')
expect(subject.total).to eql BigDecimal('74.20')
end
end
context 'with rules' do
let(:rules) { [
Checkout::MultiBuyPromotion.new('001', BigDecimal('8.50'), 2),
Checkout::TotalSpendPromotion.new(BigDecimal('60.0'), 10)
] }
it 'can scan items' do
subject.scan('001')
expect(subject.total).to eql BigDecimal('9.25')
end
it 'can scan multiple items and applies discount for total spend' do
subject.scan('001')
subject.scan('002')
subject.scan('003')
expect(subject.total).to eql BigDecimal('66.78')
end
it 'can scan multiple items and applies multibuy discount' do
subject.scan('001')
subject.scan('003')
subject.scan('001')
expect(subject.total).to eql BigDecimal('36.95')
end
it 'can scan multiple items and applies both multibuy and total spend discounts' do
subject.scan('001')
subject.scan('002')
subject.scan('001')
subject.scan('003')
expect(subject.total).to eql BigDecimal('73.76')
end
end
end
| true
|
b5b1a1d877010c23f61ae108c8769e25cca8a56b
|
Ruby
|
lrotschy/Ruby-Exercises
|
/Basics/advanced_12_9.rb
|
UTF-8
| 1,571
| 3.640625
| 4
|
[] |
no_license
|
# array = [Rational(1, 2), Rational(2, 1)]
# p array.sum < 3
require 'pry'
require 'pry-byebug'
def egyptian(num)
counter = 1
rationals = []
loop do
# binding.pry
next_frac = Rational(1, counter)
if rationals.sum + next_frac <= num
rationals.push(next_frac)
end
counter += 1
break if rationals.sum >= num
end
rationals.map { |rat| rat.denominator }
end
p egyptian(Rational(1, 1))
p egyptian(Rational(2, 1))
p egyptian(Rational(3, 1))
p egyptian(Rational(20, 1))
p egyptian(Rational(725, 1))
def unegyptian(denominators)
fractions = denominators.map { |d| Rational(1, d)}
fractions.sum
end
p unegyptian(egyptian(Rational(1, 1)))
p unegyptian(egyptian(Rational(2, 1)))
p unegyptian(egyptian(Rational(3, 1)))
p unegyptian(egyptian(Rational(1, 2))) == Rational(1, 2)
p unegyptian(egyptian(Rational(3, 4))) == Rational(3, 4)
p unegyptian(egyptian(Rational(39, 20))) == Rational(39, 20)
p unegyptian(egyptian(Rational(127, 130))) == Rational(127, 130)
p unegyptian(egyptian(Rational(5, 7))) == Rational(5, 7)
p unegyptian(egyptian(Rational(1, 1))) == Rational(1, 1)
p unegyptian(egyptian(Rational(2, 1))) == Rational(2, 1)
p unegyptian(egyptian(Rational(3, 1))) == Rational(3, 1)
# def egyptian(num)
# denom = 1
# denominators = []
#
# loop do
# current_num = Rational(1, denom)
# if num - current_num >= 0
# num -= current_num
# denominators.push(denom)
# end
# denom += 1
# break if num <= 0
# end
# denominators
# end
# p egyptian(Rational(1, 1))
# p egyptian(Rational(2, 1))
# p egyptian(Rational(3, 1))
| true
|
a755d96685c38dae7e5009c997b1c46bc1ffb9fd
|
Ruby
|
tardate/ebook-toolchains
|
/epubbery/bin/epubbery
|
UTF-8
| 1,901
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
#!/usr/bin/env ruby
@gem_dir = File.expand_path(File.dirname(__FILE__) + '/..')
$: << File.join(@gem_dir, 'lib')
require 'fileutils'
require File.join(@gem_dir, 'lib', 'epubbery')
@epub = Epub.new
if ARGV[0]
@destination = ARGV[0]
@base_dir = File.expand_path(File.dirname(__FILE__) + '/..')
puts "Creating templates..."
FileUtils.mkdir_p @destination
puts "Copying necessary files..."
FileUtils.cp_r File.join(@base_dir, 'templates'), @destination
FileUtils.cp_r File.join(@base_dir, 'lib'), @destination
FileUtils.cp_r File.join(@base_dir, 'bin'), @destination
FileUtils.cp File.join(@base_dir, 'config_sample.yml'), File.join(@destination, 'config.yml')
puts "Done! Go to #{@destination} and edit config.yml and then run epubbery from that directory."
elsif File.exist?('config.yml')
@config = YAML::load(File.read('config.yml'))
@epub_folder = File.join(Dir.getwd, @config[:temp_epub_folder])
@epub.make_skeleton Dir.getwd, @epub_folder, @config[:default_template]
@book = Book.new @config[:book_title], @config[:author]
@book.chapters = Epub.read_chapters(@config[:chapter_glob])
@epub.write_templates(@book)
# TODO: use rubyzip or zipruby or something - they all seem to be a PITA compared to unix zip
FileUtils.cd @epub_folder
FileUtils.rm @config[:file_name] if File.exists?(@config[:file_name])
puts "\nGenerating #{@epub_folder}/#{@config[:file_name]}"
system "zip -0Xq #{@config[:file_name]} mimetype"
system "zip -Xr9Dq #{@config[:file_name]} *"
puts "\nRunning epubcheck..."
system "java -jar #{@config[:epubcheck]} #{@config[:file_name]}"
else
puts "USAGE:\n"
puts "To create a new epubbery project, run:"
puts " epubbery /path/to/new/epub/project\n"
puts "To generate an epub from inside an epubbery project, run:"
puts " epubbery"
puts "(a config.yml file is required in the same directory)"
exit
end
| true
|
f1e531e5f0faaa55ca3ed7a31689aa6cae6f83b7
|
Ruby
|
jimmyle414/key-for-min-value-online-web-sp-000
|
/key_for_min.rb
|
UTF-8
| 230
| 3.375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# 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)
return nil if name_hash.empty?
name_hash.max_by {|k, v| 0-v}[0]
end
| true
|
d0209a5be4bb1866331ee485e80c14a831051a0f
|
Ruby
|
JaniceYR/002_aA
|
/w1d2/01_project/match/humanplayer.rb
|
UTF-8
| 501
| 3.53125
| 4
|
[] |
no_license
|
class HumanPlayer
attr_reader :name, :board
attr_accessor :score
def initialize(name, board)
@name = name
@score = 0
@board = board
end
def guess
render
puts "Please enter the position of the card"
puts "Example x,y "
gets.chomp.split(",").map(&:to_i)
end
def render (pos = nil)
rendered = @board.board.map do |row|
row.map do |card|
card.visible ? card.value : "X"
end
end
rendered.each{|row| puts row.join(" ") }
end
end
| true
|
6a05f66ebe5bc777a532dfa4a82e254ffb9de586
|
Ruby
|
samirahmed/bonmetruck.com
|
/lib/copy/bin/copy
|
UTF-8
| 671
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
begin
require 'copy'
rescue LoadError
require 'rubygems'
require 'copy'
end
require 'copy/version'
require 'optparse'
OptionParser.new do |opts|
opts.banner = "Usage: copy [options]"
opts.on('-n', '--new [DIR]', 'Create a new Copy site in DIR') do |dir|
dir ||= '.'
site = File.dirname(File.expand_path(__FILE__)) + '/../lib/copy/generators/site/'
puts `mkdir -p #{dir} && cp -Riv #{site} #{dir}`
puts "Done!"
exit(0)
end
opts.on('-v', '--version') { puts "Copy v#{Copy::VERSION}"; exit(0) }
end.parse!
puts "Run `copy -n DIR' to generate a new Copy site in DIR."
puts "Run `copy --help' for all options."
exit(0)
| true
|
0e8f566708198d1baf4aa389ab2ae4caf1dba13d
|
Ruby
|
joelramsey/raven
|
/db/seeds.rb
|
UTF-8
| 2,126
| 2.515625
| 3
|
[] |
no_license
|
require 'faker'
require 'yajl'
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# user = User.create!({provider: 'email', uid: '1234567', email: 'test@gmail.com', password: '!QAZxsw2'})
# project = user.projects.create!({name: 'Chemistry Stuff', description: 'A test project with chemistry stuff'})
# record = project.records.create!({title: 'first source', result: 'Results from source one'})
# citation = Citation.create!({text: 'some citation stuff', record_id: 1})
# #Create Users
# user = User.create!({
# last_name: 'ramsey',
# first_name: 'joel',
# provider: 'email',
# uid: '',
# email: 'joel@me.com',
# password: 'joelthepole'
# })
# users = User.all
#
# # Create Projects
# project = user.projects.create!(
# name: Faker::Lorem.sentence,
# description: Faker::Lorem.paragraph
# )
# projects = Project.all
#
# # Create Resolutions
# resolution = user.resolutions.create!(
# entities: Faker::Lorem.sentence
# )
# resolutions = Resolution.all
#
# # Create Records
# 20.times do
# record = project.records.create!(
# result: Faker::Lorem.paragraph
# )
# end
# records = Record.all
# citations = Citation.all
file = File.join(Rails.root, 'db', 'sample.json')
json = File.new(file, 'r')
parser = Yajl::Parser.new
hash = parser.parse(json)
num = 0
#hash = hash.to_json
hash.each do |stuff|
Article.create(text: stuff)
puts num += 1
sleep(0.25)
end
articles = Article.all
# puts "Seeding finished"
# puts "#{User.count} users created"
# puts "#{Project.count} projects created"
# puts "#{Resolution.count} resolutions created"
# puts "#{Record.count} records created"
# puts "#{Citation.count} citations created"
puts "#{Article.count} articles created"
| true
|
95b51f8a968dcb1d0fb84a1815797c91cce655e3
|
Ruby
|
fog/fog-aws
|
/lib/fog/aws/requests/rds/create_db_parameter_group.rb
|
UTF-8
| 1,942
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module Fog
module AWS
class RDS
class Real
require 'fog/aws/parsers/rds/create_db_parameter_group'
# create a database parameter group
# http://docs.amazonwebservices.com/AmazonRDS/latest/APIReference/API_CreateDBParameterGroup.html
# ==== Parameters
# * DBParameterGroupName <~String> - name of the parameter group
# * DBParameterGroupFamily <~String> - The DB parameter group family name. Current valid values: MySQL5.1 | MySQL5.5
# * Description <~String> - The description for the DB Parameter Grou
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
def create_db_parameter_group(group_name, group_family, description)
request({
'Action' => 'CreateDBParameterGroup',
'DBParameterGroupName' => group_name,
'DBParameterGroupFamily' => group_family,
'Description' => description,
:parser => Fog::Parsers::AWS::RDS::CreateDbParameterGroup.new
})
end
end
class Mock
def create_db_parameter_group(group_name, group_family, description)
response = Excon::Response.new
if self.data[:parameter_groups] and self.data[:parameter_groups][group_name]
raise Fog::AWS::RDS::IdentifierTaken.new("Parameter group #{group_name} already exists")
end
data = {
'DBParameterGroupName' => group_name,
'DBParameterGroupFamily' => group_family.downcase,
'Description' => description
}
self.data[:parameter_groups][group_name] = data
response.body = {
"ResponseMetadata"=>{ "RequestId"=> Fog::AWS::Mock.request_id },
"CreateDBParameterGroupResult"=> {"DBParameterGroup"=> data}
}
response.status = 200
response
end
end
end
end
end
| true
|
aea0fd0fa55652c67e7a40074a48e8a0fffb80dd
|
Ruby
|
idokko/cally
|
/app/forms/message_form.rb
|
UTF-8
| 673
| 2.5625
| 3
|
[] |
no_license
|
class MessageForm
include ActiveModel::Model
# attr_accessorメソッド
# クラス外部からインスタンス変数を参照、変更可能にする
attr_accessor :content, :user_id, :room_id, :photos
validates :content_or_photo, presence: true
private
def content_or_photo
self.content.present? || MessageImage.photos.present?
end
def save!
# もし無効ならfalseを返す
return false if invalid?
message = Message.new(content: content, user_id: user_id, room_id: room_id)
message.message_images.build(photos: photos).save!
message.save! ? true : false
end
end
| true
|
4adb3bde6be1720bd287e7aa89998a6ecb23f565
|
Ruby
|
domitian/blackjack
|
/app/models/game.rb
|
UTF-8
| 4,198
| 2.8125
| 3
|
[] |
no_license
|
class Game < ActiveRecord::Base
# State machine for controlling the state of the game
include AASM
cattr_accessor :card_stack
@@num_card_decks = 6
# Storing the all 6 deck of card objects in this array
@@card_stack = Array.new(@@num_card_decks , CardDeck.new(%w{ 11 2 3 4 5 6 7 8 9 10 10 10 10}).deck_of_cards).flatten
serialize :cards_dealt, Array
has_many :game_steps
has_one :game_stat
enum state: {
started: 0,
player_move: 1,
ended: 2
}
enum winner: {
dealer: DEALER,
player: PLAYER
}
aasm :column => :state, :enum => true do
state :started, :initial => true, :after_enter => :deal_initial_hands
state :player_move, :after_enter => :greater_than_equal_to_21?
state :ended
event :control_to_player do
transitions :from => [:started], :to => :player_move
end
event :end_game do
transitions :from => [:player_move], :to => :ended, :after => :store_stats
end
end
def self.start_game bet_amt
game = Game.new.tap do |g|
g.bet_amount = bet_amt
g.save
end
end
def hit
self.cards_dealt << pick_random_card_from_available_cards
self.save
self.game_steps.create(move_type: 'hit',cards_dealt_to_player: [self.cards_dealt.last])
greater_than_equal_to_21?
end
def stand
self.cards_dealt << pick_random_card_from_available_cards
self.save
self.game_steps.create(move_type: 'stand',cards_dealt_to_dealer: [self.cards_dealt.last])
unless greater_than_equal_to_21?
@dealer_scores = dealer_score
@player_scores = player_score
if @dealer_scores <= 16
stand
else
if @player_scores > @dealer_scores
self.winner = PLAYER
elsif @dealer_scores > @player_scores
self.winner = DEALER
end
end_game!
end
end
end
def greater_than_equal_to_21?
puts "player score is #{player_score}, dealer_score is #{dealer_score}"
@player_scores = player_score
@dealer_scores = dealer_score
if @player_scores > 21 || @dealer_scores == 21
self.winner = DEALER
elsif @dealer_scores > 21 || @player_scores == 21
self.winner = PLAYER
else
return false
end
self.ended_at = Time.now
end_game!
return true
end
def player_score
player_cards.inject(0){|sum,e|
sum += e.value.to_i}
end
def dealer_score
dealer_cards.inject(0){|sum,e| sum += e.value.to_i}
end
def player_cards
cards_dealt_to_player = []
self.game_steps.each do |s|
cards_dealt_to_player.concat s.cards_dealt_to_player
end
@player_card_objects = @@card_stack.values_at *cards_dealt_to_player
end
def dealer_cards
cards_dealt_to_dealer = []
self.game_steps.each do |s|
cards_dealt_to_dealer.concat s.cards_dealt_to_dealer
end
@dealer_card_objects = @@card_stack.values_at *cards_dealt_to_dealer
end
def deal_initial_hands
# Picking three cards randomly to give 2 cards to player and 1 to dealer
self.cards_dealt << pick_random_card_from_available_cards
self.cards_dealt << pick_random_card_from_available_cards
self.cards_dealt << pick_random_card_from_available_cards
self.save
self.game_steps.create(move_type: 'deal',cards_dealt_to_player: self.cards_dealt[0..1],cards_dealt_to_dealer: self.cards_dealt[2..2])
self.control_to_player
end
private
def store_stats
GameStat.create(player_score: @player_scores,dealer_score: @dealer_scores,game_id: self.id)
end
def pick_random_card_from_available_cards
loop do
card_stack_index = rand(312)
unless self.cards_dealt.include? card_stack_index
return card_stack_index
end
end
end
end
| true
|
30c6402fb231aea7760416dec1824ccda123f7aa
|
Ruby
|
DouglasAllen/code-Metaprogramming_Ruby
|
/raw-code/PART_II_Metaprogramming_in_Rails/gems/activesupport-2.3.2/lib/active_support/core_ext/array/extract_options.rb
|
UTF-8
| 979
| 3.140625
| 3
|
[] |
no_license
|
#---
# Excerpted from "Metaprogramming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ppmetr2 for more book information.
#---
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Array #:nodoc:
module ExtractOptions
# Extracts options from a set of arguments. Removes and returns the last
# element in the array if it's a hash, otherwise returns a blank hash.
#
# def options(*args)
# args.extract_options!
# end
#
# options(1, 2) # => {}
# options(1, 2, :a => :b) # => {:a=>:b}
def extract_options!
last.is_a?(::Hash) ? pop : {}
end
end
end
end
end
| true
|
d63c711337040289f88d39a7a406a7d67c1d2ad8
|
Ruby
|
BottosWorld/triangle-classification-onl01-seng-pt-012120
|
/lib/triangle.rb
|
UTF-8
| 882
| 3.59375
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Triangle
def initialize(side1, side2, side3)
@triangle_sides = []
@triangle_sides << side1
@triangle_sides << side2
@triangle_sides << side3
end
def valid?
sum_1_2 = @triangle_sides[0] + @triangle_sides[1]
sum_1_3 = @triangle_sides[0] + @triangle_sides[2]
sum_2_3 = @triangle_sides[1] + @triangle_sides[2]
if (@triangle_sides.none? {|side| side <= 0}) &&
(sum_1_2 > @triangle_sides[2] && sum_1_3 > @triangle_sides[1] && sum_2_3 > @triangle_sides[0])
return true
else
return false
end
end
def kind
if valid?
if @triangle_sides.uniq.length == 1
return :equilateral
elsif @triangle_sides.uniq.length == 2
return :isosceles
else
return :scalene
end
else
raise TriangleError
end
end
class TriangleError < StandardError
end
end
| true
|
027965ba735b70ec3046df0aeafd740a91077c2d
|
Ruby
|
anthonyhamou/rails-yelp-mvp
|
/db/seeds.rb
|
UTF-8
| 863
| 2.65625
| 3
|
[] |
no_license
|
puts 'Cleaning database...'
Restaurant.destroy_all
puts 'Creating restaurants...'
restaurants_attributes = [
{
name: 'Dishoom',
address: '7 Boundary St, London E2 7JE',
phone_number: '0618493012',
category: 'japanese'
},
{
name: 'Pizza East',
address: '56A Shoreditch High St, London E1 6PQ',
phone_number: '0612895623',
category: 'italian'
},
{
name: 'Epicure',
address: 'rue Oberkampf',
phone_number: '0670389609',
category: 'french'
},
{
name: 'Burger Fries',
address: 'choux de bruxelles',
phone_number: '0645656637',
category: 'belgian'
},
{
name: 'Au temple maudit',
address: 'bakeer street',
phone_number: '0619305821',
category: 'chinese'
},
]
Restaurant.create!(restaurants_attributes)
puts 'Finished!'
| true
|
2d9ad2f1d923530fb7a881a6d7b10bace16b1ec1
|
Ruby
|
johnschoeman/AppAcademyProjects
|
/W2D3/first_tdd/lib/first_tdd.rb
|
UTF-8
| 749
| 3.265625
| 3
|
[] |
no_license
|
class Array
def my_uniq
self.uniq
end
def two_sum
res = []
(0...length-1).each do |i|
(i+1..length-1).each do |j|
res.push([i,j]) if self[i] + self[j] == 0
end
end
res
end
def my_transpose
self.transpose
end
end
def stock_picker(arr)
curr_prof_days = nil
largest_prof = -9000000
(0...arr.length-1).each do |start_pos|
(start_pos+1..arr.length-1).each do |end_pos|
curr_prof = 0
# check_prof = arr[start_pos] + arr[end_pos]
curr_prof -= arr[start_pos]
curr_prof += arr[end_pos]
if curr_prof > largest_prof && curr_prof > 0
curr_prof_days = [start_pos, end_pos]
largest_prof = curr_prof
end
end
end
curr_prof_days
end
| true
|
5a7a3351f270eb9995fa24b5624bd6c5d251bf1e
|
Ruby
|
rhoml/Portus
|
/spec/helpers/teams_helper_spec.rb
|
UTF-8
| 1,406
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
require "rails_helper"
RSpec.describe TeamsHelper, type: :helper do
let(:admin) { create(:admin) }
let(:owner) { create(:user) }
let(:viewer) { create(:user) }
let(:contributor) { create(:user) }
let(:team) do
create(:team,
owners: [owner],
contributors: [contributor],
viewers: [viewer])
end
describe "can_manage_team?" do
it "returns true if current user is an owner of the team" do
sign_in owner
expect(helper.can_manage_team?(team)).to be true
end
it "returns false if current user is a viewer of the team" do
sign_in viewer
expect(helper.can_manage_team?(team)).to be false
end
it "returns false if current user is a contributor of the team" do
sign_in contributor
expect(helper.can_manage_team?(team)).to be false
end
it "returns false if current user is an admin even if he is not related with the team" do
sign_in admin
expect(helper.can_manage_team?(team)).to be true
end
end
describe "role within team" do
it "returns the role of the current user inside of the team" do
sign_in viewer
expect(helper.role_within_team(team)).to eq "Viewer"
end
it "returns - for users that are not part of the team" do
sign_in create(:admin)
expect(helper.role_within_team(team)).to eq "-"
end
end
end
| true
|
02038bf817fd10b9cc97650c2a29c528346b7377
|
Ruby
|
danielkwon7/Algorithms
|
/skeleton/lib/assessment01.rb
|
UTF-8
| 2,680
| 4
| 4
|
[] |
no_license
|
require 'byebug'
class Array
# Monkey patch the Array class and add a my_inject method. If my_inject receives
# no argument, then use the first element of the array as the default accumulator.
def my_inject(accumulator = nil, &prc)
prc ||= Proc.new{|x,y| x + y}
ev = accumulator
accumulator ||= self[0]
self.each_with_index do |x, idx|
next if ev.nil? && idx == 0
accumulator = prc.call(accumulator, x)
end
accumulator
end
end
# primes(num) returns an array of the first "num" primes.
# You may wish to use an is_prime? helper method.
def is_prime?(num)
(2..num-1).each do |x|
return false if num % x == 0
end
true
end
def primes(num)
i = 2
arr = []
until arr.length == num
arr << i if is_prime?(i)
i += 1
end
arr
end
# Write a recursive method that returns the first "num" factorial numbers.
# Note that the 1st factorial number is 0!, which equals 1. The 2nd factorial
# is 1!, the 3rd factorial is 2!, etc.
def factorials_rec(num)
return [1] if num == 1
prev = factorials_rec(num-1)
prev + [prev.last * (num-1)]
end
class Array
# Write an Array#dups method that will return a hash containing the indices of all
# duplicate elements. The keys are the duplicate elements; the values are
# arrays of their indices in ascending order, e.g.
# [1, 3, 4, 3, 0, 3, 0].dups => { 3 => [1, 3, 5], 0 => [4, 6] }
def dups
hash = Hash.new{[]}
self.each_with_index do |x, idx|
hash[x] += [idx]
end
hash.select{|_, y| y.length > 1}
end
end
class String
# Write a String#symmetric_substrings method that returns an array of substrings
# that are palindromes, e.g. "cool".symmetric_substrings => ["oo"]
# Only include substrings of length > 1.
def symmetric_substrings
arr = []
(0..self.length-2).each do |x|
(x+1..self.length-1).each do |y|
str = self[x..y]
arr << str if str == str.reverse
end
end
arr
end
end
class Array
# Write an Array#merge_sort method; it should not modify the original array.
def merge_sort(&prc)
return self if self.length < 2
mid = self.length / 2
sorted_left = self.take(mid).merge_sort(&prc)
sorted_right = self.drop(mid).merge_sort(&prc)
Array.merge(sorted_left, sorted_right, &prc)
end
private
def self.merge(left, right, &prc)
arr = []
prc ||= Proc.new{|x,y| x <=> y}
until left.empty? || right.empty?
x, y = [left.first, right.first]
case prc.call(x, y)
when -1
arr << left.shift
when 0
arr << left.shifit
when 1
arr << right.shift
end
end
arr + left + right
end
end
| true
|
271ac0987cf4146222ee17906653632a72f4bdaf
|
Ruby
|
brannerchinese/RubySlides
|
/mvc_coffeecup_example/coffee_cup.rb
|
UTF-8
| 491
| 3.609375
| 4
|
[] |
no_license
|
class CoffeeCup
attr_reader :amount_left
def initialize
fill
end
def fill
@amount_left = 100 # Percent full
end
def empty
@amount_left = 0
end
def gulp
@amount_left -= Random.rand(17..35)
end
def sip
@amount_left -= 5
end
def to_s
if @amount_left == 100
"This cup is now full."
elsif @amount_left <= 0
"This cup is now empty — please fill it."
else
"There is #{@amount_left}% left."
end
end
end
| true
|
f9116ccd337aef2f01cf9938e69fb82d04545555
|
Ruby
|
joe-hamilton/RB_101
|
/rb_small_problems/medium_2/3.rb
|
UTF-8
| 3,447
| 4.6875
| 5
|
[] |
no_license
|
# Lettercase Percentage Ratio
=begin
(Understand the Problem)
Problem:
Write a method that takes a string, and then returns a hash that contains 3 entries:
- one represents the percentage of characters in the string that are lowercase letters
- one the percentage of characters that are uppercase letters
- one the percentage of characters that are neither
Inputs: String
Outputs: Hash
Questions:
1. Do we count non-alphanumeric characters as characters when counting?
Explicit Rules:
1. You may assume that the string will always contain at least one character
2.
Implicit Rules:
1. The values in the output Hash should be a decimal number
2.
Mental Model:
- Write a method that takes a String and outputs a Hash containing 3 keys: lowercase, uppercase, neither
- The method should count the respective characters and populate the values in the Hash depending on the characters in the input String
(Examples/Test Cases)
letter_percentages('abCdef 123') == { lowercase: 50.0, uppercase: 10.0, neither: 40.0 }
letter_percentages('AbCd +Ef') == { lowercase: 37.5, uppercase: 37.5, neither: 25.0 }
letter_percentages('123') == { lowercase: 0.0, uppercase: 0.0, neither: 100.0 }
(Data Structure)
Hash
(Algorithm)
- Define method `letter_percentages` with one parameter `str`
- Create a Hash with 3 keys: lowercase, uppercase, neither, with values of 0. Assign to `case_count`. Make sure the values are decimal numbers
- Split `str` into individual characters and iterate through it
- As you iterate through the individual elements, add 1 to the value of the respective key the current character applies to
- Define method `calculate_to_percentage` with 2 parameters `hsh` and `str`
- Iterate through `hsh` and divide the values by the size of `str` followed by multiplying that value by 100
- Return `hsh`
- Call the `calculate_to_percentage` method and pass in `case_count` and `str` as arguments
(Code)
=end
# Alternate Solution
=begin
UPPERCASE = ('A'..'Z').to_a
LOWERCASE = ('a'..'z').to_a
def return_character_hsh(str)
character_hsh = { lowercase: 0, uppercase: 0, neither: 0}
str.each_char do |char|
if LOWERCASE.include?(char)
character_hsh[:lowercase] += 1
elsif UPPERCASE.include?(char)
character_hsh[:uppercase] += 1
else
character_hsh[:neither] += 1
end
end
character_hsh
end
=end
def letter_percentages(str)
character_count = str.length
character_hsh = return_character_hsh(str)
character_hsh.each do |key, value|
character_hsh[key] = (value.to_f/character_count) * 100
end
character_hsh
end
def letter_percentages(str)
case_count = { lowercase: 0, uppercase: 0, neither: 0}
str.each_char do |char|
case char
when char =~ /[a-z]/ && char.downcase then case_count[:lowercase] += 1.0
when char =~ /[A-Z]/ && char.upcase then case_count[:uppercase] += 1.0
else case_count[:neither] += 1.0
end
end
calculate_to_percentage(case_count, str)
end
def calculate_to_percentage(hsh, str)
hsh.each do |key, value|
hsh[key] = (value / str.size) * 100
end
hsh
end
p letter_percentages('abCdef 123') == { lowercase: 50.0, uppercase: 10.0, neither: 40.0 }
p letter_percentages('AbCd +Ef') == { lowercase: 37.5, uppercase: 37.5, neither: 25.0 }
p letter_percentages('123') == { lowercase: 0.0, uppercase: 0.0, neither: 100.0 }
| true
|
9ad1f86e6099cbb15600f88b96c7ae83cf20b68f
|
Ruby
|
CDR2003/Brotorift
|
/src/lib/generators/bot_generator.rb
|
UTF-8
| 13,944
| 2.921875
| 3
|
[] |
no_license
|
require 'erb'
require_relative '../case_helper'
class EnumTypeDef
def bot_name
@name.underscore
end
def bot_read_name
"read_#{self.bot_name}"
end
def bot_write_name
"write_#{self.bot_name}"
end
def bot_read
"#{self.bot_read_name}(data)"
end
def bot_write member_name
"#{self.bot_write_name}(data, #{member_name})"
end
def bot_reader
"#{self.bot_read_name}/1"
end
def bot_writer
"#{self.bot_write_name}/2"
end
def bot_type
@elements.values.map { |e| e.bot_name } .join ' | '
end
end
class EnumElementDef
def bot_name
':' + @name.underscore
end
end
class BuiltinTypeDef
def bot_type
case @name
when 'Bool'
return 'boolean()'
when 'Byte'
return 'byte()'
when 'Short'
return 'integer()'
when 'Int'
return 'integer()'
when 'Long'
return 'integer()'
when 'UShort'
return 'non_neg_integer()'
when 'UInt'
return 'non_neg_integer()'
when 'ULong'
return 'non_neg_integer()'
when 'Float'
return 'float()'
when 'Double'
return 'float()'
when 'String'
return 'String.t()'
when 'DateTime'
return 'DateTime.t()'
when 'ByteBuffer'
return 'binary()'
when 'Vector2'
return '{float(), float()}'
when 'Vector3'
return '{float(), float(), float()}'
when 'Color'
return '{float(), float(), float(), float()}'
else
return @name
end
end
def bot_read
case @name
when 'Bool'
return "Brotorift.Binary.read_bool(data)"
when 'Byte'
return "Brotorift.Binary.read_byte(data)"
when 'Short'
return "Brotorift.Binary.read_short(data)"
when 'Int'
return "Brotorift.Binary.read_int(data)"
when 'Long'
return "Brotorift.Binary.read_long(data)"
when 'UShort'
return "Brotorift.Binary.read_ushort(data)"
when 'UInt'
return "Brotorift.Binary.read_uint(data)"
when 'ULong'
return "Brotorift.Binary.read_ulong(data)"
when 'Float'
return "Brotorift.Binary.read_float(data)"
when 'Double'
return "Brotorift.Binary.read_double(data)"
when 'String'
return "Brotorift.Binary.read_string(data)"
when 'ByteBuffer'
return "Brotorift.Binary.read_byte_buffer(data)"
when 'Vector2'
return "Brotorift.Binary.read_vector2(data)"
when 'Vector3'
return "Brotorift.Binary.read_vector3(data)"
when 'Color'
return "Brotorift.Binary.read_color(data)"
else
throw 'Invalid operation'
end
end
def bot_write member_name
case @name
when 'Bool'
return "Brotorift.Binary.write_bool(data, #{member_name})"
when 'Byte'
return "Brotorift.Binary.write_byte(data, #{member_name})"
when 'Short'
return "Brotorift.Binary.write_short(data, #{member_name})"
when 'Int'
return "Brotorift.Binary.write_int(data, #{member_name})"
when 'Long'
return "Brotorift.Binary.write_long(data, #{member_name})"
when 'UShort'
return "Brotorift.Binary.write_ushort(data, #{member_name})"
when 'UInt'
return "Brotorift.Binary.write_uint(data, #{member_name})"
when 'ULong'
return "Brotorift.Binary.write_ulong(data, #{member_name})"
when 'Float'
return "Brotorift.Binary.write_float(data, #{member_name})"
when 'Double'
return "Brotorift.Binary.write_double(data, #{member_name})"
when 'String'
return "Brotorift.Binary.write_string(data, #{member_name})"
when 'ByteBuffer'
return "Brotorift.Binary.write_byte_buffer(data, #{member_name})"
when 'Vector2'
return "Brotorift.Binary.write_vector2(data, #{member_name})"
when 'Vector3'
return "Brotorift.Binary.write_vector3(data, #{member_name})"
when 'Color'
return "Brotorift.Binary.write_color(data, #{member_name})"
else
throw 'Invalid operation'
end
end
def bot_reader
case @name
when 'Bool'
return "&Brotorift.Binary.read_bool/1"
when 'Byte'
return "&Brotorift.Binary.read_byte/1"
when 'Short'
return "&Brotorift.Binary.read_short/1"
when 'Int'
return "&Brotorift.Binary.read_int/1"
when 'Long'
return "&Brotorift.Binary.read_long/1"
when 'UShort'
return "&Brotorift.Binary.read_ushort/1"
when 'UInt'
return "&Brotorift.Binary.read_uint/1"
when 'ULong'
return "&Brotorift.Binary.read_ulong/1"
when 'Float'
return "&Brotorift.Binary.read_float/1"
when 'Double'
return "&Brotorift.Binary.read_double/1"
when 'String'
return "&Brotorift.Binary.read_string/1"
when 'ByteBuffer'
return "&Brotorift.Binary.read_byte_buffer/1"
when 'Vector2'
return "&Brotorift.Binary.read_vector2/1"
when 'Vector3'
return "&Brotorift.Binary.read_vector3/1"
when 'Color'
return "&Brotorift.Binary.read_color/1"
else
throw 'Invalid operation'
end
end
def bot_writer
case @name
when 'Bool'
return "&Brotorift.Binary.write_bool/2"
when 'Byte'
return "&Brotorift.Binary.write_byte/2"
when 'Short'
return "&Brotorift.Binary.write_short/2"
when 'Int'
return "&Brotorift.Binary.write_int/2"
when 'Long'
return "&Brotorift.Binary.write_long/2"
when 'UShort'
return "&Brotorift.Binary.write_ushort/2"
when 'UInt'
return "&Brotorift.Binary.write_uint/2"
when 'ULong'
return "&Brotorift.Binary.write_ulong/2"
when 'Float'
return "&Brotorift.Binary.write_float/2"
when 'Double'
return "&Brotorift.Binary.write_double/2"
when 'String'
return "&Brotorift.Binary.write_string/2"
when 'ByteBuffer'
return "&Brotorift.Binary.write_byte_buffer/2"
when 'Vector2'
return "&Brotorift.Binary.write_vector2/2"
when 'Vector3'
return "&Brotorift.Binary.write_vector3/2"
when 'Color'
return "&Brotorift.Binary.write_color/2"
else
throw 'Invalid operation'
end
end
end
class StructTypeDef
def bot_members
@members.map { |m| ":" + m.bot_name } .join ', '
end
def bot_members_with_types node
@members.map { |m| m.bot_name + ": " + m.type.bot_type(node) } .join ', '
end
def bot_members_with_values
@members.map { |m| m.bot_name + ": " + m.bot_name } .join ', '
end
def bot_type node
"#{node.namespace}.#{@name}.t"
end
def bot_read node
"#{node.namespace}.#{@name}.read(data)"
end
def bot_write node, member_name
"#{node.namespace}.#{@name}.write(data, #{member_name})"
end
def bot_reader node
"&#{node.namespace}.#{@name}.read/1"
end
def bot_writer node
"&#{node.namespace}.#{@name}.write/2"
end
end
class TypeInstanceDef
def bot_type node
return self.bot_list node if @type.name == 'List'
return self.bot_set node if @type.name == 'Set'
return self.bot_map node if @type.name == 'Map'
return @type.bot_type if @type.is_a? BuiltinTypeDef or @type.is_a? EnumTypeDef
return @type.bot_type node if @type.is_a? StructTypeDef
end
def bot_read node
return self.bot_list_read node if @type.name == 'List'
return self.bot_set_read node if @type.name == 'Set'
return self.bot_map_read node if @type.name == 'Map'
return @type.bot_read if @type.is_a? BuiltinTypeDef or @type.is_a? EnumTypeDef
return @type.bot_read node if @type.is_a? StructTypeDef
end
def bot_write node, member_name
return self.bot_list_write node, member_name if @type.name == 'List'
return self.bot_set_write node, member_name if @type.name == 'Set'
return self.bot_map_write node, member_name if @type.name == 'Map'
return @type.bot_write member_name if @type.is_a? BuiltinTypeDef or @type.is_a? EnumTypeDef
return @type.bot_write node, member_name if @type.is_a? StructTypeDef
end
def bot_reader node
return self.bot_list_reader node if @type.name == 'List'
return self.bot_set_reader node if @type.name == 'Set'
return self.bot_map_reader node if @type.name == 'Map'
return @type.bot_reader if @type.is_a? BuiltinTypeDef or @type.is_a? EnumTypeDef
return @type.bot_reader node if @type.is_a? StructTypeDef
end
def bot_writer node
return self.bot_list_writer node if @type.name == 'List'
return self.bot_set_writer node if @type.name == 'Set'
return self.bot_map_writer node if @type.name == 'Map'
return @type.bot_writer if @type.is_a? BuiltinTypeDef or @type.is_a? EnumTypeDef
return @type.bot_writer node if @type.is_a? StructTypeDef
end
def bot_list node
'list(' + @params[0].bot_type(node) + ')'
end
def bot_list_read node
'Brotorift.Binary.read_list(data, ' + @params[0].bot_reader(node) + ')'
end
def bot_list_write node, member_name
'Brotorift.Binary.write_list(data, ' + member_name + ', ' + @params[0].bot_writer(node) + ')'
end
def bot_list_reader node
'&Brotorift.Binary.read_list(&1, ' + @params[0].bot_reader(node) + ')'
end
def bot_list_writer node
'&Brotorift.Binary.write_list(&1, &2, ' + @params[0].bot_writer(node) + ')'
end
def bot_set node
'MapSet.t(' + @params[0].bot_type(node) + ')'
end
def bot_set_read node
'Brotorift.Binary.read_set(data, ' + @params[0].bot_reader(node) + ')'
end
def bot_set_write node, member_name
'Brotorift.Binary.write_set(data, ' + member_name + ', ' + @params[0].bot_writer(node) + ')'
end
def bot_set_reader node
'&Brotorift.Binary.read_set(&1, ' + @params[0].bot_reader(node) + ')'
end
def bot_set_writer node
'&Brotorift.Binary.write_set(&1, &2, ' + @params[0].bot_writer(node) + ')'
end
def bot_map node
'%{' + @params[0].bot_type(node) + ' => ' + @params[1].bot_type(node) + '}'
end
def bot_map_read node
'Brotorift.Binary.read_map(data, ' + @params[0].bot_reader(node) + ', ' + @params[1].bot_reader(node) + ')'
end
def bot_map_write node, member_name
'Brotorift.Binary.write_map(data, ' + member_name + ', ' + @params[0].bot_writer(node) + ', ' + @params[1].bot_writer(node) + ')'
end
def bot_map_reader node
'&Brotorift.Binary.read_map(&1, ' + @params[0].bot_reader(node) + ', ' + @params[1].bot_reader(node) + ')'
end
def bot_map_writer node
'&Brotorift.Binary.write_map(&1, &2, ' + @params[0].bot_writer(node) + ', ' + @params[1].bot_writer(node) + ')'
end
end
class MemberDef
def bot_name
@name.underscore
end
end
class MessageDef
def bot_header_name
"@header_#{self.bot_name}"
end
def bot_name
@name.underscore
end
def bot_send_name
"send_#{self.bot_name}"
end
def bot_receive_name
"receive_#{self.bot_name}"
end
def bot_params
return '' if members.empty?
params = members.map { |m| m.bot_name } .join ', '
', ' + params
end
def bot_returns
return '' if members.empty?
members.map { |m| m.bot_name } .join ', '
end
def bot_params_with_types node
return '' if members.empty?
params = members.map { |m| m.bot_name + ' :: ' + m.type.bot_type(node) } .join ', '
', ' + params
end
def bot_return_types node
return '' if members.empty?
members.map { |m| m.type.bot_type(node) }.join ', '
end
end
class NodeDef
def bot_name
@name.underscore
end
def bot_client
@name + 'BotClient'
end
end
class BotGenerator < Generator
def initialize
super 'bot', :client
end
def generate node, runtime
self.generate_file node, runtime, 'bot_types_generator', "#{node.bot_name}_types"
self.generate_file node, runtime, 'bot_generator', node.bot_name
end
def generate_file node, runtime, template_file, generated_file
folder = File.expand_path File.dirname __FILE__
erb_file = folder + "/#{template_file}.ex.erb"
template = File.read erb_file
erb = ERB.new template
content = erb.result binding
output_dir = File.dirname runtime.filename
output_path = File.join output_dir, "#{generated_file}_bot.ex"
File.write output_path, content
end
end
Generator.add BotGenerator.new
| true
|
6c4bd185cbc68ebc209a435c02ff4c349dcdab13
|
Ruby
|
mejibyte/chords
|
/lib/chords/html_formatter.rb
|
UTF-8
| 1,192
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
require 'chords/png_formatter'
require 'base64'
module Chords
# Formats fingerings as <img/> tags (base64-encoded data URIs)
class HTMLFormatter
class NonCache
def fetch(key); yield end
end
attr_accessor :cache
def initialize(fretboard, cache=NonCache.new)
@fretboard = fretboard
@cache = cache
@png_formatter = PNGFormatter.new(@fretboard)
end
# TODO: accept a separator element in opts
def print(title, fingerings, opts={})
html = title.empty? ? '' : "<h2>#{title}</h2>\n"
fingerings.each do |fingering|
html += get_element(fingering, opts)
end
if opts[:inline]
html
else
File.open('chords.html', 'w') do |file|
file.write html
end
puts "Wrote chords.html"
end
end
private
def get_element(fingering, opts)
@cache.fetch(fingering.fid) do
png_data = @png_formatter.print(nil, [fingering], opts)
"<img src=\"data:image/png;base64,#{Base64.encode64(png_data)}\" />\n"
end
end
end
end
# TODO: change pdf and png formatter to be required only when needed
| true
|
d5a4ea283a1712656f28bba5823173d82f0c0c5b
|
Ruby
|
fardeen9983/Ultimate-Dux
|
/Languages/Ruby/Basics/files.rb
|
UTF-8
| 2,868
| 4.375
| 4
|
[] |
no_license
|
# File I/O
# In ruby we have an inbuilt collection of classes with features taht enable us to manipulate files
# The main calss amongst these is File. It has variety of options to open a file, read from it and write as well
# Opening a file - Make sure the file is provided in the same folder as the ruby file or else provide the full path to the file
# Pass the file name as parameter to the open function defined in the File class
# There are various modes as to how we open we file. We can pass r for reading, w for writing, etc
File.open("data.txt", "r") do |file|
# Now we have a variable that depicts the file we opened
# Print the file in the format Ruby interprets it
puts file
# The filesystem uses a pointer to track what has been read and what portion of file is remaining
# The cursor moves as we read or write data
# Read one character from file
puts "\nFirst character : " + file.readchar()
# Read one line from the file
# Misses the first cahracter as it has been read already and the pointer has moved past that
puts "First line : \n" + file.readline()
# Print the contents of the file
# The cursor has moved to the second line so first one will be skipped
# Uses the read function which returns entire file content as string
puts "File contents:\n" + file.read()
# Once you read all the file content, you will have reach the end of file
# Any read operations will lead to error as there is nothing to read anymore
end
# Can no longer use the file below
# Reopen the file
File.open("data.txt", "r") do |file|
# Read all the lines as array of strings
file.readlines().each_with_index do |line, index|
puts "Line #{index + 1} : #{line}"
end
end
# Use the file variable outside
file = File.open("data.txt", "r")
# We can perform all operations we did in the file blog
# Remember to close the file when no longer used
file.close()
# Writing to a file
# First step is to open the file this time eith the "w" flag for write. But this erase all existing content and create a new file if it doesnt exist
# The better way is to append to the content of the file, if deletion is not an option. Use the flag "a" in that case
File.open("data.txt", "a") do |file|
file.write("\nThe sun is brighter today")
end
# Creating a new File
# It is as simplee as opening anew file with "w" flag
# In this case as the file doesnt exist already, it will be created first and then opened
File.open("new.txt", "w") do |file|
file.write("\nThe sun is brighter today")
end
# The read and write mode
# So by using the "r+" flag we open the file with both read and wirte option. We start from the beginning of the file
File.open("data.txt", "r+") do |file|
# Skip 2 lines
2.times do
file.readline()
end
file.write("Overwrite 3rd line")
end
| true
|
706b3852fa3b3acbd2ea4251d21f52518ac7a302
|
Ruby
|
redbone1983/launch_school
|
/01_Pre_Course/08_More_Stuff/inline_exception_example.rb
|
UTF-8
| 1,145
| 4.5
| 4
|
[] |
no_license
|
# zero = 0
# puts "Before each call"
# zero.each { |element| puts element} rescue puts "Can't do that!"
# puts "After each call"
=begin
Before each call
Can't do that!
After each call
=end
# => without the <rescue> this returns a syntax error
# zero = 0
# puts "Before each call"
# zero.each { |element| puts element} puts "Can't do that!"
# puts "After each call"
zero = [0, 0, 0, 0]
puts "Before each call"
zero.each { |element| puts element} rescue puts "Can't do that!"
puts "After each call"
# The inline <rescue> never runs because the <.each> method is passed a proper array zero = [0, 0, 0, 0]
=begin
Before each call
0
0
0
0
After each call
=end
# Important to know #
# It does so because it isn't possible to call the each method on an Integer which is the value of the zero variable. If we remove the rescue block, the second puts method will not execute because the program will exit when it runs into the error. You can see why the word "rescue" is relevant here. We are effectively rescuing our program from coming to a grinding halt. If we give this same code the proper variable, our rescue block never gets executed.
| true
|
b9cf613648258892d24240a20aed743b45a214e8
|
Ruby
|
Olive7ee/RubyS1
|
/lib/01_pyramids.rb
|
UTF-8
| 440
| 3.75
| 4
|
[] |
no_license
|
puts "Comment souhaitez-vous d'etage dans votre magnifique pyramide ? "
count = gets.chomp.to_i
#compte à rebourd de 1 jusqu'au chiffre
1.upto(count) do |i|
i.upto(count - 1) { print " " }
i.times { print "# " }
print "\n"
end
# -1 sur le milieu pour eviter le doublon
count = count - 1
# décompte du chiffre jusqu'a 1
count.downto(1) do |i|
i.upto(count) { print " " }
i.times { print "# " }
print "\n"
end
| true
|
0f4f7a41c6dded6061a51a74fac2b84619cd13f8
|
Ruby
|
gaar4ica/humanized_full_messages
|
/lib/humanized_full_messages/hash.rb
|
UTF-8
| 147
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
class Hash
def rekey(h)
dup.rekey! h
end
def rekey!(h)
h.each { |k, newk| store(newk, delete(k)) if has_key? k }
self
end
end
| true
|
b9f9e42d0d45f0e59cdf3119c1bb9c41a7df8094
|
Ruby
|
Dimesky/phase-0-tracks
|
/ruby/gps2_2.rb
|
UTF-8
| 4,278
| 4.5625
| 5
|
[] |
no_license
|
# Method to create a list
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# Allow for the method to take a string argument
# set default quantity - take the number of items in the string and create a quantity separated by spaces
# print the list to the console [can you use one of your other methods here?] Print each item back to the user
# output: Hash
# Method to add an item to a list
# input: item name and optional quantity, hash
# steps:
# Update the hash with the new items as the key and the quantity of each as the value
# output: hash
# Method to remove an item from the list
# input: hash, item name to remove
# steps:
# Figure out which item needs to be removed
# Check if the item exists, IF it does, remove the item from the list. If mulitples of the item exist, only remove 1 item.
# If it doesn't exist, keep all original items
# output: hash
# Method to update the quantity of an item
# input: hash, item, quantity
# steps:
# Find the index of the item we want to update
# Re-write the number of items that exist
# output: hash
# Method to print a list and make it look pretty
# input: hash
# steps:
# Iterate through hash
# On each iteration, ensure that the output of that item - number pair looks pretty
# output: string
def create_a_list(items)
item_array = items.split(' ')
item_hash = {}
item_array.each do |item|
item_hash[item] = 1
end
return item_hash
end
def add_item_to_list(item_name, item_hash, quantity = 1)
item_hash.store(item_name, quantity)
return item_hash
end
def remove_item_from_list(item_name, item_hash)
item_hash.delete_if {|item, number| item == item_name}
return item_hash
end
def update_quantity(item_name, item_hash, quantity)
if item_hash.has_key?(item_name)
item_hash[item_name] = quantity
end
return item_hash
end
def beautify(item_hash)
puts "Here is your grocery list: "
puts "-------------------------- "
puts ""
item_hash.each {|item, number| puts "#{item}: #{number}"}
end
# grocery_list = create_a_list("carrots apples cereal pizza")
# add_item_to_list("donuts", grocery_list, 5)
# remove_item_from_list("apples", grocery_list)
# update_quantity("carrots", grocery_list, 3)
# beautify(grocery_list)
new_list = create_a_list("donuts peppers milk")
add_item_to_list("lemonade", new_list, 2)
add_item_to_list("tomatoes", new_list, 3)
add_item_to_list("onions", new_list, 1)
add_item_to_list("ice cream", new_list, 4)
remove_item_from_list("lemonade", new_list)
update_quantity("ice cream", new_list, 1)
beautify(new_list)
#1. I learned that pseudocode is best when it is very descriptive in a step by step fashion. If it isn't descriptive, it
# => is much harder to use to accurately translate it to actual code. Pseudocode also has to include what data will be
# => input, and what will be output when defining methods.
#
#2. The tradeoffs of using arrays and hashes for this assignment is that srings can easily be converted into arrays, while it's
# => harder to turn them into hashes. However, hashes are easier to use when you want to keep track of differing amounts
# => of certain items that was called for in this exercise.
#
#3. A mthod returns the evaluation of the last statement that was listed in the method itself. That's why in each of our methods
# => we used an explicit return so that the implicit value (sometims an enumerator) was replaced with a hash value.
#
#4. You can pass any object into a method as an argument, even other method calls (which are subsequently evaluated to something
# => else before the outer method uses it as an argument.)
#
#5. You can pass information between methods by returning a value from a method, that is then used as an argument passed into the
# => parameter that was defined in another method declaration. This allows the new method to access the data that was manipulated
# => from the code that was defined in the original method.
#
#6. The concepts that were solidified in this challenge were how to pseudocode effectively, global vs local scope of variables,
# => and using explicit vs implicit return values. For me, the difficulty still lies with wrapping my brain around defining very
# => simple methods instead of long verbose ones.
| true
|
9693836ae275bbd646982262a010718501f80e9d
|
Ruby
|
G5/backups-manager
|
/lib/app_list.rb
|
UTF-8
| 1,151
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
class AppList
APP_TYPES = [ :cau, :cls, :clw, :cms, :cpas, :cxm, :dsh, :nae, :other ]
def self.get
app_list_uri = "https://api.heroku.com/apps"
headers = HerokuApiHelpers.default_headers(range: "name ..; max=1000;")
response = HTTPClient.get app_list_uri, nil, headers
data = JSON.parse response.body
# Heroku returns up to 1000 records at a time. A response code
# of 206 means we only got a subset, so go back for more data.
while response.code == 206
headers[:range] = response.headers["Next-Range"].gsub("]", "..")
response = HTTPClient.get app_list_uri, nil, headers
next_batch = JSON.parse response.body
data += next_batch
end
data
end
def self.sorted
app_list = self.get
sorted_apps = {}
APP_TYPES.each do |app_type|
sorted_apps[app_type] = []
end
app_list.each do |app|
split_name = app["name"].split("-")
if split_name.length > 3 && APP_TYPES.include?(split_name[1].to_sym)
grouping = split_name[1]
else
grouping = "other"
end
sorted_apps[grouping.to_sym] << app
end
sorted_apps
end
end
| true
|
4d134d9b6f05187508c8c72ca7a30989e99b61b0
|
Ruby
|
anoam/customers_locations
|
/lib/domain/point.rb
|
UTF-8
| 1,968
| 3.6875
| 4
|
[] |
no_license
|
# frozen_string_literal: true
module Domain
# Geo-point
class Point
RAD_PER_DEG = Math::PI / 180
EARTH_RADIUS = 6_371 # in kilometers
attr_reader :latitude, :longitude
# Check arguments and creates new instance
# @param latitude [Numerical] geo latitude
# @param longitude [Numerical] geo longitude
# @return [Point]
# @raise [InvalidDataError] if parameters invalid
def self.build(latitude:, longitude:)
raise(InvalidDataError, "Invalid latitude") unless latitude.is_a?(Numeric)
raise(InvalidDataError, "Invalid longitude") unless longitude.is_a?(Numeric)
raise(InvalidDataError, "Invalid latitude") unless latitude.between?(-90, 90)
raise(InvalidDataError, "Invalid longitude") unless longitude.between?(-180, 180)
new(latitude: latitude, longitude: longitude)
end
# @param latitude [Numerical] geo latitude
# @param longitude [Numerical] geo longitude
def initialize(latitude:, longitude:)
@latitude = latitude
@longitude = longitude
end
# rubocop:disable Metrics/AbcSize
# Calculates distance to other point in kilometers
# @param other [#latitude, #longitude]
# @return [Numeric] distance in kilometers
def distance_to(other)
latitude_rad = to_rad(latitude)
longitude_rad = to_rad(longitude)
other_latitude_rad = other.latitude * RAD_PER_DEG
other_longitude_rad = other.longitude * RAD_PER_DEG
# Deltas, converted to rad
delta_longitude_rad = longitude_rad - other_longitude_rad
delta_latitude_rad = latitude_rad - other_latitude_rad
distance_rad = Math.sin(delta_latitude_rad / 2)**2 +
Math.cos(latitude_rad) * Math.cos(other_latitude_rad) * Math.sin(delta_longitude_rad / 2)**2
2 * Math.asin(Math.sqrt(distance_rad)) * EARTH_RADIUS
end
# rubocop:enable Metrics/AbcSize
private
def to_rad(val)
val * RAD_PER_DEG
end
end
end
| true
|
1ff0376952fbfdfc15a45258c4b6c5b34e2743f6
|
Ruby
|
RITBreakingBread/EffortLog
|
/lib/util/week_mapper.rb
|
UTF-8
| 458
| 3
| 3
|
[
"MIT"
] |
permissive
|
class Util::WeekMapper
#a map of the week number to a range of dates surrounding that week
@@mapper = {
1 => ["2015-08-25 15:00", "2015-08-31 23:59"],
2 => ["2015-09-01 15:00", "2015-09-07 23:59"],
3 => ["2015-09-08 00:00", "2015-09-14 23:59"],
4 => ["2015-09-15 00:00", "2015-09-21 23:59"]
}
#given the week number, return the start and end date of that week
def self.week_range(week_number)
@@mapper[week_number]
end
end
| true
|
3fdf6ea94d6aa748762eb7e757d0b4ac8a14263f
|
Ruby
|
rdavidreid/ruby_chess
|
/lib/pieces/bishop.rb
|
UTF-8
| 486
| 3.234375
| 3
|
[] |
no_license
|
require_relative 'sliding_piece.rb'
class Bishop < Sliding_Piece
def initialize(color,board)
super(color,board)
if color == "white"
@icon = " ♝ "
else
@icon = " ♗ "
end
@slider = true
end
def moves(current_pos)
arr = []
arr += diagonal_moves(current_pos, 1, 1)
arr += diagonal_moves(current_pos, 1, -1)
arr += diagonal_moves(current_pos, -1, 1)
arr += diagonal_moves(current_pos, -1, -1)
return arr
end
end
| true
|
ff473fd30302ab839b81f7f670b8986d3513b657
|
Ruby
|
tatsiana-makers/domain-modelling
|
/do_not_look_until_after_workshop/book_library_starter_code.rb
|
UTF-8
| 265
| 3.171875
| 3
|
[] |
no_license
|
class Book
def initialize(name, author)
@name = name
@author = author
@damaged = false
end
end
class Library
def initialize
@books = []
end
def add(book)
end
def count_damaged_books
end
def books_by(author)
end
end
| true
|
b82cf88a6011ac34f48cf8133b1486dff016d1ff
|
Ruby
|
mraspberry/learning_ruby
|
/src/ruby_in_20_min/ex2.rb
|
UTF-8
| 425
| 4.125
| 4
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# frozen_string_literal: true
class Greeter
def initialize(name = "world")
@name = name.capitalize # this is an instance variable
end
# don't have to put the 'self' arg or even parens. This is sus
def greet
puts "Hello, #{@name}!"
end
def bye
puts "Goodbye #{@name}. Don't let the door hit you on the way out"
end
end
greeter = Greeter.new("world")
greeter.greet
greeter.bye
| true
|
1fe7a1295a94d59aa56e5fa625b074add2843ec7
|
Ruby
|
jhedden/jackhammer
|
/web/app/lib/common/models/wp_item/vulnerable.rb
|
UTF-8
| 1,140
| 2.640625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
# encoding: UTF-8
class WpItem
module Vulnerable
attr_accessor :db_file, :identifier
# Get the vulnerabilities associated to the WpItem
# Filters out already fixed vulnerabilities
#
# @return [ Vulnerabilities ]
def vulnerabilities
return @vulnerabilities if @vulnerabilities
@vulnerabilities = Vulnerabilities.new
[*db_data['vulnerabilities']].each do |vulnerability|
vulnerability = Vulnerability.load_from_json_item(vulnerability)
@vulnerabilities << vulnerability if vulnerable_to?(vulnerability)
end
@vulnerabilities
end
def vulnerable?
vulnerabilities.empty? ? false : true
end
# Checks if a item is vulnerable to a specific vulnerability
#
# @param [ Vulnerability ] vuln Vulnerability to check the item against
#
# @return [ Boolean ]
def vulnerable_to?(vuln)
if version && vuln && vuln.fixed_in && !vuln.fixed_in.empty?
unless VersionCompare::lesser_or_equal?(vuln.fixed_in, version)
return true
end
else
return true
end
return false
end
end
end
| true
|
16faa032bef17de022236806ec35cd3323875dee
|
Ruby
|
sumedhpendurkar/rottenpotatoes-rails-intro
|
/app/models/movie.rb
|
UTF-8
| 192
| 2.578125
| 3
|
[] |
no_license
|
class Movie < ActiveRecord::Base
def self.get_all_ratings
temp = Array.new
self.select('rating').uniq.each {|ele| temp.push(ele.rating)}
temp.sort.uniq
end
end
| true
|
c1868abe29277c0f8a161dfc0f6ada128b5f04ab
|
Ruby
|
amanelis/netdna2
|
/spec/core_ext/hash_spec.rb
|
UTF-8
| 1,465
| 2.90625
| 3
|
[] |
no_license
|
require 'spec_helper'
require File.join(File.dirname(__FILE__), '../../', 'lib/core_ext/hash')
describe Hash do
context "to_q" do
before(:all) do
@hash_0 = {}
@hash_1 = {"page"=>1, "pages"=>10, "page_size"=>"50", "current_page_size"=>50, "total"=>494}
@hash_2 = {page: 1, pages: 10, page_size: 50, current_page_size: 50, total: 494}
@result = "page=1&pages=10&page_size=50¤t_page_size=50&total=494"
@wrong = "page=1&pages=10&page_size=50¤t_page_size=50&total=494&"
end
it "should return '' if an empty or nil {} is called" do
method = @hash_0.to_q
method.should == '' && method.class.should == String
end
it "should return a correctly formatted response for a 1.8.7 formatted Hash:{}" do
method = @hash_1.to_q
method.should == @result && method.class.should == String
end
it "should return a correctly formatted response for a 1.9.2 formatted Hash:{}" do
method = @hash_2.to_q
method.should == @result && method.class.should == String
end
it "should not return a string with a trailing '&' for the .chomp! method should alter this - 1.8.7 Hash:{}" do
method = @hash_1.to_q
method.should_not == @wrong
end
it "should not return a string with a trailing '&' for the .chomp! method should alter this - 1.9.2 Hash:{}" do
method = @hash_2.to_q
method.should_not == @wrong
end
end
end
| true
|
c319a4546bfa05aa9ce9b1f1762ff2a974a56f85
|
Ruby
|
ashucoding/programming-univbasics-3-build-a-calculator-lab-online-web-prework
|
/lib/math.rb
|
UTF-8
| 313
| 3.09375
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def addition(num1, num2)
return num1 + num2
end
def subtraction(num1, num2)
return num1 - num2
end
def division(num1, num2)
return num1 / num2
end
def multiplication(num1, num2)
return num1 * num2
end
def modulo(num1, num2)
return num1 % num2
end
def square_root(num)
Math.square_root (num1, num2)
end
| true
|
f779baac0fa7557e6b5c1a0a3811d8e42696b618
|
Ruby
|
colinbull/get-into-teaching-app
|
/lib/acronyms.rb
|
UTF-8
| 865
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
class Acronyms
ABBR_REGEXP = %r{\b([A-Z][A-Z]+)\b}.freeze
def initialize(content, acronyms)
@document = parse_html(content)
@acronyms = acronyms || {}
end
def render
@document.tap(&method(:replace_acronyms)).to_html
end
private
def parse_html(content)
Nokogiri::HTML::DocumentFragment.parse(content)
end
def replace_acronyms(document)
document.traverse do |node|
next unless node.text?
replacements = 0
replacement = node.content.gsub(ABBR_REGEXP) do |acronym|
expanded = acronym_for(acronym)
next acronym unless expanded
replacements += 1
expanded
end
node.replace(replacement) if replacements.positive?
end
end
def acronym_for(acronym)
if @acronyms.key? acronym
"<abbr title=\"#{@acronyms[acronym]}\">#{acronym}</abbr>"
end
end
end
| true
|
259db24feb8f115aadf5f20186ec4ccd908f0ce4
|
Ruby
|
HopeFrost/ruby_challenges
|
/love_loop.rb
|
UTF-8
| 74
| 3.28125
| 3
|
[] |
no_license
|
love = "love"
while (love == "love")
puts "I'll love you forever"
end
| true
|
65b17aad18b9fa983f02cf5ea10e95b80d46419f
|
Ruby
|
Blaked84/mork
|
/lib/mork/mimage.rb
|
UTF-8
| 4,955
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
require 'mork/npatch'
require 'mork/magicko'
module Mork
# @private
class Mimage
include Extensions
attr_reader :rm
attr_reader :choxq # choices per question
attr_reader :status
def initialize(path, grom)
@mack = Magicko.new path
@grom = grom.set_page_size @mack.width, @mack.height
@choxq = [(0...@grom.max_choices_per_question).to_a] * grom.max_questions
@rm = {} # registration mark centers
@valid = register
end
def valid?
@valid
end
def low_contrast?
@rm.any? { |k,v| v < @grom.reg_min_contrast }
end
def status
{
tl: @rm[:tl][:status],
tr: @rm[:tr][:status],
br: @rm[:br][:status],
bl: @rm[:bl][:status]
}
end
def set_ch(choxq)
@choxq = choxq.map { |ncho| (0...ncho).to_a }
# if set_ch is called more than once, discard memoization
@marked_choices = @choice_mean_darkness = nil
end
def choice_mean_darkness
@choice_mean_darkness ||= begin
itemator(@choxq) { |q,c| reg_pixels.average @grom.choice_cell_area(q, c) }
end
end
def marked
@marked_choices ||= begin
choice_mean_darkness.map do |cho|
[].tap do |choices|
cho.map.with_index do |drk, c|
choices << c if drk < choice_threshold
end
end
end
end
end
def barcode_bits
@barcode_bits ||= begin
@grom.barcode_bits.times.map do |b|
reg_pixels.average(@grom.barcode_bit_area b+1) < barcode_threshold
end
end
end
def overlay(what, where)
areas = case where
when :barcode
@grom.barcode_areas barcode_bits
when :cal
@grom.calibration_cell_areas
when :marked
choice_cell_areas marked
when :all
choice_cell_areas @choxq
when :max
@grom.choice_cell_areas.flatten
when Array
choice_cell_areas where
else
fail ArgumentError, 'Invalid overlay argument “where”'
end
round = where != :barcode
@mack.send what, areas, round
end
# write the underlying MiniMagick::Image to disk;
# if no file name is given, image is processed in-place;
# if the 2nd arg is false, then stretching is not applied
def save(fname=nil, reg=true)
pp = reg ? @rm : nil
@mack.save fname, pp
end
def save_registration(fname)
each_corner { |c| @mack.plus @rm[c][:x], @rm[c][:y], 30 }
each_corner { |c| @mack.outline [@grom.rm_crop_area(c)], false }
@mack.save fname, nil
end
# ============================================================#
private #
# ============================================================#
def itemator(cells)
cells.map.with_index do |cho, q|
cho.map { |c| yield q, c }
end
end
def choice_cell_areas(cells)
if cells.length > @grom.max_questions
fail ArgumentError, 'Maximum number of responses exceeded'
end
if cells.any? { |q| q.any? { |c| c >= @grom.max_choices_per_question } }
fail ArgumentError, 'Maximum number of choices exceeded'
end
itemator(cells) { |q,c| @grom.choice_cell_area q, c }.flatten
end
def each_corner
[:tl, :tr, :br, :bl].each { |c| yield c }
end
def choice_threshold
@choice_threshold ||= begin
dcm = choice_mean_darkness.flatten.min
(cal_cell_mean-dcm) * @grom.choice_threshold + dcm
end
end
def cal_cell_mean
m = @grom.calibration_cell_areas.map { |c| reg_pixels.average c }
m.inject(:+) / m.length.to_f
end
def barcode_threshold
@barcode_threshold ||= (paper_white + ink_black) / 2
end
def ink_black
reg_pixels.average @grom.ink_black_area
end
def paper_white
reg_pixels.average @grom.paper_white_area
end
def reg_pixels
@reg_pixels ||= NPatch.new @mack.registered_bytes(@rm), @mack.width, @mack.height
end
# find the XY coordinates of the 4 registration marks,
# plus the stdev of the search area as quality control
def register
each_corner { |c| @rm[c] = rm_centroid_on c }
@rm.all? { |k,v| v[:status] == :ok }
end
# returns the centroid of the dark region within the given area
# in the XY coordinates of the entire image
def rm_centroid_on(corner)
c = @grom.rm_crop_area(corner)
p = @mack.rm_patch(c, @grom.rm_blur, @grom.rm_dilate)
# byebug
n = NPatch.new(p, c.w, c.h)
cx, cy, sd = n.centroid
st = (cx < 2) or (cy < 2) or (cy > c.h-2) or (cx > c.w-2)
status = st ? :edgy : :ok
return {x: cx+c.x, y: cy+c.y, sd: sd, status: status}
end
end
end
| true
|
17f7c866a94ccdb3d7bb2f1fce4525b250a25b1c
|
Ruby
|
CalebKnox/ruby-music-library-cli-v-000
|
/lib/music-library-controller.rb
|
UTF-8
| 1,650
| 3.28125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class MusicLibraryController
attr_accessor :path
def initialize(path = "./db/mp3s")
@path = path
MusicImporter.new(@path).import
end
def call
input = ""
while input != "exit"
input = gets.strip
case input
when "list songs"
songs
when "list artists"
artists
when "list genres"
genres
when "play song"
play_song
when "list artist"
list_artist
when "list genre"
list_genre
end
end
def songs
Song.all.sort_by{|song| song.artist.name}.each_with_index do |song, index|
puts "#{index + 1}. #{song.artist.name} - #{song.name} - #{song.genre.name}"
end
end
end
def artists
Artist.all.each do |artist|
puts "#{artist.name}"
end
end
def genres
Genre.all.each do |genre|
puts "#{genre.name}"
end
end
def play_song
puts "Which song would you like to play?"
song_name_input = gets.strip
song_to_play = Song.all.sort_by{|song| song.artist.name}[song_name_input.to_i-1]
puts "Playing #{song_to_play.artist.name} - #{song_to_play.name} - #{song_to_play.genre.name}"
end
def list_artist
puts "Which artist would you like to list songs for?"
artist_name_input = gets.strip
Artist.find_by_name(artist_name_input).songs.each do |song|
puts "#{song.artist.name} - #{song.name} - #{song.genre.name}"
end
end
def list_genre
puts "which genre would you like to list songs for?"
genre_name_input = gets.strip
Genre.find_by_name(genre_name_input).songs.each do |song|
puts "#{song.artist.name} - #{song.name} - #{song.genre.name}"
end
end
end
| true
|
47dc04f9febc7014d831379bac0f1c9eab1b7f0f
|
Ruby
|
alvesdan/dummy-api
|
/app/models/dummy_api/response.rb
|
UTF-8
| 1,387
| 2.640625
| 3
|
[] |
no_license
|
require 'active_support/inflector'
require 'ffaker'
module DummyApi
class Response
attr_reader :settings
def initialize(settings)
@settings = settings
end
def to_hash
@to_hash ||= generate_hash
end
private
def generate_hash
{}.tap do |hash|
settings[:data].each do |key, options|
hash[key] = rows(options[:fields])
end
hash[:page] = settings[:page]
hash[:per_page] = settings[:per_page]
hash[:total] = settings[:total]
end
end
def rows(fields)
Array.new([]).tap do |rows|
page_rows_count.times do
row = Hash[
fields.map do |hash|
[hash.keys.first, field_to_value(hash.values.first)]
end
]
rows << row
end
end
end
def field_to_value(field)
[
'DummyApi',
'Fields',
field.capitalize
].join('::').constantize.new.value
end
def per_page
settings[:per_page]
end
def total
settings[:total]
end
def page
settings[:page]
end
def page_rows_count
[total - previous_rows_count, per_page].min
end
def previous_rows_count
[(page * per_page - per_page), 0].max
end
end
end
require_relative 'field'
require_relative 'fields/name'
require_relative 'fields/email'
| true
|
628eefb06ae8a4916df1d4ec81d6c71cda71ce19
|
Ruby
|
johngrayau/jg_piawe
|
/spec/rule_set_spec.rb
|
UTF-8
| 11,923
| 2.640625
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Piawe::RuleSet::Rule do
let (:valid) do
Piawe::RuleSet::Rule.played_by ( {
"applicableWeeks" => "1-26",
"percentagePayable" => 90,
"overtimeIncluded" => true
} )
end
let (:invalid) do
Piawe::RuleSet::Rule.played_by ( {
"applicableWeeks" => "foo",
"percentagePayable" => "bar",
"overtimeIncluded" => "baz"
} )
end
let (:empty) do
Piawe::RuleSet::Rule.played_by ( Hash.new )
end
let (:report_date) do
Date.new(2017, 3, 1)
end
let (:person) do
Piawe::Person.played_by ( {
"name" => "test person",
"hourlyRate" => 75.0,
"overtimeRate" => 150.0,
"normalHours" => 35.0,
"overtimeHours" => 5,
"injuryDate" => (report_date - 10.weeks).strftime("%Y/%m/%d")
} )
end
let (:overtime_included) do
Piawe::RuleSet::Rule.played_by ( {
"applicableWeeks" => "1-26",
"percentagePayable" => 90,
"overtimeIncluded" => true
} )
end
let (:overtime_not_included) do
Piawe::RuleSet::Rule.played_by ( {
"applicableWeeks" => "1-26",
"percentagePayable" => 60,
"overtimeIncluded" => false
} )
end
context "given a valid rule_hash" do
it "has the correct start week" do expect( valid.start_week ).to eql( 1 ); end
it "has the correct end week" do expect( valid.end_week ).to eql( 26 ); end
it "has the correct percentage payable" do expect( valid.percentage_payable ).to eql( 90 ); end
it "has the correct overtime included" do expect( valid.overtime_included ).to eql( true ); end
end
context "given an invalid rule_hash" do
it "rejects the invalid start week value" do expect{ invalid.start_week }.to raise_error( ArgumentError, /applicableWeeks key is not in valid format/ ); end
it "rejects the invalid end week value" do expect{ invalid.end_week }.to raise_error( ArgumentError, /applicableWeeks key is not in valid format/ ); end
it "rejects the invalid percentage payable value" do expect{ invalid.percentage_payable }.to raise_error( ArgumentError, /rule_hash has a non-numeric value for percentagePayable key: #{invalid['percentagePayable']}/ ); end
it "rejects the invalid overtime included value" do expect{ invalid.overtime_included }.to raise_error( ArgumentError, /overtimeIncluded value was not a boolean true or false - value was #{ invalid['overtimeIncluded'] }/); end
end
context "given an empty rule_hash" do
it "rejects the missing start week value" do expect{ empty.start_week }.to raise_error( ArgumentError, /rule hash did not have an applicableWeeks key: #{ empty.inspect}/ ); end
it "rejects the missing end week value" do expect{ empty.end_week }.to raise_error( ArgumentError, /rule hash did not have an applicableWeeks key: #{ empty.inspect}/ ); end
it "rejects the missing percentage payable value" do expect{ empty.percentage_payable }.to raise_error( ArgumentError, /rule_hash does not have a percentagePayable key: #{empty.inspect}/ ); end
it "rejects the missing overtime included value" do expect{ empty.overtime_included }.to raise_error( ArgumentError, /rule_hash does not have an overtimeIncluded key: #{empty.inspect}/ ); end
end
context "given a matching weeks-since-injury" do
it "should match" do expect( valid.matches?( 0 ) ).to eql(true); end
it "should match" do expect( valid.matches?( 10 ) ).to eql(true); end
it "should match" do expect( valid.matches?( 25.99999999 ) ).to eql(true); end
end
context "given a non-matching weeks-since-injury" do
it "should not match" do expect( valid.matches?( 26 ) ).to eql(false); end
end
context "given a rule hash with overtime included" do
it "calculates the correct pay with overtime" do expect( overtime_included.pay_for_this_week( person ) ).to eql( 3037.5 ); end
it "creates the correct report line" do expect( overtime_included.report_line( person, report_date ).to_s ).to eql( '{:name=>"test person", :pay_for_this_week=>"3037.50", :weeks_since_injury=>"10.00", :hourly_rate=>"75.000000", :overtime_rate=>"150.000000", :normal_hours=>"35.00", :overtime_hours=>"5.00", :percentage_payable=>"90.00", :overtime_included=>"true"}' ); end
end
context "given a rule hash with overtime not included" do
it "calculates the correct pay without overtime" do expect( overtime_not_included.pay_for_this_week( person ) ).to eql( 1575.0 ); end
it "creates the correct report line" do expect( overtime_not_included.report_line(person, report_date ).to_s ).to eql( '{:name=>"test person", :pay_for_this_week=>"1575.00", :weeks_since_injury=>"10.00", :hourly_rate=>"75.000000", :overtime_rate=>"150.000000", :normal_hours=>"35.00", :overtime_hours=>"5.00", :percentage_payable=>"60.00", :overtime_included=>"false"}' ); end
end
end # describe Piawe::RuleSet::Rule
describe Piawe::RuleSet, :private do
let (:overlapping_rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "26-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "104+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:gapped_rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "28-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "105+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:early_terminated_rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "27-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53+", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "105+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:unterminated_rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "27-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false}
]
end
let (:late_starting_rules_array) do
[
{"applicableWeeks" => "10-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "27-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "105+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:valid_rules_array) do
[
{"applicableWeeks" => "1-26", "percentagePayable" => 90, "overtimeIncluded" => true},
{"applicableWeeks" => "27-52", "percentagePayable" => 80, "overtimeIncluded" => true},
{"applicableWeeks" => "53-79", "percentagePayable" => 70, "overtimeIncluded" => true},
{"applicableWeeks" => "80-104", "percentagePayable" => 60, "overtimeIncluded" => false},
{"applicableWeeks" => "105+", "percentagePayable" => 10, "overtimeIncluded" => false}
]
end
let (:valid) do Piawe::RuleSet.new( valid_rules_array ); end
let (:report_date) do
Date.new(2017, 3, 1)
end
let (:person) do
Piawe::Person.played_by ( {
"name" => "test person",
"hourlyRate" => 75.0,
"overtimeRate" => 150.0,
"normalHours" => 35.0,
"overtimeHours" => 5,
"injuryDate" => (report_date - 100.weeks).strftime("%Y/%m/%d")
} )
end
let (:person2) do
Piawe::Person.played_by ( {
"name" => "test person 2",
"hourlyRate" => 75.0,
"overtimeRate" => 150.0,
"normalHours" => 35.0,
"overtimeHours" => 5,
"injuryDate" => (report_date - 10000.weeks).strftime("%Y/%m/%d")
} )
end
context "given an invalid argument" do
it "should raise an exception" do expect { Piawe::RuleSet.new("foo") }.to raise_error( ArgumentError, /rules array is required - got "foo"/ ); end
end
context "given an empty argument" do
it "should raise an exception" do expect { Piawe::RuleSet.new( Array.new ) }.to raise_error( ArgumentError, /rules array must contain at least one entry/ ); end
end
context "given an overlapping rules array" do
it "should raise an exception" do expect { Piawe::RuleSet.new(overlapping_rules_array) }.to raise_error( ArgumentError, /rule 1 ends at week 26 but rule 2 starts at week 26 - each rule should start one week after the prior rule ends/ ); end
end
context "given a gapped rules array" do
it "should raise an exception" do expect { Piawe::RuleSet.new(gapped_rules_array) }.to raise_error( ArgumentError, /rule 1 ends at week 26 but rule 2 starts at week 28 - each rule should start one week after the prior rule ends/ ); end
end
context "given an early-terminating rules array" do
it "should raise an exception" do expect { Piawe::RuleSet.new(early_terminated_rules_array) }.to raise_error( ArgumentError, /rule 3 has a terminating \+ sign, and should have been the last rule, however there was a subsequent rule: #{early_terminated_rules_array[3].inspect}/ ); end
end
context "given an un-terminated rules array" do
it "should raise an exception" do expect { Piawe::RuleSet.new(unterminated_rules_array) }.to raise_error( ArgumentError, /last rule must have a terminating \+ sign/ ); end
end
context "given a late starting rules array" do
it "should raise an exception" do expect { Piawe::RuleSet.new(late_starting_rules_array) }.to raise_error( ArgumentError, /rule 1 should start at week 1, but starts at week 10/ ); end
end
context "given a valid rules array" do
it "should have the correct size" do expect( valid.rules.size ).to eql(5); end
it "should have the correct start weeks" do expect( valid.rules.map( &:start_week ) ).to match_array( [ 1, 27, 53, 80, 105 ] ); end
it "should have the correct end weeks" do expect( valid.rules.map( &:end_week ) ).to match_array( [ 26, 52, 79, 104, nil ] ); end
it "should have the correct percentage payables" do expect( valid.rules.map( &:percentage_payable ) ).to match_array( [ 90, 80, 70, 60, 10 ] ); end
it "should have the correct overtime includeds" do expect( valid.rules.map( &:overtime_included ) ).to match_array( [ true, true, true, false, false ] ); end
it "should return the right early report line" do expect( valid.report_line(person, report_date ).to_s ).to eql( '{:name=>"test person", :pay_for_this_week=>"1575.00", :weeks_since_injury=>"100.00", :hourly_rate=>"75.000000", :overtime_rate=>"150.000000", :normal_hours=>"35.00", :overtime_hours=>"5.00", :percentage_payable=>"60.00", :overtime_included=>"false"}' ); end
it "should return the right late report line" do expect( valid.report_line(person2, report_date ).to_s ).to eql( '{:name=>"test person 2", :pay_for_this_week=>"262.50", :weeks_since_injury=>"10000.00", :hourly_rate=>"75.000000", :overtime_rate=>"150.000000", :normal_hours=>"35.00", :overtime_hours=>"5.00", :percentage_payable=>"10.00", :overtime_included=>"false"}' ); end
end
end # describe RuleSet
| true
|
4f1eb77b8cb81960b2a7ae774ab6f6aa3c5e065c
|
Ruby
|
PatrickArthur/profit_margin_generators
|
/revenue_calculator.rb
|
UTF-8
| 898
| 3.375
| 3
|
[] |
no_license
|
## ruby class that imports csv of gift cards sold to a business and generates key business
## indicators like cost, income, average spint per order etc....., checks that business
## card value isnt more then the revenue recieved for it and makes sure that
## cards are not redeemed before they are purchased or sold before being redeemed
class RevenueCalculator
require 'csv'
require 'profit_margin.rb'
require 'calculate_profit.rb'
attr_reader :file
attr_accessor :orders
def self.generate_report(file)
new(file).initiate_process
end
def initialize(file)
@file = file
@orders = []
###will add in way to print errors
end
def initiate_process
CSV.foreach(file) do |row|
data = ProfitMargin.new(row)
orders << data unless !data.valid?
end
CalculateProfit.key_indicators(orders)
end
end
RevenueCalculator.generate_report("file.csv")
| true
|
6737b5ed1303a14709849c36be92d46fbfff39d6
|
Ruby
|
yuichi-1208/vendingmachine
|
/vending_6.rb
|
UTF-8
| 2,288
| 3.734375
| 4
|
[] |
no_license
|
class VendingMachine
attr_reader :items, :slot_money, :sales_money
def initialize(items:)
@items = items
@slot_money = 0
@sales_money = 0
end
MONEY = [10, 50, 100, 500, 1000].freeze
def slot_money(money)
unless MONEY.include?(money)
puts "お取り扱いできません"
@slot_money += money
return return_money
end
@slot_money += money
puts "投入金額:#{@slot_money}円"
end
def current_slot_money
@slot_money
end
def return_money
puts "お釣りは #{@slot_money}円です"
@slot_money = 0
end
def sales
puts "売り上げ: #{@sales_money}円"
end
def menu
puts "メニューはこちらです"
puts "*" * 50
@items.each_with_index do |item, i|
puts "#{i}: #{item[:name]} (#{item[:price]}円)" if judge(i)
end
puts "*" * 50
end
def purchase(drink_number)
if judge(drink_number)
puts "#{items[drink_number][:name]} を購入しました!"
items[drink_number][:stock] -= 1
@sales_money += items[drink_number][:price]
@slot_money = current_slot_money - items[drink_number][:price]
return_money
end
end
def judge(drink_number)
if items[drink_number][:price] <= current_slot_money && items[drink_number][:stock] > 0
true
else
false
end
end
def item_info
items.each do |item|
puts "名前: #{item[:name]} 値段: #{item[:price]} 在庫: #{item[:stock]}個"
end
end
end
class Drink
attr_reader :item
def initialize
@item = [{name: "コーラ", price: 120, stock: 5}]
end
def add_item(name, price)
@item.push({name: name, price: price, stock: 5})
end
def item_reset
@item = []
end
def current_item
@item
end
def item_info
@item.each do |item|
puts "名前: #{item[:name]} 値段: #{item[:price]} 在庫: #{item[:stock]}個"
end
end
end
# require '/Users/oyamayuichi/workspace/vending_macine/vending_6.rb'
# drink = Drink.new
# drink.add_item("水", 100)
# drink.add_item("レッドブル", 200)
# items = drink.current_item
# vm = VendingMachine.new(items: items)
# vm.slot_money (1000)
# vm.menu
# vm.purchase(0)
# drink.item_info
# drink.item_reset
# vm.judge(0)
# vm.return_money
# vm.sales
# vm.item_info
| true
|
b49e40f625220d70e562dcca7b06912bea16bf4c
|
Ruby
|
devonhackley/algorithms
|
/Dynamic Programming/longest_increasing_seqence.rb
|
UTF-8
| 345
| 3.609375
| 4
|
[] |
no_license
|
def longest_increasing_seq(line)
ary = line.split(", ").map{|i| i.to_i }
res = [ary[0]]
(1...ary.size).each do |i|
if ary[i] > res[-1]
res << ary[i]
elsif ary[i] < res[-1] && ary[i] > res[-2]
res.pop
res << ary[i]
end
end
res
end
a = "15, 27, 14, 38, 26, 55, 46, 65, 0, 85"
p longest_increasing_seq(a)
| true
|
dda8f07889b05ccaa6f2d3b157f58f420fce5d27
|
Ruby
|
pinedevelop/zenvia-sms
|
/lib/zenvia/sms.rb
|
UTF-8
| 1,865
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
require 'rest-client'
require 'zenvia/configuration'
require 'zenvia/sms/detail_code'
require 'zenvia/sms/error'
require 'zenvia/sms/status_code'
require 'zenvia/sms/version'
module Zenvia
class SMS
BASE_URL = 'https://api-rest.zenvia.com/services'.freeze
def initialize(from: nil, to:, message:, callback: nil, id: nil, aggregate_id: nil)
@from = from
@to = to
@message = message
@callback = callback
@id = id
@aggregate_id = aggregate_id
end
def deliver
send
end
def schedule(time)
send(schedule_for: time)
end
def cancel
SMS.cancel(@id)
end
private
def send(schedule_for: nil)
schedule = schedule_for.strftime('%FT%T') if schedule_for
data = {
sendSmsRequest: {
from: @from,
to: @to,
schedule: schedule,
msg: @message,
callbackOption: @callback,
id: @id,
aggregateId: @aggregate_id
}
}
SMS.to_zenvia('send-sms', data.to_json)
end
class << self
def cancel(id)
SMS.to_zenvia("cancel-sms/#{id}", nil, :blocked)
end
def to_zenvia(endpoint, json_data, expected_status = :ok)
json_response = RestClient.post "#{BASE_URL}/#{endpoint}", json_data, default_headers
response = JSON.parse(json_response).values.first
status_code = StatusCode[response['statusCode']]
detail_code = DetailCode[response['detailCode']]
raise Error.new(status_code, detail_code, response['detailDescription']) unless status_code == expected_status
response
end
def default_headers
{
content_type: 'application/json',
authorization: "Basic #{Zenvia.config.authorization}",
accept: 'application/json'
}
end
end
end
end
| true
|
9aa2feead463b290d25b98b4a440d8253fa318da
|
Ruby
|
rgpass/talkative_robot
|
/talkative_robot.rb
|
UTF-8
| 1,007
| 4.0625
| 4
|
[] |
no_license
|
require 'pry'
# puts "Test message"
# puts "We're running this in the Terminal"
# puts "What is your name?"
# user_name = gets.chomp
# puts "Hey #{user_name}"
# puts "How are you doing?"
# mood = gets.chomp.downcase
# puts "Glad to hear you're #{mood}?"
if 5 > 6
puts "first response"
else
puts "default response"
end
# if !(false)
# puts "obvi"
# end
# unless true
# puts "wait what"
# else
# puts "obvi"
# end
# if store_proximity < 1 #miles
# go_to_store
# end
# go_to_store if store_proximity < 1 #miles
# puts "Wuddup" if 5 > 4 # => Wuddup
# puts "Testing" unless 5 > 4
a = 5
# case
# when a > 5
# puts "it's greater than 5"
# when a < 5
# puts "it's less than 5"
# when a == 5
# puts "it's 5!"
# else
# puts "it's not a number"
# end
case a
when 1..5 # a == 1 a == 2 a == 3
puts "It's between 1 and 5"
when 6 # a == 6
puts "It's 6"
when String # a.class == String
puts "You passed a string"
else
puts "You gave me #{a} -- I have no idea what to do with that."
end
| true
|
d5a9ea014d90af06c281381cf9548cf24d850488
|
Ruby
|
tiev/respanol
|
/lib/respanol/examenes/conjugacion_examen.rb
|
UTF-8
| 495
| 2.671875
| 3
|
[] |
no_license
|
module Respanol
module Examen
class ConjugacionExamen < ExamenBase
def initialize(verbos = nil)
@verbos = Array(verbos)
end
def conjugado(klase = nil)
klases = @verbos
klases = klases | Array(klase) unless klase.nil?
kl = klases.sample
pro = Pronombre.todos.sample
prefijo(kl)
ensayar("#{pro} ") do |v|
kl::CONJUGACION.find_index(v) == Pronombre.verbo_indice(pro)
end
end
end
end
end
| true
|
c3c1f9411308e7eb31c863cf071141ee940a1022
|
Ruby
|
moralesalberto/trebuchet
|
/trebuchet/trebuchet.rb
|
UTF-8
| 314
| 2.8125
| 3
|
[] |
no_license
|
class Trebuchet
attr_reader :game_window
def initialize(game_window)
@game_window = game_window
end
def base
@base ||= Base.new(self)
end
def lever
@lever ||= Lever.new(self)
end
def draw
base.draw
lever.draw
end
def update
lever.update
end
end
| true
|
135e86a67d0403e54e7d034c41420f05fdb909b5
|
Ruby
|
CodeCoreYVR/awesome_answers_mar_21
|
/db/seeds.rb
|
UTF-8
| 2,571
| 2.796875
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
#To run this file use command: rails db:seed
Like.destroy_all
Tagging.destroy_all
Tag.destroy_all
User.destroy_all
Answer.destroy_all # .delete_all
Question.destroy_all
## Diff b/w delete_all and destroy_all
# delete_all will forceably remove records from the corresponding table without activating any rails callbacks.
# destroy_all will remove the records but also call the model callbacks
NUM_QUESTION=200
PASSWORD='supersecret'
super_user= User.create(
first_name: "Jon",
last_name: 'Snow',
address: '628 6th Avenue, New Westminster, BC, Canada', #Faker::Address.street_address
email: 'js@winterfell.gov',
password: PASSWORD,
is_admin: true
)
10.times do
first_name= Faker:: Name.first_name
last_name= Faker::Name.last_name
User.create(
first_name: first_name,
last_name: last_name,
address: '700 Royal Avenue, New Westminster, BC, Canada',
email: "#{first_name}.#{last_name}@example.com",
password: PASSWORD
)
end
users=User.all
NUM_TAGS = 20
NUM_TAGS.times do
Tag.create(
name: Faker::Vehicle.make
)
end
tags = Tag.all
NUM_QUESTION.times do
created_at = Faker::Date.backward(days:365 * 5)
q=Question.create(
title: Faker::Hacker.say_something_smart,
body: Faker::GreekPhilosophers.quote,
view_count: rand(100_000),
created_at: created_at,
updated_at: created_at,
user: users.sample
)
if q.persisted? # we can also use .valid? to check the data that is entered in db was valid or not
q.answers= rand(0..15).times.map do
Answer.new(body: Faker::GreekPhilosophers.quote,user: users.sample)
end
end
q.likers = users.shuffle.slice(0, rand(users.count))
q.tags = tags.shuffle.slice(0, rand(tags.count))
end
questions = Question.all
answer=Answer.all
puts Cowsay.say("Generated #{questions.count} questions", :sheep)
puts Cowsay.say("Generated #{answer.count} answers", :tux)
puts Cowsay.say("Generated #{users.count} users", :beavis)
puts Cowsay.say("Login with #{super_user.email} and password: #{PASSWORD}", :koala)
puts Cowsay.say("Generated #{Like.count} likes", :frogs)
puts Cowsay.say("Generated #{Tag.count} tags", :bunny)
| true
|
7f117f648d52ca6ab6613f070c38f2f01ae02852
|
Ruby
|
emattei/BEAR_MBR
|
/old_ruby/caricaRfamSeed.rb
|
UTF-8
| 12,007
| 2.765625
| 3
|
[] |
no_license
|
class String
def is_upper?
!!self.match(/\p{Upper}/)
end
def is_lower?
!!self.match(/\p{Lower}/)
# or: !self.is_upper?
end
end
IUPAC=["R","Y","M","K","S","W","B","D","H","V","N"]
ACCEPTED=[">","<","."]
def caricaAllineamento(file)
h={}
File.open(file,"r") do |f|
while line=f.gets
if line[0..6]=="#=GF AC"
@name=line.chomp.split(" ")[2].strip
if h[@name]==nil
h[@name]={}
end
elsif line.chomp[0..6]=="#=GF SQ"
f.gets
line=f.gets
while line.chomp[0..1]!="//"
if line.chomp.split(" ")[1]=="SS_cons"
if h[@name][line.chomp.split(" ")[1]]==nil
h[@name][line.chomp.split(" ")[1]]=Array.new()
h[@name][line.chomp.split(" ")[1]].push(line.chomp.split(" ")[2])
else
h[@name][line.chomp.split(" ")[1]].push(line.chomp.split(" ")[2])
end
line=f.gets
if line.chomp.split(" ")[1]=="RF"
if h[@name][line.chomp.split(" ")[1]]==nil
h[@name][line.chomp.split(" ")[1]]=Array.new()
h[@name][line.chomp.split(" ")[1]].push(line.chomp.split(" ")[2])
else
h[@name][line.chomp.split(" ")[1]].push(line.chomp.split(" ")[2])
end
line=f.gets
else
h[@name]["RF"]="UNK"
#print line
end
elsif line.chomp.split(" ")[1]!=nil #and h1["#{@name}_#{line.chomp.split(" ")[0]}"]=="ok"
if h[@name][line.chomp.split(" ")[0]]==nil
h[@name][line.chomp.split(" ")[0]]=Array.new()
h[@name][line.chomp.split(" ")[0]].push(line.chomp.split(" ")[1])
else
h[@name][line.chomp.split(" ")[0]].push(line.chomp.split(" ")[1])
end
line=f.gets
else
line=f.gets
end
end
end
end
end
return h
end
def creaConstraint(h)
constraints={}
h.each{|k,v|
if h[k]["RF"]!="UNK"
constraints[k]={}
@SS_cons=h[k]["SS_cons"].join.split(//)
@cons=""
@RF=h[k]["RF"].join.split(//)
@RF.each_with_index{|o,i|
if @SS_cons[i]==">" or @SS_cons[i]=="<"
@cons+=@SS_cons[i]
else
if o.is_upper?
if IUPAC.include?(o)==false
if @SS_cons[i]=="."
@cons+="x"
else
if ACCEPTED.include?(@SS_cons[i])==true
if i==0 and @SS_cons[i]==">"
@cons+="."
else
@cons+=@SS_cons[i]
end
else
@cons+="."
end
end
else
@cons+="."
end
else
@cons+="."
end
end
}
#constraints[k]=@cons
end
v.each{|k1,v1|
@res_str=[]
@res_con=[]
if k1!="RF" and k1!="SS_cons" and h[k]["RF"]!="UNK"
v1.join.split(//).each_with_index{|o,i|
if o!="."
if @res_str.size.to_i==0
@res_str.push(o)
if @cons[i]==">"
@res_con.push(".")
else
@res_con.push(@cons[i])
end
else
@res_str.push(o)
@res_con.push(@cons[i])
end
end
}
#print k1,"\t",@res_con,"\n"
constraints[k][k1]=@res_con.join
end
}
}
return constraints
end
def caricaFamiglie(file)
h={}
File.open(file,"r") do |f|
while line=f.gets
h[line.chomp]=true
end
end
return h
end
def caricaRidondanza(file)
h={}
File.open(file,"r") do |f|
while line=f.gets
if line[0..0]==">"
field=line.chomp.split(";")
h["#{field[2].split(" ")[0]}"]=true
end
end
end
return h
end
def creaFileFolding(res,famiglie,constraints)
s=File.open("inputRNAfold","w")
res.each{|k,v|
#if famiglie[k]
if res[k]["RF"]!="UNK"
v.each{|k1,v1|
if k1!="RF" and k1!="SS_cons" #and ridondanza[k1]
s.write(">#{k}_#{k1}\n")
s.write("#{v1.join.delete(".")}\n")
s.write("#{constraints[k][k1]}\n")
end
}
end
#end
}
end
def creaAllineamentiFinali(res)
s=File.open("./alignRfamTotale","w")
s1=File.open("./alignFramTotale_with_acc","w")
tmp=""
File.open("./famiglie.bear","r") do |f|
while line=f.gets
field=line.chomp.split("_")
famiglia=field[0][1..-1]
accession=field[1]
f.gets
f.gets
b=f.gets.chomp
if famiglia!=tmp
tmp=famiglia
s.write(">#{famiglia}\n")
s1.write(">#{famiglia}\n")
end
s1.write("#{accession}\t")
i=0
res[famiglia][accession].join.split(//).each{|o|
if o=="."
s.write(".")
s1.write(".")
else
s.write(b[i])
s1.write(b[i])
i=i+1
end
}
s.write("\n")
s1.write("\n")
end
end
end
def creaMatrice()
conta=0
@m=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0)}
@m.each_index {|i| @m[i][i]=0}
num_pa=0
count=0
freq=Hash.new(0)
dove=1
align={}
File.open("./branchCompletoCorrezione.align","r") do |f|
while line=f.gets
if line[0..0]==">"
@name=line.chomp[1..-1]
align[@name]=Array.new()
line=f.gets
align[@name].push(line.chomp)
@s=true
count+=1
else
if @s
align[@name].push(line.chomp)
end
end
end
end
align.each{|k,v|
for i in 0..v.size.to_i-2
for j in i+1..v.size.to_i-1
tmp1=v[i].split(//)
tmp2=v[j].split(//)
for z in 0..tmp1.size.to_i-1
if TOTAL.index(tmp1[z])!=nil and TOTAL.index(tmp2[z])!=nil
if tmp2[z]==tmp1[z]
@m[TOTAL.index(tmp1[z])][TOTAL.index(tmp2[z])]+=1
num_pa+=1
freq[tmp1[z]]+=1
freq[tmp2[z]]+=1
else
@m[TOTAL.index(tmp2[z])][TOTAL.index(tmp1[z])]+=1
@m[TOTAL.index(tmp1[z])][TOTAL.index(tmp2[z])]+=1
num_pa+=1
freq[tmp1[z]]+=1
freq[tmp2[z]]+=1
end
end
end
end
end
}
z=freq.values.inject{|somma,b| somma+b}
freq.each_key{|k|
freq[k]=freq[k].to_f/z.to_f
}
zzzz=0.0
@m.each_index{|i|
@m.each_index{|j|
if i==j
#if @m[i][j]!=0
# @m[i][j]=(@m[i][j].to_f/num_pa.to_f)/(freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)
#end
@m[i][j]=Math.log10(((@m[i][j].to_f/num_pa.to_f)/(freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f))) #normale
#else
#@m[i][j]=Float::INFINITY
#end
#@m[i][j]=(Math.log(((@m[i][j].to_f/num_pa.to_f)/(freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)))/(Math.log(2)/3.0)) #scalata e arrotondata
#r=(@m[i][j]).infinite?
#if r==nil
# @m[i][j]=@m[i][j].to_f.round
#end
else
#if @m[i][j]!=0
# @m[i][j]=(@m[i][j].to_f/num_pa.to_f)/(2.0*freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)
#end
@m[i][j]=Math.log10(((@m[i][j].to_f/num_pa.to_f)/(2.0*freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f))) #normale
#else
#@m[i][j]=Float::INFINITY
#end
#@m[i][j]=(Math.log(((@m[i][j].to_f/num_pa.to_f)/(2.0*freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)))/(Math.log(2)/3.0)) #scalata e arrotondata
#r=(@m[i][j]).infinite?
#if r==nil
# @m[i][j]=@m[i][j].to_f.round
#end
end
}
}
# for i in 0..@m.size.to_i-1
#for j in 0..i
# zzzz=zzzz+@m[i][0].to_f
#end
# end
print conta,"\n"
return @m
# return zzzz
end
def creaMatriceMediaFamiglia()
@m=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0.0)}
@s1=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0.0)}
@tmp=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0.0)}
numeroCoppieTotali=0
freq=Hash.new(0)
align={}
File.open("./align","r") do |f|
while line=f.gets
if line[0..0]==">"
@name=line.chomp[1..-1]
align[@name]=Array.new()
line=f.gets
align[@name].push(line.chomp)
@s=true
else
if @s
align[@name].push(line.chomp)
end
end
end
end
grandezzaTotaleFamiglie=0.0
numeroTotaleFamiglie=0
align.each{|k,v|
count_tmpUguali=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0.0)}
count_tmpDoppi=Array.new(TOTAL.size.to_i){Array.new(TOTAL.size.to_i,0.0)}
grandezzaFamiglia=v.size.to_f
grandezzaTotaleFamiglie=grandezzaTotaleFamiglie+(1.0/grandezzaFamiglia.to_f)
numeroTotaleFamiglie+=1
for i in 0..v.size.to_i-2
for j in i+1..v.size.to_i-1
tmp1=v[i].split(//)
tmp2=v[j].split(//)
for z in 0..tmp1.size.to_i-1
if TOTAL.index(tmp1[z])!=nil and TOTAL.index(tmp2[z])!=nil
if tmp2[z]==tmp1[z]
index=TOTAL.index(tmp1[z])
count_tmpUguali[index][index]+=1.0
@s1[index][index]+=1.0
numeroCoppieTotali+=1
freq[tmp1[z]]+=1
freq[tmp2[z]]+=1
else
index1=TOTAL.index(tmp1[z])
index2=TOTAL.index(tmp2[z])
@s1[index2][index1]+=1.0
@s1[index1][index2]+=1.0
count_tmpDoppi[index2][index1]+=1.0
count_tmpDoppi[index1][index2]+=1.0
numeroCoppieTotali+=1
freq[tmp1[z]]+=1
freq[tmp2[z]]+=1
end
end
end
end
end
for i in 0..@m.size.to_i-1
for j in 0..@m.size.to_i-1
if count_tmpDoppi[i][j]!=0.0 and i!=j
@m[i][j]+=count_tmpDoppi[i][j].to_f/grandezzaFamiglia.to_f
elsif i==j and count_tmpUguali[i][j]!=0.0
@m[i][j]+=count_tmpUguali[i][j].to_f/grandezzaFamiglia.to_f
# print i,"\t",j,"\t",count_tmpUguali[i][j].to_f,"\t",@m[i][j],"\n"
end
end
end
}
z=freq.values.inject{|somma,b| somma+b}
freq.each_key{|k|
freq[k]=freq[k].to_f/z.to_f
}
@m.each_index{|i|
@m.each_index{|j|
if i==j
# @m[i][j]=Math.log(((@m[i][j].to_f/num_pa.to_f)/(freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f))) #normale
if @m[i][j]!=0.0
#print i,"\t",j,"\t",@m[i][j],"\t",numeroCoppieTotali,"\t",numeroTotaleFamiglie,"\t",grandezzaTotaleFamiglie,"\t",freq[TOTAL[i]].to_f,"\n"
@m[i][j]=@m[i][j].to_f/grandezzaTotaleFamiglie.to_f
#@m[i][j]=@m[i][j].to_f/((numeroCoppieTotali.to_f/(numeroTotaleFamiglie.to_f*grandezzaTotaleFamiglie.to_f)))
# @m[i][j]=(Math.log(((@m[i][j].to_f/((numeroCoppieTotali.to_f/numeroTotaleFamiglie.to_f)*(grandezzaTotaleFamiglie.to_f)))/(freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)))/(Math.log(2)/3.0)).round #scalata e arrotondata
# else
# print i,"\t",j,"\n"
end
else
# @m[i][j]=(@m[i][j].to_f/((num_pa.to_f/numeroTotaleFamiglie.to_f)*(grandezzaTotaleFamiglie.to_f)))
# @m[i][j]=Math.log(((@m[i][j].to_f/num_pa.to_f)/(2.0*freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f))) #normale
if @m[i][j]!=0.0
#print i,"\t",j,"\t",@m[i][j],"\t",numeroCoppieTotali,"\t",numeroTotaleFamiglie,"\t",grandezzaTotaleFamiglie,"\t",freq[TOTAL[i]].to_f,"\t",freq[TOTAL[j]].to_f,"\n"
@m[i][j]=@m[i][j].to_f/grandezzaTotaleFamiglie.to_f
# @m[i][j]=(Math.log(((@m[i][j].to_f/((numeroCoppieTotali.to_f/numeroTotaleFamiglie.to_f)*(grandezzaTotaleFamiglie.to_f)))/(2.0*freq[TOTAL[i]].to_f*freq[TOTAL[j]].to_f)))/(Math.log(2)/3.0)).round #scalata e arrotondata
# else
# print i,"\t",j,"\n"
end
end
}
}
# return @m
# zzzz=0.0
for i in 0..@m.size.to_i-1
for j in 0..@m.size.to_i-1#0..i
# zzzz=zzzz+@m[i][j].to_f
@tmp[i][j]=@s1[i][j]/@m[i][j]
end
end
# return @m,zzzz
return @tmp
end
#TOTAL=["a","b","c","d","e","f","g","h","i","=","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","^","!","\"","#","$","%","&","\'","(",")","+","2","3","4","5","6","7","8","9","0",">","[","]",":"]
TOTAL=["a","b","c","d","e","f","g","h","i","=","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","^","!","\"","#","$","%","&","\'","(",")","+","2","3","4","5","6","7","8","9","0",">","[","]",":","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","{","Y","Z","~","?","_","|","/","\\","}","@"]
#res={}
#res=caricaAllineamento(ARGV[0])
#constraints={}
#constraints=creaConstraint(res)
#creaAllineamentiFinali(res)
#famiglie={}
#famiglie=caricaFamiglie(ARGV[1])
#ridondanza={}
#ridondanza=caricaRidondanza(ARGV[2])
#creaFileFolding(res,famiglie,constraints)
#%x[RNAfold --noPS -C < inputRNAfold > outputRNAfold]
s=File.open("outputRNAfold_noEnergieCompleto","w")
File.open("./outputRNAfold","r") do |f|
while line=f.gets
s.write(line)
line=f.gets
s.write(line)
line=f.gets
s.write(line.chomp.split(" ")[0])
s.write("\n")
end
end
%x[java -jar BearEncoder_BranchCompleto.jar outputRNAfold_noEnergieCompleto famiglie.Rfam]
=begin
allineamenti={}
allineamenti=creaAllineamentiFinali(res)
=end
#m=creaMatriceMediaFamiglia()
#m=creaMatrice()
#print a,"\n"
#@m.each{|x|
# print x.join("\t"),"\n"
#}
| true
|
5ea9e1b726709fe97e3b47c6f0b807db9d5f1db4
|
Ruby
|
nitinkumarsagtani/My_Training_Repo
|
/Assignment-1/pyramid.rb
|
UTF-8
| 637
| 4.3125
| 4
|
[] |
no_license
|
#Program to print Star Pyramid
class Pyramid
def initialize(no_of_lines)
@no_of_lines = no_of_lines
end
def validate_input
@no_of_lines > 1
end
def show
puts "The pyramid of #{@no_of_lines} lines is : "
@no_of_lines.times do |index|
((@no_of_lines - 1) - index).times do
print " "
end
(2*(index + 1) - 1).times do
print '*'
end
print "\n"
end
end
end
puts "Enter the number of lines in pyramid "
star_pyramid = Pyramid.new(gets.chomp.to_i)
is_valid = star_pyramid.validate_input
if is_valid
star_pyramid.show
else
puts "Input is not valid."
end
| true
|
29ee21c869eebe45426c36a66a1f1da50cfe5327
|
Ruby
|
PeytonsProfile/erbcalculate
|
/calculator.rb
|
UTF-8
| 634
| 4.3125
| 4
|
[] |
no_license
|
def firstNumber
puts 'first number'
first_number = gets.chomp.to_i
first_number
end
def secondNumber
puts 'second number'
second_number = gets.chomp.to_i
second_number
end
def question
puts 'Would you like to [add] or [subtract] or [multiply] or [divide]'
operator = gets.chomp
if operator == 'add'
answer = firstNumber + secondNumber
puts answer
elsif operator == 'subtract'
answer = firstNumber - secondNumber
puts answer
elsif operator == 'multiply'
answer = firstNumber * secondNumber
puts answer
elsif operator == 'divide'
answer = firstNumber / secondNumber
puts answer
end
end
question
| true
|
462d0906c7e7bba456b6725d8c440389d4a9be78
|
Ruby
|
spencereir/SpencerC
|
/command.rb
|
UTF-8
| 736
| 3.21875
| 3
|
[] |
no_license
|
$commands = {
"variableDeclaration" => "dec",
"print" => "LOUDLYWHISPER",
"input" => "INPUTAVARIABLEPLS"
}
$command_help = {
"#{$commands['variableDeclaration']}" => "Used to declare a variable.\nSyntax: #{$commands['variableDeclaration']} (variable name) = (value)",
"#{$commands['print']}" => "Used to print text to the screen.\nSyntax: #{$commands['print']} \"text to print\"\n or: #{$commands['print']} (variable name)",
"#{$commands['input']}" => "Used to get user input.\nSyntax: #{$commands['print']} (variable to store data in)"
}
class Command
@function = ""
@command = ""
def initialize(function, command)
@function = function
@command = command
end
def dict()
puts $commands
end
end
| true
|
98ac104f46c01be2b7112f1d87bd9836976fadd1
|
Ruby
|
ysdyt/rc2012w_g4
|
/howto.rb
|
SHIFT_JIS
| 755
| 2.53125
| 3
|
[] |
no_license
|
#encoding: Shift_JIS
class HowTo
def initialize
@setumei = Image.load("images/setumei1.png")
@setumei2 = Image.load("images/setumei2.png")
@bgm = Sound.new("BGM/story.wav")
#$select = 0 #KvȂ
end
def start
@how_flag1 = true
@how_flag2 = false
end
def act
if @how_flag1 == true
Window.draw(0,0,@setumei)
if Input.keyPush?( K_RETURN)
@how_flag1 = false
@how_flag2 = true
end
elsif @how_flag2 == true
Window.draw(0,0,@setumei2)
if Input.keyPush?( K_RETURN)
case $select
when 0
@bgm.stop
return :game
when 1
@bgm.stop
return :game2
when 2
@bgm.stop
return :game3
end
end
end
return false
end
def draw
end
end
| true
|
f4770ef7578f0e203e08cd17aed1ff3aeae9ffa3
|
Ruby
|
danvideo/BEWD_NYC_5_Homework
|
/Dan_Schanler/midterm/wunderground.rb
|
UTF-8
| 1,160
| 3.078125
| 3
|
[] |
no_license
|
# wunderground.rb
require 'rest-client'
require 'JSON'
$API_KEY = ENV['WUNDERGROUND_API_KEY']
# can get an API key from their site and put it into ENV variables as WUNDERGROUND_API_KEY
# http://www.wunderground.com/weather/api
class WeatherQuery
attr_reader :city, :state_country
def initialize city, state_country
@city = city
@state_country = state_country
end
end
class Forecast
attr_reader :time, :desc, :temp, :wind
def initialize time, desc, temp, wind
@time = time
@desc = desc
@temp = temp
@wind = wind
end
end
class QueryProcessor
def process_query weather_query
result = RestClient.get('http://api.wunderground.com/api/' + $API_KEY + '/geolookup/conditions/q/' + weather_query.state_country + '/' + weather_query.city + '.json')
parsed = JSON.parse result
time = parsed["current_observation"]["observation_time"]
desc = parsed["current_observation"]["weather"]
temp = parsed["current_observation"]["temperature_string"]
wind = parsed["current_observation"]["windchill_string"]
the_forecast = Forecast.new time, desc, temp, wind
return the_forecast
end
end
| true
|
85c10b0020c5bad11d6061c585f68b5737d3c677
|
Ruby
|
mful/nyc_housing_code_violations
|
/tasks/export_global_stats.rb
|
UTF-8
| 3,044
| 3.0625
| 3
|
[] |
no_license
|
require 'date'
require 'csv'
require_relative '../init'
require_relative '../models/building'
require_relative '../models/housing_violation'
COLUMNS = [
'Time period',
'Filed',
'Resolved',
'Mean resolution time',
'Median resolution time',
'Resolved overdue',
'Resolved mean overdue time',
'Resolved median overdue time',
'Total overdue',
'Potentially overdue',
]
IMPORT_DATE = Date.parse '2020-10-02'
def median(violations, a, b)
vals = violations.map do |v|
v.send(a) - v.send(b)
end
vals.sort!
len = vals.length
(vals[(len - 1) / 2] + vals[len / 2]) / 2.0
end
HousingViolation.where(
'certifieddate IS NOT NULL AND violationstatus = ? AND inspectiondate > ?',
'Open',
Date.parse('2020-03-16'),
).count
HousingViolation.where(
'certifieddate IS NOT NULL AND violationstatus = ? AND inspectiondate < ?',
'Open',
Date.parse('2020-01-01'),
).count
def build_row(date, operator)
row = []
# filed
row << HousingViolation.where(
"inspectiondate #{operator} ?", date).count
# resolved
row << HousingViolation.where(
"inspectiondate #{operator} ? AND (
certifieddate IS NOT NULL OR violationstatus = ?)",
date,
'Close'
).count
# mean resolution time
row << HousingViolation.where(
"inspectiondate #{operator} ? AND certifieddate IS NOT NULL",
date
).average("certifieddate - inspectiondate").to_i
# median resolution time
row << median(HousingViolation.where(
"inspectiondate #{operator} ? AND certifieddate IS NOT NULL",
date
), :certifieddate, :inspectiondate)
# resolved overdue
row << HousingViolation.where(
"inspectiondate #{operator} ? AND certifieddate IS NOT NULL AND certifieddate > originalcertifybydate",
date
).count
# resolved mean overdue time
row << HousingViolation.where(
"inspectiondate #{operator} ? AND certifieddate IS NOT NULL AND certifieddate > originalcertifybydate",
date
).average("certifieddate - originalcertifybydate").to_i
# resolved median overdue time
row << median(HousingViolation.where(
"inspectiondate #{operator} ? AND certifieddate IS NOT NULL AND certifieddate > originalcertifybydate",
date
), :certifieddate, :originalcertifybydate)
# total overdue
row << HousingViolation.where(
"inspectiondate #{operator} ? AND (
(certifieddate IS NOT NULL AND certifieddate > originalcertifybydate)
OR (certifieddate IS NULL AND violationstatus = ? AND originalcertifybydate < ?))",
date,
'Open',
IMPORT_DATE
).count
# potentially overdue
row << HousingViolation.where(
"inspectiondate #{operator} ? AND originalcertifybydate < ?",
date,
IMPORT_DATE
).count
row
end
root = "/Users/matty/Documents/Reporting/housing_code_violations/data_processor/data"
CSV.open("#{root}/global.csv", 'w') do |csv|
csv << COLUMNS
csv << ['2019'] + build_row(Date.parse('2020-01-01'), '<')
csv << ['Pandemic'] + build_row(Date.parse('2020-03-16'), '>')
csv << ['June-Sept'] + build_row(Date.parse('2020-05-31'), '>')
end
| true
|
179237b7188ae63e319b9feb0856ea7ad5b9e594
|
Ruby
|
shekbagg/Color-My-Hex
|
/app/models/image.rb
|
UTF-8
| 1,080
| 3.25
| 3
|
[] |
no_license
|
require 'chunky_png'
require 'colorscore'
# Image and color processor for the bot
class Image
# Location to store temporary images created
PATH = 'public/temp/'
IMG_WIDTH = 200
# Return file containing image of the given hex color
def self.get_image_for_hex(hex)
# Creating an image from scratch, save as an interlaced PNG
png = ChunkyPNG::Image.new(IMG_WIDTH, IMG_WIDTH, ChunkyPNG::Color.from_hex(hex))
# Name png with hex value
file_name = PATH + hex.to_s + '.png'
png.save(file_name, :interlace => true)
# Init image file
file = File.new(file_name)
return file
end
# Returns the predominant hex value for the given image
def self.get_hex_value(url)
# Creates a histogram of colors for an image
histogram = Colorscore::Histogram.new(url.to_s)
# Exract the dominant color from the histogram
hex_value = histogram.scores.first.last.hex
return '#' + hex_value
end
# Clears the /public/temp folder of all images created
def self.clear_saved_images
FileUtils.rm_rf(Dir.glob(PATH + '*'))
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.