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 |
---|---|---|---|---|---|---|---|---|---|---|---|
c17bb962f8ede0ac3fa716b49f504485013ae2d5
|
Ruby
|
andrewhbc/git-api
|
/lib/get-repos.rb
|
UTF-8
| 620 | 3.34375 | 3 |
[] |
no_license
|
require 'net/http'
require 'uri'
require 'json'
# The goal of this exercise is to have a working piece of code that queries the API and returns a list of repository names. You can simply print the names to screen.
# You can write this code in any language of choice.
# Upload your code to a public github repo and paste the link below. Your readme file should include instructions on how to run your code.
uri = URI.parse("https://api.github.com/users/andrewhbc/repos")
response = Net::HTTP.get_response(uri)
json = JSON.parse(response.body)
puts "Public repos from andrewhbc:"
json.each { |repo| puts repo['name'] }
| true |
7678961c7cf47756c9f83aaaebae1a3f04239143
|
Ruby
|
priit/adva_cms
|
/engines/adva_spam/vendor/plugins/viking/lib/viking/akismet.rb
|
UTF-8
| 6,906 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
require 'net/http'
require 'uri'
require 'set'
# Akismet
#
# Author:: David Czarnecki
# Copyright:: Copyright (c) 2005 - David Czarnecki
# License:: BSD
#
# Rewritten to be more agnostic
module Viking
class Akismet < Base
class << self
attr_accessor :valid_responses, :normal_responses, :standard_headers,
:host, :port
end
self.host = 'rest.akismet.com'
self.port = 80
self.valid_responses = Set.new(['false', ''])
self.normal_responses = valid_responses.dup << 'true'
self.standard_headers = {
'User-Agent' => "Viking (Ruby Gem) v#{Viking::VERSION::STRING}",
'Content-Type' => 'application/x-www-form-urlencoded'
}
# Create a new instance of the Akismet class
#
# ==== Arguments
# Arguments are provided in the form of a Hash with the following keys
# (as Symbols) available:
#
# +api_key+:: your Akismet API key
# +blog+:: the blog associated with your api key
#
# The following keys are available and are entirely optional. They are
# available incase communication with Akismet's servers requires a
# proxy port and/or host:
#
# * +proxy_port+
# * +proxy_host+
def initialize(options)
super
self.verified_key = false
end
# Returns +true+ if the API key has been verified, +false+ otherwise
def verified?
(@verified_key ||= verify_api_key) != :false
end
# This is basically the core of everything. This call takes a number of
# arguments and characteristics about the submitted content and then
# returns a thumbs up or thumbs down. Almost everything is optional, but
# performance can drop dramatically if you exclude certain elements.
#
# ==== Arguments
# +options+ <Hash>:: describes the comment being verified
#
# The following keys are available for the +options+ hash:
#
# +user_ip+ (*required*)::
# IP address of the comment submitter.
# +user_agent+ (*required*)::
# user agent information.
# +referrer+ (<i>note spelling</i>)::
# the content of the HTTP_REFERER header should be sent here.
# +permalink+::
# permanent location of the entry the comment was submitted to
# +comment_type+::
# may be blank, comment, trackback, pingback, or a made up value like
# "registration".
# +comment_author+::
# submitted name with the comment
# +comment_author_email+::
# submitted email address
# +comment_author_url+::
# commenter URL
# +comment_content+::
# the content that was submitted
# Other server enviroment variables::
# In PHP there is an array of enviroment variables called <tt>_SERVER</tt>
# which contains information about the web server itself as well as a
# key/value for every HTTP header sent with the request. This data is
# highly useful to Akismet as how the submited content interacts with
# the server can be very telling, so please include as much information
# as possible.
def check_comment(options={})
return false if invalid_options?
message = call_akismet('comment-check', options)
{:spam => !self.class.valid_responses.include?(message), :message => message}
end
# This call is for submitting comments that weren't marked as spam but
# should have been (i.e. false negatives). It takes identical arguments as
# +check_comment+.
def mark_as_spam(options={})
return false if invalid_options?
{:message => call_akismet('submit-spam', options)}
end
# This call is intended for the marking of false positives, things that
# were incorrectly marked as spam. It takes identical arguments as
# +check_comment+ and +mark_as_spam+.
def mark_as_ham(options={})
return false if invalid_options?
{:message => call_akismet('submit-ham', options)}
end
# Returns the URL for an Akismet request
#
# ==== Arguments
# +action+ <~to_s>:: a valid Akismet function name
#
# ==== Returns
# String
def self.url(action)
"/1.1/#{action}"
end
protected
# Internal call to Akismet. Prepares the data for posting to the Akismet
# service.
#
# ==== Arguments
# +akismet_function+ <String>::
# the Akismet function that should be called
#
# The following keys are available to configure a given call to Akismet:
#
# +user_ip+ (*required*)::
# IP address of the comment submitter.
# +user_agent+ (*required*)::
# user agent information.
# +referrer+ (<i>note spelling</i>)::
# the content of the HTTP_REFERER header should be sent here.
# +permalink+::
# the permanent location of the entry the comment was submitted to.
# +comment_type+::
# may be blank, comment, trackback, pingback, or a made up value like
# "registration".
# +comment_author+::
# submitted name with the comment
# +comment_author_email+::
# submitted email address
# +comment_author_url+::
# commenter URL
# +comment_content+::
# the content that was submitted
# Other server enviroment variables::
# In PHP there is an array of enviroment variables called <tt>_SERVER</tt>
# which contains information about the web server itself as well as a
# key/value for every HTTP header sent with the request. This data is
# highly useful to Akismet as how the submited content interacts with
# the server can be very telling, so please include as much information
# as possible.
def call_akismet(akismet_function, options={})
http_post http_instance, akismet_function, options.update(:blog => options[:blog])
end
# Call to check and verify your API key. You may then call the
# <tt>verified?</tt> method to see if your key has been validated
def verify_api_key
return :false if invalid_options?
value = http_post http_instance, 'verify-key', :key => options[:api_key], :blog => options[:blog]
self.verified_key = (value == "valid") ? true : :false
end
def http_post(http, action, options = {})
data = options.to_query
resp = http.post(self.url(action), data, self.class.standard_headers)
log_request(self.url(action), data, resp)
resp.body
end
def url(action)
"/1.1/#{action}"
end
private
attr_accessor :verified_key
def http_instance
http = Net::HTTP.new([options[:api_key], self.class.host].join("."), options[:proxy_host], options[:proxy_port])
http.read_timeout = http.open_timeout = Viking.timeout_threshold
http
end
end
end
| true |
4cad88bfa81d34fb0d610a053e687a57af643b4d
|
Ruby
|
Leozartino/PadroesDeProjeto
|
/Memento/memento.rb
|
UTF-8
| 1,534 | 3.78125 | 4 |
[] |
no_license
|
#
class Post
attr_accessor :title, :body
def initialize(title, body)
@title, @body = title, body
end
def save
PostVersion.new self
end
def rollback(version)
@title = version.title
@body = version.body
end
end
class PostVersion
attr_reader :title, :body
def initialize(post)
@title = post.title
@body = post.body
end
end
class VersionHistory # folder
attr_reader :versions
def initialize
@versions = {}
@version_number = 0
end
def add(version)
@versions[@version_number] = version
@version_number += 1
end
def version(number)
@versions[number]
end
end
# Create a Post and a Folder
post = Post.new('My First Post', 'This is my first post. I hope people like it')
folder = VersionHistory.new
# Save the Post to the folder
folder.add(post.save)
# Check Status'
puts post.title
# => My First Post
puts post.body
# => This is my first post. I hope people like it
# Update the Post and save it
post.title = 'My First Post now with a longer title!'
post.body = "I hated my first introduction. I needed to rewrite it - here's the updated version"
folder.add(post.save)
puts post.title
# => My First Post now with a longer title!
puts post.body
# => I hated my first introduction. I needed to rewrite it - here's the updated version
# Everyone hates my updated version, let's restore the old one
post.rollback(folder.version(0))
puts post.title
# => My First Post
puts post.body
# => This is my first post. I hope people like it
| true |
071aeb86cc6fcbf4304cae799ba5646200e2a43c
|
Ruby
|
daichi-fumoto/dryflower
|
/app/models/question.rb
|
UTF-8
| 5,442 | 2.703125 | 3 |
[] |
no_license
|
class Question < ActiveHash::Base
self.data = [
{id: 1, text: "自分のいいところを3つ挙げてください"},
{id: 2, text: "次の文章に当てはまる言葉を考えてみて。\n「全ての人々が・・・だったらいいのになぁ」"},
{id: 3, text: "子供の頃にもらったプレゼントの中で\n特別なものは、なに?詳しく聞かせて。"},
{id: 4, text: "あなたにとって音楽とは?"},
{id: 5, text: "あなたの思う最高に贅沢なデザートとは?"},
{id: 6, text: "「正しいこと」と「間違っていること」の判断はどうやってつけている?"},
{id: 7, text: "あなたにとっての大切な休日っていつですか?理由も教えて。"},
{id: 8, text: "自分を童話のキャラクターに例えると\nなんですか?"},
{id: 9, text: "家出をすることについてどう思う?"},
{id: 10, text: "「自発的に何かをする」って、どういうことなんだろう?"},
{id: 11, text: "学校でのおもしろエピソードを聞かせてください。"},
{id: 12, text: "あなたにとって理想の休日とは?"},
{id: 13, text: "次の文章に当てはまる言葉を考えてみて。\n「私の大好きな音楽のジャンルは・・・です」"},
{id: 14, text: "現実にはありえないけど\n挑戦してみたいことってなに?"},
{id: 15, text: "あなたの密かな野望を話してください。"},
{id: 16, text: "子供の頃、\nどんな遊びをよくしましたか?"},
{id: 17, text: "次の文章に当てはまる言葉を考えてみて。\n「1日のうちで一番好きな時間は・・・です」"},
{id: 18, text: "あなたはどんな家に住みたいですか?\くわしく説明してください。"},
{id: 19, text: "お父さんは、あなたのことをどう思っているだろう?"},
{id: 20, text: "あなたが見た怖い夢を教えて。"},
{id: 21, text: "次の誕生日に欲しいものは、なんですか?"},
{id: 22, text: "子供の頃の、水泳についての\n思い出を聞かせてください。"},
{id: 23, text: "「頑張った!」と思うのは、どんなとき?"},
{id: 24, text: "あなたにとって「信頼できる仲間とは?」"},
{id: 25, text: "これまでやってきた仕事の中で\n一番嫌だった仕事は、なんですか?"},
{id: 26, text: "1日24時間が30時間に増えたら\nその時間をどうやって使いたいと思う?"},
{id: 27, text: "テレビが生活に与える影響って\nなんだと思う?"},
{id: 28, text: "「競争社会」について、あなたの意見を\n聞かせて。"},
{id: 29, text: "あなたにとって「素直」ってなに?"},
{id: 30, text: "何かを「やりたくない!」と思ったときはどうしますか?"},
{id: 31, text: "お母さんは、あなたのことを\nどう思っているんだろう"},
{id: 32, text: "自分を色にたとえると何色だと思う?\n理由も教えて。"},
{id: 33, text: "1日中親友と過ごせるなら何をする?"},
{id: 34, text: "家から閉め出されたことがあったら\nそのときのことを話して"},
{id: 35, text: "宇宙旅行が出来るなら、宇宙で\nどんなことをしてみたい?"},
{id: 36, text: "ここ最近で、キレたことを教えて。"},
{id: 37, text: "大好きなテレビ番組について、話してください。"},
{id: 38, text: "「自慢話」をすることについて\nどう思う?"},
{id: 39, text: "最近嬉しかった褒め言葉を聞かせてください。"},
{id: 40, text: "あなたが飼いたいペット、もしくは\n飼っているペットのことを聞かせて。"},
{id: 41, text: "あなたの家の伝統を自慢してください。"},
{id: 42, text: "大好きなスポーツはなに?\n理由も教えて。"},
{id: 43, text: "次の文章に当てはまる言葉を考えてみて。\n「私は・・・な人間です」"},
{id: 44, text: "大好きな映画スターを一人挙げて。"},
{id: 45, text: "最近見た映画について、ひとこと聞かせて。"},
{id: 46, text: "次の文章に当てはまる言葉を考えてみて。\n「私は人込みの中にいると・・・」"},
{id: 47, text: "子供の頃のお気に入りの童話は?\n好きだった理由も聞かせて。"},
{id: 48, text: "あなたの好きな雑誌はなに?\n理由も教えて。"},
{id: 49, text: "学生時代で最高の一年間はいつでしたか?\n詳しく話してください。"},
{id: 50, text: "迷子になった時の話をしてください。"},
{id: 51, text: "いじめた経験があれば\n聞かせてください"},
{id: 52, text: "幼い頃の、眠るときの思い出を教えて。"},
{id: 53, text: "自分を楽器に例えたら、何度だと思う?\n理由も教えて。"},
{id: 54, text: "3年後も続けたいなと思っていることを\n3つ教えて。"},
{id: 55, text: "思いがけない出来事や\n事故について、どう思う?"}
]
end
| true |
e44c2a53e7e5b969426bfaafd27daa1e392b77df
|
Ruby
|
kellyeryan/marvel
|
/bin/run.rb
|
UTF-8
| 895 | 2.765625 | 3 |
[] |
no_license
|
require "pry"
require_relative "../lib/avenger"
require_relative "../lib/movie"
require_relative "../lib/appearance"
thor = Avenger.new("Thor", "strength")
hulk = Avenger.new("Hulk", "strength")
iron_man = Avenger.new("Tony Stark", "super smart")
black_panther = Avenger.new("Black Panther", "panther powers")
ragnarok = Movie.new("Ragnarok")
iron_man_2 = Movie.new("Iron Man 2")
avengers = Movie.new("Avengers")
infinity_wars = Movie.new("Avengers: Infinity Wars")
thor.makes_appearance_in(ragnarok)
thor.makes_appearance_in(infinity_wars)
thor.makes_appearance_in(avengers)
hulk.makes_appearance_in(ragnarok)
hulk.makes_appearance_in(avengers)
iron_man.makes_appearance_in(iron_man_2)
iron_man.makes_appearance_in(avengers)
iron_man.makes_appearance_in(infinity_wars)
black_panther.makes_appearance_in(infinity_wars)
binding.pry
1 + 1 # bug in pry that requires adding code after binding.pry
| true |
5a5a3a00418e17cc580732384f4b15fc32397eb9
|
Ruby
|
taillet/my-collect-prework
|
/lib/my_collect.rb
|
UTF-8
| 191 | 3.125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def my_collect(array)
i = 0
narray = []
if array.size == 0
return nil
else
while i < array.size
narray << yield(array[i])
i += 1
end
narray
end
end
| true |
0627fa8e07abf4186c5e07c89b6f3dc75bd779ce
|
Ruby
|
ziptofaf/duality
|
/app/helpers/vpn_helper.rb
|
UTF-8
| 3,486 | 2.8125 | 3 |
[] |
no_license
|
require 'securerandom'
module VpnHelper
def pay(amount)
error_message and raise 'THIS MUST BE POSITIVE' unless amount>=0
flash[:error]="Insufficient funds" and raise 'Insufficient funds' if balance-amount<0
user = User.find(session[:user_id])
funds = user.balance - amount
user.update_attribute :balance, funds
end
def check_if_correct(time)
error_message and raise 'Invalid contract time' unless time==3 or time==2 or time==1 or time==0.5 or time==0.1
end
def can_extend?(id) #this returns product that was used to buy an account
error_message and raise 'Invalid_id' unless Account.exists?(id: id, user_id: session[:user_id])
account = Account.find(id)
error_message and raise 'Trying to access foreign account' unless session[:user_id]==account.user_id
flash[:error]="This offer is discontinued and cannot be extended" and raise 'Product no longer exists!' unless Product.exists?(id: account.product_id)
product = Product.find(account.product_id)
return product
end
def extend_this_account(id, length)
error_message and raise 'Invalid_id' unless Account.exists?(id: id)
account = Account.find(id)
new_date = (account.expire + length.to_i.months) if length>0.5
new_date = (account.expire + 2.weeks) if length==0.5
error_message and raise 'Cant extend for less than 2 weeks' if length<0.5
account.update_attribute :expire, new_date
end
def create_account(pool, product_id, expire_value)
account=Account.new
account.login = random_hash
account.password = random_hash
account.server_pool_id = pool.id
account.user_id = session[:user_id]
account.product_id = product_id
account.active = 0
if expire_value==0.5 or expire_value==0.1
account.expire = 2.weeks.from_now if expire_value == 0.5
account.expire = 3.days.from_now if expire_value == 0.1
flash[:error] = "You can only get a free account if you never had one before" and
raise 'trying to make a second free account' and return if Account.exists?(:user_id => session[:user_id]) and expire_value == 0.1
else
account.expire = expire_value.to_i.months.from_now
end
error_message and raise 'couldnt save the record' unless account.save
end
def log_payment(product_id, value, extending=false)
return if value<=0
purchase = Purchase.new
purchase.date = Time.now
purchase.user_id=session[:user_id]
purchase.value=value
error_message and raise 'INVALID PRODUCT ID' unless Product.exists?(id: product_id)
product = Product.find(product_id)
purchase.name=product.name #this means that even if i delete the product, log is saved under proper name
purchase.name = product.name + " - extending" if extending==true
error_message and raise 'couldnt save the log record' unless purchase.save
end
def random_hash
random_string = SecureRandom.base64(30)
random_string.split(/[+,=\/]/).join
end
def parameters_to_level (parameter)
return 1 if parameter=='basic'
return 2 if parameter=='medium'
return 3 if parameter=='advanced'
return 4 if parameter=='extreme'
raise 'wrong parameters!' and return 0
end
def pool_to_level (pool)
return "Basic" if pool==1
return "Medium" if pool==2
return "Advanced" if pool==3
return "Extreme" if pool==4
end
def find_least_users (location, server_pool)
raise 'Server doesnt exist' unless Server.exists?(:location => location)
server = Server.where('location=? and server_pool_id=?', location, server_pool).order(capacity_current: :asc).first
return server
end
end
| true |
32fcea577e8ed780700a587da27a633594a97531
|
Ruby
|
olistik/custom_range
|
/lib/custom_range.rb
|
UTF-8
| 855 | 3.296875 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
class CustomRange
attr_accessor :range_set
def initialize(range_set)
@range_set = range_set
end
def [](value)
EndPoint.new value, @range_set
end
end
class EndPoint
attr_accessor :index
def initialize(value, range_set)
@range_set = range_set
@index = self.send("index_from_" + value_type(value), value)
end
def index_from_integer(value)
value % @range_set.size
end
def index_from_string(value)
@range_set.index(value)
end
def index_from_symbol(value)
index_from_string(value.to_s)
end
def succ
EndPoint.new(@index + 1, @range_set)
end
def <=>(end_point)
@index <=> end_point.index
end
def value_type(value)
[Integer, String, Symbol].find {|type| value.kind_of? type}.to_s.downcase
end
def to_s
@range_set[@index].to_s
end
end
| true |
27e34db50db60091fc7517686571ae27c1e93830
|
Ruby
|
multi-io/xml-mapping
|
/lib/xml/xxpath.rb
|
UTF-8
| 3,603 | 3.03125 | 3 |
[
"Apache-2.0"
] |
permissive
|
# xxpath -- XPath implementation for Ruby, including write access
# Copyright (C) 2004-2006 Olaf Klischat
require 'rexml/document'
require 'xml/rexml_ext'
require 'xml/xxpath/steps'
module XML
class XXPathError < RuntimeError
end
# Instances of this class hold (in a pre-compiled form) an XPath
# pattern. You call instance methods like +each+, +first+, +all+,
# <tt>create_new</tt> on instances of this class to apply the
# pattern to REXML elements.
class XXPath
# create and compile a new XPath. _xpathstr_ is the string
# representation (XPath pattern) of the path
def initialize(xpathstr)
@xpathstr = xpathstr # for error messages
# TODO: write a real XPath parser sometime
xpathstr='/'+xpathstr if xpathstr[0] != ?/
@creator_procs = [ proc{|node,create_new| node} ]
@reader_proc = proc {|nodes| nodes}
part=nil; part_expected=true
xpathstr.split(/(\/+)/)[1..-1].reverse.each do |x|
if part_expected
part=x
part_expected = false
next
end
part_expected = true
axis = case x
when '/'
:child
when '//'
:descendant
else
raise XXPathError, "XPath (#{xpathstr}): unknown axis: #{x}"
end
axis=:self if axis==:child and (part[0]==?. or part=~/^self::/) # yuck
step = Step.compile(axis,part)
@creator_procs << step.creator(@creator_procs[-1])
@reader_proc = step.reader(@reader_proc, @creator_procs[-1])
end
end
# loop over all sub-nodes of _node_ that match this XPath.
def each(node,options={},&block)
all(node,options).each(&block)
end
# the first sub-node of _node_ that matches this XPath. If nothing
# matches, raise XXPathError unless :allow_nil=>true was provided.
#
# If :ensure_created=>true is provided, first() ensures that a
# match exists in _node_, creating one if none existed before.
#
# <tt>path.first(node,:create_new=>true)</tt> is equivalent
# to <tt>path.create_new(node)</tt>.
def first(node,options={})
a=all(node,options)
if a.empty?
if options[:allow_nil]
nil
else
raise XXPathError, "path not found: #{@xpathstr}"
end
else
a[0]
end
end
# Return an Enumerable with all sub-nodes of _node_ that match
# this XPath. Returns an empty Enumerable if no match was found.
#
# If :ensure_created=>true is provided, all() ensures that a match
# exists in _node_, creating one (and returning it as the sole
# element of the returned enumerable) if none existed before.
def all(node,options={})
raise "options not a hash" unless Hash===options
if options[:create_new]
return [ @creator_procs[-1].call(node,true) ]
else
last_nodes,rest_creator = catch(:not_found) do
return @reader_proc.call([node])
end
if options[:ensure_created]
[ rest_creator.call(last_nodes[0],false) ]
else
[]
end
end
end
# create a completely new match of this XPath in
# <i>base_node</i>. "Completely new" means that a new node will be
# created for each path element, even if a matching node already
# existed in <i>base_node</i>.
#
# <tt>path.create_new(node)</tt> is equivalent to
# <tt>path.first(node,:create_new=>true)</tt>.
def create_new(base_node)
first(base_node,:create_new=>true)
end
end
end
| true |
424cbcc61acf418c54c783274edabd5557081441
|
Ruby
|
metdinov/Project-Euler
|
/problem3.rb
|
UTF-8
| 325 | 4.125 | 4 |
[] |
no_license
|
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
require 'prime'
def largest_factor(number)
upper_bound = number / 2
upper_bound.downto(2) do |n|
if number % n == 0 && n.prime?
return n
end
end
1
end
puts largest_factor(600851475143)
| true |
42b25263ea20b12fe8bfa26906a8e997fad7d788
|
Ruby
|
XenoQueen/programming-univbasics-4-square-array-online-web-prework
|
/lib/square_array.rb
|
UTF-8
| 143 | 2.6875 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def square_array(array)
numbers = [4,16,28]
square_array(numbers)
end
new_numbers = [54,68,80,102]
square_array(new_numbers)
end
| true |
8aabb6b7e9576e4df0ca58ea78b1c83d6497bbc4
|
Ruby
|
richardrguez/exercises
|
/coderbyte/medium/StringScramble.rb
|
UTF-8
| 861 | 4.21875 | 4 |
[] |
no_license
|
# Using the Ruby language, have the function StringScramble(str1,str2) take both parameters being
# passed and return the string true if a portion ofstr1 characters can be rearranged to match str2,
# otherwise return the string false. For example: if str1 is "rkqodlw" and str2 is "world" the output
# should return true. Punctuation and symbols will not be entered with the parameters.
# Use the Parameter Testing feature in the box below to test your code with different arguments.
def StringScramble(str1,str2)
a_str1 = str1.split("")
a_str2 = str2.split("")
count = 0
a_str2.each do |letter|
if a_str1.include?(letter)
count += 1
end
end
return count == a_str2.length ? true : false
end
# keep this function call here
# to see how to enter arguments in Ruby scroll down
StringScramble(STDIN.gets)
| true |
40f22f19202298b1907fe7c89efd3968d7a47e5d
|
Ruby
|
pushplataranjan/shoes4
|
/shoes-core/lib/shoes/list_box.rb
|
UTF-8
| 1,392 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
class Shoes
class ProxyArray < SimpleDelegator
attr_accessor :gui
def initialize(array, gui)
@gui = gui
super(array)
end
def method_missing(method, *args, &block)
res = super(method, *args, &block)
gui.update_items
case res
when ProxyArray, Array
self
else
res
end
end
def to_a
__getobj__
end
end
class ListBox < Common::UIElement
include Common::Changeable
include Common::Focus
include Common::State
style_with :change, :choose, :common_styles, :dimensions, :items, :state, :text
STYLES = { width: 200, height: 29, items: [""] }.freeze
def handle_block(blk)
change(&blk) if blk
end
def after_initialize
super
proxy_array = Shoes::ProxyArray.new(items, @gui)
@style[:items] = proxy_array
end
def items=(vanilla_array)
proxy_array = Shoes::ProxyArray.new(vanilla_array, @gui)
style(items: proxy_array)
@gui.update_items
end
def text
@gui.text
end
def choose(item_or_hash = nil)
case item_or_hash
when String
style(choose: item_or_hash)
@gui.choose item_or_hash
when Hash
style(choose: item_or_hash[:item])
@gui.choose item_or_hash[:item]
end
end
alias choose= choose
end
end
| true |
a33e4476be3cf3fd536f2ee5dc2d9b4f4db632c9
|
Ruby
|
altbizney/commando
|
/commando-lightbox
|
UTF-8
| 1,953 | 2.671875 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
require_relative 'commando-helpers.rb'
require 'yaml'
program :description, 'Renders LightBox projects to a frame sequence.'
program :version, '1.0.0'
def filename(id, prefix='', suffix='')
"#{prefix}#{sprintf "%05d", id}#{suffix}"
end
command :loop do |c|
c.description = 'Sorts bitmaps in <project> and moves & renames them to <output>'
c.option '--project DIR', String, 'LightBox project folder (the .lightbox directory)'
c.option '--output DIR', String, 'Output directory'
c.action do |args, options|
options.default \
project: "./",
output: "./output"
options.project = File.expand_path(options.project)
options.output = File.expand_path(options.output)
command_header(c, options)
if ! File.directory?(options.project)
crash "Project directory '#{options.project}' does not exist"
end
art_file = File.expand_path "#{options.project}/*.art"
art_file = Dir.glob(art_file)[0]
if ! File.exists?(art_file)
crash "Project directory '#{options.project}' does not seem to have an .art file..."
end
art_file = YAML.load_file art_file
if File.directory?("#{options.project}/bitmaps")
notice "Using ./bitmaps sub-directory within '#{options.project}'..."
options.project = "#{options.project}/bitmaps"
end
if ! File.directory?(options.output)
warning "Output directory '#{options.output}' does not exist, creating it..."
Dir.mkdir(options.output)
end
i = 0
art_file["frames"].each do |frame|
from = "#{options.project}/#{frame['drawingId']}.png"
to = "#{options.output}/#{filename frame['frameIndex']}.png"
next unless File.exists?(from)
FileUtils.cp from, to
i += 1
end
if i > 0
success "Moved and renamed #{i} frames to #{options.output}"
else
warning "Didn't move any files in #{options.project}..."
end
end
end
default_command :loop
| true |
63ba756ac23b97d4c4b88ffb3cd4a3631df67ab5
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/bob/923e2242a3a64550a64b5c40cf73476c.rb
|
UTF-8
| 434 | 3.4375 | 3 |
[] |
no_license
|
class Bob
def hey some_words
@some_words = some_words
making_a_big_deal ? 'Woah, chill out!'
: dumb_question ? 'Sure.'
: cold_shoulder ? 'Fine. Be that way!'
: 'Whatever.'
end
private
def making_a_big_deal
@some_words.upcase == @some_words && @some_words.match(/[A-Z]/)
end
def dumb_question
@some_words.end_with? '?'
end
def cold_shoulder
'' == @some_words.strip
end
end
| true |
82d789424d7d3fa66e6d48f020d175cb47e7de48
|
Ruby
|
victorehrich/Desafio-Trainee-2020.2-Ruby
|
/calculator/menu.rb
|
UTF-8
| 1,235 | 3.609375 | 4 |
[] |
no_license
|
require_relative 'operations'
module Calculator
class Menu
def initialize
puts "-------------------------\n| Bem vindo a calculadora |\n-------------------------"
puts "1. Média preconceituosa"
puts "2. Calculadora sem números"
puts "3. Filtrar filmes"
puts "4. Sair"
puts "Sua opção: "
optionMenu = gets.chomp.to_i
system 'clear'
#case de opcoes do menu
case optionMenu
when 1
puts "Digite o JSON com alunos e notas:"
grades = gets.chomp
puts "Digite a blacklist:"
blacklist = gets.chomp
system 'clear'
nota = Operations.new
puts "Média: #{nota.biased_mean(grades,blacklist)}"
when 2
puts "Digite o número que deseja conferir:"
numbers = gets.chomp.to_s
system 'clear'
numero = Operations.new
puts numero.no_integers(numbers)
when 3
puts "Digite o gênero:"
genres = gets.chomp
puts "Digite o ano:"
year = gets.chomp
system 'clear'
filme = Operations.new
puts filme.filter_films(genres,year)
when 4
exit
else
puts "Opção inválida:"
end
end
end
end
| true |
ce9883d191757b5c5ac22d1377db63a8f34e7ef4
|
Ruby
|
bernicetann/Two-Player-Math-Game
|
/main.rb
|
UTF-8
| 394 | 2.859375 | 3 |
[] |
no_license
|
require './player.rb'
require './math-game.rb'
require './question.rb'
game = Game.new
game.start(Player.new, Player.new)
# GAME FLOW
# put a blurb to welcome the game
# game loop(ask question, gets answer, evaluate T/F, if answer is wrong decrement
# currnt player, display blurb to current player, if current player scores 0 end game,
# display scoreboard, switch player/turns)
| true |
56e29201ba9881115b213fa5c257e9b08a632e66
|
Ruby
|
juanjegt/flowerplants
|
/lib/creates_variety.rb
|
UTF-8
| 405 | 2.75 | 3 |
[] |
no_license
|
class CreatesVariety
def self.create(variety)
variety.save && create_product(variety)
end
private
def self.create_product(variety)
product = Product.new
product.family = variety.family
product.color = variety.color
product.variety = variety
product.name = variety.family.name + ' ' + variety.color.name + ' ' + variety.name
product.save
end
end
| true |
ec3931a63d6637d1a8cdaeafe9cb50f964e4f3f5
|
Ruby
|
rikkimalh/phase-0-tracks
|
/ruby/puppy_methods.rb
|
UTF-8
| 1,256 | 4.03125 | 4 |
[] |
no_license
|
class Puppy
def fetch(toy)
puts "I brought back the #{toy}!"
toy
end
def speak(integer)
i = integer.to_i
i.times do |x|
puts "Woof!"
end
end
def roll_over
puts " *rolls over*"
end
def dog_years(human_years)
n = human_years.to_i
puts dog_age = n*7
end
def jump(num_of_jumps)
x = num_of_jumps.to_i
x.times do |x|
puts "*jumps*"
end
end
def initialize
puts "Initializing new puppy instance..."
end
end
#Driver Code
object = Puppy.new
object.fetch("ball")
object2 = Puppy.new
object2.speak("4")
object3 = Puppy.new
object3.roll_over
object4 = Puppy.new
object4.dog_years(20)
object5 = Puppy.new
object5.jump(3)
class Party
def initialize
puts "lets partayyyy!"
end
def drinks(no_drinks)
x = no_drinks.to_i
x.times do |x|
puts "You've had #{x} drinks!!"
end
def dance
puts "I'm dancing!! "
end
end
end
array_example = []
y = 1
while y <50
party_animal = Party.new
array_example << party_animal
y+= 1
end
array_example.each do |party_animal|
party_animal.drinks(6)
party_animal.dance
end
p array_example
party_animal.drinks(4)
party_animal = Party.new
party_animal.dance
party_animal = Party.new
party_animal = Party.new
| true |
b97359a40a9307b19d82383fecf02d934dd2bc6e
|
Ruby
|
bhardin/bgg-tools
|
/app/models/game.rb
|
UTF-8
| 3,361 | 2.84375 | 3 |
[] |
no_license
|
require 'array'
class Game < ActiveRecord::Base
serialize :poll, Hash
has_many :users_games
has_many :users, through: :users_games
has_many :historical_prices
attr_accessor :marketplace_history
UPDATE_TIMEFRAME = 1.month
def self.primary_name(name_array)
name_array.each do |name|
return name["value"] if name["type"] == "primary"
end
end
def historical_price_array
self.historical_prices.select {|x| x.currency == "USD"}.map {|x| x.price}
end
def update_bgg_data(force_update = false)
if self.needs_updating? || force_update
game_update_worker.perform_async(bgg_id)
end
end
def needs_updating?
# No Name or Updated within 1 month
name.nil? || self.updated_at.nil? || self.updated_at < Time.zone.now - UPDATE_TIMEFRAME
end
def update_stuff
raise "No BGG_ID for this game" if self.bgg_id.nil?
bgg_api = BggApi.new
bgg_data = bgg_api.thing(id: bgg_id,
pricehistory: 1,
stats: 1)["item"].first
self.name = Game.primary_name(bgg_data["name"])
self.thumbnail = bgg_data["thumbnail"].first if bgg_data["thumbnail"]
self.image = bgg_data["image"].first if bgg_data["image"]
self.min_players = bgg_data["minplayers"].first["value"]
self.max_players = bgg_data["maxplayers"].first["value"]
self.description = bgg_data["description"].first
self.year_published = bgg_data["yearpublished"].first["value"]
self.polls = bgg_data["poll"]
self.playing_time = bgg_data["playingtime"].first["value"]
self.minimum_age = bgg_data["minage"].first["value"]
self.average_rating = bgg_data["statistics"].first["ratings"].first["average"].first["value"]
self.bayesian_average = bgg_data["statistics"].first["ratings"].first["bayesaverage"].first["value"]
if bgg_data["marketplacehistory"] &&
bgg_data["marketplacehistory"][0] &&
bgg_data["marketplacehistory"][0]["listing"]
self.marketplace_history = bgg_data["marketplacehistory"][0]["listing"]
end
self.store_marketplace_data
self.save
# Qwirky: I have to reload the object, to pull the new data from the DB.
# If I don't save the previous line, all the other stuff (like the
# name) is forgotten.
reload
self.calculate_prices
self.save
end
# private
def calculate_prices
# if self.historical_prices
self.mean_price = self.historical_price_array.mean.round(2)
self.median_price = self.historical_price_array.median.round(2)
self.save
# end
end
def store_marketplace_data
return unless marketplace_history
self.historical_prices.destroy_all
marketplace_history.each do |listing|
condition = listing["condition"][0]["value"]
value = listing["price"][0]["value"]
currency = listing["price"][0]["currency"]
listdate = listing["listdate"][0]["value"]
sale_date = listing["saledate"][0]["value"]
hp = HistoricalPrice.new(
game_id: self.id,
date_sold: sale_date,
price: value,
currency: currency,
condition: condition
)
hp.save
end
end
private
def game_update_worker
GameUpdateWorker
end
end
| true |
a6da2e0855faad4e91576862d7429815a2ef2aaa
|
Ruby
|
gentooboontoo/gentooboontoo-gphys
|
/lib/numru/gphys/varray.rb
|
UTF-8
| 29,709 | 3.0625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
require "numru/gphys/subsetmapping"
require "numru/gphys/attribute"
require "narray_miss"
require "numru/units"
require "numru/gphys/unumeric"
require "rational" # for VArray#sqrt
require "numru/misc"
module NumRu
=begin
=class NumRu::VArray
VArray is a Virtual Array class, in which a multi-dimensional array data is
stored on memory (NArray, NArrayMiss) or in file (NetCDFVar etc).
The in-file data handling is left to subclasses such as VArrayNetCDF,
and this base class handles the following two cases:
(1) Data are stored on memory using NArray
(2) Subset of another VArray (possibly a subclass such as VArrayNetCDF).
Perhaps the latter case needs more explanation. Here, a VArray is defined
as a subset of another VArray, so the current VArray has only the link
and info on how the subset is mapped to the other VArray.
A VArray behaves just like a NArray, i.e., a numeric multi-dimensional
array. The important difference is that a VArray has a name and can
have "attributes" like a NetCDF variable. Therefore, VArray can perfectly
represent a NetCDFVar, which is realized by a sub-class VArrayNetCDF.
NOMENCLATURE
* value(s): The multi-dimensional numeric array contained in the VArray,
or its contents
* attribute(s): A combination of name and data that describes a VArray.
Often realized by NumRu::Attribute class (or it is a NetCDFAttr in
VArrayNetCDF). The name must be a string, and the type of attribute
values is restricted to a few classes for compatibility with
NetCDFAttr (See NumRu::Attribute)
==Class Methods
---VArray.new(narray=nil, attr=nil, name=nil)
A constructor
ARGUMENTS
* narray (NArray or NArrayMiss; default:nil) The array to be held.
(nil is used to initialize a mapping to another VArray by a protected
method).
* attr (NumRu::Attribute; default:nil) Attributes. If nil, an empty
attribute object is created and stored.
* name (String; default nil) Name of the VArray. If nil, it is named "noname".
RETURN VALUE
* a VArray
EXAMPLE
na = NArray.int(6,3).indgen!
va1 = VArray.new( na, nil, "test" )
---VArray.new2(ntype, shape, attr=nil, name=nil)
Another constructor. Uses parameters to initialize a NArray to hold.
ARGUMENTS
* ntype (String or NArray constants): Numeric type of the NArray to be
held (e.g., "sfloat", "float", NArray::SFLOAT, NArray::FLOAT)
* shape (Array of Integers): shape of the NArray
* attr (Attribute; default:nil) Attributes. If nil, an empty attribute
object is created and stored.
* name (String; default nil) Name of the VArray.
RETURN VALUE
* a VArray
==Instance Methods
---val
Returns the values as a NArray (or NArrayMiss).
This is the case even when the VArray is a mapping to another. Also,
this method is to be redefined in subclasses to do the same thing.
ARGUMENTS -- none
RETURN VALUE
* a NArray (or NArrayMiss)
---val=(narray)
Set values.
The whole values are set. If you want to set partly, use ((<[]=>)).
In this method, values are read from narray and set into the internal
value holder. Thus, for exampled, the numeric type is not changed
regardress the numeric type of narray. Use ((<replace_val>)) to
replace entirely with narray.
ARGUMENTS
* narray (NArray or NArrayMiss or Numeric): If Numeric, the whole
values are set to be equal to it. If NArray (or NArrayMiss), its
shape must agree with the shape of the VArray.
---replace_val(narray)
Replace the internal array data with the object narray.
Use ((<val=>)) if you want to copy the values of narray.
ARGUMENTS
* narray (NArray or NArrayMiss): as pxlained above.
Its shape must agree with the shape of the VArray (self).
RETURN VALUE
* if (self.class == VArray), self;
otherwise (if self.class is a subclass of VArray), a new VArray.
---[]
Get a subset. Its usage is the same as NArray#[]
---[]=
Set a subset. Its usage is the same as NArray#[]=
---attr
To be undefined.
---ntype
Returns the numeric type.
ARGUMENTS -- none
RETURN VALUE
* a String ("byte", "sint", "int", "sfloat", "float", "scomplex"
"complex", or "obj"). It can be used in NArray.new to initialize
another NArray.
---rank
Returns the rank (number of dimensions)
---shape
Returns the shape
---shape_current
aliased to ((<shape>)).
---length
Returns the length of the VArray
---typecode
Returns the NArray typecode
---name
Returns the name
RETURN VALUE
* (String) name of the VArray
---name=(nm)
Changes the name.
ARGUMENTS
* nm(String): the new name.
RETURN VALUE
* nm
---rename!(nm)
Changes the name (Same as ((<name=>)), but returns self)
ARGUMENTS
* nm(String): the new name.
RETURN VALUE
* self
---rename(nm)
Same as rename! but duplicate the VArray object and set its name.
This method may not be supported in sub-classes, since it is sometimes
problematic not to change the original.
---copy(to=nil)
Copy a VArray. If to is nil, works as the deep cloning (duplication of the entire object).
Both the values and the attributes are copied.
ARGUMENTS
* to (VArray (possibly a subclass) or nil): The VArray to which the
copying is made.
---reshape!( *shape )
Changes the shape without changing the total size. May not be available in subclasses.
ARGUMENTS
* shape (Array of Integer): new shape
RETURN VALUE
* self
EXAMPLE
vary = VArray.new2( "float", [10,2])
vary.reshape!(5,4) # changes the vary
vary.copy.reshape!(2,2,5) # make a deep clone and change it
# This always works with a VArray subclass, since vary.copy
# makes a deep clone to VArray with NArray.
---file
Returns a file object if the data of the VArray is in a file, nil if it is on memory
ARGUMENTS
* none
RETURN VALUE
* an object representing the file in which data are stored. Its class
depends on the file type. nil is returned if the data is not in a file.
---transpose(*dims)
Transpose. Argument specification is as in NArray.
---reshape(*shape)
Reshape. Argument specification is as in NArray.
---axis_draw_positive
Returns the direction to plot the axis (meaningful only if self is a
coordinate variable.)
The current implementation is based on NetCDF conventions,
so REDEFINE IT IN SUBCLASSES if it is not appropriate.
RETURN VALUE
* one of the following:
* true: axis should be drawn in the increasing order (to right/upward)
* false: axis should be drawn in the decreasing order
* nil: not specified
---axis_cyclic?
Returns whether the axis is cyclic (meaningful only if self is a
coordinate variable.)
The current implementation is based on NetCDF conventions,
so REDEFINE IT IN SUBCLASSES if it is not appropriate.
RETURN VALUE
* one of the following:
* true: cyclic
* false: not cyclic
* nil: not specified
---axis_modulo
Returns the modulo of a cyclic axis (meaningful only if self is a
coordinate variable and it is cyclic.)
The current implementation is based on NetCDF conventions,
so REDEFINE IT IN SUBCLASSES if it is not appropriate.
RETURN VALUE
* one of the following:
* Float if the modulo is defined
* nil if modulo is not found
---axis_cyclic_extendible?
(meaningful only if self is a coordinate variable.)
Returns true if self is cyclic and it is suitable to exend
cyclically (having the distance between both ends
equal to (modulo - dx), where dx is the mean increment).
---coerce(other)
For Numeric operators. (If you do not know it, see a manual or book of Ruby)
==Methods compatible with NArray
VArray is a numeric multi-dimensional array, so it supports most of the
methods and operators in NArray. Here, the name of those methods are just
quoted. See the documentation of NArray for their usage.
=== Math functions
====sqrt, exp, log, log10, log2, sin, cos, tan, sinh, cosh, tanh, asin, acos, atan, asinh, acosh, atanh, csc, sec, cot, csch, sech, coth, acsc, asec, acot, acsch, asech, acoth
=== Binary operators
====-, +, *, /, %, **, .add!, .sub!, .mul!, .div!, mod!, >, >=, <, <=, &, |, ^, .eq, .ne, .gt, .ge, .lt, .le, .and, .or, .xor, .not
=== Unary operators
====~ - +
=== Mean etc
====mean, sum, stddev, min, max, median
=== Other methods
These methods returns a NArray (not a VArray).
====all?, any?, none?, where, where2, floor, ceil, round, to_f, to_i, to_a
=end
class Units
# for automatic operator generation in VArray
def mul!(other); self*other; end
def div!(other); self/other; end
end # class Units
class VArray
### < basic parts to be redefined in subclasses > ###
def initialize(narray=nil, attr=nil, name=nil)
# initialize with an actual array --- initialization by subset
# mapping is made with VArray.new.initialize_mapping(...)
@name = ( name || "noname" )
@mapping = nil
@varray = nil
@ary = __check_ary_class(narray)
case attr
when Attribute
@attr = attr
when VArray
vary = attr
@attr = vary.attr_copy
when Hash
@attr = NumRu::Attribute.new
attr.each{|key,val| @attr[key]=val}
when nil
@attr = NumRu::Attribute.new
else
raise TypeError, "#{attr.class} is unsupported for the 2nd arg"
end
end
attr_reader :mapping, :varray, :ary
protected :mapping, :varray, :ary
def inspect
if !@mapping
"<'#{name}' #{ntype}#{shape.inspect} val=[#{(0...(4<length ? 4 : length)).collect do |i| @ary[i].to_s+',' end}#{'...' if 4<length}]>"
else
"<'#{name}' shape=#{shape.inspect} subset of a #{@varray.class}>"
end
end
def VArray.new2(ntype, shape, attr=nil, name=nil)
ary = NArray.new(ntype, *shape)
VArray.new(ary, attr, name)
end
def val
if @mapping
ary = @varray.ary
slicer = @mapping.slicer
if ary.is_a?(NArray) || ary.is_a?(NArrayMiss)
# interpret Hash slicers for NArray/NArrayMiss
# -- this part would not be needed if NArray supported it.
new_slicer = Array.new
for idx in 0...slicer.length
sl = slicer[idx]
if sl.is_a?(Hash)
range, step = sl.to_a[0]
dim_len = ary.shape[idx]
first = range.first
first += dim_len if first<0
last = range.last
last += dim_len if last<0
if first<0 || first>=dim_len || last<0 || last>=dim_len || step==0
raise "slicer #{slicer.inspect} for dim #{idx} is invalid (dim_len=#{dim_len})"
end
step = -step if ( (last-first)*step < 0 )
length = (last-first) / step + 1
new_slicer[idx] = first + step * NArray.int(length).indgen!
else
new_slicer[idx] = sl
end
end
slicer = new_slicer
end
ary[*slicer]
else
@ary.dup
end
end
def val=(narray)
if @mapping
@varray.ary[*@mapping.slicer] = __check_ary_class2(narray)
else
@ary[] = __check_ary_class2(narray)
end
narray
end
def replace_val(narray)
narray = __check_ary_class(narray)
if self.class != VArray
raise "replace_val to #{self.class} is disabled. Use val= instead"
end
if narray.shape != shape
raise "shape of the argument (#{narray.shape.inspect}) !="+
" self.shape (#{shape.inspect})"
end
@ary = narray
if @mapping
# to non subset
@name = @varray.name
@attr = @varray.attr_copy
@mapping = @varray = nil
end
self
end
def ntype
__ntype(typecode)
end
def name=(nm)
raise ArgumentError, "name should be a String" if ! nm.is_a?(String)
if @mapping
@varray.name = nm
else
@name = nm
end
nm
end
def rename!(nm)
self.name=nm
self
end
def rename(nm)
self.dup.rename!(nm)
end
def reshape!( *shape )
if @mapping
raise "Cannot reshape an VArray mapped to another. Use copy first to make it independent"
else
@ary.reshape!( *shape )
end
self
end
def file
if @mapping
@varray.file
else
return nil
end
end
### < basic parts invariant in subclasses > ###
def copy(to=nil)
attr = self.attr_copy( (to ? to.attr : to) )
val = self.val
if self.class==VArray && !self.mapped? && (to==nil || to.class==VArray)
val = val.dup
end
if to
to.val = val
to
else
VArray.new(val, attr, self.name)
end
end
#def reshape( *shape )
# # reshape method that returns a new entire copy (deep one).
# # ToDo :: prepare another reshape method that does not make the
# # entire copy (you could use NArray.refer, but be careful not
# # to make it public, because it's easily misused)
# newobj = self.copy
# newobj.ary.reshape!( *shape )
# newobj
#end
def mapped?
@mapping ? true : false
end
def initialize_mapping(mapping, varray)
# protected method
raise ArgumentError if ! mapping.is_a?(SubsetMapping)
raise ArgumentError if ! varray.is_a?(VArray)
if ! varray.mapping
@mapping = mapping
@varray = varray
else
# To keep the mapping within one step
@mapping = varray.mapping.composite(mapping)
@varray = varray.varray
end
@attr = NumRu::Attribute.new
@ary = nil
self
end
protected :initialize_mapping
def attr
if @mapping
@varray.attr
else
@attr
end
end
protected :attr
def attr_copy(to=nil)
attr.copy(to)
end
def att_names
attr.keys
end
def get_att(name)
attr[name]
end
def set_att(name, val)
attr[name]=val
self
end
def del_att(name)
attr.delete(name)
end
alias put_att set_att
def units
str_units = attr['units']
if !str_units || str_units==''
str_units = '1' # represents non-dimension
end
Units.new( str_units )
end
def units=(units)
attr['units'] = units.to_s
units
end
def convert_units(to)
if ! to.is_a?(Units)
to = Units.new(to)
end
myunits = self.units
if myunits != to
if calendar = self.get_att("calendar")
date0 = UNumeric.new(0,myunits).to_datetime
un0 = UNumeric.from_date(date0,to,calendar)
offset = un0.to_f
gp = self + offset
else
gp = myunits.convert2(self, to)
end
gp.units = to
gp
else
self # returns self (no duplication)
end
end
def long_name
attr['long_name']
end
def long_name=(nm)
attr['long_name'] = nm
end
def [](*slicer)
slicer = __rubber_expansion( slicer )
mapping = SubsetMapping.new(self.shape_current, slicer)
VArray.new.initialize_mapping(mapping, self)
end
def []=(*args)
val = args.pop
slicer = args
slicer = __rubber_expansion( slicer )
if val.is_a?(VArray)
val = val.val
else
val = __check_ary_class2(val)
end
if @mapping
sl= @mapping.composite(SubsetMapping.new(self.shape,slicer)).slicer
@varray[*sl]=val
else
@ary[*slicer]=val
end
val
end
def name
if @mapping
@varray.name
else
@name.dup
end
end
def transpose(*dims)
VArray.new( val.transpose(*dims), attr_copy, name )
end
def reshape(*shape)
VArray.new( val.reshape(*shape), attr_copy, name )
end
def axis_draw_positive
# Default setting is taken from a widely used netcdf convention.
# You can override it in a sub-class or using convention specific
# mixins.
positive = attr['positive']
case positive
when /up/i
true
when /down/i
false
else
nil # not defined, or if not 'up' or 'down'
end
end
def axis_cyclic?
# Default setting is taken from a widely used netcdf convention.
# You can override it in a sub-class or using convention specific
# mixins.
topology = attr['topology']
case topology
when /circular/i
true
when nil # 'topology' not defined
if /degrees?_east/ =~ attr['units']
true # special treatment a common convention for the earth
else
nil # not defined --> nil
end
else
false
end
end
def axis_modulo
# Default setting is taken from a widely used netcdf convention.
# You can override it in a sub-class or using convention specific
# mixins.
if attval=attr['modulo']
if attval.is_a?(String)
attval.to_f
else
attval[0]
end
elsif /degrees?_east/ =~ attr['units']
360.0 # special treatment: a common convention for the earth
elsif (tp = attr['topology']) and (/circular/i =~ tp)
un = Units[attr['units']]
if un == Units['degrees']
360.0
elsif un == Units['radian']
2*Math::PI
else
nil # cannot guess --> nil
end
else
nil # not defined --> nil
end
end
def axis_cyclic_extendible?
modulo = axis_modulo
return false if !modulo
v = val
width = (v[-1] - v[0]).abs
dx = width / (length-1)
eps = 1e-4
modulo = modulo.abs
extendible = ( ((width+dx) - modulo).abs < eps*modulo )
return extendible
end
### < NArray methods > ###
## ToDo: implement units handling
## ToDo: coerce
def coerce(other)
oattr = self.attr_copy
case other
when UNumeric
oattr['units'] = other.units.to_s
na_other, = NArray.new(self.typecode, 1).coerce(other.val) # scalar
c_other = VArray.new(na_other, oattr, self.name)
else
oattr['units'] = self.get_att('units') # Assume the same units
case other
when Numeric
na_other, = NArray.new(self.typecode, 1).coerce(other) # scalar
c_other = VArray.new(na_other, oattr, self.name)
when Array
na = NArray.to_na(other)
c_other = VArray.new(na, oattr, self.name)
when NArray, NArrayMiss
c_other = VArray.new(other, oattr, self.name)
else
raise "Cannot coerse #{other.class}"
end
end
[c_other, self]
end
Math_funcs_nondim = ["exp","log","log10","log2","sin","cos","tan",
"sinh","cosh","tanh","asinh","acosh",
"atanh","csc","sec","cot","csch","sech","coth",
"acsch","asech","acoth"]
Math_funcs_radian = ["asin","acos","atan","atan2","acsc","asec","acot"]
Math_funcs = Math_funcs_nondim + Math_funcs_radian + ["sqrt"]
Binary_operators_Uop = ["*","/","**", ".mul!",".div!"]
Binary_operators_Uconv = ["+","-",".add!",".sbt!"]
Binary_operators_Unone = ["%",".mod!",".imag="]
Binary_operators = Binary_operators_Uop +
Binary_operators_Uconv +
Binary_operators_Unone
Binary_operatorsL_comp = [">",">=","<","<=",
".eq",".ne",".gt",".ge",".lt",".le"]
Binary_operatorsL_other = ["&","|","^",".and",".or",".xor",".not"]
Binary_operatorsL = Binary_operatorsL_comp +
Binary_operatorsL_other
Unary_operators = ["-@","~"]
# type1 methods: returns a VArray with the same shape
# type2 methods: returns the result directly
NArray_type1_methods = ["sort", "sort_index",
"floor","ceil","round","to_f","to_i","to_type","abs",
"real","im","imag","angle","arg","conj","conjugate","cumsum",
"indgen","random"]
NArray_type2_methods1 = ["all?","any?","none?","where","where2",
"to_a", "to_string"]
NArray_type2_methods2 = ["rank", "shape", "total","length"]
NArray_type2_methods3 = ["typecode"]
NArray_type3_methods = ["mean","sum","stddev","min","max","median"]
# remaining: "transpose"
NArray_type2_methods = Array.new.push(*NArray_type2_methods1).
push(*NArray_type2_methods2).
push(*NArray_type2_methods3)
for f in Math_funcs_nondim
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}(*arg)
newattr = self.attr_copy
newattr['units'] = '1'
case arg.length
when 0
VArray.new( Misc::EMath.#{f}(self.val), newattr, self.name )
#when 1 # for atan2
# ar = arg[0].respond_to?(:val) ? arg[0].val : arg[0]
# VArray.new( Misc::EMath.#{f}(self.val, ar), newattr, self.name )
else
raise ArgumentError, "# of args must be 0 or 1"
end
end
EOS
end
for f in Math_funcs_radian
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}(*arg)
newattr = self.attr_copy
newattr['units'] = 'rad'
case arg.length
when 0
VArray.new( Misc::EMath.#{f}(self.val), newattr, self.name )
when 1 # for atan2
ar = arg[0].respond_to?(:val) ? arg[0].val : arg[0]
## ar = ar.to_f # NMath.atan2 does not work with NArray.int
VArray.new( Misc::EMath.#{f}(self.val, ar), newattr, self.name )
else
raise ArgumentError, "# of args must be 0 or 1"
end
end
EOS
end
def sqrt
va = VArray.new( Misc::EMath.sqrt(self.val), self.attr_copy, self.name )
va.units = units**Rational(1,2)
va
end
for f in Binary_operators_Uop
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f.delete(".")}(other)
case other
when VArray, UNumeric
vl = self.val
vr = other.val
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
va = VArray.new( ary, self.attr_copy, self.name )
va.units= self.units#{f}(other.units) if "#{f}" != "**"
va
when Numeric, NArray, NArrayMiss, Array
vl = self.val
vr = other
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
va = VArray.new( ary, self.attr_copy, self.name )
if "#{f}" == "**" && other.is_a?(Numeric)
va.units= self.units#{f}(other)
end
va
else
c_me, c_other = other.coerce(self)
c_me#{f}(c_other)
end
end
EOS
end
for f in Binary_operators_Uconv
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f.delete(".")}(other)
case other
when VArray, UNumeric
if self.get_att('units')
# self have non nil units
oval = other.units.convert2(other.val,self.units)
uni = self.units
else
oval = other.val
uni = other.units
end
vl = self.val
vr = oval
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
va = VArray.new( ary, self.attr_copy, self.name )
va.units = uni
va
when Numeric, NArray, NArrayMiss, Array
vl = self.val
vr = other
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
VArray.new( ary, self.attr_copy, self.name )
else
c_me, c_other = other.coerce(self)
c_me#{f}(c_other)
end
end
EOS
end
for f in Binary_operators_Unone
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f.delete(".")}(other)
case other
when VArray, UNumeric
vl = self.val
vr = other.val
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
VArray.new( ary, self.attr_copy, self.name )
when Numeric, NArray, NArrayMiss, Array
vl = self.val
vr = other
if !( vl.is_a?(NArray) and vr.is_a?(NArrayMiss) )
ary = vl#{f}(vr)
else
ary = NArrayMiss.to_nam(vl)#{f}(vr)
end
VArray.new( ary, self.attr_copy, self.name )
else
c_me, c_other = other.coerce(self)
c_me#{f}(c_other)
end
end
EOS
end
for f in Binary_operatorsL_comp
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f.delete(".")}(other)
# returns NArray
case other
when VArray, UNumeric
self.val#{f}( other.units.convert2(other.val,units) )
when Numeric, NArray, NArrayMiss, Array
self.val#{f}(other)
else
c_me, c_other = other.coerce(self)
self#{f}(other)
end
end
EOS
end
for f in Binary_operatorsL_other
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f.delete(".")}(other)
# returns NArray
case other
when VArray, UNumeric
self.val#{f}(other.val)
when Numeric, NArray, NArrayMiss, Array
self.val#{f}(other)
else
c_me, c_other = other.coerce(self)
self#{f}(other)
end
end
EOS
end
for f in Unary_operators
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}
ary = #{f.delete("@")} self.val
VArray.new( ary, self.attr_copy, self.name )
end
EOS
end
def +@
self
end
for f in NArray_type1_methods
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}(*args)
newattr = self.attr_copy
newattr['units'] = '1' if "#{f}"=="angle" || "#{f}"=="arg"
VArray.new(self.val.#{f}(*args), newattr, self.name )
end
EOS
end
for f in NArray_type2_methods1
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}(*args)
self.val.#{f}(*args)
end
EOS
end
for f in NArray_type2_methods2
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}
if @mapping
@mapping.#{f}
else
@ary.#{f}
end
end
EOS
end
for f in NArray_type2_methods3
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}
if @mapping
@varray.ary.#{f}
else
@ary.#{f}
end
end
EOS
end
for f in NArray_type3_methods
eval <<-EOS, nil, __FILE__, __LINE__+1
def #{f}(*args)
result = self.val.#{f}(*args)
if result.is_a?(NArray) || result.is_a?(NArrayMiss)
VArray.new(result , self.attr_copy, self.name )
elsif result.nil?
result
else
UNumeric[result, units] # used to be 'result' (not UNumeric)
end
end
EOS
end
alias shape_current shape
## < marshal dump/load >
def marshal_dump
[@name, @mapping, @varray, @ary, @attr]
end
def marshal_load(ary)
@name, @mapping, @varray, @ary, @attr = *ary
end
## < private methods >
private
def __rubber_expansion( args )
if (id = args.index(false)) # substitution into id
# false is incuded
alen = args.length
if args.rindex(false) != id
raise ArguemntError,"only one rubber dimension is permitted"
elsif alen > rank+1
raise ArgumentError, "too many args"
end
ar = ( id!=0 ? args[0..id-1] : [] )
args = ar + [true]*(rank-alen+1) + args[id+1..-1]
end
args
end
def __check_ary_class(narray)
case narray
when NArray, NArrayMiss, nil
else
raise ArgumentError, "Invalid array class: #{narray.class}"
end
narray
end
def __check_ary_class2(narray)
case narray
when NArray, NArrayMiss, nil, Numeric
else
raise ArgumentError, "Invalid array class: #{narray.class}"
end
narray
end
def __ntype(typecode)
case typecode
when NArray::BYTE
"byte"
when NArray::SINT
"sint"
when NArray::LINT
"int"
when NArray::SFLOAT
"sfloat"
when NArray::DFLOAT
"float"
when NArray::SCOMPLEX
"scomplex"
when NArray::DCOMPLEX
"complex"
when NArray::ROBJ
"obj"
end
end
end # class VArray
end
##################################
### < test > ###
if $0 == __FILE__
include NumRu
p va = VArray.new( NArray.int(6,2,3).indgen!, nil, 'va' )
va.units="m"
va.long_name="test data"
vs = va[2..4,0,0..1]
p "@@@",vs.rank,vs.shape,vs.total,vs.val,vs.get_att("name")
p '@@@@',vs.long_name,vs.units.to_s
vs.val=999
p "*1*",va
co,=va.coerce(UNumeric.new(1,Units.new("rad")))
p '*coerce*',co, co.units
p "*2*",vt = vs/9, vs + vt
p "*3*",vt.log10
p "*4*",(vt < vs)
vt.name='vvvttt'
p "*5*",(3+vt), vt.sin, vt.cos
vc = vt.copy
p 'atan2'
vv = VArray.new( NArray.sfloat(5).indgen!, nil, 'vv' )
p vv.atan2(vv).val
p "eq",vc.eq(vt),vc.equal?(vt)
vd = VArray.new( NArray.int(6).indgen!+10 )
p "+++",vd[1],vd[1].rank,vd[1].val
p va.val
p vs
p va.sort.val
p vs.to_a, vs.to_string, vs.to_f, vs.to_type(NArray::SINT)
p "@@@",va.max, va.max(0), va.max(0,1)
vkg = VArray.new( NArray.float(4,3).indgen!, nil, 'vkg' )
vkg.units = 'kg'
vg = vkg.copy
vg.units = 'g'
vmul = vkg*vg
p '##', vkg.val, vmul.get_att('units'), vmul.units
p '##', (vkg + vg).val, (vg + vkg).val, vkg > vg
p '*convert_units*'
p vg.units,vg.val
vkg = vg.convert_units('kg')
p vkg.units,vkg.val
p '*axis conventions*'
p vx = VArray.new( NArray.int(6).indgen!, nil, 'x' )
vx.put_att("topology","circular")
vx.set_att('modulo',[360.0])
vx.set_att('positive','down')
p vx.axis_draw_positive, vx.axis_cyclic?, vx.axis_modulo
p ' cyclic extendible:'
p vx.axis_cyclic_extendible?
vx.set_att('modulo',[6.0])
p vx.axis_cyclic_extendible?
p '*typecode*'
p vx.typecode, vx[0..1].typecode
end
| true |
074d15ff2f86af6a2af75ecb91da3aea9855f29a
|
Ruby
|
MarhicJeromeGIT/exact_cover
|
/spec/exact_cover/cover_solver_spec.rb
|
UTF-8
| 3,175 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
require "byebug"
RSpec.describe ExactCover::CoverSolver do
subject { described_class.new(matrix) }
describe "#call" do
context "empty matrix" do
let(:matrix) do
[]
end
it "raises an error" do
expect { subject.call }.to raise_error(ExactCover::CoverSolver::InvalidMatrixSize)
end
end
context "when there is a solution" do
context "simple matrix" do
let(:matrix) do
[
[0, 1],
[1, 0]
]
end
it "finds the solution" do
solutions = subject.call
expect(solutions.count).to eq 1
expect(solutions.first).to eq(
[
[1, 0],
[0, 1]
]
)
end
end
context "complex matrix" do
let(:matrix) do
[
[0, 0, 1, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 0, 1],
[0, 1, 1, 0, 0, 1, 0],
[1, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1],
[0, 0, 0, 1, 1, 0, 1]
]
end
it "finds the only solution" do
solutions = subject.call
expect(solutions.count).to eq 1
expect(solutions.first).to eq(
[
[1, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1]
]
)
end
end
end
context "when there are several solutions" do
let(:matrix) do
[
[1, 1],
[0, 1],
[1, 0]
]
end
it "enumerates all the solutions" do
solutions = subject.call
expect(solutions.to_a).to eq(
[
[[1, 1]],
[[1, 0], [0, 1]]
]
)
end
context "when the rows are reversed" do
let(:matrix) do
[
[0, 1],
[1, 0],
[1, 1]
]
end
it "enumerates all the solutions" do
solutions = subject.call
expect(solutions.to_a).to eq(
[
[[1, 0], [0, 1]],
[[1, 1]],
]
)
end
end
end
context "when there is no solution" do
context "simple matrix" do
let(:matrix) do
[
[0, 0],
[1, 0]
]
end
it "doesn't find any solution" do
solutions = subject.call
expect(solutions.count).to eq 0
expect(solutions.first).to be nil
end
end
end
context "identity matrix" do
let(:matrix) do
matrix = []
(0..19).each do |row|
matrix[row] = Array.new(20, 0)
matrix[row][row] = 1
end
matrix
end
it "returns all the row" do
solutions = subject.call
expect(solutions.first).to eq matrix
end
context "when the matrix is shuffled" do
before do
matrix.shuffle!
end
it "returns all the row" do
solutions = subject.call
expect(solutions.first.sort).to eq matrix.sort
end
end
end
end
end
| true |
000a79e875cd67a36f89232b6c48cf4f3d0ec037
|
Ruby
|
extended-debug/briar
|
/bin/briar
|
UTF-8
| 2,294 | 2.5625 | 3 |
[
"MIT",
"Beerware"
] |
permissive
|
#!/usr/bin/env ruby
#http://tech.natemurray.com/2007/03/ruby-shell-commands.html
require 'find'
require 'rainbow'
require 'require_relative'
require 'ansi/logger'
@log = ANSI::Logger.new(STDOUT)
require 'dotenv'
Dotenv.load
require_relative './briar_help'
require_relative './briar_resign'
require_relative './briar_install'
require_relative './briar_console'
require_relative './briar_rm'
require_relative './briar_xtc'
require_relative './briar_report'
require_relative './briar_sim'
require_relative './briar_tags'
num_args = ARGV.length
def briar_version
puts "#{Briar::VERSION}"
end
if num_args == 0
print_usage
exit 0
end
if num_args == 1 and (ARGV[0] == 'help' or ARGV[0] == 'version')
command = ARGV[0]
case command
when 'help'
print_usage
when 'version'
briar_version
else
@log.error{"'#{command}' is not defined"}
@log.error('can you try something else?')
exit 1
end
exit 0
end
if num_args == 2 and ARGV[0] == 'help'
command = ARGV[1]
case command
when 'console'
print_console_help
when 'cucumber-reports'
print_cucumber_reports_help
when 'install'
print_install_help
when 'resign'
print_resign_help
when 'report'
print_report_help
when 'rm'
print_rm_help
when 'sim'
print_sim_help
when 'tags'
print_tags_help
when 'version'
print_version_help
when '.xamarin'
print_dot_xamarin_help
when 'xtc'
print_xtc_help
when 'xtc-profiles'
print_xtc_profiles_help
else
@log.error("'#{command}' is not defined, so there is no help for you")
exit 1
end
exit 0
end
command = ARGV[0]
args = ARGV.drop(1)
case command
when 'console'
briar_console(args)
when 'install'
briar_install(args)
when 'report'
briar_report(args)
when 'resign'
briar_resign(args)
when 'rm'
briar_rm(args)
when 'sim'
briar_sim(args)
when 'tags'
briar_tags(args)
when 'xtc'
briar_xtc(args)
# deprecated
when BRIAR_RM_CAL_TARGETS
puts Rainbow('DEPRECATED 0.1.3 - replaced with $ briar rm sim-targets').yellow
briar_rm(['sim-targets'])
else
@log.error{"'#{command}' is not defined"}
@log.error('can you try something else?')
exit 1
end
exit 0
| true |
9c7ddc3563e9e794518acd9ed6d696c45ad392fd
|
Ruby
|
wrumble/checkout-tech-test
|
/lib/Promotion_Rules.rb
|
UTF-8
| 448 | 2.859375 | 3 |
[] |
no_license
|
class Promotion_Rules
attr_accessor :list
def initialize
@list = {}
end
def add new_rule
count = list.count + 1
list[count] = new_rule
end
def delete rule_code
list.delete_if { |key| key == rule_code }
end
def update rule_code, updated_rule
list.select{ |key| list[key] = updated_rule if key == rule_code }
end
def find rule_code
list.select{ |key| return list[key] if key == rule_code}
end
end
| true |
fba94e38dad3c9a35dace08d705331dbd68d6a8d
|
Ruby
|
jalena-penaligon/backend_prework
|
/day_5/hash.rb
|
UTF-8
| 2,770 | 4 | 4 |
[] |
no_license
|
# create a mapping of state to abbreciation
states = {
'Oregon' => 'OR',
'Florida' => 'FL',
'California' => 'CA',
'New York' => 'NY',
'Michigan' => 'MI',
'Colorado' => 'CO',
'Arizona' => 'AZ'
}
# Create a basic set of states and some cities in them
cities = {
'CA' => 'San Francisco',
'MI' => 'Detroit',
'FL' => 'Jacksonville',
'CO' => 'Denver',
'AZ' => 'Phoenix',
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# puts out some cities
puts '-' * 10
puts "NY State has: #{cities['NY']}"
puts "OR State has: #{cities['OR']}"
# puts some states
puts '-' * 10
puts "Michigan's abbreviation is: #{states['Michigan']}"
puts "Florida's abbreviation is: #{states['Florida']}"
# do it by using the state then cities dict
puts '-' * 10
puts "Michigan has: #{cities[states['Michigan']]}"
puts "Florida has: #{cities[states['Florida']]}"
puts '-' * 10
states.each do |state, abbrev|
puts "#{state} is abbreviated #{abbrev}"
end
#puts every city in states
puts '-' * 10
cities.each do |abbrev, city|
puts "#{abbrev} has the city #{city}"
end
# now do both at the same time
puts '-' * 10
states.each do |state, abbrev|
city = cities[abbrev]
puts "#{state} is abbreviated #{abbrev} and has city #{city}"
end
puts '-' * 10
# by default, ruby says "nil" when something isn't in there
state = states['Texas']
if !state
puts "Sorry, no Texas."
end
# default values using ||= with the nil result
city = cities['TX']
city ||= 'Does Not Exist'
puts "The city for the state 'TX' is #{city}"
countries = {
'Greece' => 'Santorini',
'Netherlands' => 'Amsterdam',
'Israel' => 'Tel Aviv',
'Czech Republic' => 'Prague'
}
fave = {
'Santorini' => 'boating at sunset',
'Amsterdam' => 'biking at Vondelpark',
'Tel Aviv' => 'swimming in the Dead Sea',
'Prague' => 'Barcelo spa day'
}
# puts out some cities
puts '-' * 10
puts "In Greece we visited: #{countries['Greece']}"
puts "In Netherlands we visisted: #{countries['Netherlands']}"
puts "In #{countries['Greece']} our favorite activity was #{fave['Santorini']}"
puts "Did I like #{countries['Israel']} or #{countries['Czech Republic']} better? Hard to say, #{fave['Tel Aviv']} was pretty epic."
produce ={
"apples" => 3,
"oranges" => 1,
"carrots" => 12,
}
puts "There are #{produce['oranges']} oranges in the fridge."
produce["grapes"] = 221
puts produce
produce["oranges"] = 6
puts produce
puts produce.keys
puts produce.values
produces = {apples: 3, oranges: 1, carrots: 12}
puts "There are #{produces[:oranges]} oranges in the fridge."
states = {"CO" => "Colorado", "IA" => "Iowa", "OK" => "Oklahoma"}
puts "#{states['IA']}"
states.each do |abbrev, name|
puts "#{abbrev}"
end
#VALUES
states.each do |abbrev, name|
puts "#{name}"
end
| true |
fdbdf0af8d6fe4328ad2c15ca8ab7d6bf24f0853
|
Ruby
|
jennyjean8675309/alphabetize-in-esperanto-dc-web-100818
|
/lib/alphabetize.rb
|
UTF-8
| 193 | 3.359375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
ESPERANTO_ALPHABET = "abcĉdefgĝhĥijĵklmnoprsŝtuŭvz".chars
def alphabetize(arr)
arr.sort_by do |phrase|
phrase.chars.map { |c| ESPERANTO_ALPHABET.index(c) }
end
end
| true |
9bcb880d35cd3cdd3ad3f9aaf312b2af10481e67
|
Ruby
|
asadexpert/teamflow
|
/src/tests/unit/MessageManager_test.rb
|
UTF-8
| 566 | 2.734375 | 3 |
[] |
no_license
|
require 'minitest/autorun'
require_relative '../../web/model/MessageManager.rb'
class TestMessageManager < MiniTest::Test
def setup
@mgr = MessageManager.new
end
def test_that_message_manager_returns_a_global_hash
# setup initializes $messages in global scope, so just check it exists and is empty
assert_equal(0, $messages.length)
end
def test_that_i_can_add_a_message_with_key
@mgr.add_message_with_key('test_message_key', 'This is a test message')
assert_equal('This is a test message', $messages['test_message_key'])
end
end
| true |
e7c460a5b9b8b9a13538b4c7329cf8f212a3d29d
|
Ruby
|
ryotarai/isucon5
|
/access-log.rb
|
UTF-8
| 1,849 | 2.515625 | 3 |
[] |
no_license
|
#!/home/isucon/.local/ruby/bin/ruby
class Log
def initialize(h)
@h = h
end
def response_time
# unit: ms
@h['reqtime'].to_f * 1000
end
def endpoint
case [@h['method'], @h['uri']]
when ['GET', '/initialize']
'GET /initialize'
when ['GET', '/']
'GET /'
when ['GET', '/login']
'GET /login'
when ['POST', '/login']
'POST /login'
when ['GET', '/signup']
'GET /signup'
when ['POST', '/signup']
'POST /signup'
when ['GET', '/user.js']
'GET /user.js'
when ['GET', '/data']
'GET /data'
when ['GET', '/modify']
'GET /modify'
when ['POST', '/modify']
'POST /modify'
when ['GET', '/css/bootstrap.min.css'], ['GET', '/css/signin.css'], ['GET', '/css/jumbotron-narrow.css']
'GET css'
when ['GET', '/js/jquery-1.11.3.js'], ['GET', '/js/bootstrap.js'], ['GET', '/js/airisu.js']
'GET js'
end
end
end
class Stat < Struct.new(:total_count, :total_time, :average)
end
stats = {}
ARGF.each_line do |line|
h = {}
line.chomp.split("\t").each do |seg|
key, val = seg.split(':', 2)
if val =~ /\A\d+\z/
val = val.to_i
end
h[key] = val
end
next if h.size == 1
next if h['ua'] != 'Isucon5q bench'
log = Log.new(h)
e = log.endpoint
unless e
p h
raise 'Unknown endpoint'
end
stats[e] ||= Stat.new(0, 0)
stats[e].total_count += 1
stats[e].total_time += log.response_time
end
stats.each do |_, stat|
stat.average = stat.total_time.to_f / stat.total_count
end
stats.sort_by { |e, stat| -stat.total_time }.each do |e, stat|
if stat.average >= 0
meth, path = e.split(' ', 2)
printf("%5s %-25s total %.2f s (access: %d, average: %.1f ms)\n", meth, path, stat.total_time / 1000.0, stat.total_count, stat.average)
end
end
# vim: set et sw=2 sts=2 autoindent:
| true |
4fbf0c73e938c1a91028cf182cd048e38a0d70d9
|
Ruby
|
RyanMora/TDD-Poker
|
/tdd_project/lib/test_driven_development.rb
|
UTF-8
| 914 | 3.421875 | 3 |
[] |
no_license
|
class Array
def my_uniq
uniq = []
self.each do |el|
uniq << el unless uniq.include?(el)
end
uniq
end
def two_sum
pairs = []
(0...length).each do |i|
((i + 1)...length).each do |j|
sum = self[i] + self[j]
pairs << [ i,j] if sum == 0
end
end
pairs
end
def my_transpose
transposed = []
self.each_index do |i|
sub_transposed = []
self.each_index do |j|
sub_transposed << self[j][i]
end
transposed << sub_transposed
end
transposed
end
def stock_picker
best_days = [0,1]
self.each_index do |i|
(i + 1...length).each do |j|
current_best_sum = self[best_days[1]] - self[best_days[0]]
current_sum = self[j] - self[i]
best_days = [i,j] if current_sum > current_best_sum
end
end
"buy day #{best_days[0]}, sell day #{best_days[1]}"
end
end
| true |
d3e4a9d2017a60a044b71ca2eadff11e4a317c9c
|
Ruby
|
sepandb/learn_ruby
|
/04_pig_latin/pig_latin.rb
|
UTF-8
| 1,291 | 4.15625 | 4 |
[] |
no_license
|
def starts_with_vowel(string)
string + "ay"
end
def starts_with_consonant(string)
first_letter = string[0]
beginning = string.delete(first_letter)
beginning + first_letter + "ay"
end
def starts_with_two_consonants(string)
first_letters = string[0] + string[1]
beginning = string.delete(first_letters)
beginning + first_letters + "ay"
end
def starts_with_three_consonants(string)
first_letters = string[0] + string[1] + string[2]
beginning = string.delete(first_letters)
beginning + first_letters + "ay"
end
def translate(string)
alphabet = ("a".."z").to_a
vowel = ["a", "e", "i", "o", "u"]
consonant = alphabet - vowel
sen_array = string.split
sentence = ""
sen_array.each do |word|
if (vowel.include?(word[0]))
sentence = sentence + starts_with_vowel(word)
elsif (consonant.include?(word[0]) && consonant.include?(word[1]) && consonant.include?(word[2]) || ("s" + word[1] + word[2] == "squ"))
sentence = sentence + starts_with_three_consonants(word)
elsif (consonant.include?(word[0]) && consonant.include?(word[1]) || (word[0] + word[1] == "qu"))
sentence = sentence + starts_with_two_consonants(word)
elsif (consonant.include?(word[0]))
sentence = sentence + starts_with_consonant(word)
end
sentence = "#{sentence} "
end
sentence.strip
end
| true |
4badfcf5ca84b020f4aec5fc0440ecea8b4f3758
|
Ruby
|
SwatiJadhav46/max-sum-and-sub-array
|
/specs/max_sum_and_sub_array_spec.rb
|
UTF-8
| 1,573 | 2.828125 | 3 |
[] |
no_license
|
require 'minitest/autorun'
require_relative '../max_sum_and_sub_array.rb'
describe "Test max suma and sub array opration class" do
describe "Check result of opration, Should return set expected sum and array of elements" do
it "Test Case 1" do
arr = [3, -5, 2, 0, 1, -3, 2, -4, 2]
sum_of_sub_array_obj = MaxSumAndSubArray.new(arr)
sum_of_sub_array_obj.get_result
_(sum_of_sub_array_obj.resultant_sub_array.sum).must_equal 3
_(sum_of_sub_array_obj.resultant_sub_array).must_equal [3]
end
it "Test Case 2" do
arr = [-5, 2, 0, 1, -3, 22, 10, -4, 2, 1, -10]
sum_of_sub_array_obj = MaxSumAndSubArray.new(arr)
sum_of_sub_array_obj.get_result
_(sum_of_sub_array_obj.resultant_sub_array.sum).must_equal 32
_(sum_of_sub_array_obj.resultant_sub_array).must_equal [22, 10]
end
it "Test Case 3" do
arr = [-1, 2, 1]
sum_of_sub_array_obj = MaxSumAndSubArray.new(arr)
sum_of_sub_array_obj.get_result
_(sum_of_sub_array_obj.resultant_sub_array.sum).must_equal 3
_(sum_of_sub_array_obj.resultant_sub_array).must_equal [2, 1]
end
it "Test Case 4" do
arr = [-1, 3, -2, 1, 1, 1, 1, 1, 1, 1, 0, 1, -10]
sum_of_sub_array_obj = MaxSumAndSubArray.new(arr)
sum_of_sub_array_obj.get_result
p "------------------------------"
p sum_of_sub_array_obj.resultant_sub_array
_(sum_of_sub_array_obj.resultant_sub_array.sum).must_equal 8
_(sum_of_sub_array_obj.resultant_sub_array).must_equal [1, 1, 1, 1, 1, 1, 1, 0, 1]
end
end
end
| true |
096d321041233278fb5ae9ebdb650a2fcd8c7961
|
Ruby
|
gjanee/advent-of-code-2019
|
/13.rb
|
UTF-8
| 6,787 | 3.8125 | 4 |
[] |
no_license
|
# --- Day 13: Care Package ---
#
# As you ponder the solitude of space and the ever-increasing
# three-hour roundtrip for messages between you and Earth, you notice
# that the Space Mail Indicator Light is blinking. To help keep you
# sane, the Elves have sent you a care package.
#
# It's a new game for the ship's arcade cabinet! Unfortunately, the
# arcade is all the way on the other end of the ship. Surely, it
# won't be hard to build your own - the care package even comes with
# schematics.
#
# The arcade cabinet runs Intcode software like the game the Elves
# sent (your puzzle input). It has a primitive screen capable of
# drawing square tiles on a grid. The software draws tiles to the
# screen with output instructions: every three output instructions
# specify the x position (distance from the left), y position
# (distance from the top), and tile id. The tile id is interpreted as
# follows:
#
# - 0 is an empty tile. No game object appears in this tile.
# - 1 is a wall tile. Walls are indestructible barriers.
# - 2 is a block tile. Blocks can be broken by the ball.
# - 3 is a horizontal paddle tile. The paddle is indestructible.
# - 4 is a ball tile. The ball moves diagonally and bounces off
# objects.
#
# For example, a sequence of output values like 1,2,3,6,5,4 would draw
# a horizontal paddle tile (1 tile from the left and 2 tiles from the
# top) and a ball tile (6 tiles from the left and 5 tiles from the
# top).
#
# Start the game. How many block tiles are on the screen when the
# game exits?
Program = open("13.in").read.scan(/-?\d+/).map(&:to_i)
def run(&block)
# Runs the program to completion; yields to the associated block for
# input and output.
p = Program.clone
ip = 0
rb = 0 # relative base
loc = lambda {|i|
case (p[ip]/10**(i+1))%10
when 0
p[ip+i]
when 1
ip+i
when 2
p[ip+i]+rb
end
}
param = lambda {|i| p[loc[i]] || 0 }
while true
case p[ip]%100
when 1
p[loc[3]] = param[1] + param[2]
ip += 4
when 2
p[loc[3]] = param[1] * param[2]
ip += 4
when 3
p[loc[1]] = yield(:input, nil)
ip += 2
when 4
yield(:output, param[1])
ip += 2
when 5
ip = (param[1] != 0 ? param[2] : ip+3)
when 6
ip = (param[1] == 0 ? param[2] : ip+3)
when 7
p[loc[3]] = (param[1] < param[2] ? 1 : 0)
ip += 4
when 8
p[loc[3]] = (param[1] == param[2] ? 1 : 0)
ip += 4
when 9
rb += param[1]
ip += 2
when 99
break
end
end
end
grid = {}
i = 0
x = y = nil
run {|io,v|
if io == :output
case i
when 0
x = v
when 1
y = v
when 2
grid[[x,y]] = v
end
i = (i+1)%3
end
}
puts grid.values.count(2)
# --- Part Two ---
#
# The game didn't run because you didn't put in any quarters.
# Unfortunately, you did not bring any quarters. Memory address 0
# represents the number of quarters that have been inserted; set it to
# 2 to play for free.
#
# The arcade cabinet has a joystick that can move left and right. The
# software reads the position of the joystick with input instructions:
#
# - If the joystick is in the neutral position, provide 0.
# - If the joystick is tilted to the left, provide -1.
# - If the joystick is tilted to the right, provide 1.
#
# The arcade cabinet also has a segment display capable of showing a
# single number that represents the player's current score. When
# three output instructions specify X=-1, Y=0, the third output
# instruction is not a tile; the value instead specifies the new score
# to show in the segment display. For example, a sequence of output
# values like -1,0,12345 would show 12345 as the player's current
# score.
#
# Beat the game by breaking all the blocks. What is your score after
# the last block is broken?
#
# --------------------
#
# It took some experimentation and visualization to understand the
# nature of this game. The game initially looks like this, in which
# "#" are walls, "=" is the paddle, "O" is the ball, and "." are
# blocks:
#
# #####################################
# # #
# # .. .. .......... . .. . ... #
# # ... .. ............ . ...... . #
# # .... . .. ... ... .. . . . . #
# # .... ...... ....... .. ... ... #
# # ........ . .. ... .. ... . . #
# # .. . .. .. .. ........ ... .. #
# # ... .... .. .... . ........ . #
# # .... ... .. .. ... .. .. .. #
# # . . .. . . .. ... ... . .. #
# # ..... . .. ... ... .. ... .. #
# # .... . .... ... . .. . ... #
# # .. ... . .... . .. . .... #
# # #
# # O #
# # #
# # #
# # = #
# # #
#
# The ball travels continuously and diagonally, bouncing off walls,
# the paddle, and blocks; blocks are destroyed on contact. The game
# ends when all blocks have been destroyed, or if the ball drops out
# of the bottom of the grid. The paddle can be moved left or right
# (only) in response to joystick commands. Thus, this game is
# essentially Pong.
#
# In each cycle, the game reads a joystick command, moves the paddle
# left or right (or not at all), and then moves the ball. To ensure
# that the game remains in play, we need only track the paddle
# horizontally as the ball moves horizontally. Helpfully, at the
# start the ball and paddle are already aligned for a collision.
#
# Run this program with a "visualize" command line argument to see the
# progression of the game graphically (requires the curses gem). A
# second, optional argument can be a floating point number to insert
# a sleep delay between frames.
visualize = (ARGV[0] == "visualize")
delay = ARGV[1].to_f
if visualize
require "curses"
Curses.init_screen
end
draw = Proc.new {
Curses.clear
Curses.setpos(0, 0)
xmin, xmax = grid.keys.map {|x,y| x }.minmax
ymin, ymax = grid.keys.map {|x,y| y }.minmax
(ymin..ymax).each do |y|
Curses.addstr((xmin..xmax).map {|x| " #.=O"[grid[[x,y]]||0] }.join + "\n")
end
Curses.refresh
}
Program[0] = 2
grid = {}
i = 0
x = y = paddle_x = ball_x = score = nil
begin
run {|io,v|
if io == :input
ball_x <=> paddle_x
else
case i
when 0
x = v
when 1
y = v
when 2
if x == -1 && y == 0
score = v
else
grid[[x,y]] = v
paddle_x = x if v == 3
ball_x = x if v == 4
if visualize
draw.call
sleep(delay)
end
end
end
i = (i+1)%3
end
}
ensure
Curses.close_screen if visualize
end
puts score
| true |
fa15e26d74c299986d926c742e0d09ac4bdb1087
|
Ruby
|
rcluca/developer-exercise
|
/ruby/blackjack/tests/persontest.rb
|
UTF-8
| 4,857 | 3.296875 | 3 |
[] |
no_license
|
require 'test/unit'
require_relative 'stub_classes.rb'
require_relative '../blackjack'
require_relative '../person'
class PersonTest < Test::Unit::TestCase
def setup
@deck_stub = DeckStub.new
end
def test_given_a_player_hits_then_their_hand_size_increases_by_one
player = Blackjack.start_playing(@deck_stub)
player.hit_me
assert(player.hand.cards.size == 3)
end
def test_given_a_player_has_a_two_card_hand_without_aces_then_player_hand_value_is_calculated_correctly
player = Blackjack.start_playing(@deck_stub)
possible_hand_values = player.possible_hand_values
assert(possible_hand_values.size == 1)
assert(possible_hand_values.any? {|value| value == 10})
end
def test_given_a_player_has_a_three_card_hand_with_one_ace_then_player_hand_value_is_calculated_correctly
player = Blackjack.start_playing(@deck_stub)
player.hit_me
possible_hand_values = player.possible_hand_values
assert(possible_hand_values.size == 2)
assert(possible_hand_values.any? {|value| value == 11})
assert(possible_hand_values.any? {|value| value == 21})
end
def test_given_a_player_has_a_four_card_hand_with_two_aces_then_player_hand_value_is_calculated_correctly
player = Blackjack.start_playing(@deck_stub)
player.hit_me
player.hit_me
possible_hand_values = player.possible_hand_values
assert(possible_hand_values.size == 2)
assert(possible_hand_values.any? {|value| value == 12})
assert(possible_hand_values.any? {|value| value == 22})
end
def test_given_a_player_has_a_two_card_hand_worth_less_than_21_then_player_has_not_won
player = Blackjack.start_playing(@deck_stub)
assert(player.win == false)
end
def test_given_a_player_has_a_two_card_hand_with_one_ace_and_a_card_worth_ten_then_player_has_won
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:ace),Card.new(:hearts,:two),Card.new(:hearts,:three)]
player = Blackjack.start_playing(DeckStub.new(cards))
assert(player.win == true)
end
def test_given_a_player_has_a_winning_hand_then_they_can_no_longer_hit
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:ace),Card.new(:hearts,:two),Card.new(:hearts,:three)]
player = Blackjack.start_playing(DeckStub.new(cards))
assert(player.hand.cards.size == 2)
player.hit_me
assert(player.hand.cards.size == 2)
end
def test_given_a_player_has_a_two_card_hand_worth_less_than_21_then_player_has_not_busted
player = Blackjack.start_playing(@deck_stub)
assert(player.bust == false)
end
def test_given_a_player_has_a_hand_worth_over_21_then_player_has_busted
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:queen),Card.new(:hearts,:two),Card.new(:hearts,:three),Card.new(:hearts,:two)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.hit_me
assert(player.bust == true)
end
def test_given_a_player_has_a_busted_hand_then_they_can_no_longer_hit
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:queen),Card.new(:hearts,:two),Card.new(:hearts,:three),Card.new(:hearts,:two)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.hit_me
assert(player.hand.cards.size == 3)
player.hit_me
assert(player.hand.cards.size == 3)
end
def test_given_a_player_has_a_hand_higher_than_dealer_and_neither_have_busted_then_player_wins
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:queen),Card.new(:hearts,:seven),Card.new(:hearts,:eight),Card.new(:hearts,:two)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.stay
assert(player.win == true)
end
def test_given_a_player_has_a_hand_higher_than_dealer_and_dealer_busts_then_player_wins
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:queen),Card.new(:hearts,:seven),Card.new(:hearts,:eight),Card.new(:hearts,:nine)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.stay
assert(player.win == true)
end
def test_given_a_dealer_has_a_hand_higher_than_player_and_neither_have_busted_then_dealer_wins
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:seven),Card.new(:hearts,:jack),Card.new(:hearts,:eight)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.stay
assert(player.win == false)
end
def test_given_a_dealer_has_an_immediately_winning_hand_then_dealer_wins
cards = [Card.new(:hearts,:ten),Card.new(:hearts,:seven),Card.new(:hearts,:jack),Card.new(:hearts,:ace)]
player = Blackjack.start_playing(DeckStub.new(cards))
player.stay
assert(player.win == false)
end
end
| true |
7f5c04c90eaca7e7ee00aba3967faa290d097857
|
Ruby
|
dmartinez09/PruebaRuby
|
/PruebaDiego.rb
|
UTF-8
| 2,414 | 3.765625 | 4 |
[] |
no_license
|
#Prueba 1 Ruby
#Menu de 4 opciones
def option
print "__________________________________"
puts "****MENU****"
puts "1) Generar archivo con promedios"
puts "2) Inasistencias totales"
puts "3) Alumnos que aprobaron"
puts "4) Salir"
print "___________________________________\n\n"
puts "Debe ingresar una opcion: "
opcion = gets.chomp.to_i
return opcion
end
#metodo que recibe la nota necesarioa para la aprobacion
def notaminima(nota = 5)
data = ""
array = []
contadornota = 0
file = File.open("promediosAlumnos.csv", "r")
contenido = file.readlines()
#File.open("promedios.csv", "r"){|file|
# data = file.readlines
#}
contenido.each do |i|
arreglo = i.split(",")
#contadornota = contadornota + arreglo.to_i
#if ret[1].to_i > 5
array.push(arreglo[0]) if arreglo[1].to_i >= nota
#end
end
return array
end
continuar = true
system ("clear")
while continuar
case option
#ejercio1
when 1
data = ""
File.open("notas.csv", "r"){|file|
data = file.readlines
}
data.each do |i|
contador = 0
tot = 0
promedios = 0
array = i.split (",")
array.each do |x|
if x.to_i !=0
contador = contador + 1
tot = tot + x.to_i
end
end
promedios = tot.to_f/contador if contador !=0
system ("touch promediosAlumnos.csv")
File.open("promediosAlumnos.csv","a"){|file| file.puts"#{array[0]}. #{promedios}"}
end
puts ("Archivo generdo correctamente, presione alguna tecla para volver al menu")
gets
system("clear")
#mostras inasistencia por pantalla
when 2
data = ""
File.open("notas.csv", "r"){|file|
data = file.readlines
}
data.each do |i|
alumno = ""
contador = 0
array = i.split(",")
array.each do |x|
contador+=1 if x==" A"
alumno = array[0]
end
puts "el alumno es #{alumno} y su inasistencia total es #{contador}"
end
puts ("Presione alguna tecla para volver al menu")
gets
system("clear")
when 3
puts ("los alumnos aprobados son: 3 ")
#@notaminima = aprobados
#array = i
#puts ("los alumnos aprobados son: #{i}")
#notaminima.each{|i| puts i}
puts ("Presione alguna tecla para volver al menu")
gets
when 4
continue = false
break
else
puts "intentelo nuevamente"
end
end
| true |
a343b3eb190afa898509a1d64385dbbf027a445e
|
Ruby
|
TonyNarisi/battleship-challenge
|
/view/game_messages.rb
|
UTF-8
| 1,409 | 3.734375 | 4 |
[] |
no_license
|
module GameMessages
def self.welcome_message
puts "Welcome to Battleship!"
puts "Here is your board:"
end
def self.illegal_placement
puts "That is an illegal placement."
end
def self.computer_chosen_coordinates
puts "The computer has chosen their ship placement. Begin game!"
end
def self.num_of_shots(player)
num_of_shots = player.ships.select { |ship| !ship.sunken? }.length
puts "You have #{num_of_shots} shots to fire this round."
end
def self.computer_num_of_shots(computer)
num_of_shots = computer.ships.select { |ship| !ship.sunken? }.length
puts "The computer has #{num_of_shots} shots to fire this round."
end
def self.sunk(ship)
puts "You sunk your opponent's #{ship.name}!" + "\n "
end
def self.computer_sunk(ship)
puts "The computer sunk your #{ship.name}!"
end
def self.goodbye
puts "Goodbye, thank you for playing!"
end
def self.repeat_coordinate
puts "You have already chosen that coordinate, please choose again."
end
def self.successful_shot(coordinate)
puts "#{coordinate} hit!" + "\n "
end
def self.missed_shot(coordinate)
puts "#{coordinate} missed!" + "\n "
end
def self.successful_computer_shot(coordinate)
puts "Computer hits at #{coordinate}!" + "\n "
end
def self.missed_computer_shot(coordinate)
puts "Computer misses at #{coordinate}!" + "\n "
end
end
| true |
1ad845210eae339508ebc06296743e5c9f934376
|
Ruby
|
InfernoPC/exercism-code
|
/ruby/high-scores/high_scores.rb
|
UTF-8
| 473 | 3.375 | 3 |
[] |
no_license
|
class HighScores
attr_reader :scores
def initialize(scores)
@scores = scores
end
def latest
@scores.last
end
def personal_best
@scores.max
end
def personal_top
@scores.sort.reverse[0..2]
end
def report
if self.latest == self.personal_best
"Your latest score was #{self.latest}. That's your personal best!"
else
"Your latest score was #{self.latest}. That's #{self.personal_best - self.latest} short of your personal best!"
end
end
end
| true |
5aa26697d1beb6ac7e1c4fc7e89a30f99aa7c1bb
|
Ruby
|
learn-co-students/austin-web-120919
|
/mod_1/hashes-and-the-internet/app.rb
|
UTF-8
| 1,535 | 3.671875 | 4 |
[] |
no_license
|
require 'pry'
require 'rest-client'
require 'json'
def welcome
puts "Welcome the Book Searcher"
puts "Please enter a search term:"
end
def get_user_input
gets.chomp
end
def fetch_books(search_term)
response = RestClient.get("https://www.googleapis.com/books/v1/volumes?q=#{search_term}")
#binding.pry
JSON.parse(response.body)
end
def get_title(book)
#binding.pry
book["volumeInfo"]["title"]
end
def get_authors(book)
if book["volumeInfo"]["authors"]
book["volumeInfo"]["authors"].join(" and ")
else
"No authors found"
end
end
def get_description(book)
if book["volumeInfo"]["description"]
book["volumeInfo"]["description"][0..140] + "..."
else
"No description found"
end
end
def print_book(title, authors, description)
puts "*" * 30
puts "Title: #{title}"
puts "Authors: #{authors}"
puts "Description: #{description}"
end
def run
welcome
search_term = get_user_input
fetch_books(search_term)["items"].each do |book|
#binding.pry
title = get_title(book)
authors = get_authors(book)
description = get_description(book)
print_book(title, authors, description)
end
end
run
# RestClient.get 'http://example.com/resource'
#GET Request - get some data from a server/API
#Server Response - data that comes back after a request is made
#Developer Console - Your new home (integrated browser environment)
#APIs - Data for a machine to read
#JSON - JavaScript Object Notation -- String
#Ruby Gems - reusable code
| true |
af73424e9414071f0f246e0258c4fc80ca8888e5
|
Ruby
|
apelerin/THP-S3-Jeudi-MassSendMails
|
/lib/app/townhalls_follower.rb
|
UTF-8
| 3,481 | 2.953125 | 3 |
[] |
no_license
|
require 'twitter'
require 'dotenv'
require 'pry'
require 'csv'
require 'nokogiri'
require 'open-uri'
Dotenv.load('../../.env')
class TwitterBot
attr_accessor :session_twitter, :city_names_array, :townhall_twitter_handle, :townhall_twitter_handle_via_csv
def initialize
#On initialise directement la session avec l'API Twitter
@session_twitter =
Twitter::REST::Client.new do |config|
config.consumer_key = ENV['TWITTER_API_KEY']
config.consumer_secret = ENV['TWITTER_API_SECRET']
config.access_token = ENV['TWITTER_ACCESS_TOKEN']
config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET']
end
@city_names_array = []
@townhall_twitter_handle = []
@townhall_twitter_handle_via_csv = []
end
#Cette méthode va suivre tous les handles présent dans le fichier CSV
def follow_mass
#On gère l'exception pour les comptes Twitter qui n'existent plus
@townhall_twitter_handle_via_csv.each do |handle|
begin
@session_twitter.follow("#{handle}")
rescue Twitter::Error::NotFound => e
next
end
end
#puts "----- OPERATION DONE. YOU FOLLOWED ALL THE HANDLES OF ANALYZED TOWNHALLS ------"
end
#On récupérer le nom des villes du CSV
def get_city_name_from_file
CSV.foreach("../../db/townhalls.csv") do |line|
@city_names_array << line[0]
end
end
#Cette méthode va récupérer les handles Twitter des mairies et les stocker dans une variable d'instance
def get_townhall_handle
@city_names_array.each do |name|
#Cela permet d'encoder l'URL au format URI pour que Nokogori fonctionne correctement
google_search_page_URL = URI.encode("https://www.google.fr/search?q=twitter+mairie+#{name}")
google_search_page_URL = URI.parse(google_search_page_URL)
text_URL = Nokogiri::HTML(open(google_search_page_URL))
townhall_twitter_URL = URI.encode(text_URL.css('cite')[0].text)
townhall_twitter_URL = URI.parse(townhall_twitter_URL)
#On a géré les pages de plusieurs manières : condition if quand ce ne sont pas des pages Twitter, exception quand on nous retourne une page 404, condition if si on est pas sur la page de profil Twitter attendue
if townhall_twitter_URL.to_s.include?("twitter") == true
begin
twitter_URL = Nokogiri::HTML(open(townhall_twitter_URL))
rescue OpenURI::HTTPError => e
next
end
if twitter_URL.css('b.u-linkComplex-target')[0].nil? == false
puts name
@townhall_twitter_handle << twitter_URL.css('b.u-linkComplex-target')[0].text
end
end
end
end
#Méthode qui va ajouter les handles en dernière colonne du fichier
def add_a_handle_column_in_csv
#On va tout d'abord récupérer les données du fichier pour les mettre dans un array tout en ajoutant les handles
complete_line_for_CSV = []
count = 0
File.open("../../db/townhalls.csv") do |read|
read.each_line do |line|
complete_line_for_CSV << line.delete("\n")+",#{@townhall_twitter_handle[count]}"
count += 1
end
end
#On prend toutes les valeurs du tableau et on les ajouter dans le fichier .csv
count = 0
File.open("../../db/townhalls.csv", "w") do |file|
while count < complete_line_for_CSV.size
file.write(complete_line_for_CSV[count])
file.puts
count += 1
end
end
end
def get_handles_from_csv
f = CSV.foreach("../../db/townhalls.csv") do |line|
if line[3] != nil
@townhall_twitter_handle_via_csv << line[3]
end
end
puts @townhall_twitter_handle_via_csv
end
end
| true |
115eb19f12d9cfe29f78ea25e953e4c43a7158ba
|
Ruby
|
paulopatto/foot_stats
|
/lib/foot_stats/team.rb
|
UTF-8
| 1,206 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
module FootStats
class Team < Resource
attribute_accessor :source_id, :full_name, :city, :country
# Return all possible team players
#
# @return [Array]
#
def players(options = {})
Player.all(options.merge(team: source_id))
end
def self.all(options={})
championship_id = options.fetch(:championship)
request = Request.new self, :IdCampeonato => options.fetch(:championship)
response = request.parse stream_key: "team-championship-#{championship_id}"
return response.error if response.error?
updated_response response, options
end
def self.parse_response(response)
response.collect do |team|
Team.new(
:source_id => team['@Id'].to_i,
:full_name => team['@Nome'],
:city => team['@Cidade'],
:country => team['@Pais']
)
end
end
# Return the resource name to request to FootStats.
#
# @return [String]
#
def self.resource_name
'ListaEquipesCampeonato'
end
# Return the resource key that is fetch from the API response.
#
# @return [String]
#
def self.resource_key
'Equipe'
end
end
end
| true |
423f781959ecae137b656df34497860cd1e5d4e1
|
Ruby
|
afunai/bike
|
/t/test_parser.rb
|
UTF-8
| 41,265 | 2.75 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
# encoding: UTF-8
# Author:: Akira FUNAI
# Copyright:: Copyright (c) 2009 Akira FUNAI
require "#{::File.dirname __FILE__}/t"
class TC_Parser < Test::Unit::TestCase
def setup
end
def teardown
end
def test_scan_tokens
assert_equal(
{:tokens => ['foo', 'bar', 'baz']},
Bike::Parser.scan_tokens(StringScanner.new('foo bar baz')),
'Parser.scan_tokens should be able to parse unquoted tokens into array'
)
assert_equal(
{:tokens => ['foo', 'bar', 'baz baz']},
Bike::Parser.scan_tokens(StringScanner.new('foo "bar" "baz baz"')),
'Parser.scan_tokens should be able to parse quoted tokens'
)
assert_equal(
{:tokens => ['foo', 'bar', 'baz']},
Bike::Parser.scan_tokens(StringScanner.new("foo 'bar' baz")),
'Parser.scan_tokens should be able to parse quoted tokens'
)
assert_equal(
{:tokens => ['foo', 'bar', 'baz']},
Bike::Parser.scan_tokens(StringScanner.new("foo 'bar' baz) qux")),
'Parser.scan_tokens should stop scanning at an ending bracket'
)
assert_equal(
{:tokens => ['foo', 'bar (bar?)', 'baz']},
Bike::Parser.scan_tokens(StringScanner.new("foo 'bar (bar?)' baz) qux")),
'Parser.scan_tokens should ignore brackets inside quoted tokens'
)
end
def test_parse_empty_tag
result = Bike::Parser.parse_html('hello $(foo = bar "baz baz") world')
assert_equal(
{'foo' => {:klass => 'bar', :tokens => ['baz baz']}},
result[:item],
'Parser.parse_html should be able to parse empty bike tags'
)
assert_equal(
{:index => 'hello $(foo) world'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
result = Bike::Parser.parse_html <<'_html'
<h1>$(foo=bar "baz baz")</h1>
<p>$(bar=a b c)</p>
_html
assert_equal(
{
'foo' => {:klass => 'bar', :tokens => ['baz baz']},
'bar' => {:klass => 'a', :tokens => ['b', 'c']},
},
result[:item],
'Parser.parse_html should be able to parse empty bike tags'
)
assert_equal(
{:index => <<'_html'},
<h1>$(foo)</h1>
<p>$(bar)</p>
_html
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_parse_empty_tag_in_comment
html = 'hello <!-- $(foo = bar "baz baz") --> world'
result = Bike::Parser.parse_html html
assert_equal(
{},
result[:item],
'Parser.parse_html should skip bike tags in a comment'
)
assert_equal(
{:index => html},
result[:tmpl],
'Parser.parse_html should skip bike tags in a comment'
)
html = '<script><![CDATA[ $(foo = bar "baz baz") ]]></script>'
result = Bike::Parser.parse_html html
assert_equal(
{},
result[:item],
'Parser.parse_html should skip bike tags in a comment'
)
assert_equal(
{:index => html},
result[:tmpl],
'Parser.parse_html should skip bike tags in a comment'
)
end
def test_obscure_markup
result = Bike::Parser.parse_html('hello $(foo = bar $(baz=1) baz) world')
assert_equal(
{'foo' => {:klass => 'bar', :tokens => ['$(baz=1']}},
result[:item],
'Parser.parse_html should not parse nested empty tag'
)
assert_equal(
{:index => 'hello $(foo) baz) world'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
result = Bike::Parser.parse_html('hello $(foo = bar baz world')
assert_equal(
{'foo' => {:klass => 'bar', :tokens => ['baz', 'world']}},
result[:item],
'Parser.parse_html should be able to parse a tag that is not closed'
)
assert_equal(
{:index => 'hello $(foo)'},
result[:tmpl],
'Parser.parse_html should be able to parse a tag that is not closed'
)
result = Bike::Parser.parse_html('hello $(foo = bar "baz"world)')
assert_equal(
{'foo' => {:klass => 'bar', :tokens => ['baz', 'world']}},
result[:item],
'Parser.parse_html should be able to parse tokens without a delimiter'
)
assert_equal(
{:index => 'hello $(foo)'},
result[:tmpl],
'Parser.parse_html should be able to parse tokens without a delimiter'
)
result = Bike::Parser.parse_html('hello $(foo = bar, "baz")')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['baz']}},
result[:item],
'The first token should be regarded as [:klass]'
)
end
def test_parse_token
assert_equal(
{:width => 160, :height => 120},
Bike::Parser.parse_token(nil, '160*120', {}),
'Parser.parse_token should be able to parse dimension tokens'
)
assert_equal(
{:min => 1, :max => 32},
Bike::Parser.parse_token(nil, '1..32', {}),
'Parser.parse_token should be able to parse range tokens'
)
assert_equal(
{:max => 32},
Bike::Parser.parse_token(nil, '..32', {}),
'Parser.parse_token should be able to parse partial range tokens'
)
assert_equal(
{:min => 1},
Bike::Parser.parse_token(nil, '1..', {}),
'Parser.parse_token should be able to parse partial range tokens'
)
assert_equal(
{:min => -32, :max => -1},
Bike::Parser.parse_token(nil, '-32..-1', {}),
'Parser.parse_token should be able to parse minus range tokens'
)
assert_equal(
{:options => ['foo']},
Bike::Parser.parse_token(',', 'foo', {}),
'Parser.parse_token should be able to parse option tokens'
)
assert_equal(
{:options => ['foo', 'bar']},
Bike::Parser.parse_token(',', 'bar', {:options => ['foo']}),
'Parser.parse_token should be able to parse option tokens'
)
assert_equal(
{:default => 'bar'},
Bike::Parser.parse_token(':', 'bar', {}),
'Parser.parse_token should be able to parse default tokens'
)
assert_equal(
{:defaults => ['bar', 'baz']},
Bike::Parser.parse_token(';', 'baz', {:defaults => ['bar']}),
'Parser.parse_token should be able to parse defaults tokens'
)
end
def test_parse_options
result = Bike::Parser.parse_html('hello $(foo = bar , "baz baz", "world", hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should be able to parse a sequence of CSV'
)
result = Bike::Parser.parse_html('hello $(foo = bar "baz baz", "world", hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should be able to parse a sequence of CSV'
)
end
def test_parse_options_with_spaces
result = Bike::Parser.parse_html('hello $(foo = bar world, qux)')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['world', 'qux']}},
result[:item],
'Parser.parse_html should allow spaces after the comma'
)
result = Bike::Parser.parse_html('hello $(foo = bar world , qux)')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['qux'], :tokens => ['world']}},
result[:item],
'Parser.parse_html should not allow spaces before the comma'
)
result = Bike::Parser.parse_html('hello $(foo = bar "baz baz", "world", hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :options => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should allow spaces after the comma'
)
result = Bike::Parser.parse_html(<<'_eos')
hello $(foo =
bar
"baz baz",
"world",
hi
qux)
_eos
assert_equal(
{'foo' => {:klass => 'bar', :options => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should allow spaces after the comma'
)
end
def test_parse_defaults
result = Bike::Parser.parse_html('hello $(foo = bar ;"baz baz";"world";hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should be able to parse a sequence of CSV as [:defaults]'
)
result = Bike::Parser.parse_html('hello $(foo = bar "baz baz";"world";hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should be able to parse a sequence of CSV as [:defaults]'
)
end
def test_parse_defaults_with_spaces
result = Bike::Parser.parse_html('hello $(foo=bar world; qux)')
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['world', 'qux']}},
result[:item],
'Parser.parse_html should allow spaces after the semicolon'
)
result = Bike::Parser.parse_html('hello $(foo=bar world ;qux)')
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['qux'], :tokens => ['world']}},
result[:item],
'Parser.parse_html should not allow spaces before the semicolon'
)
result = Bike::Parser.parse_html('hello $(foo=bar "baz baz"; "world"; hi qux)')
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should allow spaces after the comma'
)
result = Bike::Parser.parse_html(<<'_eos')
hello $(foo =
bar
"baz baz";
"world";
hi
qux)
_eos
assert_equal(
{'foo' => {:klass => 'bar', :defaults => ['baz baz', 'world', 'hi'], :tokens => ['qux']}},
result[:item],
'Parser.parse_html should allow spaces after the comma'
)
end
def test_parse_meta_tag
result = Bike::Parser.parse_html <<'_html'
<html>
<meta name="bike-owner" content="frank" />
</html>
_html
assert_equal(
{
:tmpl => {
:index => <<'_html',
<html>
</html>
_html
},
:item => {},
:owner => 'frank',
:label => nil,
},
result,
'Parser.parse_html should scrape meta vals from <meta>'
)
result = Bike::Parser.parse_html <<'_html'
<html>
<meta name="bike-owner" content="frank" />
<meta name="bike-group" content="bob,carl" />
<meta name="bike-foo" content="bar, baz" />
<meta name="bike-label" content="Qux" />
</html>
_html
assert_equal(
{
:tmpl => {
:index => <<'_html',
<html>
</html>
_html
},
:item => {},
:owner => 'frank',
:group => %w(bob carl),
:foo => %w(bar baz),
:label => 'Qux',
},
result,
'Parser.parse_html should scrape meta vals from <meta>'
)
end
def test_parse_duplicate_tag
result = Bike::Parser.parse_html('hello $(foo = bar "baz baz") world $(foo=boo) $(foo)!')
assert_equal(
{'foo' => {:klass => 'boo'}},
result[:item],
'definition tags are overridden by a preceding definition'
)
assert_equal(
{:index => 'hello $(foo) world $(foo) $(foo)!'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_scan_inner_html
s = StringScanner.new 'bar</foo>bar'
inner_html, close_tag = Bike::Parser.scan_inner_html(s, 'foo')
assert_equal(
'bar',
inner_html,
'Parser.scan_inner_html should extract the inner html from the scanner'
)
assert_equal(
'</foo>',
close_tag,
'Parser.scan_inner_html should extract the inner html from the scanner'
)
s = StringScanner.new '<foo>bar</foo></foo>'
inner_html, close_tag = Bike::Parser.scan_inner_html(s, 'foo')
assert_equal(
'<foo>bar</foo>',
inner_html,
'Parser.scan_inner_html should be aware of nested tags'
)
s = StringScanner.new "baz\n <foo>bar</foo>\n</foo>"
inner_html, close_tag = Bike::Parser.scan_inner_html(s, 'foo')
assert_equal(
"baz\n <foo>bar</foo>\n",
inner_html,
'Parser.scan_inner_html should be aware of nested tags'
)
end
def test_scan_comment
s = StringScanner.new 'baz -->'
inner_html, close_tag = Bike::Parser.scan_inner_html(s, '!--')
assert_equal(
'baz',
inner_html,
'Parser.scan_inner_html should parse html comments'
)
assert_equal(
' -->',
close_tag,
'Parser.scan_inner_html should parse html comments'
)
s = StringScanner.new "baz\n <!--bar-->\n-->"
inner_html, close_tag = Bike::Parser.scan_inner_html(s, '!--')
assert_equal(
"baz\n <!--bar-->\n",
inner_html,
'Parser.scan_inner_html should parse nested comments'
)
end
def test_scan_cdata
s = StringScanner.new 'baz ]]>'
inner_html, close_tag = Bike::Parser.scan_inner_html(s, '<![CDATA[')
assert_equal(
'baz',
inner_html,
'Parser.scan_inner_html should parse CDATA section'
)
assert_equal(
' ]]>',
close_tag,
'Parser.scan_inner_html should parse CDATA section'
)
end
def test_parse_block_tag
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><li>hello</li></ul>
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">$()</ul>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li>hello</li>'},
:item => {},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse block bike tags'
)
assert_equal(
{:index => '$(foo.message)$(foo)'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo">
<li>hello</li>
</ul>
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">
$()</ul>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => " <li>hello</li>\n"},
:item => {},
},
}
},
},
result[:item],
'Parser.parse_html should be able to parse block bike tags'
)
assert_equal(
{:index => '$(foo.message)$(foo)'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
result = Bike::Parser.parse_html <<'_html'
hello <ul class="app-blog" id="foo"><li>hello</li></ul> world
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">$()</ul>$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li>hello</li>'},
:item => {},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse block bike tags'
)
assert_equal(
{:index => <<'_html'},
hello$(foo.message)$(foo) world
_html
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
result = Bike::Parser.parse_html <<'_html'
hello <!-- cruel --> <ul class="app-blog" id="foo"><li>hello</li></ul> world
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">$()</ul>$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li>hello</li>'},
:item => {},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse block bike tags'
)
assert_equal(
{:index => <<'_html'},
hello <!-- cruel -->$(foo.message)$(foo) world
_html
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_parse_block_tag_in_comment
[
<<'_html',
hello <!--<ul class="app-blog" id="test1"><li>hello</li></ul>--> world
_html
<<'_html',
<!--
<ul class="app-blog" id="test2">
<li>hello</li>
</ul>
-->
_html
<<'_html',
foo <!--
<ul class="app-blog" id="test3">
<li>hello</li>
</ul>
--> bar
_html
<<'_html',
foo <!--
<ul class="app-blog" id="test4">
<li>hello</li>
</ul>
--> bar
_html
<<'_html',
foo <!--
<ul class="app-blog" id="test5">
<!-- may_preview -->
<li>hello</li>
</ul>
--> bar
_html
<<'_html',
<![CDATA[
<ul class="app-blog" id="test6">
<!-- may_preview -->
<li>hello</li>
</ul>
]]>
_html
<<'_html',
<!--
<ul class="app-blog" id="test7">
<!-- may_preview -->
<li>hello</li>
</ul>
_html
].each {|html|
result = Bike::Parser.parse_html html
assert_equal(
{},
result[:item],
'Parser.parse_html should skip bike tags in a comment'
)
assert_equal(
{:index => html},
result[:tmpl],
'Parser.parse_html should skip bike tags in a comment'
)
}
end
def test_parse_block_tag_obsolete_runo_class
result = Bike::Parser.parse_html <<'_html'
<ul class="runo-blog" id="foo"><li>hello</li></ul>
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_html'.chomp,
<ul class="runo-blog" id="@(name)">$()</ul>
$(.navi)$(.submit)$(.action_create)
_html
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li>hello</li>'},
:item => {},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse old runo tags'
)
end
def test_parse_block_tag_obsolete_body_class
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><div>oops.</div><li class="body">hello</li></ul>
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_html'.chomp,
<ul class="app-blog" id="@(name)"><div>oops.</div>$()</ul>
$(.navi)$(.submit)$(.action_create)
_html
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li class="body">hello</li>'},
:item => {},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse block bike tags'
)
end
def test_look_a_like_block_tag
result = Bike::Parser.parse_html <<'_html'
hello <ul class="not-app-blog" id="foo"><li>hello</li></ul> world
_html
assert_equal(
{:index => <<'_tmpl'},
hello <ul class="not-app-blog" id="foo"><li>hello</li></ul> world
_tmpl
result[:tmpl],
"Parser.parse_html[:tmpl] should skip a class which does not start with 'bike'"
)
end
def test_block_tags_with_options
result = Bike::Parser.parse_html <<'_html'
hello
<table class="app-blog" id="foo">
<!-- 1..20 barbaz -->
<tbody class="model"><!-- qux --><tr><th>$(bar=text)</th><th>$(baz=text)</th></tr></tbody>
</table>
world
_html
assert_equal(
{
'foo' => {
:min => 1,
:max => 20,
:tokens => ['barbaz'],
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<table class="app-blog" id="@(name)">
<!-- 1..20 barbaz -->
$() </table>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {
:index => <<'_tmpl',
<tbody class="model"><!-- qux --><tr><th>$(.a_update)$(bar)</a></th><th>$(baz)$(.hidden)</th></tr></tbody>
_tmpl
},
:item => {
'bar' => {:klass => 'text'},
'baz' => {:klass => 'text'},
},
},
},
},
},
result[:item],
'Parser.parse_html should aware of <tbody class="model">'
)
end
def test_block_tags_with_tbody
result = Bike::Parser.parse_html <<'_html'
hello
<table class="app-blog" id="foo">
<thead><tr><th>BAR</th><th>BAZ</th></tr></thead>
<tbody class="model"><tr><th>$(bar=text)</th><th>$(baz=text)</th></tr></tbody>
</table>
world
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<table class="app-blog" id="@(name)">
<thead><tr><th>BAR</th><th>BAZ</th></tr></thead>
$() </table>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {
:index => <<'_tmpl',
<tbody class="model"><tr><th>$(.a_update)$(bar)</a></th><th>$(baz)$(.hidden)</th></tr></tbody>
_tmpl
},
:item => {
'bar' => {:klass => 'text'},
'baz' => {:klass => 'text'},
},
},
},
},
},
result[:item],
'Parser.parse_html should aware of <tbody class="model">'
)
assert_equal(
{:index => <<'_tmpl'},
hello
$(foo.message)$(foo)world
_tmpl
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_parse_xml
result = Bike::Parser.parse_xml <<'_html'
<channel class="app-rss">
<link>@(href)</link>
<item class="model">
<title>$(title)</title>
</item>
</channel>
_html
assert_equal(
{
:label => nil,
:tmpl => {:index => '$(main)'},
:item => {
'main' => {
:item => {
'default' => {
:label => nil,
:item => {},
:tmpl => {
:index => <<'_xml'
<item>
<title>$(title)</title>
</item>
_xml
},
},
},
:tmpl => {
:index => <<'_xml',
<channel>
<link>@(href)</link>
$()</channel>
_xml
},
:klass => 'set-dynamic',
:workflow => 'rss',
}
},
},
result,
'Parser.parse_html should aware of <item>'
)
end
def test_parse_item_label
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><li title="Greeting">hello</li></ul>
_html
assert_equal(
'Greeting',
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should pick up item labels from title attrs'
)
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><!-- foo --><li title="Greeting">hello</li></ul>
_html
assert_equal(
'Greeting',
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should pick up item labels from title attrs'
)
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><!-- foo --><li><div title="Foo">hello</div></li></ul>
_html
assert_nil(
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should pick up item labels only from the first tags'
)
end
def test_parse_item_label_plural
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><li title="tEntry, tEntries">hello</li></ul>
_html
assert_equal(
'tEntry',
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should split plural item labels'
)
assert_equal(
['tEntry', 'tEntries'],
Bike::I18n.msg['tEntry'],
'Parser.parse_html should I18n.merge_msg! the plural item labels'
)
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><li title="tFooFoo, BarBar, BazBaz">hello</li></ul>
_html
assert_equal(
'tFooFoo',
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should split plural item labels'
)
assert_equal(
['tFooFoo', 'BarBar', 'BazBaz'],
Bike::I18n.msg['tFooFoo'],
'Parser.parse_html should I18n.merge_msg! the plural item labels'
)
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo"><li title="tQux">hello</li></ul>
_html
assert_equal(
'tQux',
result[:item]['foo'][:item]['default'][:label],
'Parser.parse_html should split plural item labels'
)
assert_equal(
['tQux', 'tQux', 'tQux', 'tQux'],
Bike::I18n.msg['tQux'],
'Parser.parse_html should repeat a singular label to fill all possible plural forms'
)
end
def test_block_tags_with_nested_tbody
result = Bike::Parser.parse_html <<'_html'
hello
<table class="app-blog" id="foo">
<thead><tr><th>BAR</th><th>BAZ</th></tr></thead>
<tbody class="model"><tbody><tr><th>$(bar=text)</th><th>$(baz=text)</th></tr></tbody></tbody>
</table>
world
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<table class="app-blog" id="@(name)">
<thead><tr><th>BAR</th><th>BAZ</th></tr></thead>
$() </table>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {
:index => <<'_tmpl',
<tbody class="model"><tbody><tr><th>$(.a_update)$(bar)</a></th><th>$(baz)$(.hidden)</th></tr></tbody></tbody>
_tmpl
},
:item => {
'bar' => {:klass => 'text'},
'baz' => {:klass => 'text'},
},
},
},
},
},
result[:item],
'Parser.parse_html should aware of nested <tbody class="model">'
)
end
def test_nested_block_tags
result = Bike::Parser.parse_html <<'_html'
<ul class="app-blog" id="foo">
<li>
<ul class="app-blog" id="bar"><li>baz</li></ul>
</li>
</ul>
_html
assert_equal(
{
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">
$()</ul>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {
:index => <<'_tmpl',
<li>
$(bar.message)$(.a_update)$(bar)$(.hidden)</a> </li>
_tmpl
},
:item => {
'bar' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul class="app-blog" id="@(name)">$()</ul>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {:index => '<li>baz</li>'},
:item => {},
},
},
},
},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse nested block bike tags'
)
assert_equal(
{:index => '$(foo.message)$(foo)'},
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_combination
result = Bike::Parser.parse_html <<'_html'
<html>
<h1>$(title=text 32)</h1>
<ul id="foo" class="app-blog">
<li>
$(subject=text 64)
$(body=textarea 72*10)
<ul><li>qux</li></ul>
</li>
</ul>
</html>
_html
assert_equal(
{
'title' => {:klass => 'text', :tokens => ['32']},
'foo' => {
:klass => 'set-dynamic',
:workflow => 'blog',
:tmpl => {
:index => <<'_tmpl'.chomp,
<ul id="@(name)" class="app-blog">
$() </ul>
$(.navi)$(.submit)$(.action_create)
_tmpl
},
:item => {
'default' => {
:label => nil,
:tmpl => {
:index => <<'_tmpl',
<li>
$(.a_update)$(subject)</a>
$(body)$(.hidden)
<ul><li>qux</li></ul>
</li>
_tmpl
},
:item => {
'body' => {
:width => 72,
:height => 10,
:klass => 'textarea',
},
'subject' => {
:tokens => ['64'],
:klass => 'text',
},
},
},
},
},
},
result[:item],
'Parser.parse_html should be able to parse combination of mixed bike tags'
)
assert_equal(
{:index => <<'_tmpl'},
<html>
<h1>$(title)</h1>
$(foo.message)$(foo)</html>
_tmpl
result[:tmpl],
'Parser.parse_html[:tmpl] should be a proper template'
)
end
def test_gsub_block
match = nil
result = Bike::Parser.gsub_block('a<div class="foo">bar</div>c', 'foo') {|open, inner, close|
match = [open, inner, close]
'b'
}
assert_equal(
'abc',
result,
'Parser.gsub_block should replace tag blocks of the matching class with the given value'
)
assert_equal(
['<div class="foo">', 'bar', '</div>'],
match,
'Parser.gsub_block should pass the matching element to its block'
)
result = Bike::Parser.gsub_block('<p><div class="foo">bar</div></p>', 'foo') {|open, inner, close|
match = [open, inner, close]
'b'
}
assert_equal(
'<p>b</p>',
result,
'Parser.gsub_block should replace tag blocks of the matching class with the given value'
)
assert_equal(
['<div class="foo">', 'bar', '</div>'],
match,
'Parser.gsub_block should pass the matching element to its block'
)
result = Bike::Parser.gsub_block('a<p><div class="foo">bar</div></p>c', 'foo') {|open, inner, close|
match = [open, inner, close]
'b'
}
assert_equal(
'a<p>b</p>c',
result,
'Parser.gsub_block should replace tag blocks of the matching class with the given value'
)
assert_equal(
['<div class="foo">', 'bar', '</div>'],
match,
'Parser.gsub_block should pass the matching element to its block'
)
end
def _test_gsub_action_tmpl(html)
result = {}
html = Bike::Parser.gsub_action_tmpl(html) {|id, action, *tmpl|
result[:id] = id
result[:action] = action
result[:tmpl] = tmpl.join
'b'
}
[result, html]
end
def test_gsub_action_tmpl
result, html = _test_gsub_action_tmpl 'a<div class="foo-navi">Foo</div>c'
assert_equal(
{
:id => 'foo',
:action => :navi,
:tmpl => '<div class="foo-navi">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
assert_equal(
'abc',
html,
'Parser.gsub_action_tmpl should replace the action template with a value from the block'
)
result, html = _test_gsub_action_tmpl 'a<div class="bar foo-navi">Foo</div>c'
assert_equal(
{
:id => 'foo',
:action => :navi,
:tmpl => '<div class="bar foo-navi">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
result, html = _test_gsub_action_tmpl 'a<div class="bar foo-navi baz">Foo</div>c'
assert_equal(
{
:id => 'foo',
:action => :navi,
:tmpl => '<div class="bar foo-navi baz">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
result, html = _test_gsub_action_tmpl 'a<div class="bar foo-done baz">Foo</div>c'
assert_equal(
{
:id => 'foo',
:action => :done,
:tmpl => '<div class="bar foo-done baz">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
end
def test_gsub_action_tmpl_with_empty_id
result, html = _test_gsub_action_tmpl 'a<div class="navi">Foo</div>c'
assert_equal(
{
:id => nil,
:action => :navi,
:tmpl => '<div class="navi">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
result, html = _test_gsub_action_tmpl 'a<div class="foo navi">Foo</div>c'
assert_equal(
{
:id => nil,
:action => :navi,
:tmpl => '<div class="foo navi">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
result, html = _test_gsub_action_tmpl 'a<div class="foo navi baz">Foo</div>c'
assert_equal(
{
:id => nil,
:action => :navi,
:tmpl => '<div class="foo navi baz">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield action templates'
)
end
def test_gsub_action_tmpl_with_ambiguous_klass
result, html = _test_gsub_action_tmpl 'a<div class="not_navi">Foo</div>c'
assert_equal(
{},
result,
'Parser.gsub_action_tmpl should ignore classes other than action, view, navi or submit'
)
result, html = _test_gsub_action_tmpl 'a<div class="navi_bar">Foo</div>c'
assert_equal(
{
:id => nil,
:action => :navi_bar,
:tmpl => '<div class="navi_bar">Foo</div>',
},
result,
'Parser.gsub_action_tmpl should yield an action template if the klass looks like special'
)
end
def test_action_tmpl_in_ss
result = Bike::Parser.parse_html <<'_html'
<html>
<ul id="foo" class="app-blog">
<li>$(subject=text)</li>
</ul>
<div class="foo-navi">bar</div>
</html>
_html
assert_equal(
<<'_tmpl',
<div class="foo-navi">bar</div>
_tmpl
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should parse action templates in the html'
)
assert_equal(
{:index => <<'_tmpl'},
<html>
$(foo.message)$(foo)$(foo.navi)</html>
_tmpl
result[:tmpl],
'Parser.parse_html should replace action templates with proper tags'
)
end
def test_action_tmpl_in_ss_with_nil_id
result = Bike::Parser.parse_html <<'_html'
<html>
<ul id="main" class="app-blog">
<li>$(subject=text)</li>
</ul>
<div class="navi">bar</div>
</html>
_html
assert_equal(
<<'_tmpl',
<div class="navi">bar</div>
_tmpl
result[:item]['main'][:tmpl][:navi],
"Parser.parse_html should set action templates to item['main'] by default"
)
assert_equal(
{:index => <<'_tmpl'},
<html>
$(main.message)$(main)$(main.navi)</html>
_tmpl
result[:tmpl],
"Parser.parse_html should set action templates to item['main'] by default"
)
end
def test_action_tmpl_in_ss_with_non_existent_id
result = Bike::Parser.parse_html <<'_html'
<html>
<ul id="main" class="app-blog">
<li>$(subject=text)</li>
</ul>
<div class="non_existent-navi">bar</div>
</html>
_html
assert_nil(
result[:item]['non_existent'],
'Parser.parse_html should ignore the action template without a corresponding SD'
)
assert_equal(
{:index => <<'_tmpl'},
<html>
$(main.message)$(main) <div class="non_existent-navi">bar</div>
</html>
_tmpl
result[:tmpl],
'Parser.parse_html should ignore the action template without a corresponding SD'
)
end
def test_action_tmpl_in_ss_with_nested_action_tmpl
result = Bike::Parser.parse_html <<'_html'
<html>
<ul id="foo" class="app-blog">
<li>$(subject=text)</li>
</ul>
<div class="foo-navi"><span class="navi_prev">prev</span></div>
</html>
_html
assert_equal(
<<'_html',
<div class="foo-navi">$(.navi_prev)</div>
_html
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should parse nested action templates'
)
assert_equal(
'<span class="navi_prev">prev</span>',
result[:item]['foo'][:tmpl][:navi_prev],
'Parser.parse_html should parse nested action templates'
)
assert_equal(
{
:index => <<'_html'.chomp,
<ul id="@(name)" class="app-blog">
$() </ul>
$(.submit)$(.action_create)
_html
:navi => <<'_html',
<div class="foo-navi">$(.navi_prev)</div>
_html
:navi_prev => '<span class="navi_prev">prev</span>',
},
result[:item]['foo'][:tmpl],
'Parser.parse_html should parse nested action templates'
)
result = Bike::Parser.parse_html <<'_html'
<html>
<ul id="foo" class="app-blog">
<li>$(subject=text)</li>
</ul>
<div class="foo-navi"><span class="bar-navi_prev">prev</span></div>
</html>
_html
assert_equal(
'<span class="bar-navi_prev">prev</span>',
result[:item]['foo'][:tmpl][:navi_prev],
'Parser.parse_html should ignore the id of a nested action template'
)
end
def test_action_tmpl_in_sd
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
<div class="navi">bar</div>
</ul>
_html
assert_equal(
<<'_html',
<div class="navi">bar</div>
_html
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should parse action templates in sd[:tmpl]'
)
assert_match(
%r{\$\(\.navi\)},
result[:item]['foo'][:tmpl][:index],
'Parser.parse_html should parse action templates in sd[:tmpl]'
)
end
def test_action_tmpl_in_sd_with_nested_action_tmpl
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
<div class="navi"><span class="navi_prev">prev</span></div>
</ul>
_html
assert_equal(
<<'_html',
<div class="navi">$(.navi_prev)</div>
_html
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should parse nested action templates in sd[:tmpl]'
)
assert_equal(
'<span class="navi_prev">prev</span>',
result[:item]['foo'][:tmpl][:navi_prev],
'Parser.parse_html should parse nested action templates in sd[:tmpl]'
)
end
def test_action_tmpl_in_comment
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
<!--
<div class="navi"><span class="navi_prev">prev</span></div>
-->
</ul>
_html
assert_nil(
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should skip action templates in a comment'
)
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
<div class="navi"><!--<span class="navi_prev">prev</span>--></div>
</ul>
_html
assert_equal(
<<'_html',
<div class="navi"><!--<span class="navi_prev">prev</span>--></div>
_html
result[:item]['foo'][:tmpl][:navi],
'Parser.parse_html should skip action templates in a comment'
)
end
def test_supplement_sd
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
</ul>
_html
assert_match(
/\$\(\.navi\)/,
result[:item]['foo'][:tmpl][:index],
'Parser.supplement_sd should supplement sd[:tmpl] with default menus'
)
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<div class="navi">bar</div>
<li class="model">$(text)</li>
</ul>
_html
assert_no_match(
/\$\(\.navi\).*\$\(\.navi\)/m,
result[:item]['foo'][:tmpl][:index],
'Parser.supplement_sd should not supplement sd[:tmpl] when it already has the menu'
)
result = Bike::Parser.parse_html <<'_html'
<div class="foo-navi">bar</div>
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
</ul>
_html
assert_no_match(
/\$\(\.navi\)/,
result[:item]['foo'][:tmpl][:index],
'Parser.supplement_sd should not supplement sd[:tmpl] when it already has the menu'
)
end
def test_supplement_ss
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text)</li>
</ul>
_html
assert_match(
/\$\(\.a_update\)/,
result[:item]['foo'][:item]['default'][:tmpl][:index],
'Parser.supplement_ss should supplement ss[:tmpl] with default menus'
)
result = Bike::Parser.parse_html <<'_html'
<ul id="foo" class="app-blog">
<li class="model">$(text) $(.action_update)</li>
</ul>
_html
assert_no_match(
/\$\(\.a_update\)/,
result[:item]['foo'][:item]['default'][:tmpl][:index],
'Parser.supplement_ss should not supplement ss[:tmpl] when it already has the menu'
)
end
end
| true |
f8eb78d4de2de8eb705fd5e4f1b5264efcf2c695
|
Ruby
|
AaronRohrbacher/favorite_things_ruby
|
/lib/favorite_things_ruby.rb
|
UTF-8
| 973 | 3.1875 | 3 |
[] |
no_license
|
class Item
@@list = []
attr_reader :id, :rank
attr_accessor :name
def initialize(attributes)
@name = attributes.fetch(:name)
@rank = attributes.fetch(:rank)
@id = @@list.length + 1
end
def self.all()
@@list
end
def save()
@@list.push(self)
end
def self.clear()
@@list = []
end
def self.find(id)
item_id = id.to_i()
@@list.each do |item|
if item.id == item_id
return item
end
end
end
# def self.find_index(id)
# item_id = id.to_i()
# @@list.each do |item|
# if item.id == item_id
# return item
# end
# end
# end
def self.sort()
@@list.sort_by {|item| item.rank}
end
def self.validation(name, rank)
name_to_check = name
rank_to_check = rank.to_i
return_value = true
@@list.each do |item|
if item.name == name_to_check || item.rank == rank_to_check
return false
end
end
return_value
end
end
| true |
e814bb96f83d5116d8ea1a933240895e4f0c28f0
|
Ruby
|
jagregory/pact
|
/lib/pact/consumer/consumer_contract_builder.rb
|
UTF-8
| 4,248 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
require 'uri'
require 'json/add/regexp'
require 'pact/logging'
require 'pact/consumer/mock_service_client'
require_relative 'interactions_filter'
module Pact
module Consumer
class ConsumerContractBuilder
include Pact::Logging
attr_reader :consumer_contract
def initialize(attributes)
@interaction_builder = nil
@mock_service_client = MockServiceClient.new(attributes[:provider_name], attributes[:port])
@consumer_contract = Pact::ConsumerContract.new(
:consumer => ServiceConsumer.new(name: attributes[:consumer_name]),
:provider => ServiceProvider.new(name: attributes[:provider_name])
)
@consumer_contract.interactions = interactions_for_new_consumer_contract(attributes[:pactfile_write_mode])
@interactions_filter = filter(@consumer_contract.interactions, attributes[:pactfile_write_mode])
end
def given(provider_state)
interaction_builder.given(provider_state)
end
def upon_receiving(description)
interaction_builder.upon_receiving(description)
end
def interaction_builder
@interaction_builder ||=
begin
interaction_builder = InteractionBuilder.new
interaction_builder.on_interaction_fully_defined do | interaction |
self.handle_interaction_fully_defined(interaction)
end
interaction_builder
end
end
def verify example_description
mock_service_client.verify example_description
end
def log msg
mock_service_client.log msg
end
def wait_for_interactions options
wait_max_seconds = options.fetch(:wait_max_seconds, 3)
poll_interval = options.fetch(:poll_interval, 0.1)
mock_service_client.wait_for_interactions wait_max_seconds, poll_interval
end
def handle_interaction_fully_defined interaction
interactions_filter << interaction
mock_service_client.add_expected_interaction interaction #TODO: What will happen if duplicate added?
consumer_contract.update_pactfile
self.interaction_builder = nil
end
private
attr_reader :mock_service_client
attr_reader :interactions_filter
attr_writer :interaction_builder
def interactions_for_new_consumer_contract pactfile_write_mode
pactfile_write_mode == :update ? existing_interactions : []
end
def filter interactions, pactfile_write_mode
if pactfile_write_mode == :update
UpdatableInteractionsFilter.new(interactions)
else
DistinctInteractionsFilter.new(interactions)
end
end
def warn_and_stderr msg
$stderr.puts msg
logger.warn msg
end
def info_and_puts msg
$stdout.puts msg
logger.info msg
end
def existing_interactions
interactions = []
if pactfile_exists?
begin
interactions = existing_consumer_contract.interactions
info_and_puts "*****************************************************************************"
info_and_puts "Updating existing file .#{consumer_contract.pactfile_path.gsub(Dir.pwd, '')} as config.pactfile_write_mode is :update"
info_and_puts "Only interactions defined in this test run will be updated."
info_and_puts "As interactions are identified by description and provider state, pleased note that if either of these have changed, the old interactions won't be removed from the pact file until the specs are next run with :pactfile_write_mode => :overwrite."
info_and_puts "*****************************************************************************"
rescue StandardError => e
warn_and_stderr "Could not load existing consumer contract from #{consumer_contract.pactfile_path} due to #{e}"
warn_and_stderr "Creating a new file."
end
end
interactions
end
def pactfile_exists?
File.exist?(consumer_contract.pactfile_path)
end
def existing_consumer_contract
Pact::ConsumerContract.from_uri(consumer_contract.pactfile_path)
end
end
end
end
| true |
395dd8a3d6e461804ed1b7cd0c388d9de602e94f
|
Ruby
|
pemacy/Launch_School
|
/Coursework/100/109/Exercises/Easy6/cute_angles.rb
|
UTF-8
| 238 | 3.265625 | 3 |
[] |
no_license
|
DEGREE = "\xC2\xB0"
def dms(num)
decimal = num - num.truncate
minutes = (decimal * 60).abs
seconds = ((minutes - minutes.truncate) * 60).round
"%(#{num.truncate}#{DEGREE}#{minutes.truncate}'#{seconds}\")"
end
puts dms(-123.234)
| true |
ccea591045c4d2cb1193223dcd74a87cced60392
|
Ruby
|
saravanan121533/cc-web-boot
|
/day_1/assign/10_does_it_include_c.rb
|
UTF-8
| 364 | 4.5625 | 5 |
[] |
no_license
|
# Write a code that takes user's input and then prints out "Yes it has C"
# if entered input contains the letter "C" (upper or lower case).
# And it prints "There is no C" if it doesn't
puts "Enter value to check for letter C: "
input = gets.chomp.strip.downcase
c_count = input.count("c")
if c_count > 0
puts "Yes it has C."
else
puts "There is no C."
end
| true |
7f23e84299ad9b1f75c944bc69d6940e1850a72c
|
Ruby
|
Wyattwicks/home
|
/lib/building.rb
|
UTF-8
| 1,137 | 3.328125 | 3 |
[] |
no_license
|
require './lib/building'
require './lib/apartment'
require './lib/renter'
class Building
attr_reader :units, :renters, :bedrooms, :number
def initialize
@units = []
end
def add_unit(unit)
@units << unit
end
def renters
@renters = []
@units.find_all do |unit|
@renters << unit.renter.name
end
@renters
end
def average_rent
@average_rent = []
@units.find_all do |unit|
@average_rent << unit.monthly_rent
end
@average_rent.inject{|sum, el| sum + el }.to_f / @average_rent.size
end
def rented_units
@rented_units = []
@units.find_all do |unit|
if unit.renter == nil
nil
else
@rented_units << unit
end
end
end
def renter_with_highest_rent
highest_rent = []
@rented_units.max_by do |unit|
highest_rent << unit.renter
end
highest_rent[0]
end
def units_by_number_of_bedrooms
bedroom_hash = Hash.new
@units.max_by do |unit|
bedroom_hash.each do |bedrooms:, number:|
end
end
bedroom_hash.max_by do |bedrooms:|
end
bedroom_hash
end
end
| true |
1c0817b6c6aced952764c6694632b31972f05f9a
|
Ruby
|
lymanwong/Ruby-Stuff
|
/learn_ruby/00_hello/adder.rb
|
UTF-8
| 109 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
total = 0
loop do
p "Enter a number"
num = gets.strip
total += num.to_i
p "Total: " + total.to_s
end
| true |
a2293e477e452092d3658a705f926d4be583f97f
|
Ruby
|
ethunk/phase10
|
/meetups-in-space/app/models/meetup.rb
|
UTF-8
| 917 | 2.5625 | 3 |
[] |
no_license
|
class Meetup < ActiveRecord::Base
has_many :attendees
has_many :users, through: :attendees
validates :name, :location, :description, presence: true
def creator
meetup_id = self.id
user_id = Attendee.where('meetup_id = ? AND creator = true ', meetup_id)[0].user_id
return User.where('users.id = ?', user_id)[0].username
end
# SELECT meetups.id AS meetupid, users.username, users.avatar_url, attendees.creator FROM attendees
# JOIN meetups ON meetups.id = attendees.meetupid
# JOIN users ON users.id = attendees.user_id;
# By convention, Rails guesses that the column used to hold the foreign key on this model is the
# name of the association with the suffix _id added. The :foreign_key option lets you set the name
# of the foreign key directly:
# class Order < ActiveRecord::Base
# belongs_to :customer, :class_name => "Patron", :foreign_key => "patron_id"
# end
end
| true |
b30abff409f940ed71e9e5d580f64844b8ac987d
|
Ruby
|
abstraktor/racket-port_scanner
|
/syn_scan.rb
|
UTF-8
| 2,291 | 2.953125 | 3 |
[] |
no_license
|
require 'monitor'
require 'pcaprub'
require 'racket'
ERR_NEED_ROOT = "Execute me as root! I need to bypass your operating systems network stack!\nYou might want to do: \n\trvmsudo %s %s" %[$0, $*.join(" ")]
#this is a threadsafe, stealth syn-scan
class SynScan < Monitor
# lets bypass the os network stack and build custom packets with racket
include Racket
def initialize(dst_ip, port)
abort ERR_NEED_ROOT if Process.uid != 0 # care for root rights
@dst_ip = dst_ip
@port = port
@@timeout = 2
open_listener # ok let's start listening at first to ensure we 'hear' the response
send # send the actual syn package
listen # wait for an answer or timeout to happen and handle the result
end
# start capture with pcaprub
def open_listener
@listener = PCAPRUB::Pcap.open_live(IFACE, 65535, false, 1)
@listener.setfilter("tcp port #{@port} and tcp[tcpflags] & tcp-ack != 0")
end
def send
@p = Racket.new
@p.iface = IFACE
@p.l3 = L3::IPv4.new
@p.l3.src_ip = SRC_IP
@p.l3.dst_ip = @dst_ip
@p.l3.protocol = 6
@p.l3.ttl = 64
@p.l4 = L4::TCP.new
@p.l4.src_port = next_src_port
@p.l4.dst_port = @port
@p.l4.flag_syn = 1
#p.l4.window = 2048
# build checksum and length fields
@p.l4.fix!(@p.l3.src_ip, @p.l3.dst_ip, "") # last param for next payload
# just send the packet
@p.sendpacket
end
def listen
t = 0
# wait for an answer or the timeout
until [email protected] or t==@@timeout do
sleep 0.3
t += 1
end
return if t==@@timeout # timeout! this does not fit to the RFCs. Should we retry it or ignore?
# build a packet out of these raw data (ip starts at 14)
p3 = L3::IPv4.new(data[14,data.length])
# tcp lays on ip
p4 = L4::TCP.new(p3.payload)
# evaluate whether this is what I'm waiting for
if p4.src_port==@port and p3.src_ip==@dst_ip then
puts @port if p4.flag_syn==1 and p4.flag_ack==1 #this is the only answer conforming to the RFCs
else
listen #this is not, what I'm waiting for. continue waiting!
end
end
# well this gives some variation to the process so that the computers don't get bored
def next_src_port
1024 + rand(65535 - 1024)
end
end
| true |
eb77cd5260916931135c1ad3ce763d890ba5b89c
|
Ruby
|
orenyomtov/ironbee
|
/fast/suggest.rb
|
UTF-8
| 3,921 | 2.828125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env ruby
# Suggest fast modifiers for rules.
#
# This script should be given an IronBee rules file on standard in. It will
# search for @rx or @dfa operators in those rules and analyize the regular
# expressions for appropriate fast patterns. The rule file, plus annotation
# comments, will be emitted to standard out.
#
# Requires `gem install regexp_parser`.
#
# Author: Christopher Alfeld <[email protected]>
$:.unshift(File.dirname(__FILE__))
require 're_to_ac'
# Don't try to handle any alternation expression (a|b|c) with more than this
# many alternatives, including subexpressions.
MAX_ALTERNATIONS = 5
# Any expression that repreats more than this many types; repeat only this
# many times. E.g., x{20} will be treated as x{10}.
MAX_REPETITIONS = 10
# Fields that are covered by fast.
FIELDS = [
'REQUEST_METHOD',
'REQUEST_URI',
'REQUEST_PROTOCOL',
'REQUEST_HEADERS',
'REQUEST_URI_PARAMS',
'RESPONSE_PROTOCOL',
'RESPONSE_STATUS',
'RESPONSE_MESSAGE',
'RESPONSE_HEADERS',
'ARGS'
]
FIELD_RE = Regexp.new('\b(' + FIELDS.join('|') + ')[^A-Za-z]')
rx_mode = ARGV.member?('--rx')
lua_mode = ARGV.member?('--lua')
$comment = lua_mode ? '--' : '#'
# Evaluate if a rule is a candidate for an fast modifier.
def potential_rule(line)
line =~ /\s@(rx|dfa) / && # Has a regexp
line !~ /\bfast:/ && # Does not already have an fast
line !~ /\st:/ && # Does not have a transformation
line =~ FIELD_RE # Involves a field fast knows about.
end
# Extract regular expressions from a Rule.
def extract_regexps(line)
r = []
line.scan(/\s@(rx|dfa) (?:"((?:\\"|[^"])+)"|([^ ]+?))(\s|$)/) {r << $2}
r
end
# Format pattern for inclusion in rule.
def format_patterns(patterns)
patterns.collect {|x| "\"fast:#{x}\""}.join(' ')
end
def format_patterns_lua(patterns)
patterns.collect {|x| "action(\"fast:#{x}\")"}.join(':')
end
# Is this pattern considered valid?
def valid_pattern(s)
s.length > 3
end
# Main loop.
lua_eligible = false
STDIN.each do |line|
begin
if rx_mode
res = [line.chomp]
elsif lua_mode
res = []
if line =~ /^\s*Sig|Action/
lua_eligible = false
elsif line =~ /\bfields?\((.+)\)/
if $1 =~ /[A-Za-z_]+/
if FIELDS.member?($&)
lua_eligible = true
end
end
elsif lua_eligible && line =~ /\bop\(\s*('|"|\[(=*)\[)rx(?:'|"|\]\2\])\s*,\s*('|"|\[(=*)\[)(.+)(?:'|"|\]\4\])/
res = [$5]
end
elsif potential_rule(line)
res = extract_regexps(line)
else
res = []
end
rescue Exception => err
puts "#{$comment} FAST Error looking at line: #{err}"
puts line
res = []
end
res.each do |re|
if re.nil?
puts "#{$comment} FAST Failed to extract regexp. Malformed rule?"
next
end
# Validate with ruby.
begin
Regexp.new(re)
rescue Exception => err
puts "#{$comment} FAST Ruby Says: #{err}"
end
begin
result = ReToAC::extract(re, MAX_ALTERNATIONS, MAX_REPETITIONS)
rescue Exception => err
puts "#{$comment} FAST Exception: #{err}"
result = []
end
next if result.empty?
# Filter out invalid patterns.
result = result.collect {|r| r.select {|s| valid_pattern(s)}}
# If any row is now empty, we are done.
next if result.find {|r| r.empty?}
suggestion = ReToAC::craft_suggestion(result)
if suggestion
puts "#{$comment} FAST RE: #{re}"
if lua_mode
puts "#{$comment} FAST Suggest: #{format_patterns_lua(suggestion)}"
else
puts "#{$comment} FAST Suggest: #{format_patterns(suggestion)}"
end
if result.size > 1 || result.first.size > 1
puts "#{$comment} FAST Result Table: "
puts "#{$comment} FAST " +
(result.collect do |row|
'( ' + row.join(' AND ') + ' )'
end.join(" OR\n# FAST "))
end
end
end
puts line
end
| true |
571fc05c419de0cf0e8a4d79b65d1f73818c8ca4
|
Ruby
|
petertseng/exercism-problem-specifications
|
/exercises/palindrome-products/verify.rb
|
UTF-8
| 1,856 | 3.34375 | 3 |
[
"MIT"
] |
permissive
|
require 'json'
require_relative '../../verify'
json = JSON.parse(File.read(File.join(__dir__, 'canonical-data.json')))
cases = by_property(json['cases'], %w(smallest largest))
# We can't actually get fancy here; searching by diagonal doesn't work.
# https://codereview.stackexchange.com/questions/63304/finding-palindromic-numbers-most-efficiently
# So just search linearly, trying to be a little smart:
# Terminate inner/outer searches when candidate can't beat winner.
# This is fast enough.
# If more is needed, maybe consider exploiting divisibility by 11,
# https://www.xarg.org/puzzle/project-euler/problem-4/
#
# (start: Int) number the search should start from.
# (range_from_start: Int => Range[Int]) make a range starting from the given start.
# (cmp: Symbol) symbol of comparison used to compare winner to a candidate
def palindromes(start, range_from_start, cmp)
raise 'no' if range_from_start[start].size == 0
stats = {skip1: nil, skip2s: [], checks: 0}
winner = nil
products = []
range_from_start[start].each { |a|
next if a % 10 == 0
break stats[:skip1] = a if winner&.send(cmp, a * a)
range_from_start[a].each { |b|
stats[:checks] += 1
product = a * b
break stats[:skip2s] << [a, b].freeze if winner&.send(cmp, product)
next if (d = product.digits).reverse != d
if product == winner
products << [a, b].sort
else
winner = product
products = [[a, b].sort]
end
}
}
#p stats
{'value' => winner, 'factors' => products}
end
def smallest(min, max)
palindromes(min, ->x { x..max }, :<)
end
def largest(min, max)
palindromes(max, ->x { x.downto(min) }, :>)
end
verify(cases['smallest'], property: 'smallest') { |i, _|
smallest(i['min'], i['max'])
}
verify(cases['largest'], property: 'largest') { |i, _|
largest(i['min'], i['max'])
}
| true |
d3ac3c61a40b2582000510045deb9168cc4e8221
|
Ruby
|
ThomasMcP/week_02_day_2_lab
|
/bus.rb
|
UTF-8
| 441 | 3.9375 | 4 |
[] |
no_license
|
class Bus
attr_reader :route_number, :destination, :passengers
def initialize(route_number, destination)
@route_number = route_number
@destination = destination
@passengers = []
end
def drive()
return "Brum brum"
end
def pick_up(passenger)
@passengers << passenger
end
def drop_off(passenger)
for person in @passengers
@passenger.delete(passenger) if person == passenger
end
end
end
| true |
c3e27790df63c82e8437455413112048cb81c19e
|
Ruby
|
kirweekend/I704_Ruby
|
/project/game.rb
|
UTF-8
| 3,214 | 2.984375 | 3 |
[] |
no_license
|
require 'gosu'
require_relative 'player'
require_relative 'bomb'
require_relative 'bullet'
require_relative 'explosion'
module Game
class Space < Gosu::Window
attr_reader :score
WIDTH = 960
HEIGHT = 720
PLAYER_WIDTH = 480
PLAYER_HEIGHT = 360
BOMB_FREQUENCY = 0.03
def initialize
super(WIDTH, HEIGHT)
self.caption = "Space Game"
@background_image = Gosu::Image.new("assets/sky.jpg", :tileable => true)
@image = Gosu::Image.new("assets/heart.png")
@player = Player.new(self)
@player.size(PLAYER_WIDTH, PLAYER_HEIGHT)
@bullets = []
@bombs = []
@explosions = []
@score = 0
@beep = Gosu::Sample.new "assets/shoot.ogg"
@boom = Gosu::Sample.new "assets/explosion.ogg"
@font = Gosu::Font.new(40)
end
def button_down(id)
if id == Gosu::KbSpace
@bullets.push(Bullet.new(self, @player.x, @player.y, @player.angle))
@beep.play
end
end
def draw
if @new_game
@new_game.draw("Final Score: #{@score}", 315, 320, 4, 1.0, 1.0, Gosu::Color::YELLOW)
@new_game.draw("Press Return to Try Again", 200, 270, 4, 1.0, 1.0, Gosu::Color::YELLOW)
@background_image.draw(0,0,0)
@bullets = []
@bombs = []
@explosions = []
else
@player.draw()
@bullets.each(&:draw)
@bombs.each(&:draw)
@explosions.each(&:draw)
@background_image.draw(0,0,0)
@image.draw(40, 15, 3)
@font.draw("#{score}", 100, 14, 3, 1.0, 1.0, Gosu::Color::YELLOW)
end
end
def update
@player.turn_left if button_down?(Gosu::KB_A)
@player.turn_right if button_down?(Gosu::KB_D)
@player.accelerate if button_down?(Gosu::KB_W)
@player.move
if rand < BOMB_FREQUENCY
@bombs.push(Bomb.new(self))
end
@bombs.each(&:move)
@bullets.each(&:move)
@bombs.each do |bomb|
@bullets.each do |bullet|
distance = Gosu.distance(bomb.x, bomb.y, bullet.x, bullet.y)
if distance < bomb.radius + bullet.radius
@explosions << Explosion.new(self, bomb.x, bomb.y)
@bombs.delete bomb
@bullets.delete bullet
@boom.play
@score += 10
end
end
end
@bombs.each do |bomb|
distance_p = Gosu.distance(bomb.x, bomb.y, @player.x, @player.y)
if distance_p < bomb.radius + @player.radius
@explosions << Explosion.new(self, bomb.x, bomb.y)
@bombs.delete bomb
@new_game = Gosu::Font.new(50)
end
end
@explosions.each do |explosion|
@explosions.delete explosion if explosion.finished
end
@bombs.each do |bomb|
@bombs.delete bomb if bomb.y > HEIGHT + bomb.radius
end
@bullets.each do |bullet|
@bullets.delete bullet unless bullet.onscreen?
end
if @new_game and button_down? Gosu::KbReturn
@new_game = nil
@score = 0
@player = Player.new(self)
@player.size(PLAYER_WIDTH, PLAYER_HEIGHT)
@bullets = []
@bombs = []
@explosions = []
end
end
end
end
Game::Space.new.show
| true |
d5c8008ce9dde164a256a45c3029642a5632c0ee
|
Ruby
|
yuihyama/funcrock
|
/examples/primefactors_example.rb
|
UTF-8
| 718 | 3.75 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require './lib/primefactors'
p primefactors(20) # => [2, 5]
puts primefactors(20)
# =>
# 2
# 5
print primefactors(20), "\n" # => [2, 5]
p primefactors(1) # => []
p primefactors(-20) # => [2, 5]
# p primefactors(0) # => ZeroDivisionError
puts primefactors(1) # => (nil)
puts
(1..45).each { |n| print primefactors(n), "\n" }
# =>
# []
# [2]
# [3]
# [2]
# [5]
# [2, 3]
# [7]
# [2]
# [3]
# [2, 5]
# [11]
# [2, 3]
# [13]
# [2, 7]
# [3, 5]
# [2]
# [17]
# [2, 3]
# [19]
# [2, 5]
# [3, 7]
# [2, 11]
# [23]
# [2, 3]
# [5]
# [2, 13]
# [3]
# [2, 7]
# [29]
# [2, 3, 5]
# [31]
# [2]
# [3, 11]
# [2, 17]
# [5, 7]
# [2, 3]
# [37]
# [2, 19]
# [3, 13]
# [2, 5]
# [41]
# [2, 3, 7]
# [43]
# [2, 11]
# [3, 5]
| true |
3470ba9e50bb7d7572a179078dc85a1e47a5fcef
|
Ruby
|
JoelQ/game-of-life
|
/spec/terminal_spec.rb
|
UTF-8
| 598 | 2.703125 | 3 |
[] |
no_license
|
require 'spec_helper'
describe "Terminal" do
before(:each) do
@terminal = Terminal.new
end
# it "should convert the world.cells 2d array into an array of lines" do
# @terminal.world = World.new(4,3)
# @terminal.output_world
# @terminal.two_d_to_string.should == [" "*4, " "*4, " "*4]
# end
#
# it "should convert user pattern to a 2d array of true/false values" do
# live = Terminal::LIVE
# dead = Terminal::DEAD
# u_pattern = ["#{live}#{live}", "#{dead}#{dead}"]
# @terminal.pattern_to_a(u_pattern).should == [[true, false], [true, false]]
# end
end
| true |
21534ee68a81972e6c9b038859f872857eda9c95
|
Ruby
|
mmcnickle-float/aoc2020
|
/day4/test_passport_file.rb
|
UTF-8
| 2,294 | 2.578125 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'minitest/autorun'
require 'minitest/spec'
require_relative 'passport_file'
require_relative 'fields'
describe PassportFile do
describe '#passports' do
it 'returns a list of passports' do
passport_filedata = <<~PASSPORT_FILEDATA
ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in
PASSPORT_FILEDATA
file = StringIO.new(passport_filedata)
passport_file = PassportFile.new(file)
expected_passports = [
Passport.new(
{
ecl: Field::Ecl.new('gry'),
pid: Field::Pid.new('860033327'),
eyr: Field::Eyr.new(2020),
hcl: Field::Hcl.new('#fffffd'),
byr: Field::Byr.new(1937),
iyr: Field::Iyr.new(2017),
cid: Field::Cid.new('147'),
hgt: Field::Hgt.new(183, 'cm')
}
),
Passport.new(
{
ecl: Field::Ecl.new('amb'),
pid: Field::Pid.new('028048884'),
eyr: Field::Eyr.new(2023),
hcl: Field::Hcl.new('#cfa07d'),
byr: Field::Byr.new(1929),
iyr: Field::Iyr.new(2013),
cid: Field::Cid.new('350')
}
),
Passport.new(
{
ecl: Field::Ecl.new('brn'),
pid: Field::Pid.new('760753108'),
eyr: Field::Eyr.new(2024),
hcl: Field::Hcl.new('#ae17e1'),
byr: Field::Byr.new(1931),
iyr: Field::Iyr.new(2013),
hgt: Field::Hgt.new(179, 'cm')
}
),
Passport.new(
{
ecl: Field::Ecl.new('brn'),
pid: Field::Pid.new('166559648'),
eyr: Field::Eyr.new(2025),
hcl: Field::Hcl.new('#cfa07d'),
iyr: Field::Iyr.new(2011),
hgt: Field::Hgt.new(59, 'in')
}
)
]
passports = passport_file.passports
assert_equal(expected_passports, passports)
end
end
end
| true |
e4ea6d5b6f86568831df55a27f522c7e2b22e9c6
|
Ruby
|
CardozoIgnacio/Ruby_Tp
|
/Tp8/ej_04.rb
|
UTF-8
| 782 | 3.375 | 3 |
[] |
no_license
|
puts "Para cada registro del archivo creado en el punto1, solicite
el ingreso del suelod de cada persona y guarde esa dupla (nombre+sueldo)
eb yb byevi archivo.(El dato sueldo debe estar formateado a un tamaño gual para todos los registros)"
def formatera_sueldo(sueldo,cant)
while (cant!=sueldo.size())
sueldo="0"+sueldo
end
return sueldo
end
def formato_columan(elem,espaciado)
while (espaciado!=elem.size())
elem=elem+" "
end
return elem
end
arch_nombre=File.new("./Datos/datos_ej01.data","r")
arch_sueldo=File.new("./Datos/datos_ej04.data","w")
arch_nombre.each do |nombre|
nombre=nombre.chomp
sueldo=gets.chomp.to_s
registro=formato_columan(nombre,15)+ formatera_sueldo(sueldo,8)
arch_sueldo.puts(registro)
end
| true |
c42e3c5ed2078ec42345e545e4cc531a9c720477
|
Ruby
|
Aviory/Dark_Library
|
/src/entities/book.rb
|
UTF-8
| 411 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
require_relative "../entities/author"
class Book
attr_reader :author, :title
def initialize(title, author)
if !title.is_a?(String) or title.size == nil or author.is_a?(Author)
begin
raise CustomError.new("Invalid argument")
rescue => e
puts e.msg
end
else
@title = title
@author = author
end
end
def to_s
" #{title}: #{author}"
end
end
| true |
db3202f8a1f85743fdb6b8a6d6322d030d705292
|
Ruby
|
atsumori/sp_authentication
|
/lib/sp_authentication/generator.rb
|
UTF-8
| 1,391 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
module SpAuthentication
class Generator
class << self
# signatureを生成する
# 処理概要
# 1. httpリクエストメソッド、url、キーでアルファベット順にソートしたリクエストパラメータの順番で&で連結し、rfc3986形式でurlエンコーディングを行います
# 2. 1で生成した文字列をシークレットキーを使ってhmacsha1 アルゴリズムでhash値を生成します
# 3. 2で生成したhash値をbase64エンコードします
def create_signature(method, url, parameters, secret_key)
target_str = "#{method}&#{url}"
params_array = Array.new
if parameters.length > 0
parameters.sort.each do |key, value|
params_array << "#{key}=#{CGI.escape(value)}"
end
params_str = params_array.join("&")
target_str = target_str + "&#{params_str}"
end
if SpAuthentication.print_debug
SpAuthenticationLogger.logger.info("encript target: #{target_str}")
end
digest = OpenSSL::Digest::Digest.new('sha1')
ret = CGI.escape(Base64.strict_encode64(OpenSSL::HMAC.digest(digest, secret_key, target_str)))
if SpAuthentication.print_debug
SpAuthenticationLogger.logger.info("encripted string: #{ret}")
end
return ret
end
end
end
end
| true |
22f53efa7cf542ac90073421d3b37af1fbe9fe4b
|
Ruby
|
danicortesloba/E6CP1A1
|
/3 ciclos anidados/ejercicio3.rb
|
UTF-8
| 437 | 3.90625 | 4 |
[] |
no_license
|
# Construir un programa que permita ingresar un número por teclado e imprimir
# la tabla de multiplicar del número ingresado. Debe repetir la operación hasta
# que se ingrese un 0 (cero).
# Ingrese un número (0 para salir): _
puts "Ingrese un número (0 para salir)"
num = gets.chomp.to_i
while num != 0
for i in 1..10
puts i * num
i += 1
end
puts "Ingrese un número (0 para salir)"
num = gets.chomp.to_i
end
| true |
3a9d8eb4d47c733cbbc5c850b3dba3370677d446
|
Ruby
|
BrennanFulmer/ttt-game-status-bootcamp-prep-000
|
/lib/game_status.rb
|
UTF-8
| 856 | 3.78125 | 4 |
[] |
no_license
|
# Helper Method
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
WIN_COMBINATIONS = [
[0,1,2],
[3,4,5],
[6,7,8],
[0,4,8],
[2,4,6],
[0,3,6],
[1,4,7],
[2,5,8]
]
def won?(board)
result = false
WIN_COMBINATIONS.each do |set|
if board[set[0]] == "X" && board[set[1]] == "X" && board[set[2]] == "X"
result = set
elsif board[set[0]] == "O" && board[set[1]] == "O" && board[set[2]] == "O"
result = set
end
end
result
end
def full?(board)
filled = board.all? do |spot|
spot != " " && spot != ""
end
filled
end
def draw?(board)
won?(board) == false && full?(board)
end
def over?(board)
won?(board) != false || draw?(board)
end
def winner(board)
outcome = won?(board)
if outcome != false
board[outcome[0]]
else
nil
end
end
| true |
e3b0f5f3150d0470f8458e584920af3c8def6f17
|
Ruby
|
thekatainthehat/thekatainthehat-sessions
|
/110401_miniXPDayBenelux/acceptance_tests.rb
|
UTF-8
| 306 | 2.71875 | 3 |
[] |
no_license
|
require "test/unit"
class AcceptanceTests < Test::Unit::TestCase;def test_making_money; beret = Beret.new 4; rabbit = SomethingThatMoves.new; beret.please_be_at 3, 15; rabbit.please_be_at 4, 14; assert_equal 0.€, beret.money; rabbit.would_you_please_fall_down; assert_equal 1.€, beret.money; end ;end;
| true |
a9eb58e194c72d67ff0c497a9cb61380aab97bbe
|
Ruby
|
carpetofgreenness/food4u
|
/lib/stilltasty.rb
|
UTF-8
| 872 | 3.125 | 3 |
[] |
no_license
|
class StillTasty
require "net/http"
require "json"
def self.search(food)
food = food.tr(" ", "&").tr("—", "-")
p food
uri = URI("https://shelf-life-api.herokuapp.com/search?q=#{food}")
response = Net::HTTP.get(uri)
json = JSON.parse(response)
result = json[0]["id"]
uri2 = URI("https://shelf-life-api.herokuapp.com/guides/#{result}")
response2 = Net::HTTP.get(uri2)
json2 = JSON.parse(response2)
end
def self.name_search(food)
food = food.tr(" ", "&")
uri = URI("https://shelf-life-api.herokuapp.com/search?q=#{food}")
response = Net::HTTP.get(uri)
json = JSON.parse(response)
# result = json[0]["id"]
end
def self.guide_search(id_num)
uri = URI("https://shelf-life-api.herokuapp.com/guides/#{id_num}")
response = Net::HTTP.get(uri)
json = JSON.parse(response)
end
end
# p StillTasty.search("apple")
| true |
39f7cd607860f154dd723f11086763cb4f28167c
|
Ruby
|
luis-novoa/desafio-back-end
|
/app/services/input_formatter.rb
|
UTF-8
| 1,341 | 3.21875 | 3 |
[] |
no_license
|
class InputFormatter
def initialize(string)
@string = string
end
def extract_infos
@string = @string.split('')
transaction_type = @string.shift.to_i
date = @string.slice!(0, 8).join('')
value = @string.slice!(0, 10)
cpf = @string.slice!(0, 11)
credit_card = @string.slice!(0, 12).join('')
time = @string.slice!(0, 6).join('')
owner = @string.slice!(0, 14).join('').rstrip
company = @string.slice!(0, 19).join('').rstrip
{
transaction: {
transaction_type: transaction_type,
date: Time.parse(date + time),
value: value_formatter(value, transaction_type),
cpf: cpf_formatter(cpf),
credit_card: credit_card
},
company: {
owner: owner,
name: company
}
}
end
private
def date_formatter(array)
array = array[6..7] + ['/'] + array[4..5] + ['/'] + array[0..3]
array.join('')
end
def value_formatter(array, type)
array = array.join('').to_f / 100
return array * -1 if [2, 3, 9].include?(type)
array
end
def cpf_formatter(array)
array = array[0...3] + ['.'] + array[3...6] + ['.'] + array[6...9] + ['-'] + array[9...11]
array.join('')
end
def time_formatter(array)
array = array[0...2] + [':'] + array[2...4] + [':'] + array[4...6]
array.join('')
end
end
| true |
06cadb1661f1bc8c6238dd8a47fe823b81f1756e
|
Ruby
|
ben7x7/bebessiere
|
/db/seeds.rb
|
UTF-8
| 1,875 | 2.703125 | 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 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)
require "open-uri"
require "json"
Dessert.destroy_all
Ingredient.destroy_all
desserts = [
{
name: "Gâteau au Yaourt",
technique: "Mettre le four à préchauffer à 210 deg. Dans un grand récipient, verser la farine, le sucre, les oeufs, le yaourt, la levure, l'huile, l'amende amère ou rhum. Bien mélanger et le verser dans un moule à cake préalablement préparé avec du papier d'aluminium. Enfourner et laisser cuir pendant 45 min. "
},
{
name: "Charlotte aux Fruits",
technique: "Préparation de la mousse aux fruits"
},
{
name: "Macarons",
technique: "Mettre le four à préchauffer à 230 deg. Dans un récipient, verser le sucre glace et la poudre d\'amende. Monter les blancs en neige et mélanger délicatement avec le mélange sucre-amende. A l\'aide d\'une poche à douille, faire des petits tas de 4cm de diamètre environ sur une plaque à patisserie. Humidifier avec un pinceau le dessus du macaron et saupoudrer de sucre glace. Enfourner et reduiser la temperature du four à 120 deg. Laisser cuire pendant 15 min."
},
{
name: "Dacquoise",
technique: "Mettre le four à préchauffer à 230 deg. Dans un récipient, verser le sucre glace, la poudre d\'amende et la farine."
}
]
desserts.each { |dessert| Dessert.create(dessert)}
file = "https://raw.githubusercontent.com/ben7x7/seed-database/master/seed-bebessiere/ingredients.json"
sample = JSON.parse(open(file).read)
sample["ingredients"].each do |ingredient|
Ingredient.create! ingredient
end
| true |
1e0e8e4d168061218134f4ce623c700ebfdf47fd
|
Ruby
|
sigvei/pgn2tex
|
/lib/pgn2tex/texable.rb
|
UTF-8
| 1,103 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
require "erb"
module Pgn2tex
module Texable
# Converts the object to LaTeX, by running an ERB template. Templates
# need to be put in lib/pgn2tex/templates/, and be named <Class>.tex.erb, where
# Class is the name of the class the Texable module is included in.
#
# Note that this method will likely be called only on top-level objects like
# {Pgn2tex::Database}. The ERB templates for Database then calls {Pgn2tex::Game#to_tex}
# object, and so on.
#
# @return [String] A LaTeX representation of the object
def to_tex
filename = File.join(File.dirname(__FILE__), "templates", class_name + ".tex.erb")
template = File.read(filename)
@object = self
ERB.new(template, 0, "-").result(binding)
end
# Escapes the string for inclusion in LaTeX files
#
# @param input [String] the string to escape
# @return [String] the escaped string
def texescape(input)
input.gsub("#", "\\#")
end
module_function(:texescape)
private
def class_name
self.class.name.split("::").last
end
end
end
| true |
5f4d5621f80033b90311d2380f97e834db0d8572
|
Ruby
|
Jeremy-Barrass/learn_to_program
|
/ch13-creating-new-classes/extend_built_in_classes.rb
|
UTF-8
| 826 | 4.28125 | 4 |
[] |
no_license
|
class Integer
# your code here
def factorial
if self < 0
return 'You can\'t take the factorial of a negative number!'
end
if self <= 1
1
else
self * (self-1).factorial
end
end
def to_roman
# your code here
numerals = Hash.new
numerals[1] = "I"
numerals[5] = "V"
numerals[10] = "X"
numerals[50] = "L"
numerals[100] = "C"
numerals[500] = "D"
numerals[1000] = "M"
numeral = ""
if self < 1 || self > 3000
puts "Please choose a number between 1 and 3000"
end
left = self
div = [1000,500,100,50,10,5,1]
while left > 0
div.each do |n|
write = left / n
left = left - write * n
if write > 0
numeral = numeral + numerals[n] * write
end
end
end
return numeral
end
end
puts 239.to_roman
# puts 6.factorial
| true |
14e416495aa29f34d19137cf20ccd9337d0ee5fc
|
Ruby
|
iangreenleaf/rrrex
|
/lib/rrrex/match.rb
|
UTF-8
| 826 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
module Rrrex
class Match
end
end
require 'rrrex/regexp'
require 'rrrex/string_match'
require 'rrrex/range_match'
require 'rrrex/or_match'
require 'rrrex/concat_match'
require 'rrrex/not_match'
module Rrrex
class Match
def self.convert( atom )
if atom.kind_of? Match
atom
elsif atom.kind_of? Range
RangeMatch.new atom
else
StringMatch.new atom
end
end
def wrap( s )
"(?:#{s})"
end
def match(str)
Regexp.new( self ).match str
end
def or(atom)
OrMatch.new self, atom
end
def +(p)
ConcatMatch.new self, p
end
def not(atom)
ConcatMatch.new NotMatch.new( atom ), self
end
def group_names
[]
end
protected
def input( atom )
self.class.convert atom
end
end
end
| true |
77fc1271c9e5a5480fa330f482811ba1d137a18c
|
Ruby
|
atd/google_scholar
|
/lib/google_scholar/article.rb
|
UTF-8
| 754 | 2.671875 | 3 |
[] |
no_license
|
module GoogleScholar
class Article
class << self
include ActiveSupport::Memoizable
end
attr_reader :doc
def initialize(doc)
@doc = doc
end
def title
doc.css("h3").text
end
def link
doc.css('h3 a').first['href']
end
def details
doc.css('.gs_a').first.text
end
def cites_element
doc.css('.gs_fl a').select{ |l| l.text =~ /^Cited by/ }.first
end
def cites_link
cites_element ?
GoogleScholar::ROOT_URL + cites_element['href'] :
nil
end
def cites_count
cites_element ?
cites_element.text.gsub("Cited by ", "").to_i :
0
end
memoize :title, :link, :details, :cites_link, :cites_count
end
end
| true |
bd668df65ba98b5b647de48c832c775e18290e0e
|
Ruby
|
MattSHeil/Iron_Hack
|
/week_3/exercise/ratings_imdb/app.rb
|
UTF-8
| 97 | 2.625 | 3 |
[] |
no_license
|
require('imdb')
trek_search = Imdb::Search.new('Star Trek')
movies = trek_search.new
p movies
| true |
10876f0bd8295b13ec015a3a2ffe7619eb7aa8f6
|
Ruby
|
leduc81/hipme
|
/app/models/outfit.rb
|
UTF-8
| 1,471 | 2.625 | 3 |
[] |
no_license
|
class Outfit < ActiveRecord::Base
attr_accessor :address
belongs_to :user
has_many :bookings
has_attached_file :picture,
styles: { large: "800x800>", medium: "300x300>", thumb: "100x100>" }
validates_attachment_content_type :picture,
content_type: /\Aimage\/.*\z/
ALL_STYLES = [ "Urban", "Hipster", "For a job interview", "For a night out" ]
ALL_SIZES = [ "165cm", "170cm", "175cm", "180cm", "185cm", "190cm" ]
ALL_RANGES = ["2", "5", "10"]
after_validation :set_address
geocoded_by :address
after_validation :geocode
# true if has booking between 2 dates (format date or string)
def has_bookings_at_period(checkin_date, checkout_date)
# convert to date if string
checkin_date = Date.parse(checkin_date) if checkin_date.is_a? String
checkout_date = Date.parse(checkout_date) if checkout_date.is_a? String
# if no consistency in period
return true if checkout_date < checkout_date
# prevent charging dataset for more than 100 days long
return true if (checkout_date-checkin_date) >= 100
# raise error ?
self.bookings.each do |booking|
(booking.checkin..booking.checkout).each do |d|
# booking for this outfit at these dates
return true if (checkin_date..checkout_date).include? d
end
end
# no booking at this date
return false
end
def set_address
self.address = "#{self.user.street} #{self.user.zip} #{self.user.city} #{self.user.country}"
end
end
| true |
a47e90eed797ed808468757199fef4f506483b3c
|
Ruby
|
ballman/hoops
|
/lib/fox_game_fetcher.rb
|
UTF-8
| 978 | 2.5625 | 3 |
[] |
no_license
|
require 'net/http'
class FoxGameFetcher < GameFetcher
URL = 'msn.foxsports.com'
def get_game_list_html(game_date, url, conference_id='all')
conference_id ||= 'all'
path = '/collegebasketball/scores?scheduleDayCode=' + game_date.strftime("%Y-%m-%d") +
'&conference=' + conference_id.to_s
Net::HTTP.start(url) do |http|
response = http.get(path)
response.body
end
end
def create_game_list(html)
games = Array.new
html.grep(/<a href=\"([^>]*)\">Box Score/m) do | match |
games << $1.sub(/cbk/, 'collegebasketball')
end
return games
end
def create_game_file(date, content, source_id)
return FoxGameFile.new(:game_date => date, :content => content, :source_id => source_id)
end
def loaded_games(date)
FoxGameFile.find(:all, :conditions => [ "game_date = ?", date ]).collect do | game |
game.source_id
end
end
def get_game_source_id(url)
url.slice(url.index("=") + 1..-1)
end
end
| true |
66a906af05637d59e283f8f7af8bd6a7f0f23b73
|
Ruby
|
Finble/learn_to_program
|
/ch09-writing-your-own-methods/roman_numerals.rb
|
UTF-8
| 909 | 3.40625 | 3 |
[] |
no_license
|
def roman_numeral (num)
thous = (num/1000)
hunds = (num % 1000/100)
tens = (num % 100/10)
ones = (num % 10)
roman = 'M' * thous
if hunds == 9
roman = roman + 'CM'
elsif hunds == 4
roman = roman + 'CD'
else
roman = roman + 'D' * (num % 1000/500)
roman = roman + 'C' * (num % 500/100)
end
if tens == 9
roman = roman + 'XC'
elsif tens == 4
roman = roman + 'XL'
else
roman = roman + 'L' * (num % 100/50)
roman = roman + 'X' * (num % 50/10)
end
if ones == 9
roman = roman + 'IX'
elsif ones == 4
roman = roman + 'IV'
else
roman = roman + 'V' * (num % 10/5)
roman = roman + 'I' * (num % 5/1)
end
roman
end
puts roman_numeral(1999)
# again, I have done this Q a few times (over last few years) - it's the long CP solution but is the solution that's clearest to me
# however, working on a hash + iteration method, timed out but will revisit
# rspec passed
| true |
c14d91daf79c5441a52d1328ad6b3eaee1d39cfa
|
Ruby
|
lucasjct/Ruby-Brief-Introdution
|
/basico/estruturaCondicional.rb
|
UTF-8
| 480 | 4.0625 | 4 |
[] |
no_license
|
puts "Digite o numero 1 ou 2"
value = gets.to_i
=begin
if value == 1
puts "valor é igual a 1"
elsif value == 2
puts "valor é igual a 2"
else
puts "valor não é igual a 1"
end
=end
#Estrututa unless - executa o código se a condicional for falsa
#unless value == 2
# puts "condição falsa"
#else
# puts "condição verdadeira"
#end
case value
when 0
puts "você digitou 0"
when 1
puts "você digitou 1"
else
puts "opção invalida"
end
| true |
0b294b0522b794e5a315d3c77dc2b0ce375a86a5
|
Ruby
|
rwatari/minesweeper
|
/game.rb
|
UTF-8
| 1,182 | 3.578125 | 4 |
[] |
no_license
|
require_relative "board"
require_relative "tile"
require 'byebug'
require 'yaml'
class Game
def self.load(filename)
saved_state = File.read(filename)
Game.new(YAML::load(saved_state))
end
def initialize(board)
@board = board
@game_over = false
end
def parse_pos(string)
string.scan(/\d/).map(&:to_i)
end
def save
puts "Enter a file name"
saved_file_name = gets.chomp
saved_game = @board.to_yaml
File.open(saved_file_name, 'w') do |file|
file.write(saved_game)
end
end
def play_turn
puts "Enter a position (ex: 3, 4)"
pos = parse_pos(gets.chomp)
puts "Reveal (r) or Flag (f) or Save (s)?"
act = gets.chomp.downcase
if act == "f"
@board[pos].flag
@board.render
elsif act == "s"
save
else
if !@board[pos].flagged && @board[pos].bomb?
@board.reveal_all
@board.render
puts "You loooose"
@game_over = true
else
@board.reveal(pos)
@board.render
end
end
end
def play
@board.render
play_turn until @game_over || won?
puts "You win!" if won?
end
def won?
@board.won?
end
end
| true |
d906bc6d32ca199245664e4d0b991ab5bd656559
|
Ruby
|
foodini/bash_environment
|
/projecteuler/0057.rb
|
UTF-8
| 275 | 3.453125 | 3 |
[] |
no_license
|
def digits(i)
count=0
while i>0
count+=1
i/=10
end
count
end
num = 1
den = 1
count = 0
1000.times do
num += den
tmp = num
num = den
den = tmp
num += den
if digits(num) > digits(den) then count += 1 end
end
puts count
| true |
ceb80dcb7144313bdac9af046836328644df895d
|
Ruby
|
dkitchenerable/code-teasers
|
/tests/arrays/max_profit_test.rb
|
UTF-8
| 636 | 3.109375 | 3 |
[] |
no_license
|
require 'minitest/autorun'
require_relative '../../arrays/max_profit.rb'
class TestMaxProfit < MiniTest::Unit::TestCase
def setup
@result = [1,6,5]
end
def test_minimum
assert_equal(@result, max_profit([1,6]))
end
def test_left_end
assert_equal(@result, max_profit([1,6,1,4,3,5]))
end
def test_middle
assert_equal([5,19,14], max_profit([8,5,12,9,19,1]))
end
def test_right_end
assert_equal(@result, max_profit([3,5,2,4,1,6]))
end
def test_negative_max
assert_equal([4,3,-1], max_profit([8,4,3,1]))
end
def test_zero_max
assert_equal([4,4,0], max_profit([8,4,4,1]))
end
end
| true |
c04af354b3905ce760ba3957470d32e115dc0bbc
|
Ruby
|
Kento75/ruby-example
|
/sec3-2/next_loop.rb
|
UTF-8
| 253 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
languages = %w(Perl Python Ruby Smalltalk JavaScript)
languages.each do |language|
puts language
next unless language == 'Ruby' # next は多言語の continue
puts 'I found Ruby!!!!' # nextの条件にマッチしなかった場合出力
end
| true |
589629f47eeabfc5272489d8908621a7500514b7
|
Ruby
|
Sun5hine/reverse-each-word-ruby-cartoon-collections-000
|
/reverse_each_word.rb
|
UTF-8
| 91 | 3.296875 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def reverse_each_word(string)
string.split(" ").collect {|x| x.reverse}.join(" ")
end
| true |
bebdfb8fe3aa59447f0a67b58921c31a6e02d2cd
|
Ruby
|
HirenBhalani/My-Pro
|
/27.rb
|
UTF-8
| 445 | 3.5625 | 4 |
[] |
no_license
|
people = 20
cats =30
dogs = 15
if people < cats
puts "Too many cats! The world is doomed"
end
if people>cats
puts "Not many cats! The world is saved"
end
if people<dogs
puts "THe world is drooled on!"
end
if people>dogs
puts "The world is dry!"
end
dogs+=5
if people>=dogs
puts "People are greter then or equal dogs."
end
if people<=dogs
puts "People are less then or equal t odogs."
end
if people==dogs
puts "People are dogs"
end
| true |
011247bdac8f29625c856c56d9a2a49c8394601c
|
Ruby
|
curufinwe/open_bridge
|
/client/lib/gui/beam.rb
|
UTF-8
| 412 | 2.859375 | 3 |
[] |
no_license
|
class Beam
def initialize(game, from_pos, to_pos, color)
@from = from_pos
@to = to_pos
@color = color
@game = game
@graphics = game.add.graphics(0,0)
draw!
after 0.2.seconds do
@graphics.destroy
end
end
def draw!
@graphics.clear
@graphics.lineStyle(1, @color , 2)
x,y = *@from
@graphics.moveTo(x,y)
x,y = *@to
@graphics.lineTo(x,y)
end
end
| true |
2c3716f0f292936347c81c6e97ed35776c0fc82c
|
Ruby
|
amsmyth1/yardsourcing-engine
|
/spec/requests/api/v1/yard_search_spec.rb
|
UTF-8
| 6,016 | 2.5625 | 3 |
[] |
no_license
|
require 'rails_helper'
RSpec.describe "Yard Search" do
describe "Happy Path" do
it "returns yard records that match the zipcode criteria" do
yard_1 = create(:yard, zipcode: '19125')
yard_2 = create(:yard, zipcode: '19125')
yard_3 = create(:yard, zipcode: '19125')
yard_4 = create(:yard, zipcode: '54678')
yard_5 = create(:yard, zipcode: '11122')
get "/api/v1/yards/yard_search?location=19125"
expect(response).to be_successful
yards = JSON.parse(response.body, symbolize_names:true)
expect(yards).to be_a(Hash)
expect(yards[:data]).to be_an(Array)
expect(yards[:data].first).to be_a(Hash)
expect(yards[:data].first[:type]).to eq('yard')
expect(yards[:data].count).to eq(3)
expect(yards[:data].first[:id]).to eq(yard_1.id.to_s)
expect(yards[:data].last[:id]).to eq(yard_3.id.to_s)
yard_ids = yards[:data].map do |yard|
yard[:id].to_i
end
expect(yard_ids.include?(yard_4.id)).to eq(false)
expect(yard_ids.include?(yard_5.id)).to eq(false)
end
it "returns yard records that match zipcode and purposes search criteria" do
yard_1 = create(:yard, zipcode: '19125')
yard_2 = create(:yard, zipcode: '19125')
yard_3 = create(:yard, zipcode: '19125')
yard_4 = create(:yard, zipcode: '54678')
yard_5 = create(:yard, zipcode: '11122')
pet_yard = create(:purpose, name: "Pet Yard")
party_yard = create(:purpose, name: "Party Yard")
hobby_yard = create(:purpose, name: "Hobby Yard")
yard_1.purposes << pet_yard
yard_3.purposes << pet_yard
yard_5.purposes << pet_yard
yard_1.purposes << hobby_yard
yard_3.purposes << hobby_yard
yard_5.purposes << hobby_yard
yard_4.purposes << hobby_yard
yard_2.purposes << party_yard
yard_4.purposes << party_yard
get "/api/v1/yards/yard_search?location=19125&purposes[]=pet+yard&purposes[]=hobby+yard"
expect(response).to be_successful
yards = JSON.parse(response.body, symbolize_names:true)
expect(yards).to be_a(Hash)
expect(yards[:data]).to be_an(Array)
expect(yards[:data].first).to be_a(Hash)
expect(yards[:data].first[:id]).to eq(yard_1.id.to_s)
expect(yards[:data].last[:id]).to eq(yard_3.id.to_s)
yard_ids = yards[:data].map {|yard| yard[:id].to_i}
expect(yard_ids.include?(yard_2.id)).to eq(false)
expect(yard_ids.include?(yard_4.id)).to eq(false)
expect(yard_ids.include?(yard_5.id)).to eq(false)
end
end
describe "Sad Path" do
it "returns an empty array when no zipcode matches the criteria" do
get "/api/v1/yards/yard_search?location=13456"
expect(response).to be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(json).to be_a(Hash)
expect(json[:data]).to be_an(Array)
expect(json[:data].empty?).to eq(true)
end
it "returns an empty array when no zipcode and no purposes match the criteria" do
get "/api/v1/yards/yard_search?location=13456&purposes=pet+rental&hobby+rental"
expect(response).to be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(json).to be_a(Hash)
expect(json[:data]).to be_an(Array)
expect(json[:data].empty?).to eq(true)
end
it "returns an empty array with no zipcode matches but has matching purposes" do
yard_1 = create(:yard, zipcode: '19125')
yard_2 = create(:yard, zipcode: '19125')
yard_3 = create(:yard, zipcode: '19125')
pet_yard = create(:purpose, name: "Pet Yard")
hobby_yard = create(:purpose, name: "Hobby Yard")
yard_1.purposes << pet_yard
yard_3.purposes << pet_yard
yard_3.purposes << hobby_yard
get "/api/v1/yards/yard_search?location=12345&purposes[]=pet+yard&purposes[]=hobby+yard"
expect(response).to be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(json).to be_a(Hash)
expect(json[:data]).to be_an(Array)
expect(json[:data].empty?).to eq(true)
end
end
describe 'Edge Cases' do
it "returns an error when no query parameters are sent" do
get "/api/v1/yards/yard_search"
expect(response).to_not be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(response).to have_http_status(:bad_request)
expect(json[:error]).to be_a(String)
expect(json[:error]).to eq("Please enter a zipcode to search available yards")
end
it "returns an error when the location parameter is not sent" do
yard_1 = create(:yard, zipcode: '19125')
pet_yard = create(:purpose, name: "Pet Yard")
hobby_yard = create(:purpose, name: "Hobby Yard")
yard_1.purposes << pet_yard
yard_1.purposes << hobby_yard
get "/api/v1/yards/yard_search?purposes[]=pet+yard&purposes[]=hobby+yard"
expect(response).to_not be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(response).to have_http_status(:bad_request)
expect(json[:error]).to be_a(String)
expect(json[:error]).to eq("Please enter a zipcode to search available yards")
end
it "returns an error when the zipcode contains alpha characters" do
get "/api/v1/yards/yard_search?location=134A6"
expect(response).to_not be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(response).to have_http_status(:bad_request)
expect(json[:error]).to be_a(String)
expect(json[:error]).to eq("Invalid zipcode")
end
it "returns an error when the zipcode is not 5 numeric characters" do
get "/api/v1/yards/yard_search?location=1346"
expect(response).to_not be_successful
json = JSON.parse(response.body, symbolize_names:true)
expect(response).to have_http_status(:bad_request)
expect(json[:error]).to be_a(String)
expect(json[:error]).to eq("Invalid zipcode")
end
end
end
| true |
583727f3065f6167f35af0112162b787601bc408
|
Ruby
|
JoshCheek/project-euler
|
/079.rb
|
UTF-8
| 275 | 3.484375 | 3 |
[] |
no_license
|
# https://projecteuler.net/problem=65
E = [2]
1.upto(100) { |k| E << 1 << 2*k << 1 }
def e(n)
return E[0].to_r if n < 1
E[0] + 1r/e2(1, n)
end
def e2(crnt, stop)
return E[crnt] if crnt == stop
E[crnt] + 1r/e2(crnt+1, stop)
end
e(99).numerator.digits.sum # => 272
| true |
ad1087b98568d525f075ce32c20d3402c9aa7a3c
|
Ruby
|
Stearnzy/final_ic_2008
|
/lib/pantry.rb
|
UTF-8
| 575 | 3.53125 | 4 |
[] |
no_license
|
class Pantry
attr_reader :stock
def initialize
@stock = Hash.new(0)
end
def stock_check(ingredient)
@stock[ingredient]
end
def restock(ingredient, quantity)
@stock[ingredient] += quantity
end
def enough_ingredients_for?(recipe)
ing_list_complete =recipe.ingredients.map do |ing|
if self.stock_check(ing) < recipe.ingredients_required[ing]
false
elsif self.stock_check(ing) >= recipe.ingredients_required[ing]
true
end
end
if ing_list_complete.all?
true
else
false
end
end
end
| true |
0d1199619dbbf4e3b5fcc4622cd295d2323c13c9
|
Ruby
|
Chanson9892/oo-tic-tac-toe-ruby-intro-000
|
/lib/tic_tac_toe.rb
|
UTF-8
| 2,673 | 3.8125 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class TicTacToe
def initialize(board = nil)
@board = board || Array.new(9, " ")
end
def display_board
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end
def input_to_index(user_input)
user_input.to_i - 1
end
def move(index, player = "X")
@board[index] = player
end
def position_taken?(index)
if @board[index] == " " || @board[index] == "" || @board[index] == nil
return false
else
return true
end
end
def valid_move?(index)
def position_taken?(index)
if @board[index] == " " || @board[index] == "" || @board[index] == nil
return false
else
return true
end
end
def on_board?(index)
if index.between?(0, 8) == true
return true
else
return false
end
end
if (position_taken?(index)) == false && (on_board?(index) == true)
return true
else
return false
end
end
def turn
puts "Please enter 1-9:"
user_input = gets.strip
index = input_to_index(user_input)
if valid_move?(index)
move(index, current_player)
display_board
else
turn
end
end
def turn_count
counter = 0
@board.each do |index|
if (index == "X" || index == "O")
counter += 1
end
end
counter
end
def current_player
if turn_count % 2 == 0
return "X"
else
return "O"
end
end
WIN_COMBINATIONS = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
def won?
WIN_COMBINATIONS.each do |win_combination|
win_index_1 = win_combination[0]
win_index_2 = win_combination[1]
win_index_3 = win_combination[2]
position_1 = @board[win_index_1] # value of board at win_index_1
position_2 = @board[win_index_2] # value of board at win_index_2
position_3 = @board[win_index_3] # value of board at win_index_3
if position_1 == "X" && position_2 == "X" && position_3 == "X"
return win_combination
elsif position_1 == "O" && position_2 == "O" && position_3 == "O"
return win_combination
end
end
return false
end
def full?
@board.all? {|i| i == "X" || i == "O"}
end
def draw?
if !won? && full?
return true
else won?
return false
end
end
def over?
if draw? || won? || full?
return true
end
end
def winner
index = []
index = won?
if index == false
return nil
elsif @board[index[0]] == "X"
return "X"
else
return "O"
end
end
def play
until over?
turn
end
if won?
winner == "X" || winner == "O"
puts "Congratulations #{winner}!"
elsif draw?
puts "Cat's Game!"
end
end
end
| true |
17b20701d5097c0298d22c6c331778173af4490d
|
Ruby
|
5t111111/racc-example-hs
|
/hs.rb
|
UTF-8
| 356 | 3.015625 | 3 |
[] |
no_license
|
class HS
def initialize(receiver:, method:, args:)
@receiver = receiver
@method = method
@args = args
def @receiver.method_missing(method, args)
case method
when :elem
p args.include?(self.to_i)
else
raise NoMethodError
end
end
end
def call
@receiver.send(@method, *@args)
end
end
| true |
f97a49cdc1ce53178c20e5d8e730cc6ce3cedef9
|
Ruby
|
francoisdevlin/config-expressions
|
/config-expression
|
UTF-8
| 3,471 | 2.921875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'json'
require 'optparse'
require_relative 'ruby/lib/matchers'
require_relative 'ruby/lib/functions'
command = ARGV[0]
available_commands = ["lookup","explain"].sort
unless available_commands.include? command
print "'#{command}' is not a valid command, it must be one of:\n"
available_commands.each {|c| print "\t#{c}\n"}
exit 1
end
args = ARGV.drop(1)
config_file_path="conf.jsonw"
$no_color = false
opt_parser = OptionParser.new do |opts|
opts.banner = "Usage: config-expression #{command} [OPTIONS] PATH"
opts.separator ""
opts.separator "Specific options:"
# Mandatory argument.
opts.on("-f", "--file FILE",
"Reads json config from file, defaults to #{config_file_path}") do |conf_file|
config_file_path = conf_file
end
opts.on("--no-color", "Disables color in the output") {|v| $no_color=true}
end
class String
def black; $no_color ? self : "\e[30m#{self}\e[0m" end
def red; $no_color ? self : "\e[31m#{self}\e[0m" end
def green; $no_color ? self : "\e[32m#{self}\e[0m" end
def yellow; $no_color ? self : "\e[33m#{self}\e[0m" end
def blue; $no_color ? self : "\e[34m#{self}\e[0m" end
def magenta; $no_color ? self : "\e[35m#{self}\e[0m" end
def cyan; $no_color ? self : "\e[36m#{self}\e[0m" end
def gray; $no_color ? self : "\e[37m#{self}\e[0m" end
end
opt_parser.parse!(args)
conf_path = args[0];
path = conf_path.split('.')
config_file = File.read(config_file_path)
config = JSON.parse(config_file)
start_state = ConfExpr::PatternState.new
start_state.path = path
result = ConfExpr.recursion_2(start_state,config)
def explain(pattern, state, conf)
if state.state == :complete
return "HIT ".green + ": #{pattern} VALUE: '#{state.value}'"
elsif state.state == :collision
return "COLLIDE".red + ": #{pattern} VALUE: '#{state.value}'"
else
value = conf
state.evaluated_path.each {|p| value = value[p] unless value.nil?}
has_children = value.instance_of? Hash
message = ": #{pattern}"
message += ", ignoring children" if has_children
return "MISS ".yellow + message.gray
end
end
if command == "lookup"
=begin
h = hash_factory(config)
begin
path.each {|label| h = h[label] unless h.nil?}
puts h
rescue RuntimeError=> e
puts "Uh-oh: #{e}"
exit 1
end
=end
result = result.reject{|a,b| b.state == :missing }
if result.nil? or result.size == 0
puts "Could not find #{conf_path}"
exit 1
end
highest_expression = result[0][0]
highest_result = result[0][1]
if highest_result.state == :complete
puts highest_result.value
exit 0
end
if highest_result.state == :collision
repeats = result.select{|a,b| b.state == :collision}
print "Ambiguous match for '#{conf_path}', the following expressions have the same priority:\n"
repeats.each {|a,b| print "'#{a}'\n"}
exit 1
end
puts "Could not find #{conf_path}"
exit 1
elsif command == "explain"
i = 0
print "The following rules were evaluated in this order, the first hit is returned\n"
final_result = nil
locality = nil;
result.each do |pattern,state|
i+= 1
if (state.locality != locality)
print "Entering locality '#{state.locality.join(".")}'\n"
end
locality = state.locality
print "Rule %5d: #{explain pattern, state, config}\n" %[i]
final_result = state.value if state.state == :complete and final_result.nil?
end
if final_result.nil?
print "Could not find #{conf_path}"
else
puts final_result
end
exit 0
end
| true |
c94fe3166a1b54a081684902c4e60d859632e410
|
Ruby
|
PhilippePerret/WriterToolbox2
|
/__SITE__/unanunscript/page_cours/main.rb
|
UTF-8
| 3,560 | 2.59375 | 3 |
[] |
no_license
|
# encoding: utf-8
# Seul un auteur du programme ou un administrateur peut passer par ici
#
user.unanunscript? || user.admin? || raise('Section interdite.')
#
# Pour l'affichage d'une page de cours du programme UN AN UN SCRIPT.
# Noter que c'est presque le même module que pour la collection Narration
#
class Unan
class PageCours
attr_reader :id, :data
attr_reader :dyn_file, :md_file
# Instanciation
def initialize pid
@id = pid
get_data
def_paths
end
# Méthode principale retournant le code de la page (ou du chapitre,
# du sous-chapitre) à afficher.
#
# Si la page n'est pas à jour, il faut l'actualiser.
def full_content
uptodate? || begin
Unan.require_module('update_page_cours')
update_page_dyn
end
deserb(dyn_file)
end
def boutons_edition_if_admin
user.admin? || (return '')
c = String.new
c << '<div class="admin_edit_links">'
c << "<a href=\"admin/unanunscript/#{id}?op=edit_data\" target=\"_new\">data</a>"
if type == :page
escaped_path = CGI.escape(md_file)
c << "<a href=\"admin/edit_text?path=#{escaped_path}\" target=\"_new\">text</a>"
end
c << '</div>'
return c
end
# ---------------------------------------------------------------------
#
# MÉTHODES DE DONNÉES
#
# ---------------------------------------------------------------------
# Retourne TRUE si le fichier dynamique est à jour
def uptodate?
exist? &&
File.exist?(dyn_file) &&
code_dyna_is_a_jour
end
def code_dyna_is_a_jour
return File.stat(dyn_file).mtime > File.stat(md_file).mtime
end
def exist?
@page_existe === nil && (@page_existe = !data.nil?)
@page_existe
end
# Retourne le type de la page, i.e. :page, :chap ou :schap
# Je conserve ça de la collection Narration, mais normalement c'est inutile
# ici puisqu'il n'y a que des pages de cours dans le programme UAUS. On pourra
# supprimer cette propriété.
def type
:page
end
#--------------------------------------------------------------------------------
#
# MÉTHODES DE CONSTRUCTION DE LA PAGE
#
#--------------------------------------------------------------------------------
def base_n_table ; @base_n_table ||= [:unan, 'pages_cours'] end
private
def get_data
@data = site.db.select(:unan,'pages_cours',{id:id}).first
end
# Méthodes qui définit les différentes paths de la page courante
# C'est la nouvelle méthode, avec un path qui dépend seulement du
# dossier (ID) et de l'id de la page.
def def_paths
affixe_path = File.join(folder_pages,id.to_s)
@md_file = File.join(folder_pages,'source', "#{id}.md")
@dyn_file = File.join(folder_pages,'dyn', "#{id}.dyn.erb")
end
def folder_pages
@folder_pages ||= File.join('.','__SITE__','unanunscript','page_cours','_text_')
end
end #/Page
end #/Narration
# Retourne l'instance {Unan::PageCours} de la page de cours courante.
# Noter qu'elle doit toujours être définie et que si aucun identifiant n'est inscrit,
# alors la méthode raise de façon fatale.
# Noter que pour passer par ici l'auteur doit forcément être un auteur unanunscript ou
# un administrateur. C'est vérifié avant, en haut de ce module.
def page
@page ||= Unan::PageCours.new(site.route.objet_id || raise('Vous ne pouvez pas atteindre cette page.'))
end
| true |
26d9523aeb9412205ed293b473b15ab1289deba0
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/bob/a0e681f94b4d4f879ef99f52da9816e2.rb
|
UTF-8
| 1,787 | 3.421875 | 3 |
[] |
no_license
|
class Bob
# Public API, method under test.
def hey( input )
interaction = interaction_for( clean( input ) )
interaction.response
end
# Internal - return the interaction class for the given input
def interaction_for( input )
interactions.find{ |k| k.handles?( input ) }
end
# Internal - The list of responder classes that have a criteria
def normal_interactions
[ Question, Fine, Woah ]
end
# Internal The class that holds the default interaction
def default_interaction
Whatever
end
# Internal - all the interactions, making sure that the last interaction is
# the default
def interactions
normal_interactions << default_interaction
end
# pre processing the input for all interactions
def clean( input )
input.gsub( %r/\s+/, '' )
end
end
# Parent class of all Interactions. It defines Interaction DSL that child
# classes use to configure themselves.
#
# Each child class MUST use `matches` and `response` to define under what
# conditions it will match an input, and what it will respond with.
class Interaction
def self.matches( *m )
return @matches if m.empty?
@matches = m.first
end
def self.response( *r )
return @response if r.empty?
@response = r.first
end
def self.handles?( input )
input =~ matches
end
end
# Default Interaction
class Whatever < Interaction
matches %r/.*/
response "Whatever."
end
# Matches input that has no lower case characters
class Woah < Interaction
matches %r/\A[^a-z]+\Z/
response "Woah, chill out!"
end
# Matches empty input
class Fine < Interaction
matches %r/\A\Z/
response "Fine. Be that way."
end
# Matches input that ends in a question mark (?)
class Question < Interaction
matches %r/\?\Z/i
response "Sure."
end
| true |
cfebe37feec11111686d04ba572d38a4fbe09a6c
|
Ruby
|
sharath666/wd-june
|
/ruby/array_search.rb
|
UTF-8
| 464 | 4.03125 | 4 |
[] |
no_license
|
numbers = []
puts "enter 5 numbers"
5.times do
n = gets.to_i
numbers.push(n)
#numbers.push(gets.to_i)
end
puts "Input : #{numbers}"
puts "Enter the number to be searched"
search_number=gets.to_i
count=0
#1st approach
numbers.each do |num|
if num == search_number
count +=1
end
end
#2nd approach
count = numbers.count(search_number)
if count == 0
puts"#{search_number} not found"
else
puts "The number : #{search_number} is found #{count} times"
end
| true |
f6f2ce076023ef6f5b8a87605f3a2db066c30e37
|
Ruby
|
bethsecor/ruby-exercisms
|
/pangram/pangram.rb
|
UTF-8
| 296 | 3.28125 | 3 |
[] |
no_license
|
class Pangram
VERSION = 1
def self.is_pangram?(string)
alphabet = "abcdefghijklmnopqrstuvwxyz".chars
string_lower = string.downcase
letter_count = 0
alphabet.each do |letter|
letter_count += 1 if string_lower.include?(letter)
end
letter_count == 26
end
end
| true |
43965b05ca4ab8ff4d472e01e0d90b0cb180b1e2
|
Ruby
|
adarsh-rai/rails-adv-training
|
/app/helpers/format_helper.rb
|
UTF-8
| 352 | 2.53125 | 3 |
[] |
no_license
|
module FormatHelper
def custom_format name='Guest'
"Hello #{name}"
end
def custom_class alert_type = 'success'
return "alert alert-success" if alert_type == 'success'
return "alert alert-danger" if alert_type == 'alert'
return "alert alert-warning" if alert_type == 'warning'
return "alert alert-info" if alert_type == 'info'
end
end
| true |
b82f06b2a2ad2bcd37ce1218d74481d47455489a
|
Ruby
|
kkornafel82/blocipedia
|
/db/seeds.rb
|
UTF-8
| 1,595 | 2.78125 | 3 |
[] |
no_license
|
require 'faker'
1.times do
user = User.new(
name: "member1",
email: "[email protected]",
password: "helloworld",
role: "standard"
)
user.skip_confirmation!
user.save!
end
1.times do
user = User.new(
name: "member2",
email: "[email protected]",
password: "helloworld",
role: "standard"
)
user.skip_confirmation!
user.save!
end
1.times do
user = User.new(
name: "member3",
email: "[email protected]",
password: "helloworld",
role: "standard"
)
user.skip_confirmation!
user.save!
end
1.times do
user = User.new(
name: "member4",
email: "[email protected]",
password: "helloworld",
role: "standard"
)
user.skip_confirmation!
user.save!
end
1.times do
user = User.new(
name: "admin",
email: "[email protected]",
password: "helloworld",
role: "admin"
)
user.skip_confirmation!
user.save!
end
users = User.all
options = [true, false]
50.times do
Wiki.create!(
title: Faker::Lorem.sentence,
body: Faker::Lorem.paragraph,
user: users.sample,
private: options.sample
)
end
1.times do
item = Wiki.create!(
user: User.first,
title: "wiki 1",
body: "This is the first wiki that I have created as a test",
private: false,
created_at: rand(10.minutes .. 1.year).ago
)
end
1.times do
item = Wiki.create!(
user: User.first,
title: "wiki 2",
body: "This is the second wiki that I have created as a test",
private: false,
created_at: rand(10.minutes .. 1.year).ago
)
end
puts "Seed finished"
puts "#{Wiki.count} Wikis created"
| true |
4abcf3bc80a140a2ce36757ac596d87e34cea74d
|
Ruby
|
LilianaEverett/w04_Ruby_Project_Vet_Management
|
/models/vet.rb
|
UTF-8
| 1,609 | 3.234375 | 3 |
[] |
no_license
|
require_relative( '../db/sql_runner' )
require_relative('./patient')
class Vet
attr_reader :id
attr_accessor :first_name, :last_name
def initialize( options )
@id = options['id'].to_i if options['id']
@first_name = options['first_name']
@last_name = options['last_name']
end
def save()
sql = "INSERT INTO vets
(
first_name,
last_name
)
VALUES
(
$1, $2
)
RETURNING id"
values = [@first_name, @last_name]
results = SqlRunner.run(sql, values)
@id = results.first()['id'].to_i
end
def update()
sql = "UPDATE vets
SET
(
first_name,
last_name
) =
(
$1, $2
)
WHERE id = $3"
values = [@first_name, @last_name, @id]
SqlRunner.run(sql, values)
end
def self.all()
sql = "SELECT * FROM vets"
results = SqlRunner.run( sql )
return results.map { |vet| Vet.new( vet ) }
end
def self.delete_all()
sql = "DELETE FROM vets"
SqlRunner.run( sql )
end
def delete
sql = "DELETE FROM vets
WHERE id = $1"
values = [id]
SqlRunner.run( sql, values )
end
def self.find_by_id( id )
sql = "SELECT * FROM vets
WHERE id = $1"
values = [id]
results = SqlRunner.run( sql, values )
return self.new( results.first )
end
def format_name
return "#{@first_name.capitalize} #{@last_name.capitalize}"
end
def patients
sql = "SELECT * FROM patients WHERE vet_id = $1"
values = [@id]
patients_data = SqlRunner.run(sql, values)
patients = Patient.map_items(patients_data)
return patients
end
end
| true |
f04f3f018579b02d21ab51e14f31bb0095a2d221
|
Ruby
|
samuelwford/adventofcode
|
/2020/12/p2.rb
|
UTF-8
| 1,415 | 3.453125 | 3 |
[] |
no_license
|
#!/usr/bin/ruby -w
file = "input.txt"
input = File.readlines(ARGV[0] || File.join(File.dirname(__FILE__), file), chomp: true)
x, y, wx, wy = 0, 0, 10, 1
ds = ['east', 'south', 'west', 'north']
input.each do |i|
puts "ship at (#{x}, #{y}), waypoint at (#{wx}, #{wy}), instruction #{i}"
c, v = i[0], i[1..].to_i
case c
when 'N'
puts " - move waypoint north #{v}"
wy += v
when 'S'
puts " - move waypoint south #{v}"
wy -= v
when 'E'
puts " - move waypoint east #{v}"
wx += v
when 'W'
puts " - move waypoint west #{v}"
wx -= v
when 'F'
puts " - move ship forward #{v} * (#{wx}, #{wy})"
x += wx * v
y += wy * v
when 'L'
puts " - rotate way point counter-clockwise around ship #{v / 90} times"
case v / 90
when 1
wx, wy = -wy, wx
when 2
wx, wy = -wx, -wy
when 3
wx, wy = wy, -wx
else
puts "ERROR: unknown waypoint rotation"
break
end
when 'R'
puts " - rotate way point clockwise around ship #{v / 90} times"
case v / 90
when 1
wx, wy = wy, -wx
when 2
wx, wy = -wx, -wy
when 3
wx, wy = -wy, wx
else
puts "ERROR: unknown waypoint rotation"
break
end
else
puts "ERROR: unknown instruction #{i}"
break
end
puts " - ship now at (#{x}, #{y}), waypoint at (#{wx}, #{wy})"
#gets
end
puts "|#{x}| + |#{y}| = #{x.abs + y.abs}"
| true |
ef5ea6bccb6a79116a1b5451f5e41e92c2323454
|
Ruby
|
nwtgck/ruby_js_obj
|
/lib/js_obj.rb
|
UTF-8
| 249 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
require "js_obj/version"
class Hash
def method_missing name, value=nil
if name.match(/=$/)
self[name[0..-2].intern] = value
elsif !name.nil?
key?(name) ? self[name] : key?(name.to_s) ? self[name.to_s] : nil
else
super
end
end
end
| true |
444c008eee51ce2d27c9088010ba7fb9a034574b
|
Ruby
|
xxheronxx/conference-root
|
/app/models/admin.rb
|
UTF-8
| 1,375 | 2.546875 | 3 |
[] |
no_license
|
require 'digest/sha2'
class Admin < ActiveRecord::Base
attr_reader :password
ENCRYPT = Digest::SHA256
has_many :sessions, :dependent => :destroy
validates_uniqueness_of :name, :message => "is already in use by another admin"
validates_format_of :name, :with => /^([a-z0-9_]{2,16})$/i,
:message => "must be 4 to 16 letters, numbers or underscores and have no spaces"
validates_format_of :password, :with => /^([\x20-\x7E]){4,16}$/,
:message => "must be 4 to 16 characters",
:unless => :password_is_not_being_updated?
validates_confirmation_of :password
before_save :scrub_name
after_save :flush_passwords
def self.find_by_name_and_password(name, password)
admin = self.find_by_name(name)
if admin and admin.encrypted_password == ENCRYPT.hexdigest(password + admin.salt)
return admin
end
end
def password=(password)
@password = password
unless password_is_not_being_updated?
self.salt = [Array.new(9){rand(256).chr}.join].pack('m').chomp
self.encrypted_password = ENCRYPT.hexdigest(password + self.salt)
end
end
private
def scrub_name
self.name.downcase!
end
def flush_passwords
@password = @password_confirmation = nil
end
def password_is_not_being_updated?
self.id and self.password.blank?
end
end
| true |
065123272d85b8f5f0a726b8424305555bdddbb7
|
Ruby
|
SamanAtashi/Enumerables_Ruby_Project
|
/enumerables.rb
|
UTF-8
| 4,569 | 2.953125 | 3 |
[] |
no_license
|
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/ModuleLength
# rubocop:disable Metrics/BlockNesting
# rubocop:disable Lint/DuplicateBranch
# rubocop:disable Lint/ToEnumArguments
module Enumerable
def my_each
return enum_for(:my_each) unless block_given?
i = 0
new_arr = *self
while i < new_arr.length
if new_arr.instance_of?(Array)
yield new_arr[i]
elsif new_arr.instance_of?(Hash)
yield(new_arr.keys[i], new_arr.values[i])
end
i += 1
end
self if instance_of?(Array) || instance_of?(Range)
end
def my_each_with_index
return enum_for(:my_each_with_index) unless block_given?
i = 0
my_each do |item|
yield(item, i)
i += 1
end
end
def my_select
return enum_for(:my_select) unless block_given?
new_self = *self
new_arr = []
new_hash = {}
if instance_of?(Hash)
j = 0
while j < length
new_hash[keys[j]] = values[j] if yield(keys[j], values[j])
j += 1
end
new_hash
elsif new_self.instance_of?(Array)
i = 0
while i < new_self.length
new_arr << new_self[i] if yield new_self[i]
i += 1
end
new_arr
end
end
def my_all?(sth = nil)
new_self = *self
return true if new_self.empty?
if block_given?
new_self.my_each do |item|
return false unless yield item
end
else
new_self.my_each do |item|
if sth.instance_of?(Regexp)
return false if item.match?(sth) == false
elsif sth.is_a? Class
return false unless item.is_a? sth
elsif [nil, false].include?(sth)
if length == 1
return true if sth == item
elsif [false, nil].include?(item)
return false
end
else
return false unless item == sth
end
end
end
true
end
def my_any?(sth = nil)
new_self = *self
return false if new_self.empty?
if block_given?
new_self.my_each do |item|
return true if yield item
end
else
new_self.my_each do |item|
if sth.instance_of?(Regexp)
return true if item.match?(sth)
elsif sth.is_a? Class
return true if item.is_a? sth
elsif sth.nil?
to_a.my_each { |i| return true if i }
elsif [true].include?(new_self)
return true
elsif sth == item
return true
end
end
end
false
end
def my_none?(sth = nil)
new_self = *self
return true if new_self.empty?
if block_given?
new_self.my_each do |item|
return false if yield item
end
else
new_self.my_each do |item|
if sth.instance_of?(Regexp)
return false if item.match?(sth)
elsif sth.is_a? Class
return false if item.is_a? sth
elsif [[nil], [false], [nil, false], [false, nil]].include?(new_self)
return true
else
return false if sth == item
return false if sth.nil? && item
return true
end
end
end
true
end
def my_count(arg = nil)
i = 0
if arg
my_each do |item|
i += 1 if item == arg
end
elsif block_given?
my_each do |item|
i += 1 if yield item
end
else
i = to_a.length
end
i
end
def my_map(proc = nil)
return to_enum(:my_map) unless block_given? || !proc.nil?
new_arr = []
if proc
to_a.my_each do |item|
new_arr.push(proc.call(item))
end
else
to_a.my_each do |item|
new_arr.push(yield item)
end
end
new_arr
end
def my_inject(accum = nil, current = nil)
if (!accum.nil? && current.nil?) && (accum.is_a?(Symbol) || accum.is_a?(String))
current = accum
accum = nil
end
if !block_given? && !current.nil?
to_a.my_each do |item|
accum = accum.nil? ? item : accum.send(current, item)
end
else
to_a.my_each do |item|
accum = accum.nil? ? item : yield(accum, item)
end
end
accum
end
end
def multiply_els(sth)
sth.my_inject(:*)
end
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/ModuleLength
# rubocop:enable Metrics/BlockNesting
# rubocop:enable Lint/DuplicateBranch
# rubocop:enable Lint/ToEnumArguments
| true |
910f222a9523db993242c85a741a723048b94f0f
|
Ruby
|
shageman/component-based-rails-applications-book
|
/docker/geminabox/gems/trueskill-e404f45af5b3/spec/saulabs/gauss/distribution_spec.rb
|
UTF-8
| 5,717 | 2.890625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# -*- encoding : utf-8 -*-
require File.expand_path('spec/spec_helper.rb')
describe Gauss::Distribution, "#initialize" do
it "should set the mean to 10.1" do
Gauss::Distribution.new(10.1, 0.4).mean.should == 10.1
end
it "should set the deviation to 0.4" do
Gauss::Distribution.new(10.1, 0.4).deviation.should == 0.4
end
it "should set the mean to 0.0 if the given mean is not finite" do
Gauss::Distribution.new(1 / 0.0, 0.4).mean.should == 0.0
end
it "should set the deviation to 0.0 if the given deviation is not finite" do
Gauss::Distribution.new(10.1, 1 / 0.0).deviation.should == 0.0
end
end
describe Gauss::Distribution, "#with_deviation" do
before :each do
@dist = Gauss::Distribution.with_deviation(25.0, 8.333333)
end
it "should have a default mean value of 25.0" do
@dist.mean.should == 25.0
end
it "should have a default deviation of 8.333333" do
@dist.deviation.should be_within(0.000001).of(8.333333)
end
it "should set the variance to 69.444438" do
@dist.variance.should be_within(0.0001).of(69.4444)
end
it "should set the precision to 0.0144" do
@dist.precision.should be_within(0.0001).of(0.0144)
end
it "should set the precision_mean to 0.36" do
@dist.precision_mean.should be_within(0.0001).of(0.36)
end
end
describe Gauss::Distribution, "#with_precision" do
before :each do
@dist = Gauss::Distribution.with_precision(0.36, 0.0144)
end
it "should have a default mean value of 25.0" do
@dist.mean.should == 25.0
end
it "should have a default deviation of 8.333333" do
@dist.deviation.should be_within(0.000001).of(8.333333)
end
it "should set the variance to 69.444438" do
@dist.variance.should be_within(0.0001).of(69.4444)
end
it "should set the precision to 0.0144" do
@dist.precision.should be_within(0.0001).of(0.0144)
end
it "should set the precision_mean to 0.36" do
@dist.precision_mean.should be_within(0.0001).of(0.36)
end
it "sets the precision to 0.0 if it is negative and does not throw an exception" do
expect {
Gauss::Distribution.with_precision(0.36, -0.0144)
}.to_not raise_error
end
end
describe Gauss::Distribution, "absolute difference (-)" do
before :each do
@dist = Gauss::Distribution.with_deviation(25.0, 8.333333)
end
it "should be 0.0 for the same distribution" do
(@dist - @dist).should == 0.0
end
it "should equal the precision mean if the 0-distribution is subtracted" do
(@dist - Gauss::Distribution.new).should == @dist.precision_mean
end
it "should be 130.399408 for (22, 0.4) - (12, 1.3)" do
(Gauss::Distribution.new(22, 0.4) - Gauss::Distribution.new(12, 1.3)).should be_within(tolerance).of(130.399408)
end
end
describe Gauss::Distribution, "#value_at" do
it "should have a value of 0.073654 for x = 2" do
Gauss::Distribution.new(4,5).value_at(2).should be_within(tolerance).of(0.073654)
end
end
describe Gauss::Distribution, "multiplication (*)" do
it "should have a mean of 0.2" do
(Gauss::Distribution.new(0,1) * Gauss::Distribution.new(2,3)).mean.should be_within(0.00001).of(0.2)
end
it "should have a deviation of 3.0 / Math.sqrt(10)" do
(Gauss::Distribution.new(0,1) * Gauss::Distribution.new(2,3)).deviation.should be_within(0.00001).of(3.0 / Math.sqrt(10))
end
end
describe Gauss::Distribution, "#log_product_normalization" do
it "should have calculate -3.0979981" do
lp = Gauss::Distribution.log_product_normalization(Gauss::Distribution.new(4,5), Gauss::Distribution.new(6,7))
lp.should be_within(0.000001).of(-3.0979981)
end
end
describe Gauss::Distribution, "functions" do
describe 'value = 0.27' do
it "#cumulative_distribution_function should return 0.6064198 for 0.27" do
Gauss::Distribution.cumulative_distribution_function(0.27).should be_within(0.00001).of(0.6064198)
Gauss::Distribution.cdf(2.0).should be_within(0.00001).of(0.9772498)
end
it "#probability_density_function should return 0.384662" do
Gauss::Distribution.probability_density_function(0.27).should be_within(0.0001).of(0.384662)
end
it "#quantile_function should return ~ -0.6128123 at 0.27" do
Gauss::Distribution.quantile_function(0.27).should be_within(0.00001).of(-0.6128123)
end
it "#quantile_function should return ~ 1.281551 at 0.9" do
Gauss::Distribution.quantile_function(0.9).should be_within(0.00001).of(1.281551)
end
it "#erf_inv should return 0.0888559 at 0.9" do
Gauss::Distribution.inv_erf(0.9).should be_within(0.00001).of(0.0888559)
end
it "#erf_inv should return 0.779983 at 0.27" do
Gauss::Distribution.inv_erf(0.27).should be_within(0.00001).of(0.779983)
end
it "#erf_inv should return 100 at -0.5" do
Gauss::Distribution.inv_erf(-0.5).should be_within(0.00001).of(100)
end
it "#erf should return 0.203091 at 0.9" do
Gauss::Distribution.erf(0.9).should be_within(0.00001).of(0.203091)
end
it "#erf should return 0.702581 at 0.27" do
Gauss::Distribution.erf(0.27).should be_within(0.00001).of(0.702581)
end
it "#erf should return 1.520499 at -0.5" do
Gauss::Distribution.erf(-0.5).should be_within(0.00001).of(1.520499)
end
end
end
describe Gauss::Distribution, "#replace" do
before :each do
@dist1 = Gauss::Distribution.with_deviation(25.0, 8.333333)
@dist2 = Gauss::Distribution.with_deviation(9.0, 4)
end
it "should be equal to the replaced distribution" do
@dist1.replace(@dist2)
@dist1.should == @dist2
end
end
| true |
6e68d405fc596e3dcc448ab626500c9cd108dd32
|
Ruby
|
haider-sheikh/assignment
|
/calender.rb
|
UTF-8
| 6,793 | 3.828125 | 4 |
[] |
no_license
|
require_relative 'event'
class Calender
attr_reader :hash
def initialize
@hash = {}
end
def display_portal
loop do
puts "\n\t\t****Welcome to Calendar****"
puts "\t\t 1. Add New Event"
puts "\t\t 2. Remove Event"
puts "\t\t 3. Edit Event"
puts "\t\t 4. Print Month View"
puts "\t\t 5. Events on speicific date"
puts "\t\t 6. View All Events of a month"
puts "\t\t 7. Exit\n\n"
print "\t\t Enter Choice : "
@choice = gets.chomp
break if @choice.eql? '7'
print "\n\t\t Wrong Input \n" unless (1..7).include? @choice.to_i
evaluate
end
end
def take_input
print "\t\t Enter Month(1..12) : "
month = gets.to_i
print "\t\t Enter Day(1..31) : "
day = gets.to_i
print "\t\t Enter Year : "
year = gets.to_i
[year, month, day]
end
def edit_event input
begin
date = Date.new(input[0], input[1], input[2])
date = date.to_s.to_sym
if @hash.key? date
print "\t\t\t\t Events on #{date}\n"
puts "\t\tIndex \t\t Event Name \t Event Desc"
@hash[date].each_with_index do |event, idx|
print "\t\t#{idx + 1}\t\t"
event.show
end
print "\n\t\tEnter index to edit : "
input = gets.chomp.to_i
if input.positive? && @hash[date].include?(@hash[date][input - 1])
event = @hash[date][input - 1]
puts "\t\t Old event name : #{event.name}"
puts "\t\t Old event desc : #{event.desc}\n"
print "\t\t Enter New event name : "
name_of_event = gets.chomp
print "\t\t Enter New event desc : "
desc_of_event = gets.chomp
event.name = name_of_event
event.desc = desc_of_event
puts "\n\t\t Event Updated Successfully......\n"
else
puts "\n\t\tInvalid index\n"
end
else
puts "\n\t\tNo Event for this date......\n"
end
rescue Date::Error
puts "\t\tInvalid Date"
end
end
def remove_event input
begin
date = Date.new(input[0], input[1], input[2])
date = date.to_s.to_sym
if @hash.key? date
print "\t\t\t\t Events on #{date}\n"
puts "\t\tIndex \t\t Event Name \t Event Desc"
@hash[date].each_with_index do |event, idx|
print "\t\t#{idx + 1}\t\t"
event.show
end
print "\n\t\tEnter index to remove : "
input = gets.chomp.to_i
if input.positive? && @hash[date].include?(@hash[date][input - 1])
@hash[date].delete_at(input - 1)
puts "\n\t\tEvent Deleted Successfully......\n"
@hash.delete(date) if @hash[date].empty?
else
puts "\n\t\tInvalid index\n"
end
else
puts "\n\t\tNo Event for this date......\n"
end
rescue Date::Error
puts "\t\tInvalid Date"
"\t\tInvalid Date" # returning value for unit test cases
end
end
def add_new_event input
begin
date = Date.new(input[0], input[1], input[2])
date = date.to_s.to_sym
@hash[date] = [] unless @hash.key? date
name_of_event = input[3]
desc_of_event = input[4]
event = Event.new(name_of_event, desc_of_event)
@hash[date] << event
puts "\n\n\t\tEvent Added Successfully\n\n"
"\n\n\t\tEvent Added Successfully\n\n"
rescue Date::Error
puts "\t\tInvalid Date"
"\t\tInvalid Date"
end
end
def view_specific_event input
begin
date = Date.new(input[0], input[1], input[2])
date = date.to_s.to_sym
if @hash.key? date
puts "\t\tDate \t\t Event Name \t Event Desc"
print "\t\t #{date}\n"
@hash[date].each do |event|
print "\t\t\t\t"
event.show
end
else
puts "\n\t\tNo Event for this date......\n"
"\n\t\tNo Event for this date......\n"# returning value for unit test cases
end
rescue Date::Error
puts "\t\tInvalid Date"
"\t\tInvalid Date" # returning value for unit test cases
end
end
def get_day(date)
day = date.wday
day += 7 if day.zero?
day
end
def print_month_view
print "\t\t Enter Month(1..12) : "
month = gets.to_i
print "\t\t Enter Year : "
year = gets.to_i
unless (1..12).include?(month)
puts "\n\t\tInvalid Date"
return
end
all_month_dates = []
(1..31).each do |x|
begin
date = Date.new(year.to_i, month.to_i, x)
rescue Date::Error
date = nil
end
all_month_dates << date.to_s.to_sym unless date.to_s.eql? ''
end
count = get_day(Date.new(year, month, 1))
count -= 1
puts "\n\t\t\t Month View"
puts "M\tT\tW\tT\tF\tS\tS"
(0...count).each do
print "\t"
end
(1...32).each do |x|
begin
Date.new(year, month, x)
rescue Date::Error
next
end
if count == 7
print "\n"
count = 0
end
if @hash.key? all_month_dates[x - 1]
print "#{x}(#{@hash[all_month_dates[x - 1]].count}) "
else
print "#{x}\t"
end
count += 1
end
end
def view_specific_month_event
print "\t\t Enter Month(1..12) : "
month = gets.to_i
print "\t\t Enter Year : "
year = gets.to_i
unless (1..12).include?(month)
puts "\t\tInvalid Date"
return
end
all_month_dates = []
(1..31).each do |x|
begin
date = Date.new(year.to_i, month.to_i, x)
rescue Date::Error
date = nil
end
all_month_dates << date.to_s.to_sym unless date.to_s.eql? ''
end
puts "\t\tDate \t\t Event Name \t Event Desc"
all_month_dates.each do |month_date|
if @hash.key? month_date
print "\t\t #{month_date}\n"
@hash[month_date].each do |event|
print "\t\t\t\t"
event.show
end
end
end
end
def evaluate
case @choice.to_i
when 1
puts "\n\t\t****Add New Event****"
input = take_input
print "\t\t Enter event name : "
name_of_event = gets.chomp
print "\t\t Enter event desc : "
desc_of_event = gets.chomp
input << name_of_event << desc_of_event
add_new_event input
when 2
puts "\n\t\t****Remove Event****"
remove_event take_input
when 3
puts "\n\t\t****Edit Event****"
edit_event take_input
when 4
puts "\n\t\t****Specific Month Events (Month View Style) ****"
print_month_view
when 5
puts "\n\t\t****Specific Event****"
view_specific_event take_input
when 6
puts "\n\t\t****Specific Month Events****"
view_specific_month_event
end
end
end
| true |
9b966ae936c7be9e98f3e1afbeb6861d2319cc0d
|
Ruby
|
rcuhljr/rosalind
|
/rosalind_distance_matrix.rb
|
UTF-8
| 656 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
load 'fasta.rb'
load 'dna.rb'
fasta = FASTA.new()
fasrecs = fasta.load_file "dist_matrix.fas"
def p_distance(start, target)
DNA.new(start).hamming_distance(target).to_f/target.size
end
File.open('results.txt', "w") do |output|
samples = fasrecs.values
sample_size = samples.size
half_matrix = {}
samples.each_with_index do |sample, outer_i|
samples[outer_i..-1].each_with_index do |target, inner_i|
half_matrix[[inner_i+outer_i,outer_i].sort] = p_distance(sample, target)
end
end
(0..sample_size-1).each{|row| (0..sample_size-1).each{|column| output.print "%.5f " % half_matrix[[row,column].sort] }; output.puts }
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.