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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
07a316d63e778c9d78a128e4395b53dbdcc0972f | Ruby | Caldary/W02-D05-homework | /guests.rb | UTF-8 | 292 | 3.390625 | 3 | [] | no_license | class Guests
attr_reader(:name, :age, :wallet)
attr_writer(:wallet)
def initialize(name, age, wallet)
@name = name
@age = age
@wallet = wallet
end
def spend_money(money)
if @wallet >= 0
@wallet -= money
end
end
end | true |
2ebe8f429da42d087fca44c014d32f5f2662cf78 | Ruby | chadjemmett/Exercise-programs | /leap_year2.rb | UTF-8 | 609 | 4.0625 | 4 | [] | no_license | #completed Jan 14, 2012
#leap year program
#get the start year and end year. Convert to integer
puts "please type in the starting year"
start_year = gets.chomp.to_i
puts "please type in the end year."
end_year = gets.chomp.to_i
#this is just for clarity and show.
puts "*************************"
puts "Here are the leap years for the range you typed in."
#the meat of the program.
while
start_year <= end_year
if start_year%4 == 0 && start_year%100 != 0
puts start_year
end
if start_year%100 == 0 && start_year%400 == 0
puts start_year
end
start_year = start_year + 1
end
| true |
7965187840c0d01f7c154620249f040743c6df7d | Ruby | raghubetina/app_scaffold | /modeler/rails_model.rb | UTF-8 | 1,118 | 2.546875 | 3 | [] | no_license | require 'active_support/inflector'
require_relative 'rails_column'
class RailsModel
attr_reader :name
attr_reader :has_many
attr_reader :columns
def add_has_many(model)
@has_many << model.name.underscore.pluralize.to_sym
end
def belongs_to
@belongs_to ||= @foreign_keys.map { |fk| fk.to_s.sub(/_id$/,'').to_sym }.sort
end
def class_path(app_root)
@class_path ||= File.join(app_root, "app", "models", "#{name.underscore}.rb")
end
def index_path(app_root)
@index_path ||= File.join(app_root, "app", "views", name.pluralize.underscore, "index.html.erb")
end
def show_path(app_root)
@show_path ||= File.join(app_root, "app", "views", name.pluralize.underscore, "show.html.erb")
end
def form_path(app_root)
@show_path ||= File.join(app_root, "app", "views", name.pluralize.underscore, "_form.html.erb")
end
def initialize(name, columns)
@name = name.strip.classify
@columns = columns.compact.map { |c| RailsColumn.new(c) }
@foreign_keys = @columns.select { |c| c.foreign_key? }.map { |c| c.name }.sort
@has_many = []
end
end
| true |
44ec399cdf629a3eeceba8e6141cad667e82a9e7 | Ruby | bigorbach/noble-houses-of-westeros | /app/models/house.rb | UTF-8 | 1,551 | 2.890625 | 3 | [] | no_license | class House
attr_reader :url, :name, :region, :coat_of_arms, :words, :titles, :seats, :current_lord, :heir, :overlord,
:founded, :founder, :died_out, :ancestral_weapons, :cadet_branches, :sworn_members
def initalize
@url = url
@name = name
@region = region
@coat_of_arms = coat_of_arms
@words = words
@titles = titles
@seats = seats
@current_lord = current_lord
@heir = heir
@overlord = overlord
@founded = founded
@founder = founder
@died_out = died_out
@ancestral_weapons = ancestral_weapons
@cadet_branches = cadet_branches
@sworn_members = sworn_members
end
def url
get_house_data["url"]
end
def name
get_house_data["name"]
end
def region
get_house_data["region"]
end
def coat_of_arms
get_house_data["coatOfArms"]
end
def words
get_house_data["words"]
end
def titles
get_house_data["titles"]
end
def seats
get_house_data["seats"]
end
def current_lord
get_house_data["currentLord"]
end
def heir
get_house_data["heir"]
end
def overlord
get_house_data["overlord"]
end
def founded
get_house_data["founded"]
end
def founder
get_house_data["founder"]
end
def died_out
get_house_data["diedOut"]
end
def ancestral_weapons
get_house_data["ancestralWeapons"]
end
def cadet_branches
get_house_data["cadetBranches"]
end
def founder
get_house_data["swornMembers"]
end
def get_house_data
@house_data ||= HouseCall.new.fetch_data
end
end
| true |
0624df37f4dea6fb18c4355e48a2b890449d04ad | Ruby | rubydoobydoo/meetings | /homeworks/ben/sinatra-shop-1/app.rb | UTF-8 | 2,918 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | require 'sinatra'
require_relative './gemfile.rb'
require_relative './db/create_db.rb'
require_relative './db/config.rb'
require_relative './models/product.rb'
require_relative './models/cart.rb'
#require_relative "./models/crawl.rb"
require_relative "./models/email_provider.rb"
require_relative "./models/mail_account.rb"
require_relative './helpers/product_initializers.rb'
require_relative './api/api.rb'
# def render_correct_template(string, params)
# format = "normal" if params["format"].nil?
# case format
# when "plain" then return string
# when "normal" then return erb string
# else return "Error occured: Invalid format!"
# end
# end
configure do
enable :sessions
end
helpers do
def username
session[:identity] ? session[:identity] : 'Hello stranger'
end
end
get '/sessiontest' do
session["value"] ||= "Hello world!"
"The cookie you've created contains the value: #{session["value"]}. The entire cookie is #{session}"
end
get '/stream' do
stream do |out|
out << "It's gonna be legen -\n"
sleep 0.5
out << " (wait for it) \n"
sleep 1
out << "- dary!\n"
end
end
before '/secure/*' do
if !session[:identity] then
session[:previous_url] = request.path
@error = 'Sorry guacamole, you need to be logged in to visit ' + request.path
halt erb(:login_form)
end
end
get '/hi/:name' do
erb("<h1>Hello #{params[:name]}</h1>", params)
end
get '/' do
erb :index
end
# get '/posts/:id' do
# params[:id]
# end
get '/products' do
products = Product.show_products
erb "#{products}"
end
post '/products/buy' do
cart = Cart.carts.first
cart.params[:name]
end
get '/product_search' do
erb :product_search
end
post '/product_search/search' do
products = Product.find_product_by_name(params[:product_name])
if products != ""
erb "#{products}"
else
erb "I couldn't find #{params[product_name]}"
end
end
get '/products/delete/:id' do
erb Product.delete(params[:id])
end
get '/cart' do
cart = Cart.carts.first
erb cart.show_bill
end
get '/login/form' do
erb :login_form
end
post '/login/attempt' do
session[:identity] = params['username']
where_user_came_from = session[:previous_url] || '/'
redirect to where_user_came_from
end
get '/contact/form' do
erb :contact_form
end
post '/contact/send_data' do
erb "Thank you, <b>#{params['prename']} #{params['last_name']}</b>. Your email <b>#{params['email']}</b> has been recorded."
end
get '/admin/new_product' do
erb :new_product_form
end
post '/admin/new_product_create' do
item = Product.new(params['product_name'], params['price'].to_f, params['discount'].to_f)
erb "Thanks for creating #{item.name}."
end
get '/logout' do
session.delete(:identity)
erb "<div class='alert alert-message'>Logged out</div>"
end
get '/secure/place' do
erb "This is a secret place that only <%=session[:identity]%> has access to!"
end
| true |
3bf43a864ca470270fed66fafd1a3122b86a5def | Ruby | avdgaag/redmine-api | /lib/redmine/accept_json.rb | UTF-8 | 1,386 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'json'
require 'delegate'
module Redmine
# A decorator object for RestClient that provides immediate JSON-parsing
# capabilities. Rather than dealing with raw response objects, this decorator
# helps us get at parsed JSON data immediately.
#
# This decorator works by intercepting outgoing requests and adding an
# +Accept+ header to indicate we would like to receive JSON data
# back. Responses will then be parsed, given they actually are JSON, and both
# the parsed response body and the original response are returned.
class AcceptJson < SimpleDelegator
# Value of the outgoing +Accept+ header.
ACCEPT = 'application/json'.freeze
# Matcher for recognizing response content types.
CONTENT_TYPE = %r{application/json}
# Wrap requests to add an `Accept` header to ask for JSON, and parse
# response bodies as JSON data.
def get(path, headers = {})
response = super(path, { 'Accept' => ACCEPT }.merge(headers.to_h))
case response.content_type
when CONTENT_TYPE then [parse_response(response), response]
else raise "Unknown content type #{response.content_type.inspect}"
end
end
private
def parse_response(response)
JSON.parse(response.body)
rescue JSON::ParserError => e
# TODO: log output here
p response
p response.to_hash
raise e
end
end
end
| true |
f2cf6f1056632c866f2c15b8aa7db08aa225c2dc | Ruby | blackhatethicalhacking/whitewidow | /lib/modules/core/tools/site_info.rb | UTF-8 | 1,318 | 2.859375 | 3 | [] | no_license | require_relative '../../../../lib/imports/constants_and_requires'
#
# Pull the information of the site that is available. Pulls the server (apache, redhat, etc) and the IP address
# that the site resolves to
#
module SiteInfo
#
# Get the IP address that the site resolves to using Socket
#
def self.capture_ip(site, regex)
uri = URI.parse(site)
true_url = uri.hostname
ip = IPSocket::getaddress(true_url)
if !(ip =~ /#{regex}/) # IPv6 regex
return ip.to_s.cyan
else
if ip.ipv4_mapped
return ip.native.to_s.cyan
else
return ip.to_s.cyan
end
end
end
#
# Get the site host name using Net::HTTP
#
def self.capture_host(site)
uri = URI.parse(site)
res = Net::HTTP.get_response(uri)
return res['server'] # Pull it from the hash that is created
end
#
# Get the database type from the error thrown, if it exists
#
def self.capture_db_type(site)
data = SQL_ERROR[site]
db_types = ["MySQL", "Microsoft Access", "Microsoft SQL Server",
"Oracle", "DB2", "Firebird", "PostgreSQL"] # Most commonly used DB types for web apps
db_types.each { |db|
if data.include?(db.downcase)
return db.cyan
else
return 'Unable to resolve database type'.red
end
}
end
end | true |
477767748439f1ea68cb02443dfaed1b139a91be | Ruby | kachel/anagram-detector-v-000 | /lib/anagram.rb | UTF-8 | 352 | 3.78125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Your code goes here!
require "pry"
class Anagram
attr_accessor :word
def match(word_arr)
word_arr.find_all { |m| alphabetizer(m) === alphabetizer(@word) }
# word_arr.find_all { |w| w.tr(@word, "") == "" }
end
def initialize(word)
@word = word
end
private
def alphabetizer(string)
string.chars.sort.join
end
end
| true |
eae0a6d4ee58c8821390e0e941d62b07087a527d | Ruby | Bytom-Community/Bytom-Ruby-SDK | /lib/bytom/api/keys.rb | UTF-8 | 3,239 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | module Bytom
class Keys
attr_reader :client
private :client
def initialize(client)
@client = client
end
##
# It is to create private key essentially, returns the information of key. The private key is encrypted in the file and not visible to the user.
#
# @param [string] alias_name the filed alias is a keyword in ruby. so use alias_name to map.
# @param [string] password
# @param [string] language
# @param [string] mnemonic Optional
#
# @return [Hash]
#
def create_key(alias_name:, password:, language: 'en', mnemonic: nil)
params = {
alias: alias_name,
password: password,
language: language,
mnemonic: nil
}
client.make_request('/create-key', 'post', params: params)
end
##
# Returns the list of all available keys.
#
# @return [Hash]
#
def list_keys
client.make_request('/list-keys', 'get')
end
##
# Update alias for the existed key.
#
# @param [string] xpub
# @param [string] new_alias
#
# @return [nil]
#
def update_key_alias(xpub:, new_alias:)
params = {
xpub: xpub,
new_alias: new_alias
}
client.make_request('/update-key-alias', 'post', params: params)
end
##
# Delete existed key, please make sure that there is no balance in the related accounts.
#
# @param [string] xpub
# @param [string] password
#
# @return [nil]
#
def delete_key(xpub:, password:)
params = {
xpub: xpub,
password: password
}
client.make_request('/delete-key', 'post', params: params)
end
##
# Check key password.
#
# @param [string] xpub
# @param [string] password
#
# @return [Hash] check_result, result of check key password, true is check successfully, otherwise is false.
#
def check_key_password(xpub:, password:)
params = {
xpub: xpub,
password: password
}
client.make_request('/check-key-password', 'post', params: params)
end
##
# Reset key password.
#
# @param [string] xpub
# @param [string] old_password
# @param [string] new_password
#
# @return [Hash] changed, result of reset key password, true is reset successfully, otherwise is false.
#
def reset_key_password(xpub:, old_password:, new_password:)
params = {
xpub: xpub,
old_password: old_password,
new_password: new_password
}
client.make_request('/reset-key-password', 'post', params: params)
end
##
# Returns the list of all available pubkeys by account.
#
# @param [String] account_alias optional
# @param [String] account_id optional
# @param [String] public_keyoptional
#
# @return [Hash]
#
def list_pubkeys(account_alias: nil, account_id: nil, public_key: nil)
params = {}
params = {account_alias: account_alias} if account_alias
params = {account_id: account_id} if account_id
#params = {public_key: public_key} if public_key
client.make_request('/list-pubkeys', 'post', params: params)
end
end
end | true |
423d638c69d31feab179d7e5385735e2ed6c6fe6 | Ruby | kputnam/piggly | /lib/piggly/dumper/index.rb | UTF-8 | 3,282 | 2.859375 | 3 | [
"BSD-2-Clause-Views"
] | permissive | module Piggly
module Dumper
#
# The index file stores metadata about every procedure, but the source
# code is stored in a separate file for each procedure.
#
class Index
def initialize(config)
@config = config
end
# @return [String]
def path
@config.mkpath("#{@config.cache_root}/Dumper", "index.yml")
end
# Updates the index with the given list of Procedure values
# @return [void]
def update(procedures)
newest = Util::Enumerable.index_by(procedures){|x| x.identifier }
removed = index.values.reject{|p| newest.include?(p.identifier) }
removed.each{|p| p.purge_source(@config) }
added = procedures.reject{|p| index.include?(p.identifier) }
added.each{|p| p.store_source(@config) }
changed = procedures.select do |p|
if mine = index[p.identifier]
# If both are skeletons, they will have the same source because they
# are read from the same file, so don't bother checking that case
not (mine.skeleton? and p.skeleton?) and
mine.source(@config) != p.source(@config)
end
end
changed.each{|p| p.store_source(@config) }
@index = newest
store_index
end
# Returns a list of Procedure values from the index
def procedures
index.values
end
# Returns the Procedure with the given identifier
def [](identifier)
p = index[identifier]
p.dup if p
end
# Returns the shortest human-readable label that distinctly identifies
# the given procedure from the other procedures in the index
def label(procedure)
others =
procedures.reject{|p| p.oid == procedure.oid }
same =
others.all?{|p| p.name.schema == procedure.name.schema }
name =
if same
procedure.name.name
else
procedure.name.to_s
end
samenames =
others.select{|p| p.name == procedure.name }
if samenames.empty?
# Name is unique enough
name.to_s
else
sameargs =
samenames.select{|p| p.arg_types == procedure.arg_types }
if sameargs.empty?
# Name and arg types are unique enough
"#{name}(#{procedure.arg_types.join(", ")})"
else
samemodes =
sameargs.select{|p| p.arg_modes == procedure.arg_modes }
if samemodes.empty?
# Name, arg types, and arg modes are unique enough
"#{name}(#{procedure.arg_modes.zip(procedure.arg_types).map{|a,b| "#{a} #{b}" }.join(", ")})"
end
end
end
end
private
def index
@index ||= load_index
end
# Load the index from disk
def load_index
contents =
unless File.exists?(path)
[]
else
YAML.load(File.read(path))
end
Util::Enumerable.index_by(contents){|x| x.identifier }
end
# Write the index to disk
def store_index
File.open(path, "wb"){|io| YAML.dump(procedures.map{|p| p.skeleton }, io) }
end
end
end
end
| true |
b4764688d5eb2381dd96d5a7c6a770a7716814f9 | Ruby | jamiepal/battle-thursday | /lib/bookmark.rb | UTF-8 | 219 | 2.765625 | 3 | [] | no_license | class Individualbookmark
@@bookmarkarray = []
def initialize(string)
@string = string
@@bookmarkarray << @string
end
def self.all
@@bookmarkarray
end
def showstrings
return @string
end
end
| true |
fedf1d9a5575e27caa20f9d557209946eead01bb | Ruby | SarahDrake01/ruby-enumerables-reverse-each-word-lab-london-web-080519 | /reverse_each_word.rb | UTF-8 | 461 | 3.78125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(string)
string_array = string.split(" ")
return_array = []
string_array.each do|string|
return_array << string.reverse
end
return_array.join(" ")
end
def reverse_each_word(string)
array = string.split(" ") #turn string into an array
test_array = [] #empty array
array.collect do|string| #iterate over the array
test_array << string.reverse #push and reverse each word in the array
end
test_array.join(" ")
end
| true |
53e383b3f536c701e02a2399ce8869df2c9d753d | Ruby | zegan/zillow_test | /solution1.rb | UTF-8 | 4,478 | 3.875 | 4 | [] | no_license | #####################################################
# Program : Solution1
# Author : Ian
# description :
#
# 1. Question: A solution consists of four balls from a set of four
# different colors. The user tries to guess the solution. If they
# guess the right color for the right spot, record it as being in the
# correct 'Location'. If it's the right color, but the wrong spot,
# record it as a correct 'Color'. For example: if the solution is
# 'BGRR' and the user guesses 'RGYY' they have 1 'Location' and 1
# 'Color'. A correct solution would be 4 'Location' and 0 'Color'.
# Write a program to, given a solution and a guess, calculate the
# response that we present to the user.
#
# Todo : Error Checking
#####################################################
class Game
attr_reader :colors
attr_accessor :solution, :guess
def initialize
@colors = "rgby".split(//)
@solution = "rrrr".split(//)
@guess = "yyyy".split(//)
end
#randomly generate a solution and a guess
def pick
@solution.each_index {|i| @solution[i]= @colors[rand(3)] }
4.times { |i| @guess[i] = @colors[rand(3)]}
end
#todo: guard against bad input values
def solution=(value)
value = value.downcase()
@solution = value.split(//)
end
#todo: guard against bad input values
def guess=(value)
value = value.downcase()
@guess= value.split(//)
end
# todo : clean this up no need for iteration
def show(*args)
if args.size > 1
# modify this to raise exception, later
puts 'This method takes either 0 or 1 arguments'
else
if args.size == 0
print "The solution:\n"
@solution.each_index {|i| print " #{@solution[i]} "}
print "\nA guess:\n"
@guess.each_index {|i| print " #{@guess[i]} "}
elsif args.size == 1
print "\nFound #{args[0]['l']} locations and #{args[0]['c']} colors\n"
end
end
end
# caculate the difference between the solution and the guess
# todo : simplify!
def diff
@loc = 0
@color = 0
@s = []
@g = []
# count number of colors in solution and guess
# to caculate number of correct colors
# Check for location 1st - the simplest relation
# and create new arrays without location
for i in 0..3
if(@solution[i] == @guess[i])
@loc += 1
elsif
@s.push(@solution[i])
@g.push(@guess[i])
end
end
@cnt = (@s.length - 1)
for i in 0..@cnt
for j in 0..@cnt
#print "\n #{i} "
if(@g[i] == @s[j])
@s[j] = '*'
@color += 1
break
end
end
end
return {'l'=> @loc, "c"=> @color}
end
end
class TestGame
#compare result vs expected pluss test msg
def assertEquals(results, expected, msg)
puts "\nTesting: #{msg}, #{results}, #{expected}\n"
if(results['l'] != expected['l'] || results['c'] != expected['c'])
puts "Expected #{expected} not #{results}\n"
return false
end
return true
end
end
play = Game.new
test = TestGame.new
play.pick
play.show
play.show(play.diff)
########## Tests ###########
puts "\n\n**** START TESTS ****\n\n"
# Test 1
# Expected 1 location and 2 colors
play.solution = "rgbr"
play.guess = "grbb"
play.show()
results1 = play.diff()
expected1 = {'l'=>1, 'c'=>2}
play.show(results1)
puts test.assertEquals(results1, expected1, "Test 1") ? "...PASS\n\n" :"...FAIL\n\n"
# Test 2
#'BGRR' and the user guesses 'RGYY'
play.solution = "bgrr"
play.guess = "rgyy"
results2 = play.diff()
expected2 = {'l'=>1, 'c'=>1}
puts test.assertEquals(results2, expected2, "Test 2") ? "...PASS\n\n" :"...FAIL\n\n"
# Test 3
#Expected 1 location and 2 colors
play.solution = "ggrr"
play.guess = "rryy"
play.show
results3 = play.diff()
expected3 = {'l'=>0, 'c'=>2}
#play.show(results3)
puts test.assertEquals(results3, expected3, "Test 3") ? "...PASS\n\n" :"...FAIL\n\n"
# Test 4
#'BGRR' and the user guesses 'RGYY'
play.solution = "bgrr"
play.guess = "rgyy"
results4 = play.diff()
expected4 = {'l'=>1, 'c'=>1}
puts test.assertEquals(results4, expected4, "Test 4") ? "...PASS\n\n" :"...FAIL\n\n"
# Test 4
#'BGRR' and the user guesses 'RGRR'
play.solution = "bgRR"
play.guess = "bgrr"
results5 = play.diff()
expected5 = {'l'=>4, 'c'=>0}
puts test.assertEquals(results5, expected5, "Test 5") ? "...PASS\n\n" :"...FAIL\n\n"
| true |
3a2cc56a6cc55045fe5fc52974f5eef9e382b55c | Ruby | ArwaMA/FinalProject | /CloneDetectionToolApproach/Files.rb | UTF-8 | 572 | 3.1875 | 3 | [] | no_license | #! /usr/bin/env ruby
## It represents the files that have added/changed in host commit and contain clone code of the predefined clone type.
## Each file has a name (name), list of clones in the file (clones),
## and list of donor files that have clone codes with the file.
class Files
def initialize(name, clones)
@name = name
@clones = clones
@donorFiles = Array.new
end
def setName(name)
@name = name
end
def setDonorFiles(files)
@donorFiles = files
end
def name
@name
end
def clones
@clones
end
def donorFiles
@donorFiles
end
end
| true |
538360143478aa6c13a2c28ca647f8e49b9c1cc8 | Ruby | DohertyN/intro-to-programming | /Ruby_Basics/Return/ex3.rb | UTF-8 | 154 | 3.359375 | 3 | [] | no_license | def meal
return 'Breakfast'
'Dinner'
end
puts meal
#returns 'Breakfast' since the return exits the method on line 2, thus 'Dinner' is not processed. | true |
4c6cb425f4b8d644bc95cc338dcfd12f7b369343 | Ruby | J-cmlee/CodeWars | /roman_numerals.rb | UTF-8 | 289 | 3.203125 | 3 | [] | no_license | NUMERALS = { M: 1000, CM: 900, D: 500, CD: 400, C: 100, XC: 90,
L: 50, XL: 40, X: 10, IX: 9, V: 5, IV: 4, I: 1 }
def solution(number)
return '' if number <= 0
NUMERALS.each { |key, val| return key.to_s + solution(number - val) if number >= val }
end
p solution (13256) | true |
7a466aa1f31f0ddafad6723f8e7252f1c9c8a86a | Ruby | andy-aguilar/ruby-iteration-practice-badges-and-schedules-lab-wdc01-seng-ft-060120 | /conference_badges.rb | UTF-8 | 487 | 3.96875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def badge_maker(name)
return "Hello, my name is #{name}."
end
def batch_badge_creator(array)
array.map{|name| badge_maker(name)}
end
def assign_rooms(array)
rooms_array = []
array.each_with_index do |name, index|
rooms_array << "Hello, #{name}! You'll be assigned to room #{index + 1}!"
end
return rooms_array
end
def printer(array)
batch_badge_creator(array).each{|badge| puts badge}
assign_rooms(array).each{|assignment| puts assignment}
end | true |
75e5e83d3776b547fc3bfab46be0d8243191839b | Ruby | steveh/synesthetic | /app/models/colour.rb | UTF-8 | 333 | 2.90625 | 3 | [] | no_license | class Colour
def self.random_set
options = []
segments = ["00", "33", "66", "99", "CC", "FF"]
segments.each do |a|
segments.each do |b|
segments.each do |c|
options << "#%s%s%s" % [a, b, c] unless (a == b && b == c)
end
end
end
options.sort_by{ rand }[1..26]
end
end | true |
2ec4b2c2c31129da27850511ba156eec67dc965f | Ruby | dtomasiewicz/gamz | /examples/lobby_server/game.rb | UTF-8 | 1,027 | 3.3125 | 3 | [
"MIT"
] | permissive | class Game
MIN_PLAYERS = 1
MAX_PLAYERS = nil
attr_accessor :players
def initialize(players)
@players = players
@on_inform = nil
end
def on_inform(&block)
@on_inform = block
end
def on_finished(&block)
@on_finished = block
end
def player_left(player)
@players.delete player
inform_all :player_left, player
end
def self.min_players
self::MIN_PLAYERS
end
def self.max_players
self::MAX_PLAYERS
end
protected
def inform(player, what, *details)
if player.kind_of?(Array)
player.each {|p| inform p, what, *details}
else
@on_inform.call player, what, *details if @on_inform
end
end
def inform_all(*args)
inform @players, *args
end
def inform_except(players, *args)
players = [players] unless players.kind_of?(Array)
inform @players-players, *args
end
def inform_others(what, player, *args)
inform_except player, what, player, *args
end
def finished
@on_finished.call if @on_finished
end
end
| true |
44baa880116382e63042f54c8bbe04c75d8ec257 | Ruby | saikrishnagaddipati/coderbyte-ruby | /Medium/lib/prime_checker.rb | UTF-8 | 450 | 3.578125 | 4 | [] | no_license | def PrimeChecker(number)
length = number.to_s.length
potential_primes = []
all_digits = number.to_s.split("")
all_digits.permutation(length).each do |digits|
potential_primes << digits.join.to_i
end
potential_primes.each do |integer|
return 1 if is_prime?(integer)
end
0
end
private
def is_prime?(number)
flag = true
(2..Math.sqrt(number)).each do |factor|
flag = false if number % factor == 0
end
flag
end
| true |
c73fa15108dec38433d166fb5c25f0a1d8e460b7 | Ruby | gruis/Yaram | /lib/yaram/generic-encoder.rb | UTF-8 | 2,182 | 2.515625 | 3 | [
"MIT"
] | permissive |
begin
require "ox"
rescue LoadError => e
# we'll use Marshal instead
end # begin
module Yaram
module GenericEncoder
class << self
include Encoder
if (((oxgem = Gem.loaded_specs["ox"]).is_a?(Gem::Specification)) && Gem::Requirement.new("~>1.2.7").satisfied_by?(oxgem.version))
include Ox
# Load an object that was dumped using Ox.
# @raise EncodingError if the expected URN prefix is not found.
# @param [String] m
def load(xml)
header,body = xml[0..11], xml[12..-1]
raise EncodingError.new(header) unless header == "yaram:ox: "
begin
super(body, :mode => :object)
rescue Exception => e
raise ParseError, "unable to parse '#{body}'"
end # begin
end # load(xml)
# Dump an object using Ox and prefix it with a URN.
# @param [Object] o
# @todo add the Ox version requirement to the prefix URN if the Ox format changes.
def dump(o)
"yaram:ox: " + super(o)
end # dump(o)
else
include Marshal
# Load an object that was dumped using Marshal.
# @raise EncodingError if the expected URN prefix is not found.
# @param [String] m
def load(m)
header,body = m[0..11], m[12..-1]
raise EncodingError.new(header) unless header == "yaram:mrshl:"
super(body)
end
# Dump an object using Marshal and prefix it with a URN.
# @param [Object] o
# @todo determine version of Marshal being used and include it in the URN.
# str = Marshal.dump("a marshalled message has a major and minor version")
# str[0].ord #=> 4
# str[1].ord #=> 8
def dump(o)
"yaram:mrshl:" + super(o)
end
end # ((oxgem = Gem.loaded_specs["ox"]).is_a?(Gem::Specification)) && Gem::Requirement.new("~>1.2.2").satisfied_by?(oxgem.version)
end # << self
# insert the generic encoder into the Yaram encoding chain
inject
end # module::GenericEncoder
end # module::Yaram | true |
ab343267020eea2904d544f0bef26151141c87b7 | Ruby | rolandobrown/prework-ruby-assessment-web-0715-public | /lib/000_array.rb | UTF-8 | 287 | 2.8125 | 3 | [] | no_license | languages = ["Ruby", "JavaScript", "HTML"] # => ["Ruby", "JavaScript", "HTML"]
languages.push("CSS") # => ["Ruby", "JavaScript", "HTML", "CSS"]
languages.index([1]) # => nil
languages.index("HTML") # => 2
puts languages # => nil
# >> Ruby
# >> JavaScript
# >> HTML
# >> CSS
| true |
619c3ba5f8dc4add7455e58ba96b57f733433548 | Ruby | ben7th/pin-2010 | /lib/auto_loads/base/user_related/user_avatar_adpater.rb | UTF-8 | 1,830 | 2.578125 | 3 | [] | no_license | class UserAvatarAdpater
TEMP_FILE_BASE_DIR = "/web/2010/upload_user_avatar_tempfile"
def initialize(user, raw_file)
@raw_file = raw_file
user_id_str = user.id.to_s
@temp_file_dir = File.join(TEMP_FILE_BASE_DIR, user_id_str)
@temp_file_name = File.join(@temp_file_dir, 'avatar_tmp')
@temp_file_url = pin_url_for("ui","upload_user_avatar_tempfile/#{user_id_str}/avatar_tmp")
end
# 存储上传的头像文件到一个临时文件中,并返回该文件 路径+名
def create_temp_file
FileUtils.mkdir_p(@temp_file_dir)
FileUtils.cp(@raw_file.path, @temp_file_name)
File.chmod(0666, @temp_file_name)
return self
end
# 获取临时文件图片的宽高hash
def temp_image_size
temp_file = File.new(@temp_file_name)
image = Magick::Image::read(temp_file).first
return {:height=>image.rows, :width=>image.columns}
end
def temp_image_url
@temp_file_url
end
# -------------------------------------
def self.copper_logo(user, x1, y1, width, height)
user_id_str = user.id.to_s
temp_file_dir = File.join(TEMP_FILE_BASE_DIR, user_id_str)
temp_file_name = File.join(temp_file_dir, 'avatar_tmp')
temp_file = File.new(temp_file_name)
# 读取临时文件,裁切,转换格式
img = Magick::Image::read(temp_file).first
img.crop!(x1.to_i, y1.to_i, width.to_i, height.to_i, true)
img.format = 'PNG'
# 写第二个临时文件,裁切好的PNG文件
coppered_file_name = File.join(temp_file_dir, 'avatar_tmp_coppered.png')
img.write coppered_file_name
# 赋值给user.logo (保存到云)
coppered_file = File.new(coppered_file_name)
user.update_attributes(:logo=>coppered_file)
# 移除临时文件
FileUtils.rm(temp_file_name)
FileUtils.rm(coppered_file_name)
end
end
| true |
e787ee5411258176fca7971204c350ddee4c47c2 | Ruby | ovinix/rg_oop_task | /book.rb | UTF-8 | 261 | 2.984375 | 3 | [] | no_license | class Book
attr_accessor :title, :author
def initialize(title, author)
@title, @author = title, author
end
def to_s
"#{title} by #{author}"
end
def to_yaml
YAML.dump ({
title: @title,
author: @author
})
end
end | true |
14000cd2f5ffd4ec974e93ac46908c1774f275b9 | Ruby | maiyama18/AtCoder | /abc/083/c.rb | UTF-8 | 78 | 3.015625 | 3 | [] | no_license | x, y = gets.split.map(&:to_i)
c = 0
while x <= y
c += 1
x *= 2
end
puts c | true |
75e83b8ec017ec99a18414df220b1ee9d7e82300 | Ruby | charlie-galb/oyster3 | /spec/oystercard_spec.rb | UTF-8 | 2,234 | 3.078125 | 3 | [] | no_license | require 'oystercard.rb'
describe Oystercard do
#let(:journey){ {entry_station: entry_station, exit_station: exit_station} }
let(:mock_entry) { double :mock_entry}
let(:mock_exit) { double :mock_exit}
it 'checks that the oystercard has an initial value of 0' do
expect(subject.balance).to eq 0
end
describe '#top_up' do
it { is_expected.to respond_to(:top_up).with(1).argument }
it 'checks the increase balance in the card' do
expect { subject.top_up 5 }.to change {subject.balance }.by 5
end
context 'when topped up' do
before do
subject.top_up(Oystercard::BALANCE_LIMIT)
end
it 'raises error when trying to top up to be more than £90' do
expect { subject.top_up 91 }.to raise_error('You cannot have more than £90 in your balance')
end
end
end
describe '#touch_in' do
it 'checks that the touch_in method exists' do
expect(subject).to respond_to(:touch_in)
end
it 'check if the minimum amount is at least £1' do
expect { subject.touch_in 1 }.to raise_error "balance is not enough"
end
end
describe '#touch_out' do
it 'expects class to respond to touch_out' do
expect(subject).to respond_to(:touch_out)
end
it 'checks the touch out method' do
subject.top_up(1)
subject.touch_in(1)
expect{ subject.touch_out 1 }.to change{ subject.balance }.by(-Oystercard::MINIMUM_CHARGE)
end
# it 'check that is not in journey' do
# subject.top_up(1)
# subject.touch_in(:station)
# subject.touch_out(:station)
# expect(subject).to eq in_journey
# end
end
describe 'add journeys history' do
it 'check touches in create a new journey' do
subject.top_up(5)
expect(Journey).to receive(:new)
subject.touch_in(:mock_entry)
end
it 'checks that the array of journeys is empty' do
expect(subject.journeys_history).to eq []
end
it 'stores a journey' do
subject.top_up(2)
subject.touch_in(:mock_entry)
subject.touch_out(:mock_exit)
print subject.journeys_history
expect(subject.journeys_history).to eq [{:entry_station=>:mock_entry, :exit_station=>:mock_exit}]
end
end
end
| true |
e7e440422b4cec10daf099f46ca0506970851cf6 | Ruby | alikisinyo/second-try | /ruby only/exponetMethod.rb | UTF-8 | 147 | 3.390625 | 3 | [] | no_license | def power(base , powerNum)
result = 1
powerNum.times do |index|
result = result * base
end
return result
end
puts power(2,3)
| true |
514027bb71711fbbba101cb301e86623802d73da | Ruby | cypher/rack-lolspeak | /test/spec_rack_icanhazlolcode.rb | UTF-8 | 1,908 | 2.59375 | 3 | [] | no_license | require 'test/spec'
require 'rack/mock'
require 'rack/contrib/icanhazlolcode'
context "Rack::Contrib::ICanHazLOLCode" do
context "text/plain" do
app = lambda {|env| [200, {'Content-Type' => 'text/plain'}, "Hello, kitty"] }
specify "should convert the body to lolspeak" do
status, headers, body = Rack::Contrib::ICanHazLOLCode.new(app).call({})
status.should.equal 200
body.should.equal "y halo thar, kitty"
end
end
context 'text/html' do
page_title = "This is the document's title"
title = "Glorious title of document!"
paragraph = "This is a paragraph<br />with multiple lines<br />in it."
app = lambda do |env|
body = <<"HTML"
<html>
<head>
<title>#{page_title}</title>
</head>
<body>
<h1>#{title}</h1>
<div>
<p>
#{paragraph}
</p>
</div>
</body>
</html>
HTML
[200, {'Content-Type' => 'text/html'}, body]
end
specify "should convert the title to lolspeak" do
status, headers, body = Rack::Contrib::ICanHazLOLCode.new(app).call({})
status.should.equal 200
doc = Hpricot(body)
doc.search('title').inner_html.should.equal page_title.to_lolspeak
end
specify "should convert the body to lolspeak" do
status, headers, body = Rack::Contrib::ICanHazLOLCode.new(app).call({})
status.should.equal 200
doc = Hpricot(body)
doc.search('h1').inner_html.should.equal title.to_lolspeak
doc.search('p').inner_html.should.equal paragraph.to_lolspeak
end
specify "should preserve the HTML tags" do
status, headers, body = Rack::Contrib::ICanHazLOLCode.new(app).call({})
status.should.equal 200
doc = Hpricot(body)
doc.search('h1').should.not.equal nil
doc.search('div').should.not.equal nil
doc.search('p').should.not.equal nil
doc.search('br').should.not.equal nil
end
end
end
| true |
8d631f1dd7c15e7ddc77087052373784effddaec | Ruby | davidbobeck/sudovue | /sudoku_cell.rb | UTF-8 | 1,316 | 3.03125 | 3 | [] | no_license | class SudokuCell
attr_accessor :color, :possible_colors
attr_reader :id, :h, :v, :b
#---------------------------------
def initialize(id, color = nil)
@id = id
@h = (id / 10.0).to_i
@v = id - (@h * 10)
@b = (((@v-1) / 3.0).to_i) + ((((@h-1) / 3.0).to_i) * 3) + 1
@color = color
@possible_colors = (1..9).to_a
@possible_colors = [color] unless color.nil?
end
#---------------------------------
def clear_cell
self.color = nil
self.possible_colors = (1..9).to_a
end
#---------------------------------
def reject_color(color)
if self.possible_colors.include?(color)
self.possible_colors -= [color]
return true
end
false
end
#---------------------------------
def promote_naked_single
if self.possible_colors.count == 1
winning_color = self.possible_colors.first
if self.color != winning_color
return set_color(winning_color)
end
end
false
end
#---------------------------------
def set_color(color)
return false if self.color == color
self.color = color
self.possible_colors = [color] unless color.nil?
true
end
#---------------------------------
def to_vue
{ 'id' => self.id, 'color' => self.color || 0, 'suspects' => self.possible_colors }
end
end
| true |
5743e4ee45aa6f99f7ea777d56cf292194ca5873 | Ruby | CarlEricLavoie/schedulr | /lib/schedulr/log_entry.rb | UTF-8 | 458 | 2.96875 | 3 | [] | no_license |
class LogEntry
attr_accessor :date
attr_accessor :cmd
attr_accessor :args
def to_log()
"{{#{@date.to_i}}}{{#{@cmd}}}{{#{@args}}}"
end
def initialize(date, cmd, args)
@date = date
@cmd = cmd
@args = args
end
end
def LogEntry.from(line)
data = line.scan(/\{\{(.*?)\}\}+/)
date = Time.at(data[0][0].to_i)
cmd = data[1][0]
args = data[2][0].gsub(/(\[\"?|\"?\])/, '').split(/"?, "?/)
LogEntry.new(date, cmd, args)
end
| true |
2eee5f8307c97e487abee635f14438a17a184e2e | Ruby | CouchofTomato/chess-1 | /lib/piece.rb | UTF-8 | 1,602 | 3.546875 | 4 | [] | no_license | class Piece
# Note on piece colors: The Unicode representations of chess pieces assume
# black ink on white paper. This game is being developed with a dark background
# coding environment and terminal. So the actual color of the pieces is reversed
# from their Unicode names ─ the Unicode for "black pawn" represents a white
# pawn, etc.
attr_reader :color, :symbol
attr_accessor :position
def initialize(color, position)
@color = color
@position = position
end
def white(piece)
"\e[37;1m#{piece}"
end
def black(piece)
"\e[30m#{piece}"
end
def possible_moves(board, direction)
# Used by queens, rooks and bishops.
# Returns an array of symbols of valid targets in a given direction.
# Direction 0 is towards rank 8; 1 is towards h8, and so on.
# So 0 is 'north' or Blackwards, 7 is 'northwest', 4 is 'south' or Whitewards
file = @position[0].ord - 97
rank = @position[1].to_i
dirs = [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]
moves = []
target = :"#{(file + dirs[direction][0] + 97).chr}#{rank + dirs[direction][1]}"
# Pieces can move in a given direction however many squares are free.
while board[target] == ' '
moves << target
target = :"#{((target[0].ord - 97 + dirs[direction][0]) + 97).chr}#{target[1].to_i + dirs[direction][1]}"
end
# Pieces can capture enemy pieces.
if board[target].is_a?(Piece) and board[target].color != @color
moves << target
end
moves
end
def to_s
"#{self.color} #{self.class.to_s.downcase}"
end
end
| true |
7fd4e9c6afe36bffef13e5631954b54fa45ef6f2 | Ruby | DouglasAllen/ruby-kickstart-4-rdoc | /session1/notes/11-stdin-and-stdout.rb | UTF-8 | 1,542 | 3.59375 | 4 | [] | no_license | class Session01Notes
=begin rdoc
=== STDIN STDOUT
# Programs that run in a terminal read text in, and write text out.
# This is the common interface that allows lots of different programs to
# interact with each other.
# When a program outputs text, we say it sends it to standard output
# (stdout).
# In the terminal, anything your program sends stdout will display on
# your terminal.
# For example, cat sends a file's contents to standard output,
# echo sends its arguments to standard output.
# When it reads text in, it gets that from standard input (stdin).
# In the terminal, stdin is hooked up to your keyboard.
# Whatever you type will be sent to your program's stdin.
# Use gets to read a line from stdin
user_response = gets # be careful with gets in IRB
# it's time to start writing
# script jiles with *file_name*.rb
# Use puts to write the line to stdout
puts "You said: #{user_response}"
# Watch out!
# A line of text that ends in a newline. line = "Line\n"
# When you read in the line, you also read in the newline.
# That means: line + line # => "Line\nLine\n"
# If you _actually_ wanted this: "LineLine"
# then you need to remove the newline.
# Ruby gives you a method named chomp
# that will give you that string without the newline
line = "Line\n"
line.chomp
# => "Line"
line
# => "Line\n"
# It's like a cookie monster for newlines!
=end
def session1_11_stdin_and_stdout;end
end | true |
406daa4c0fe623223368dfe4fadd4df7609b97b4 | Ruby | cmacaulay/intro-to-ar | /spec/features/user_can_view_all_horses_spec.rb | UTF-8 | 731 | 2.59375 | 3 | [] | no_license | require_relative '../spec_helper'
RSpec.describe "when user visits horses path" do
it "they view all horses" do
Jockey.create(name: "Joey")
Breed.create(name: "Palomino")
horse1 = Horse.create(name: "Penelope", age: 29, total_winnings: 34000, breed_id: 1, jockey_id: 1)
horse2 = Horse.create(name: "Pepe", age: 39, total_winnings: 1000000, breed_id: 1, jockey_id: 1)
horse3 = Horse.create(name: "Picasso", age: 15, total_winnings: 78000, breed_id: 1, jockey_id: 1)
visit('/horses')
expect(page).to have_content(horse1.name)
expect(page).to have_content(horse3.total_winnings)
expect(page).to have_content(horse1.jockey.name)
expect(page).to have_content(horse3.breed.name)
end
end
| true |
5991d81779e7a963283e150ab4c543dbb5777b7d | Ruby | dwoznicki/phase-0 | /week-5/calculate-mode/my_solution.rb | UTF-8 | 3,131 | 4.125 | 4 | [
"MIT"
] | permissive | # Calculate the mode Pairing Challenge
# I worked on this challenge [by myself, with: ]
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# What is the input? an array of stuff
# What is the output? (i.e. What should the code return?) an array, containing most frequent appearing values
# What are the steps needed to solve the problem?
=begin
define a method to do the thing that takes an array
create a new hash with array values as keys
feed the array into hash, add one to value for each instance
check which values from key/value pair are highest
place those keys into new array
return the new array
=end
# 1. Initial Solution
def mode array
hash = Hash.new(0)
#adds x as key to hash and value +1 each time x occurs in array
array.each do |x|
hash[x] += 1
end
new_array=Array.new
#compares each value with the max, pushes keys associated with max into new array
hash.each do |k, v|
if v == hash.values.max
new_array << k
end
end
return new_array
end
# 3. Refactored Solution
#Destructive
def mode array
hash = Hash.new(0)
array.each do |x|
#sets value equal to number of occurences of x in array
hash[x] = array.count x
end
hash.each do |key, value|
#deletes the key from array if its value isn't max
if value != hash.values.max
array.delete key
end
end
#uniq cleans up leftover duplicates
return array.uniq
end
# 4. Reflection
=begin
Which data structure did you and your pair decide to implement and why?
We decided to use a hash to easily connect the element with its frequency in the array. I believe we could have also made an array of nested arrays with the element at index 0 and the frequency at index 1(eg. array = [["a", 2], ["b", 1]]). This is pretty over-complicated, though, when a hash does the same thing but is easier to iterate over.
Were you more successful breaking this problem down into implementable pseudocode than the last with a pair?
Well, not necessarily. I think both this time and last time my partners and I managed to make pretty manageable pseudocode.
What issues/successes did you run into when translating your pseudocode to code?
We had a bit of trouble figuring out how to compare the values of the hash to see which one(s) was the greatest. But after finding the max method, we quickly got it. I was actually a bit surprised to find that our block for building the hash worked out perfectly the first time we tried it.
What methods did you use to iterate through the content? Did you find any good ones when you were refactoring? Were they difficult to implement?
I spent a bit of time on my own trying to solve this problem without using a hash. I experimented with the methods .max, .max_by, .sort_by, etc. But I didn't really have any luck making a more efficient solution. The best method I found was probably array.count x, which returns the number of times x occurs in array. I didn't have much trouble implementing it.
=end | true |
f6b1359877bb54826cf5d11fb3713f7ad6d1fdd8 | Ruby | bluepostit/696-mvc-basics | /router.rb | UTF-8 | 870 | 3.640625 | 4 | [] | no_license | class Router
# State
# - controller
# Behavior
# - run (loop: get user action choice)
def initialize(tasks_controller)
@tasks_controller = tasks_controller
end
def run
loop do
# display menu of actions
# ask user to choose
# dispatch the action
show_menu
action = user_choice
dispatch(action)
end
end
private
def show_menu
puts "--- Task Manager ---"
puts "1. List your tasks"
puts "2. Add a new task"
puts "3. Mark a task as done"
puts "4. Delete a task"
end
def user_choice
puts "Please enter your choice by number:"
gets.chomp.to_i
end
def dispatch(action)
case action
when 1 then @tasks_controller.list
when 2 then @tasks_controller.add
when 3 then @tasks_controller.mark_as_done
when 4 then @tasks_controller.delete
end
end
end
| true |
0f8ca76a654c0dcab07105ee773de504cef3de22 | Ruby | felipemfp/racing | /src/states/game_states/oneway.rb | UTF-8 | 1,806 | 2.765625 | 3 | [
"MIT"
] | permissive | # This class is responsible to extend the on game behavior
# to a one way scenario.
class OneWayGameState < GameState
MODE_INDEX = 0
def initialize(options = {})
super({
player_margin_left: 175.0,
player_margin_right: 335.0,
cars_angle: [0.0],
cars_pos: [180.0, 255.0, 330.0],
cars_wave: options[:main].current_difficulty[:cars_wave][MODE_INDEX],
cars_move: options[:main].current_difficulty[:cars_move],
score_factor: options[:main].current_difficulty[:score_factor]
}.merge(options))
end
def load_assets
super
@road = Road.new(Path::IMAGES + 'background-one.png')
end
def load_properties
super
@cars_interval = 7500
@distance = 0
@distance_per_car = 7.5
@distance_last_car = 0
@cars_outdated = 0
@cars_interval = 10
@cars_from_now = 0
@car_hit_distance = 145
@interval = 2
end
def clean_cars_outdated
@cars.reject! do |car|
if car.y >= 512 + 140
car.sample.stop if car.sample
@cars_outdated += 1
reject = true
end
@last_car = car if
@last_car.nil? || @last_car.y < car.y + @car_hit_distance
reject
end
end
def handle_possible_collision
return unless @cars.size > 1 && @last_car
@cars.each_with_index do |car, i|
@cars[i].speed = @last_car.speed if
@last_car.x == car.x && @last_car.y < car.y + @car_hit_distance
end
@last_car = nil
end
def handle_progression
super
if @cars_outdated - @cars_from_now == @cars_interval
@distance_per_car -= 0.5
@cars_from_now = @cars_outdated
end
end
def update
return unless @alive && !@paused
@last_car = nil
clean_cars_outdated
super
handle_possible_collision
end
def draw
super
end
end
| true |
751c90b6f9c6994556f453b02b724313b752a05a | Ruby | minoriinoue/ruby_practice | /todai/w4/others/idou_gata_test.rb | UTF-8 | 949 | 3.046875 | 3 | [] | no_license | require('test/unit')
load('./next_field.rb')
load('./make_field.rb')
class IDOU_GATA_TEST < Test::Unit::TestCase
def test_glider
# Test the period is 4. Since in 1 period, the pattern
# goes to 1 column left and 1 down row. So the pattern
# at the 1 column left and 1 down row after 1 period will
# be same as one at the starting point.
glider=[[0,1],[1,2],[2,0],[2,1],[2,2]]
original = make_field(15, 15, glider)
after_period = original.dup
period = 4
for i in 0..period-1
after_period = next_field(after_period)
end
# Check all the elements are equal between the pattern at
# the original point and the patter after a period which
# [1,1] away from the original point.
for i in 0..2
for j in 0..2
assert_equal(original[i][j], after_period[i+1][j+1])
end
end
end
end
| true |
7638958aae2249d94ad5a82b5016a5949b95baf5 | Ruby | pleonar1/backend_mod_1_prework | /section1/ex2.rb | UTF-8 | 283 | 3.6875 | 4 | [] | no_license | # A comment, this is so you can read your code later.
# Anything after the # is ignored by ruby.
puts "I could have code that looks like this." #Anything after this is ignored.
#You can also use a comment to diasble a piece of code.
# puts "THis won't run"
puts "This will run."
| true |
c1aef3f4c92343fa0923adbe752b7c950f195da9 | Ruby | techtronics/kaburiasu_temp | /app/models/battle.rb | UTF-8 | 3,548 | 2.796875 | 3 | [] | no_license | class Battle < ActiveRecord::Base
has_many :parties
before_destroy :child_destroy
#############################################################
#SQL method
#############################################################
#指定した時間分さかのぼって、同じデータがあるかを返します。
def Battle.find_same_data(user_id, battle, h_count)
to_time = Time.now
from_time = to_time - (h_count * 60 * 60 * 24) #hhからssに単位変更
pokemon_id_list = battle.parties.collect do |item|
item.pokemon_id
end
pokemon_id_list.delete_if do |item| item.nil? end
sql = <<SQL
select count(b.id) from battles b
where user_id = #{user_id}
and b.battle_environment_id = #{battle.battle_environment_id}
and b.created_at between '#{from_time.strftime("%Y-%m-%d %H:%M:%S")}' and '#{to_time.strftime("%Y-%m-%d %H:%M:%S")}'
and exists (
select count(id) as count_same from parties
where b.id = parties.battle_id
and pokemon_id IN(#{pokemon_id_list.join(',')})
group by battle_id
having count_same = 6
)
SQL
data_count = count_by_sql(sql)
data_count != 0
end
def Battle.calc_battle_count(condition)
where_statement = ModelToSql.battle_to_where(condition)
sql = <<SQL
select count(id) from
( select battles.id from battles
left join parties
on battles.id = parties.battle_id
where #{where_statement}
group by battles.id
) t
SQL
Battle.count_by_sql sql
end
def Battle.search_party(condition)
statement = ModelToSql.battle_to_where(condition)
sql = <<SQL
select count(battles.id) from battles
where #{statement}
SQL
Battle.count_by_sql sql
end
#############################################################
#method
#############################################################
#pokemon_idからpartyを作成する
def Battle.create_party(id_set)
return [] if not id_set
parties = id_set.collect do |item|
Party.new(:pokemon_id => item)
end
parties
end
#ランダムマッチかどうかを返す。
def random_match?
BattleEnvironment.random_match?(self.battle_environment_id)
end
private
def child_destroy
Party.delete_all(:battle_id => self.id)
end
#############################################################
#validate
#############################################################
validates_presence_of :battle_environment_id, :unix_time
validates_numericality_of :rate, :only_intege =>true, :greater_than_or_equal_to=>0, :if=>:rate
validate :validate_model
def validate_model
validate_parties
end
def validate_parties
#入力数チェック
if parties.size < Party::MAX_COUNT
errors.add(:parties, 'のポケモン6匹は必須です。')
elsif Party::MAX_COUNT < parties.size
errors.add(:parties, 'は6匹までしか入力できません。')
end
length = [parties.size, Party::MAX_COUNT].min
set = {}
for i in 0...length
item = parties[i]
#名称妥当性チェック
if not item.pokemon_id
errors.add(:parties, "の#{i+1}匹目のポケモンの名前を確認してください。")
next
end
#重複チェック
prev_item = set[item.pokemon_id]
if prev_item
errors.add(:parties, "の#{prev_item+1}匹目と#{i+1}匹目のポケモンが重複しています。")
else
set[item.pokemon_id] = i
end
end
end
end
| true |
5986c893658921998db1fcb5f60247c22477f1a2 | Ruby | lfeliperibeiro/Ruby_beginner | /Basic/conditionals.rb | UTF-8 | 1,109 | 4.09375 | 4 | [] | no_license | # frozen_string_literal: true
# Operadores relacionais e lógicos do Ruby são os mesmos das outras linguagens
value = 40
if value > 50
puts 'I am major of 50'
else
puts 'I am minor of 50'
end
puts 'i between with 40 and 100' if value >= 40 && value <= 100
if value > 50
puts 'I am major of 50'
elsif value == 50
puts 'I am equal of 50'
else
puts 'I am minor of 50'
end
# Apenas nil e false são avaliados com falso
# No ruby conseguimos usar uma sintaxe sugar
puts 'I am major of 50' if value > 50
# o unless é o oposto do if
puts 'I minor of 50' unless value > 50
# operador ternario é o mesmo que sempre usamos
# Usamos case também em Ruby
language = 'Ruby'
case language
when 'Ruby'
puts 'Welcome ruby course'
when 'Golang'
puts 'unavailable course'
else
puts 'I dont no this language'
end
# Se inserirmos no final to_i o ruby converte para Integer
# Exemplo:
newValue = gets.chomp.to_i
p newValue.class
p newValue
if newValue > 20
puts 'this value is major of 20'
elsif newValue == 20
puts 'this value is equal of 20'
else
puts 'this value is minor of 20'
end | true |
1fbbab9d4982060d84aef9956cd2e408907698aa | Ruby | stadelmanma/sablon | /lib/sablon/html/visitor.rb | UTF-8 | 685 | 2.8125 | 3 | [
"MIT"
] | permissive | module Sablon
class HTMLConverter
class Visitor
def visit(node)
method_name = "visit_#{node.class.node_name}"
if respond_to? method_name
public_send method_name, node
end
end
end
class GrepVisitor
attr_reader :result
def initialize(pattern)
@pattern = pattern
@result = []
end
def visit(node)
if @pattern === node
@result << node
end
end
end
class LastNewlineRemoverVisitor < Visitor
def visit_Paragraph(par)
if HTMLConverter::Newline === par.runs.nodes.last
par.runs.nodes.pop
end
end
end
end
end
| true |
d8c37f670190ce9a2f9d2f851b02739b9b15bb7b | Ruby | jamesarosen/xebec | /lib/xebec/has_nav_bars.rb | UTF-8 | 1,121 | 2.65625 | 3 | [] | no_license | require 'xebec/nav_bar'
module Xebec
# A supporting mixin for NavBarHelper and ControllerSupport.
# Looks up navigation bars by name.
module HasNavBars #:nodoc:
protected
# Looks up the named nav bar, creates it if it
# doesn't exist, and evaluates the the block, if
# given, in the scope of +self+, yielding the nav bar.
#
# @param [Symbol, String] name the name of the navigation bar to look up
# @param [Hash] html_attributes additional HTML attributes to add to the
# navigation bar
def look_up_nav_bar_and_eval(name = nil, html_attributes = {}, options = {}, &block)
name ||= Xebec::NavBar::DEFAULT_NAME
look_up_nav_bar(name, html_attributes, options).tap do |bar|
block.bind(self).call(bar) if block_given?
end
end
def look_up_nav_bar(name, html_attributes, options = {})
(nav_bars[name] ||= NavBar.new(name, html_attributes)).tap do |bar|
bar.html_attributes.merge!(html_attributes)
end
end
def nav_bars
@nav_bars ||= HashWithIndifferentAccess.new
end
end
end
| true |
db2056cc6a8698bd9e1048fc78289f4ae5da829d | Ruby | lbvf50mobile/til | /20191204_Wednesday/20191204.rb | UTF-8 | 1,608 | 3.65625 | 4 | [] | no_license | p "alias x='ruby 20191204_Wednesday/20191204.rb'"
# Leetcode: 760. Find anagram mappings.
=begin
https://leetcode.com/problems/find-anagram-mappings/
Leetcode: 760. Find anagram mappings.
Given two lists Aand B, and B is an anagram of A. B is an anagram of A means B is made by randomizing the order of the elements in A.
We want to find an index mapping P, from A to B. A mapping P[i] = j means the ith element in A appears in B at index j.
These lists A and B may contain duplicates. If there are multiple answers, output any of them.
For example, given
A = [12, 28, 46, 32, 50]
B = [50, 12, 32, 46, 28]
We should return
[1, 4, 3, 2, 0]
as P[0] = 1 because the 0th element of A appears at B[1], and P[1] = 4 because the 1st element of A appears at B[4], and so on.
Note:
A, B have equal lengths in range [1, 100].
A[i], B[i] are integers in range [0, 10^5].
=end
def input_array_and_anagram
size = rand(0...10)
return [[],[]] if size.zero?
input = (0...size).each_with_object([]){|value,obj| obj.push(rand(0..1000))}
anagram = input.shuffle
[input, anagram]
end
def check_map(mapping, a, b)
mapping.each_with_index.all?{|b_index, a_index| a[a_index] == b[b_index]}
end
def find_anagram_mappings(a,b)
b_value_key = b.each_with_index.to_h
a.map{|value| b_value_key[value]}
end
require 'minitest/autorun'
describe "find anagram mappings" do
it "find_anagram_mappings works" do
5000.times do
input, anagram = input_array_and_anagram
assert check_map(find_anagram_mappings(input,anagram), input, anagram)
end
end
end | true |
97117463fed532e41c2e2cb5bc03cfe40a32b99e | Ruby | oscarmolivera/code_farm | /Ruby/CodeWars/Collection Ruby 8 Kyu/02-[8kyu]_Remove String Spaces.rb | UTF-8 | 1,332 | 3.140625 | 3 | [] | no_license | =begin
Remove String Spaces
Simple, remove the spaces from the string, then return the resultant string.
=end
def no_space(x)
x.split.join('')
end
p no_space('8 j 8 mBliB8g imjB8B8 jl B')
# =>'8j8mBliB8gimjB8B8jlB'
p no_space('8 8 Bi fk8h B 8 BB8B B B B888 c hl8 BhB fd')
# =>'88Bifk8hB8BB8BBBB888chl8BhBfd'
p no_space('8aaaaa dddd r ')
# =>'8aaaaaddddr'
p no_space('jfBm gk lf8hg 88lbe8 ')
# =>'jfBmgklf8hg88lbe8'
p no_space('8j aam')
# =>'8jaam'
=begin ############################################# OTHERS SOLUTIONS
2)
def no_space(x)
x.gsub(" ","")
end
----------------------------------------------------------------------
3)
def no_space(x)
x.delete(" ")
end
----------------------------------------------------------------------
4)
def no_space(x)
x.tr("\s", "")
end
----------------------------------------------------------------------
5)
----------------------------------------------------------------------
6)
----------------------------------------------------------------------
7)
----------------------------------------------------------------------
8)
----------------------------------------------------------------------
9)
----------------------------------------------------------------------
10)
=end
=begin THRASH CAN ****************************************************
=end | true |
8665f77dbeb5db6fe062cecf2bca1a3ee05f2d96 | Ruby | regisbruggheman/gko_cms3 | /gko_core/db/default/sites.rb | UTF-8 | 2,445 | 2.71875 | 3 | [] | no_license | require 'highline/import'
# see last line where we create an master if there is none, asking for email and password
def prompt_for_site_title
title = ask('Title [My site]: ') do |q|
q.echo = false
q.validate = /^(|.{1,40})$/
q.responses[:not_valid] = 'Invalid site title. Must be at least 1 characters long.'
q.whitespace = :strip
end
title = 'My site' if title.blank?
title
end
def prompt_for_site_host
host = ask('Host [0.0.0.0:3000]: ') do |q|
q.echo = true
q.whitespace = :strip
end
host = "0.0.0.0:3000" if host.blank?
host
end
def prompt_for_example_pages
if ENV['AUTO_ACCEPT'] or agree("Do you want to create sample pages\ncontinue? [y/n] ")
ENV['SKIP_NAG'] = 'yes'
return true
else
say "Task cancelled, exiting."
exit
return false
end
end
def create_site
if ENV['AUTO_ACCEPT']
title = "My site #{Site.count}"
host = "0.0.0.0:3000"
else
puts 'Create the site (press enter for defaults).'
title = prompt_for_site_title
host = prompt_for_site_host
end
attributes = {
:host => host,
:title => title
}
load 'site.rb'
if Site.where(:host => host).any? #Do not use Site.by_host !!
say "\nWARNING: There is already a site with the host: #{host}, so no site changes were made. If you wish to create an additional site, please run rake db:site:create again with a different host.\n\n"
else
@site = Site.current = Site.create!(attributes)
if prompt_for_example_pages
@primary_menu = @site.sections.named("primary_menu")
#------------------------------------
puts "creating pages"
@primary_menu.children.create!({ :title => "Exemple",
:type => 'Page',
:body => lorem,
:published_at => Time.zone.now})
@primary_menu.children.create!({:title => "About",
:type => 'Page',
:body => lorem,
:published_at => Time.zone.now})
@primary_menu.children.create!({:title => "Contact",
:template => 'contact',
:type => 'Page',
:body => lorem,
:published_at => Time.zone.now})
else
end
end
end
create_site | true |
0ef5ef6322aeb5821f0a8761ed20d5ff0725950d | Ruby | yoichimichael/ruby-oo-relationships-practice-boating-school-exercise-nyc-web-033020 | /app/models/student.rb | UTF-8 | 730 | 3.171875 | 3 | [] | no_license | class Student
attr_reader :first_name
@@all = []
def initialize(first_name)
@first_name = first_name
Student.all << self
end
def self.all
@@all
end
def add_boating_test(test_name, test_status, instructor)
BoatingTest.new(self, test_name, test_status, instructor)
end
def self.find_student(student_name)
self.all.find { |student| student.first_name == student_name }
end
def find_boating_tests
BoatingTest.all.select { |test| test.student.first_name == self.first_name }
end
def grade_percentage
passed_tests = find_boating_tests.select { |test| test.status == "passed"}
(passed_tests.count.to_f / find_boating_tests.count * 100).round(2)
end
#binding.pry
end
| true |
a579e5ac2d642f9f4efdfab4e3d936adb9de0a6d | Ruby | peteonrails/ruby-gpu-examples | /bin/tree_rings_yarv.rb | UTF-8 | 655 | 2.515625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | #!/usr/bin/env ruby
#
# A baseline CPU-based benchmark program CPU/GPU performance comparision.
# Approximates the cross-sectional area of every tree ring in a tree trunk in serial and in parallel
# by taking the total area at a given radius and subtracting the area of the closest inner ring.
# Copyright © 2011 Preston Lee. All rights reserved.
# http://prestonlee.com
#
$:.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'ruby-gpu-examples'
require 'ruby-gpu-examples/barracuda'
rings = 2**24.to_i
num_threads = 4
printBanner(rings)
runCPUSingleThreaded(rings)
runCPUMultiThreaded(rings, num_threads)
# runGPU(rings)
puts("Done!\n\n") | true |
5ddda730dfa3f5f54bb4ae6901b5a9315b76befd | Ruby | christianlarwood/ruby_small_problems | /live_coding_exercises/array_of_primes.rb | UTF-8 | 1,920 | 4.65625 | 5 | [] | no_license | # Write a method that takes two numbers. Return an array containing all primes between the two numbers (include the two given numbers in your answer if they are prime). Don't use Ruby's 'prime' class.
=begin
What's the expected input(s):
- 2 integers, start number and ending number in a range
What's the expected output(s):
- array of all prime integers within the range
What are the rules (explicit & implicit requirements)?:
- number must be prime (only divisible by 1 and itself)
-
-
Clarifying Questions:
- how to handle negative numbers? no integers provided?
-
Describe your mental model (interpretation) of the problem:
- Given 2 integers, a starting number and an ending number, return an array of all prime numbers within the range.
Data Structure: Which data structures will work with each step of your mental model?
- an empty array to store all prime numbers
-
Algorithm: What are the exact steps that will transform the input(s) to the desired output(s)? Use your mental model and data structure.
- create a variable with an empty array
- iterate over every integer within the range of numbers
- if integer is prime add it to the array
- return the array
- define a method, find_primes, with 2 parameters, start_num & end_num
- initialize a variable, result, and assign to it an empty array
- use each method on the range of integers
- within loop if an integer is divisible by 1 and itself and not by 2 then add it to the result array
- return the result array
=end
# Code:
def find_primes(start_num, end_num)
result = []
(start_num...end_num).each do |num|
result << num + 2
end
p result
end
# Test Cases:
p find_primes(3, 10) == [3, 5, 7]
p find_primes(11, 20) == [11, 13, 17, 19]
# p find_primes(100, 101) == [101]
# p find_primes(1, 100) == [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
| true |
95bb7b46728660b588d44f4c67b090b2c509af1a | Ruby | jachabombazo/skillcrush1 | /git_test.rb | UTF-8 | 103 | 2.96875 | 3 | [] | no_license | puts "This file is for testing GIT only."
puts "Who are you?"
answer = gets.chomp
puts "#{answer}"
end
| true |
453707844767a4bd4a18596fda4649ebd1cd8ae4 | Ruby | thomas-kenny/udemy_rspec | /spec/double_spec.rb | UTF-8 | 930 | 3.140625 | 3 | [] | no_license | # method which returns a flexible object whose methods we can define and return values we can stipulate.
# forces pressure on us to make sure doubles match behaviour of objects they are designed to mock.
RSpec.describe 'a random double' do
it 'only allows defined methods to be invoked' do
stuntman = double("Mr. Danger", fall_off_ladder: 'Ouch', light_on_fire: true)
#methods and their returned values
expect(stuntman.fall_off_ladder).to eq('Ouch')
expect(stuntman.light_on_fire).to eq(true)
stuntman = double("Mr. Danger")
allow(stuntman).to receive(:fall_off_ladder).and_return('Ouch')
expect(stuntman.fall_off_ladder).to eq('Ouch')
stuntman = double("Mr. Danger")
allow(stuntman).to receive_messages(fall_off_ladder: 'Ouch', light_on_fire: true)
expect(stuntman.fall_off_ladder).to eq('Ouch')
expect(stuntman.light_on_fire).to eq(true)
end
end | true |
ea50f578d3c1b5f16a396ed35c9a4863120bdfc0 | Ruby | crhilditch20/week2homework_kareoke | /room.rb | UTF-8 | 1,010 | 3.484375 | 3 | [] | no_license | class Room
attr_reader :name, :guests, :capacity, :song_list, :available_space
def initialize(name, capacity, song_list)
@name = name
@capacity = capacity
@guests = []
@song_list = song_list
@available_space = nil
end
def count_guests()
@guests.length
end
def available_space
@available_space = (@capacity - @guests.length)
end
def check_in_guest(guest)
@guests.push(guest.name)
end
def check_out_guest(guest)
@guests.delete(guest.name)
end
def select_song_by_title(title)
chosen_song = nil
for song in song_list
if song.title == title
chosen_song = title
end
return chosen_song
end
end
def find_songs_by_artist(artist)
possible_songs = []
for song in song_list
possible_songs.push(song.title) if song.artist == artist
end
return possible_songs
end
def find_songs_by_genre(genre)
possible_songs = []
for song in song_list
possible_songs.push(song.title) if song.genre == genre
end
return possible_songs
end
end | true |
1b69b4d5bf0efeb3d3286133117c59f29a1f9d32 | Ruby | kelostrada/htmlformatter | /lib/htmlformatter/elixir_indenter.rb | UTF-8 | 472 | 2.5625 | 3 | [
"MIT"
] | permissive | module HtmlFormatter
class ElixirIndenter
INDENT_KEYWORDS = %w[ else ]
OUTDENT_KEYWORDS = %w[ else end ]
ELIXIR_INDENT = %r{
^ ( #{INDENT_KEYWORDS.join("|")} )\b
| ^ ( \w+\s*=\s*form\_for )
| ( -\> | do ) $
}xo
ELIXIR_OUTDENT = %r{ ^ ( #{OUTDENT_KEYWORDS.join("|")} | \} ) \b }xo
def outdent?(lines)
lines.first =~ ELIXIR_OUTDENT
end
def indent?(lines)
lines.join("\n") =~ ELIXIR_INDENT
end
end
end
| true |
103cd346692643a090597b940a21acbf3e039003 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/anagram/cb8b7039af124bfeb801df1c111342bd.rb | UTF-8 | 334 | 3.625 | 4 | [] | no_license | class Anagram
def initialize(source)
@source = source.downcase
@source_chars = @source.chars.sort.join
end
def match(answers)
answers.map(&:downcase).uniq.select { |match| contains?(match) && match != @source }
end
private
def contains?(word)
@source_chars.start_with?(word.chars.sort.join)
end
end
| true |
5c6c9c0c9143813600ce914a01e7789de89bbd98 | Ruby | CodingDojo-Ruby-03-17/fredrik-yumo | /RubyTDD/bank_account/bank_account_spec.rb | UTF-8 | 1,214 | 3.09375 | 3 | [] | no_license | require_relative 'bank_account'
RSpec.describe BankAccount do
before(:each) do
@account = BankAccount.new
end
it 'has a getter for checkings attribute' do
expect(@account.checkings).to eq(0)
@account.deposit(15.50, "checkings")
expect(@account.checkings).to eq(15.50)
end
it 'has a getter for total_money attribute' do
@account.deposit(3.00, "checkings")
@account.deposit(5.00, "savings")
expect(@account.total_money).to eq(8.00)
end
it 'has a method withdraw that allows an amount to be taken out of an account' do
@account.deposit(10.00, "checkings")
@account.withdraw(5.00, "checkings")
expect(@account.checkings).to eq(5.00)
@account.deposit(30.25, "savings")
@account.withdraw(15.25, "savings")
expect(@account.savings).to eq(15.00)
end
it 'can\'t withdraw more money than is in an account' do
expect{@account.withdraw(2.00, "checkings")}.to raise_error(InsufficientFundsError)
end
it 'doesn\'t have a getter for num_accounts attribute' do
expect{@account.num_accounts}.to raise_error(NoMethodError)
end
it 'can\'t set the interest rate' do
expect{@account.interest_rate = 0.09}.to raise_error(NoMethodError)
end
end
| true |
45cf4567ca36cba4f6d888ca8b75b1be13fdbec2 | Ruby | saasbook/courseware | /self-checks/module6/sc6-8.rb | UTF-8 | 637 | 3.015625 | 3 | [] | no_license | quiz "6.8: Testing JavaScript and AJAX" do
choice_answer do
text "Which are always true of Jasmine's it() method:
a. it can take a named function as its 2nd argument
b. it can take an anonymous function as its 2nd argument
c. it executes asynchronously"
answer "(a) and (b)"
distractor "(a) and (c)"
distractor "(b) and (c)"
distractor "All are true"
explanation "Since functions are first-class in JavaScript, there is no syntactic distinction between providing an anonymous function or the name of an existing function. Since JavaScript is single-threaded, all code including Jasmine tests execute synchronously."
end
end | true |
b46221389da4fe6399a98b9d35de8e353050d691 | Ruby | mirrec/kata | /lib/codility/fibonacci/lesson.rb | UTF-8 | 373 | 3.421875 | 3 | [] | no_license | module Codility
module Fibonacci
module Lesson
def fib_slow(n)
return n if n <= 1
fib_slow(n - 1) + fib_slow(n - 2)
end
def fib_numbers(n)
results = [0] * (n + 1)
results[1] = 1
2.upto(n) do |i|
results[i] = results[i - 1] + results[i - 2]
end
results
end
end
end
end | true |
c8067900b9b1d82102ea03e0bbbe2ebd7fa0756a | Ruby | eibay/ruby-refresher | /2-Variables/ex5.rb | UTF-8 | 424 | 4.21875 | 4 | [] | no_license | # Comparing variable outputs
# Case 1
# x = 0
# 3.times do
# x += 1
# end
# puts x
# Case 2
y = 0
3.times do
y += 1
x = y
end
puts x
# What does x print to the screen in each case?
# Do they both give errors? Are the errors different?
# Why?
# Answer
# Case 1 output is 3. Case 2 only gives error.
# X in Case 2 is defined only locally inside the
# do/end block and can be use within the block only.
| true |
aabf6e327d408954dbc2204cb41343779841ccbe | Ruby | AnnAllan/assignment_rspec_viking | /spec/warmup_spec.rb | UTF-8 | 1,104 | 3.28125 | 3 | [] | no_license | require 'warmup'
describe Warmup do
let(:warm) {Warmup.new}
describe '#gets_shout' do
it 'upcases a string' do
allow(warm).to receive(:gets).and_return('hello')
expect(warm.gets_shout).to eq('HELLO')
end
it 'puts upcased string to console' do
allow(warm).to receive(:gets).and_return('hello')
expect{warm.gets_shout}.to output("HELLO\n").to_stdout
end
end #gets_shout
describe '#triple_size' do
it 'triples size of array' do
my_double = double(:size => 4 )
expect(warm.triple_size(my_double)).to eq(12)
end
end #triple_size
describe '#calls_some_methods' do
let(:string) {"hello"}
it 'receives the #upcase! call' do
expect(string).to receive(:upcase!).and_return('HELLO')
warm.calls_some_methods(string)
end
it 'receives the #reverse! call' do
expect(string).to receive(:reverse!).and_return('OLLEH')
warm.calls_some_methods(string)
end
it 'returns different object' do
expect(string.inspect).to_not eq(warm.calls_some_methods(string).inspect)
end
end
end #Warmup Class
| true |
70302a0d18144d443638134c4681f18044b4d23a | Ruby | viswanand95/juhomi | /ex 39 hashes.rb | UTF-8 | 669 | 3.625 | 4 | [] | no_license | things = ['a','b','c','d']
things[1] = 'z'
puts "the things is: #{things}"
info = {'name' => 'Anand' , 'age' => 24 , 'height' => 178}
info['city'] = "Chennai"
info[1] = "Wow"
info[2] = "Naeto"
info
states = {
'Tamil Nadu' => 'TN',
'Kerala' => 'KL',
'Maharastra' => 'MH',
'orissa' => 'OR'
}
city = {
'CH' => 'Chennai',
'MU' => 'Mumbai',
'Hy' => 'Hydrabad'
}
city['TY'] = 'Trichy'
states['Delhi'] = 'DL'
puts "TN state is: #{city['CH']}"
puts "India country has: #{states['Delhi']}"
puts '-' * 10
states.each do |abbri,name|
puts "#{abbri} is #{name}"
end
state = states['Assam']
if !state
puts "Sorry, no Texas."
end | true |
e01ed2689b7e26d788bf9be4e055729ba19bb2c3 | Ruby | giantoak/201605_xdata_qpr | /data/twitter/aggregate_by_hour.rb | UTF-8 | 859 | 3.0625 | 3 | [] | no_license | require 'date'
INDEX_ID = 0
INDEX_DATE = 1
INDEX_YEAR = 2
INDEX_MONTH = 3
INDEX_DAY = 4
INDEX_HOUR = 5
INDEX_MINUTE = 6
row = 0
totals = {}
open('yemen_tweets_5.22.2016_timeseries.csv').each do |line|
unless row == 0
data = line.split(";")
key = "#{data[INDEX_YEAR]}-#{data[INDEX_MONTH]}-#{data[INDEX_DAY]}-#{data[INDEX_HOUR]}"
if totals.has_key?( key )
totals[key] = totals[key] + 1
else
totals[key] = 1
end
end
row = row + 1
end
print "#{totals.size} entries..\n"
file = File.open('yemen_tweets_5.22.2016.by_hour.csv','w')
file << "index,hour,message_total\n"
totals.each do | key, value |
print "#{key} -> #{value}\n"
indicies = key.split("-")
print "#{indicies}\n\n"
index = DateTime.new(indicies[0].to_i,indicies[1].to_i,indicies[2].to_i,indicies[3].to_i,0,0)
file << "#{index.strftime('%s')},#{key},#{value}\n"
end
| true |
ced39286dd027802a098a964d93404282c2831ab | Ruby | marinaneumann/train_station_database | /trains.rb | UTF-8 | 3,287 | 3.6875 | 4 | [] | no_license | require './lib/stations'
require './lib/lines'
require 'pg'
DB = PG.connect({:dbname=>'train_world'})
def main_menu
system("clear")
loop do
puts "(= Main Menu =)"
puts "[1] Operator Menu"
puts "[2] Rider Menu"
puts "[x] Exit program\n\n"
print "Choose option: "
menu_choice = gets.chomp
if menu_choice == '1'
operator_menu
elsif menu_choice == '2'
rider_menu
elsif menu_choice == 'x'
puts "Travel on."
exit
else
puts "Choose more wisely."
end
end
end
def operator_menu
loop do
puts "(= Operator Menu =)"
puts "[1] Create a new line"
puts "[2] Create a new station"
puts "[3] Add a station to a line"
puts "[4] Delete a line"
puts "[x] Exit to Main Menu\n\n"
print "Choose option: "
menu_choice = gets.chomp
if menu_choice == '1'
create_line
elsif menu_choice == '2'
create_station
elsif menu_choice == '3'
add_station_to_line
elsif menu_choice == '4'
delete_line
elsif menu_choice == 'x'
main_menu
else
puts "Failed."
end
end
end
def rider_menu
loop do
puts "(= Rider Menu =)"
puts "[1] View train lines"
puts "[2] View train stations"
puts "[3] Delete a station"
puts "[x] Exit to Main Menu\n\n"
print "Choose option: "
menu_choice = gets.chomp
if menu_choice == '1'
view_lines
elsif menu_choice == '2'
view_stations
elsif menu_choice == '3'
delete_station
elsif menu_choice == 'x'
main_menu
else
puts "Failed."
end
end
end
def create_line
puts "Enter a description of the line: "
line_input = gets.chomp
Line.new({:name =>line_input}).save
puts "#{Line.all.last.name} added to the train lines.\n\n"
end
def create_station
puts "Enter a description of the station: "
station_input = gets.chomp
Station.new({:name => station_input}).save
puts "#{Station.all.last.name} added to the train stations"
end
def delete_line
view_lines
puts "Which line would you like to delete?"
line_choice = gets.chomp.to_i
current_line = Line.find(line_choice)
current_line.delete
view_lines
end
def delete_station
view_stations
puts "Which station would you like to delete?"
station_choice = gets.chomp.to_i
current_station = Station.find(station_choice)
current_station.delete
view_stations
end
def view_lines
puts "[id] - Line name"
Line.all.each do |line|
puts "[#{line.id}] #{line.name}"
end
puts "\n\n"
end
def view_stations
puts "[id] - Station name"
Station.all.each do |station|
puts "[#{station.id}] #{station.name}"
end
puts "\n\n"
end
def view_by_line(line_id)
current_line = Line.find(line_id)
puts "#{current_line.name} line stations: "
puts "[id] Station Name"
current_line.get_stations.each do |station|
puts "[#{station.id}] #{station.name}"
end
puts "\n\n"
end
def add_station_to_line
view_lines
puts "Enter the line you would like to add a station to."
line_choice= gets.chomp.to_i
current_line = Line.find(line_choice)
view_stations
puts "Choose a station to add to the line"
station_choice = gets.chomp.to_i
current_line.add_station(station_choice)
puts "Added.\n\n"
view_by_line(line_choice)
end
main_menu
| true |
6c2240904913268868ef17ddc611c3d16a988bac | Ruby | skibox/Ruby-LearnEnough | /hello_app.rb | UTF-8 | 455 | 3.109375 | 3 | [] | no_license | require 'sinatra'
require './day.rb'
get '/' do
DAYNAMES = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"]
dayname = DAYNAMES[Time.now.wday]
"Happy #{dayname}."
end
get '/date' do
dayname = Date::DAYNAMES[Time.now.wday]
"Hello, world! Happy #{dayname}."
end
get '/dupa8' do
"Hello, world! Happy #{day_of_the_week(Time.now)} - from the file"
end
get '/greeting' do
greeting(Time.now)
end
| true |
7f38d4caeedc9329bca4b55730ca51ef73a08b86 | Ruby | traviswalkerdev/launch-school-ruby-basics | /loops2/ex6_empty_the_array.rb | UTF-8 | 337 | 3.78125 | 4 | [] | no_license | names = ['Sally', 'Joe', 'Lisa', 'Henry']
loop do
puts names.shift
break if names.size == 0
end
# Our solution prints the names from first (Sally) to last (Henry).
# Can you change this to print the names from last to first?
puts
names = ['Sally', 'Joe', 'Lisa', 'Henry']
loop do
puts names.pop
break if names.size == 0
end
| true |
8b5fb82547e13daa574496e9fab5240c91ba108e | Ruby | zstearman3/prophet-ratings | /app/services/basketball_calculations/calculations.rb | UTF-8 | 719 | 2.6875 | 3 | [] | no_license | module BasketballCalculations
module Calculations
def calculated_two_pt_percentage
(two_pt_made.to_f / two_pt_attempted.to_f).round(5)
end
def calculated_three_pt_percentage
(three_pt_made.to_f / three_pt_attempted.to_f).round(5)
end
def calculated_free_throws_percentage
(free_throws_made.to_f / free_throws_attempted.to_f).round(5)
end
def calculated_possessions
(field_goals_attempted.to_f - offensive_rebounds.to_f + turnovers.to_f +
( 0.475 * free_throws_attempted.to_f )).round(1)
end
# class << self
# calculate_shooting_percentage(attempts, makes)
# (makes.to_f / attempts.to_f).round(5)
# end
# end
end
end
| true |
44650d5383dbc0448d0a3bfc33b67acbd9623dfe | Ruby | dantelove/109_general_programming | /review/small_problems_3/8_easy8/easy8_4.rb | UTF-8 | 1,061 | 4.53125 | 5 | [] | no_license | # easy8_4.rb
# Write a method that returns a list of all substrings of a string. The
# returned list should be ordered by where in the string the substring begins.
# This means that all substrings that start at position 0 should come first,
# then all substrings that start at position 1, and so on. Since multiple
# substrings will occur at each position, the substrings at a given position
# should be returned in order from shortest to longest.
# You may (and should) use the substrings_at_start method you wrote in the
# previous exercise:
def substrings_at_start(string)
substring = string
results = []
n = -1
string.length.times do
results << substring
substring = substring.chop
end
results.reverse
end
def substrings(string)
results = []
string.length.times do
results << substrings_at_start(string)
string = string.reverse.chop.reverse
end
results.flatten
end
p substrings('abcde') == [
'a', 'ab', 'abc', 'abcd', 'abcde',
'b', 'bc', 'bcd', 'bcde',
'c', 'cd', 'cde',
'd', 'de',
'e'
] | true |
20953366bdef44b0c3e56b431a74c015ab84bff7 | Ruby | anhnguyenis/simple-checkout | /lib/item.rb | UTF-8 | 103 | 2.703125 | 3 | [] | no_license | class Item
attr_reader :price
def initialize
@price = 1
end
def scan
@price
end
end
| true |
4d95d7e408a5712453ef233fe0675c245e4dc096 | Ruby | changokun/project_euler_work | /089.rb | UTF-8 | 3,778 | 3.84375 | 4 | [] | no_license | require_relative 'functions.rb'
asset_file_name = '089_roman.txt'
class Integer
@@roman_numeral_values = {
M:1000,
D:500,
C:100,
L:50,
X:10,
V:5,
I:1
}
def self.parse_roman_numerals(roman_numerals)
roman_numerals.strip!
# puts @@roman_numeral_values.class
ret = 0
group_value = 0 # will be used inside loops
# puts roman_numerals
previous_roman_numeral = nil
for index in (0..(roman_numerals.length) -1) do
# puts index
roman_numeral = roman_numerals[index]
if index == roman_numerals.length
next_roman_numeral = nil
else
next_roman_numeral = roman_numerals[index+1]
end
# puts roman_numeral + ' ' + next_roman_numeral.to_s
if roman_numeral == previous_roman_numeral
group_value += @@roman_numeral_values[roman_numeral.to_sym]
else
# value will be added unless the next roman numeral is of a higher value.
if previous_roman_numeral && @@roman_numeral_values[previous_roman_numeral.to_sym] < @@roman_numeral_values[roman_numeral.to_sym]
# puts 'uh oh the next roman numeral is bigger: ' + roman_numeral
group_value *= -1
end
if group_value != 0
# puts 'group of ' + previous_roman_numeral + 's value: ' + group_value.to_s
ret += group_value
end
group_value = @@roman_numeral_values[roman_numeral.to_sym]
previous_roman_numeral = roman_numeral
end
end
# the last one is always added. this is somehoe not accoutned for above
if group_value != 0
# puts 'group of ' + previous_roman_numeral + 's value: ' + group_value.to_s
ret += group_value
end
return ret
end
def roman_numerals
# puts self.to_s + ' as roman numeral?'
ones = nil
tens = nil
hundreds = nil
thousands = nil
self.to_s.reverse.split('').each do | digit |
digit = digit.to_i
# puts digit
if ! ones
ones = digit
elsif ! tens
tens = digit
elsif ! hundreds
hundreds = digit
elsif ! thousands
thousands = digit
else
throw
end
end
# puts ones
# puts tens
# puts hundreds
# puts thousands
ret = ''
if thousands
thousands.times do
ret += 'M'
end
end
if hundreds
if hundreds == 9
ret += 'CM'
elsif hundreds >= 5
ret += 'D'
(hundreds - 5).times do
ret += 'C'
end
elsif hundreds == 4
ret += 'CD'
else
hundreds.times do
ret += 'C'
end
end
end
if tens
if tens == 9
ret += 'XC'
elsif tens >= 5
ret += 'L'
(tens - 5).times do
ret += 'X'
end
elsif tens == 4
ret += 'XL'
else
tens.times do
ret += 'X'
end
end
end
if ones
if ones == 9
ret += 'IX'
elsif ones >= 5
ret += 'V'
(ones - 5).times do
ret += 'I'
end
elsif ones == 4
ret += 'IV'
else
ones.times do
ret += 'I'
end
end
end
return ret
end
end
answer = 0
measure_time do
raw = File.read('assets/' + asset_file_name)
# puts raw
raw.lines do | line |
line.strip!
# puts line
line_value = Integer::parse_roman_numerals(line)
line_rewritten = line_value.roman_numerals
if line.length > line_rewritten.length
puts line + ' is ' + line_value.to_s + ' but should be written as ' + line_rewritten
answer += line.length - line_rewritten.length
end
end
puts "\n\n-----------\n" + answer.to_s + ' characters saved.'
end
| true |
875a53ceaf65aa73e8ec75b1be030f8c7c7d0366 | Ruby | bgwm/Project | /testingField/interview/test.rb~ | UTF-8 | 129 | 3.25 | 3 | [] | no_license | #!/usr/bin/ruby
class MyClass
def myMethod()
puts "TEST:MyClass.myMethod"
end
end
myClass = MyClass.new
myClass.myMethod()
| true |
835487e4f4631cec29c33269446ec361fed84296 | Ruby | paigewilliams/favorite-things-list | /spec/project_spec.rb | UTF-8 | 3,001 | 3.0625 | 3 | [] | no_license | require('pry')
require('rspec')
require('project')
describe("Item")do
before() do
Item.clear()
end
describe(".all")do
it("ensures that the list is empty in the beginning")do
expect(Item.all()).to(eq([]))
end
end
describe("#add")do
it("saves items to list")do
first_item = Item.new("bunnies", 1)
first_item.add(first_item.name, first_item.rank)
expect(Item.all()).to(eq([["bunnies", 1, 0]]))
end
end
describe("#add")do
it("allows us to access the rank of each item")do
item = Item.new("bunnies", 1)
expect(item.rank).to(eq(1))
end
end
describe("#add")do
it("allows us to access the name of each item")do
item = Item.new("bunnies", 1)
expect(item.name).to(eq("bunnies"))
end
end
describe("#add")do
it("allows us to access the id of each item")do
item = Item.new("bunnies", 1)
expect(item.id).to(eq(0))
end
end
describe("#add")do
it("creates a unique id for each item")do
first_item = Item.new("bunnies", 1)
first_item.add(first_item.name, first_item.rank)
second_item = Item.new("dogs", 2)
second_item.add(second_item.name, second_item.rank)
expect(Item.all()).to(eq([["bunnies", 1, 0], ["dogs", 2, 1]]))
end
end
describe(".find")do
it("finds an item based off of the unique ID")do
first_item = Item.new("bunnies", 1)
first_item.add(first_item.name, first_item.rank)
expect(Item.find(0)).to(eq(["bunnies", 1, 0]))
end
end
describe(".delete")do
it("deletes an item based on the ID")do
first_item = Item.new("bunnies", 1)
first_item.add(first_item.name, first_item.rank)
second_item = Item.new("dogs", 2)
second_item.add(second_item.name, second_item.rank)
expect(Item.delete(0)).to(eq([["dogs", 2, 1]]))
end
end
describe(".sort_by_rank")do
it("sorts items based on the rank")do
first_item = Item.new("bunnies", 5)
first_item.add(first_item.name, first_item.rank)
second_item = Item.new("dogs", 2)
second_item.add(second_item.name, second_item.rank)
expect(Item.sort_by_rank).to(eq([["dogs", 2, 1], ["bunnies", 5, 0]]))
end
end
describe(".sort_by_id")do
it("sorts items based on ID")do
first_item = Item.new("bunnies", 5)
first_item.add(first_item.name, first_item.rank)
second_item = Item.new("dogs", 2)
second_item.add(second_item.name, second_item.rank)
expect(Item.sort_by_id).to(eq([["bunnies", 5, 0], ["dogs", 2, 1]]))
end
end
describe(".exist?")do
it("returns true if an item already exists")do
first_item = Item.new("bunnies", 5)
first_item.add(first_item.name, first_item.rank)
expect(Item.exist?("bunnies")).to(eq(true))
end
end
describe("#update")do
it("updates an item's name and rank based on user input")do
first_item = Item.new("bunnies", 5)
first_item.add(first_item.name, first_item.rank)
Item.update("frog", 4, 0)
expect(Item.all()).to(eq([["frog", 4, 0]]))
end
end
end
| true |
c95d9a3dac33e6901895e709acd0d555cf8f3101 | Ruby | jfiander/bps | /app/lib/bps/pdf/roster/detailed/helpers.rb | UTF-8 | 3,951 | 2.59375 | 3 | [] | no_license | # frozen_string_literal: true
module BPS
module PDF
class Roster
class Detailed
CONFIG_TEXT = YAML.safe_load(
Rails.root.join('app/lib/bps/pdf/roster/detailed/text.yml').read
).deep_symbolize_keys!
module Helpers
def config_text
CONFIG_TEXT
end
def body_text(string, align: :justify)
text(
string.to_s,
size: BPS::PDF::Roster::Detailed::BODY_REG_SIZE, align: align, inline_format: true
)
end
def regular_header
bounding_box([0, 560], width: 325, height: 15) do
text(
"America's Boating Club – Birmingham Squadron",
size: BPS::PDF::Roster::Detailed::SECTION_TITLE_SIZE, style: :bold,
align: :center, color: 'BF0D3E'
)
stroke_line([0, 0], [325, 0])
end
end
def footer
bounding_box([0, -10], width: 325, height: 25) do
copyright
stroke_line([0, 30], [325, 30])
end
bounding_box([285, -10], width: 40, height: 25) do
text(
"Page #{page_number}", size: BPS::PDF::Roster::Detailed::BODY_SM_SIZE, align: :right
)
end
end
def copyright
text(
'Copyright © 2018 – Birmingham Power Squadron',
size: BPS::PDF::Roster::Detailed::BODY_SM_SIZE, align: :center
)
text(
'Member Use Only – Commercial Use Prohibited',
size: BPS::PDF::Roster::Detailed::BODY_SM_SIZE, align: :center, style: :italic
)
end
def header_footer
regular_header
footer
end
def formatted_page
start_new_page
yield
header_footer
end
def intro_block(heading, message, height)
sec_title_size = BPS::PDF::Roster::Detailed::SECTION_TITLE_SIZE
bounding_box([0, 540], width: 325, height: height) do
text heading, size: sec_title_size, style: :bold, align: :center
move_down(10)
text message, size: BPS::PDF::Roster::Detailed::BODY_REG_SIZE, align: :justify
end
end
def roster_entry(user_data, y_offset: 0)
bounding_box([0, 530 - y_offset], width: 325, height: 90) do
roster_entry_left(user_data[:left])
roster_entry_column(user_data[:middle], 155, 80)
roster_entry_column(user_data[:right], 235, 90)
end
end
def roster_entry_left(user_data)
bounding_box([0, 90], width: 155, height: 90) do
user_data.each_with_index do |field, index|
roster_entry_left_contents(field, index)
end
end
end
def roster_entry_left_contents(field, index)
index.zero? ? roster_entry_left_first(field) : body_text(field, align: :left)
end
def roster_entry_left_first(field)
roster_entry_name(field)
move_down(12)
end
def roster_entry_column(user_data, x_pos, width)
bounding_box([x_pos, 90], width: width, height: 90) do
user_data.each { |field| body_text(field, align: :left) }
end
end
def roster_entry_name(name)
Prawn::Text::Formatted::Box.new(
format_name(name),
overflow: :shrink_to_fit, style: :bold, width: 145, height: 15,
size: BPS::PDF::Roster::Detailed::HEADING_SIZE, document: self
).render
end
def halve(collection)
collection.each_slice((collection.size / 2.0).round).to_a
end
end
end
end
end
end
| true |
63be474bfd9d44cc691d196f3f9c15da069e6cca | Ruby | haozeng/exercises | /patterns/template_pattern.rb | UTF-8 | 580 | 2.6875 | 3 | [] | no_license | class HR
def hire
phone_interview
onsite_interview
follow_up
end
def phone_interview
end
def onsite_interview
end
def follow_up
end
end
class TechHR < HR
def phone_interview
puts 'do this'
end
def onsite_interview
puts 'do this'
end
def follow_up
puts 'do this'
end
end
class MarketingHR < HR
def phone_interview
puts 'do that'
end
def onsite_interview
puts 'do that'
end
def follow_up
puts 'do that'
end
end
tech_hr = TechHR.new
tech_hr.hire
marketing_hr = MarketingHR.new
marketing_hr.hire
| true |
417a80cc1ee7f458d8ac8599300e6884ba48f8db | Ruby | myfreecomm/ecommerce-client-ruby | /lib/ecommerce/resources/adjustment_order.rb | UTF-8 | 2,764 | 2.734375 | 3 | [
"MIT"
] | permissive | module Ecommerce
module Resources
#
# A wrapper to Ecommerce adjusments orders API
#
# [API]
# Documentation: http://myfreecomm.github.io/passaporte-web/ecommerce/api/index.html
#
class AdjustmentOrder < Base
attr_reader :url, :amount, :description, :valid_until, :valid_from
#
# Adjustment order API does not return the ID field
#
def id
url.split('/')[8].to_i
end
#
# Creates an Adjustment order
#
# [API]
# Method: <tt>POST /api/orders/:slug/:id/adjustments/</tt>
#
# Documentation: http://myfreecomm.github.io/passaporte-web/ecommerce/api/orders.html#criacao-de-alteracao-de-valor-para-uma-ordem-de-compra
#
def self.create(slug, order_id, params)
client.post("/api/orders/#{slug}/#{order_id}/adjustments/", body: params) do |response|
build(response)
end
end
#
# Lists all Adjustments orders of an order and return a collection
# and pagination information (represented by Ecommerce::Resources::AdjustmentOrderCollection)
#
# [API]
# Method: <tt>GET /api/orders/:slug/adjustments/</tt>
#
# Documentation: http://myfreecomm.github.io/passaporte-web/ecommerce/api/orders.html#listagem-das-alteracoes-de-valor-associadas-a-uma-ordem-de-compra
#
def self.find_all(slug, order_id, page = 1, limit = 20)
body = { page: page, limit: limit }
client.get("/api/orders/#{slug}/#{order_id}/adjustments/", body: body) do |response|
Ecommerce::Resources::AdjustmentOrderCollection.build(response)
end
end
#
# Finds an Adjustment order
#
# [API]
# Method: <tt>GET /api/orders/:slug/:order_id/adjustments/:id/</tt>
#
# Documentation: http://myfreecomm.github.io/passaporte-web/ecommerce/api/orders.html#obtencao-dos-dados-de-uma-alteracao-de-valor
#
def self.find(slug, order_id, id)
client.get("/api/orders/#{slug}/#{order_id}/adjustments/#{id}/") do |response|
build(response)
end
end
#
# Destroys an Adjustment order
#
# [API]
# Method: <tt>DELETE /api/orders/:slug/:order_id/adjustments/:id/</tt>
#
# Documentation: http://myfreecomm.github.io/passaporte-web/ecommerce/api/orders.html#remocao-de-uma-alteracao-de-valor
#
def self.destroy(order_id, slug, id)
client.delete("/api/orders/#{slug}/#{order_id}/adjustments/#{id}/") do |response|
build(response)
end
end
def self.build(response)
attributes = parsed_body(response)
attributes.empty? ? {} : new(attributes)
end
end
end
end
| true |
e2e57c472656a4dc2a9c1bdcaf807ce70e21d63c | Ruby | ecksma/wdi-darth-vader | /04_ruby/ruby_examples/ruby_method_args_with_splat.rb | UTF-8 | 281 | 3.40625 | 3 | [] | no_license | # the SPLAT *
# usage with args
# just like the JS function's arguments array
def headache(*args)
args.each do |argument|
puts "This argument: " + argument.to_s
end
end
def favourite_cities(*args)
args.each do |city|
puts 'I love the following city: ' + city
end
end
| true |
b8babf1d94a4a811f2e50c8ce847f37e237f8c4b | Ruby | amyequinn/looping-while-until-london-web-051319 | /lib/while.rb | UTF-8 | 113 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_while
levitation_force = 6
while levitation_force < 10
puts "Wingardium Leviosa"
levitation_force +=1
end
end
| true |
fc6093ecf929eeafc070772ed3aeab5ddf3ecfe9 | Ruby | abhishekgaire/Practice-Ruby-Beginner-noob | /22.rb | UTF-8 | 176 | 3.453125 | 3 | [] | no_license | def name()
names =[]
begin
puts "enter naam"
naam = gets
names << naam
puts "another naam?"
answer = gets.chomp
end while answer == "y"
puts names.sort
end
name()
| true |
29c998e143e99e5e87e91a304733cd13f9dc8d7b | Ruby | ConnorChristie/twit-stocks | /driver.rb | UTF-8 | 2,916 | 2.890625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require_relative 'lib/twit-stocks/twitter_engine.rb'
require_relative 'lib/twit-stocks/predictor.rb'
require_relative 'lib/twit-stocks/market.rb'
require_relative 'lib/twit-stocks/boost.rb'
puts "Starting to predict stocks..."
start_day = "2014-05-30"
end_day = "2014-06-04" # during this split, apple's stock ris
start_day_2 = "2014-05-26"
end_day_2 = "2014-06-01" # during this split, time warner's stock fal
start_day_3 = "2014-05-26"
end_day_3 = "2014-06-02" # during this split, broadcom's stock ris
start_day_4 = "2014-05-30"
end_day_4 = "2014-06-02" # during this split, gamestop's stock fal
start_day_5 = "2014-06-03"
end_day_5 = "2014-06-04" # this split represents the past we
learning_rate = 0.5
expected_value = 1
momentum_rate = 0.3
hidden_nodes = 20
stocks = [:AAPL, :AAPL, :AAPL, :AAPL, :GOOG, :ADBE, :BRCM, :BRCM, :TWX,
:HAS, :GME, :WYNN, :UA, :NFLX, :T, :CMCSK, :CMCSA, :CVX,
:CSCO, :BA]
search_terms = ["apple", "iphone", "ipad", "macbook",
"googleglass", "adobe", "broadcom", "baseband", "time warner",
"hasbro", "gamestop", "wynn",
"under armor", "netflix", "at&t", "comcast", "comcast", "chevron",
"cisco", "boeing"
]
#stocks = [:AAPL, :GOOG, :ADBE, :BRCM, :TWX,
# :HAS, :GME, :WYNN, :UA, :NFLX, :T, :CMCSK, :CMCSA, :CVX,
# :CSCO, :BA]
#search_terms = ["apple",
# "google", "adobe", "broadcom", "time warner",
# "hasbro", "gamestop", "wynn",
# "under armor", "netflix", "at&t", "comcast", "comcast", "chevron",
# "cisco", "boeing"
#]
boost = Boost.new(stocks.length)
twitter = TwitterEngine.new
puts "begin training neural networks..."
if !ARGV[2].nil? && ARGV[2].eql?("read") then
features = Array.new
stocks.each_with_index do |stock, index|
features << twitter.read_features(stock)
end
puts "reading from recorded tweets..."
boost.train_with_features(stocks, features, start_day, end_day, hidden_nodes, learning_rate, momentum_rate)
else
puts "pulling tweets from twitter..."
boost.train_twice_and_weight(stocks, search_terms, start_day_5, end_day_5, hidden_nodes, learning_rate, momentum_rate)
stocks.each_with_index do |stock, index|
twitter.record_features(boost.predictors[index].features, stock)
end
end
term = ARGV[0]
my_stock = ARGV[1]
twitter = TwitterEngine.new
tweets = twitter.get_tweets(term, "recent")
new_features = twitter.get_features(tweets)
twitter.print_features(new_features)
result = boost.hypothesis(new_features)
market = Market.new
quotes = market.get_prices(my_stock, "2014-06-03", "2014-06-04")
# quotes = market.get_endprices(my_stock, "2014-06-04", "2014-06-04")
# quotes << market.opening_price(my_stock)
# quotes << market.last_trade_real_time(my_stock)
delta = quotes[1].to_f - quotes[0].to_f
puts "predicting on #{ARGV[0]} with stock label #{ARGV[1]}"
puts quotes
puts "delta: " + delta.to_s
puts "classification: " + result.to_s
puts "discrete value: " + (result - 0.5).to_s
| true |
98695ec33154a12df2460399f49e8f9c7dfd1fe5 | Ruby | edwardloveall/absalom-reckoning | /spec/models/calendar_spec.rb | UTF-8 | 1,404 | 2.515625 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe Calendar do
describe 'associations' do
it { should have_many(:events).dependent(:destroy) }
it { should have_many(:invitations).dependent(:destroy) }
it { should have_many(:permissions).dependent(:destroy) }
it { should have_many(:users).through(:permissions) }
end
describe 'validations' do
it { should validate_presence_of(:current_date) }
it { should validate_presence_of(:title) }
it { should validate_length_of(:title).is_at_most(100) }
end
describe '#events_for_month()' do
it 'returns events based on an input date for a calendar' do
date = ArDate.new(year: 4711, month: 1, day: 1)
calendar = create(:calendar)
non_date = ArDate.new(year: 4711, month: 5, day: 1)
before_date = ArDate.new(year: 4710, month: 12, day: 31)
during_date = ArDate.new(year: 4711, month: 1, day: 15)
after_date = ArDate.new(year: 4711, month: 2, day: 1)
create(:event, occurred_on: non_date, calendar: calendar)
before = create(:event, occurred_on: before_date, calendar: calendar)
during = create(:event, occurred_on: during_date, calendar: calendar)
after = create(:event, occurred_on: after_date, calendar: calendar)
events = [before, during, after]
result = calendar.events_for_month(around: date)
expect(result).to match_array(events)
end
end
end
| true |
1bb69921356e05018616815766ee224a1ccf3c10 | Ruby | Alex808r/thinknetica | /ruby_basics_8/main.rb | UTF-8 | 9,393 | 3.484375 | 3 | [] | no_license | # frozen_string_literal: true
require_relative 'railway_station'
require_relative 'route'
require_relative 'train'
require_relative 'cargo_wagon'
require_relative 'cargo_train'
require_relative 'passenger_wagon'
require_relative 'passenger_train'
require_relative 'wagon'
require_relative 'validation_error'
class Main
def initialize
@stations = []
@trains = []
@routes = []
end
def user_choice
print_main_menu
loop do
puts '*** *** ***'
print 'Введите номер команды =>: '
user_input = gets.strip
case user_input
when '0' then break
when '1' then create_railway_station
when '2' then create_train
when '3' then create_route
when '4' then change_route
when '5' then set_route_to_train
when '6' then join_a_wagon
when '7' then delete_a_wagon
when '8' then move_next_station
when '9' then move_back_station
when '10' then show_stations_list
when '11' then show_trains_list
when '12' then show_trains_list_to_station
when '13' then show_routes_list
when '14' then show_the_wagons_by_the_train
when '15' then take_place
end
end
end
private
def print_main_menu
main_menu = [
'0 выход из программы',
'1 Создать станцию',
'2 Создать поезд',
'3 Создать маршрут',
'4 Редактировать маршурт(добавить / удалить станцию)',
'5 Назначить маршрут поезду',
'6 Добавить вагон к поезду',
'7 Отцепить вагон от поезда',
'8 Переместить поезд по маршруту вперед',
'9 Переместить поезд по маршруту назад',
'10 Посмотреть список станций',
'11 Посмотреть весь список поездов',
'12 Посмотреть список поездов на станции',
'13 Посмотреть список маршрутов',
'14 Посмотреть список вагонов у поезда',
'15 Занять место в вагоне'
]
main_menu.each { |menu| puts menu }
end
def create_railway_station
begin
print 'Введите наименование станции: '
name = gets.strip.capitalize
@stations.push(RailwayStation.new(name))
rescue ValidationError => e
puts e
retry
end
puts "Создана станция: #{@stations.last.name}"
@stations.last
end
def create_train
# count = 0
begin
puts 'Требования к номеру поезда три буквы или цифры в любом порядке, необязательный дефис' \
'(может быть, а может нет) и еще 2 буквы или цифры после дефиса'
print 'Введите номер поезда: '
number = gets.strip
print 'Введите тип поезда(1 - cargo / 2 - passenger): '
type = gets.strip
type == '1' ? @trains.push(CargoTrain.new(number)) : @trains.push(PassengerTrain.new(number))
rescue ValidationError => e
puts e
# count += 1
retry # if count < 3
end
puts "Создан поезд #{@trains.last}"
@trains.last
end
def stations_list(stations)
stations.each_with_index do |station, index|
puts "Индекс станции: #{index} | Наименование станции: #{station.name}"
end
end
def show_stations_list
stations_list(@stations)
end
def trains_list
@trains.each_with_index do |train, index|
puts "Индекс: #{index} | Поезд: #{train}"
# @trains
end
end
def show_trains_list
trains_list
end
def show_trains_list_to_station
station = select_station
puts "На выбранной станции #{station} следующие поезда"
# Вариант без передачи блока в метод
# station.list_train.each do |train|
# puts "Номер поезда #{train.train_number} тип поезда #{train.type_of_train}"
# end
# Вариант с передачей блока в метод trains_to_station
station.trains_to_station do |train, index|
puts "Индекс #{index} | Номер #{train.train_number} Тип #{train.type_of_train}"
end
end
def create_route
if @stations.size >= 2
"Списко всех станций: #{stations_list(@stations)}"
print 'Введите начальную станцию(индекс): '
first_station = gets.to_i
print 'Введите конечную станцию(индекс): '
last_station = gets.to_i
@routes.push(Route.new(@stations[first_station], @stations[last_station]))
@routes.last
else
puts 'У вас должно быть минимум 2 станции, чтобы создать маршрут'
nil
end
end
def select_route
@routes.each_with_index do |route, index|
puts "Индекс маршртуа #{index} | Начальная: #{route.first_station.name} Конечная: #{route.last_station.name}"
end
print 'Введите индекс маршрута: '
@routes[gets.strip.to_i]
end
def change_route
route = select_route
puts '1 - добавить / 2 - удалить'
user_choice = gets.strip.to_i
if user_choice == 1
add_station_to_route(route)
else
delete_station_to_route(route)
end
end
def show_routes_list
puts 'Все созданные маршруты'
@routes.each_with_index do |routes, index|
puts "Индекс маршрута: #{index} | Начальная: #{routes.first_station.name} Конечная: #{routes.last_station.name}"
end
end
def add_station_to_route(route)
route.add_station(select_station)
# puts "Маршрут после изменеия "
# stations_list(route.stations)
end
def delete_station_to_route(route)
if route.stations.count <= 2
puts 'Маршрут состоит из 2 станций их нельзя удалить'
nil
else
puts 'Какую станцию удалить?'
stations_list(route.stations)
route.delete_station(route.stations[gets.strip.to_i])
# puts "Маршрут после изменеия "
# stations_list(route.stations)
end
end
def select_station
@stations.each_with_index do |station, index|
puts "Номер станции #{index} название станции #{station.name}"
end
print 'Введите номер станции: '
@stations[gets.strip.to_i]
end
def select_train
@trains.each_with_index do |train, index|
puts "Индекс поезда #{index} | поезд #{train}"
end
print 'Введите индекс поезда: '
@trains[gets.strip.to_i]
end
def set_route_to_train
if @trains.empty? || @routes.empty?
puts 'У вас нет поезда или маршрута'
nil
else
select_train.take_route(select_route)
end
end
def join_a_wagon
train = select_train
puts 'Введите номер вагона'
number_wagon = gets.strip
puts train.type_of_train == 'cargo' ? 'Введите объем грузового вагона ' : 'Введите количество мест '
place_or_volume = gets.strip
case train.type_of_train
when 'cargo' then train.take_wagon(CargoWagon.new(number_wagon, place_or_volume))
when 'passenger' then train.take_wagon(PassengerWagon.new(number_wagon, place_or_volume))
end
end
def delete_a_wagon
train = select_train
if train.wagons.empty?
puts 'У поезда нет вагонов'
nil
else
train.drop_wagon
puts train.wagons.to_s
end
end
def show_the_wagons_by_the_train
train = select_train
train.wagons_to_train do |wagon, index|
if wagon.type == 'cargo'
puts "Индекс вагона #{index} | Номер #{wagon.number_wagon} Тип #{wagon.type}" \
" Объем вагона #{wagon.volume_wagon} занято #{wagon.occupied_volume}"
else
puts "Индекс вагона #{index} | Номер #{wagon.number_wagon} Тип #{wagon.type}" \
" Мест в вагоне #{wagon.number_of_seats} из них занято #{wagon.occupied_place}"
end
end
end
def select_wagon(train)
train.wagons.each_with_index do |wagon, index|
puts "Индекс #{index} | Номер #{wagon.number_wagon}"
end
print 'Введите индекс вагона '
train.wagons[gets.strip.to_i]
end
def take_place
train = select_train
wagon = select_wagon(train)
if train.type_of_train == 'cargo'
puts 'Какой объем занять? '
wagon.take_up_volume(gets.strip.to_i)
else
puts 'Занято одно место '
wagon.take_the_place
end
end
def move_next_station
select_train.move_forward
end
def move_back_station
select_train.move_bakward
end
end
Main.new.user_choice
| true |
956aa415cd22b5897000df1a3497145fd9937911 | Ruby | afalone/test_gem | /lib/test_gem/num.rb | UTF-8 | 190 | 2.625 | 3 | [
"MIT"
] | permissive | class TestGem::Num
attr_reader :value, :key
def initialize(value)
@value = value
@key = format('%s%s', '0' * (1000 - value.length), value)
end
def to_s
value
end
end
| true |
3eb289cf295c26d41b9e2219b191593deeef1946 | Ruby | pr0d1r2/breach-mitigation-rails | /lib/breach_mitigation/masking_secrets.rb | UTF-8 | 2,417 | 2.765625 | 3 | [
"MIT"
] | permissive | module BreachMitigation
class MaskingSecrets
class << self
AUTHENTICITY_TOKEN_LENGTH = 32
# Sets the token value for the current session and returns it in
# a masked form that's safe to send to the client. See section
# 3.4 of "BREACH: Reviving the CRIME attack".
def masked_authenticity_token(session)
one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
encrypted_csrf_token = xor_byte_strings(one_time_pad, real_csrf_token(session))
masked_token = one_time_pad + encrypted_csrf_token
Base64.strict_encode64(masked_token)
end
# Checks the client's masked token to see if it matches the
# session token. Essentially the inverse of
# +masked_authenticity_token+.
def valid_authenticity_token?(session, encoded_masked_token)
return false if encoded_masked_token.nil? || encoded_masked_token.empty?
masked_token = Base64.strict_decode64(encoded_masked_token)
# See if it's actually a masked token or not. In order to
# deploy this code, we should be able to handle any unmasked
# tokens that we've issued without error.
if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
# This is actually an unmasked token
Rails.logger.warn "WARNING: the client is using an unmasked authenticity token. This is expected if you have just upgraded to masked tokens, but if these messages continue long after the upgrade, then something fishy is going on."
masked_token == real_csrf_token(session)
elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
# Split the token into the one-time pad and the encrypted
# value and decrypt it
one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
csrf_token = xor_byte_strings(one_time_pad, encrypted_csrf_token)
csrf_token == real_csrf_token(session)
else
false # Token is malformed
end
end
private
def real_csrf_token(session)
session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
Base64.strict_decode64(session[:_csrf_token])
end
def xor_byte_strings(s1, s2)
s1.bytes.zip(s2.bytes).map { |(c1,c2)| c1 ^ c2 }.pack('c*')
end
end
end
end
| true |
f912f4c73d2ae2840866e2cb6ec0507702c5a096 | Ruby | AlvaroTovarDev/sei40 | /week10/burning-airlines-immersive/ba-rails-backend/db/seeds.rb | UTF-8 | 2,219 | 3.0625 | 3 | [] | no_license |
User.destroy_all
print "Creating users... "
u1 = User.create! name: 'Test User 1', email: 'one@one.com', password: 'chicken'
u2 = User.create! name: 'Test User 2', email: 'two@two.com', password: 'chicken'
u3 = User.create! name: 'Test User 3', email: 'three@three.com', password: 'chicken'
puts "created #{User.count} users."
Airplane.destroy_all
print "Creating airplanes... "
a1 = Airplane.create! name: '737', rows: 40, cols: 6
a2 = Airplane.create! name: '737 MAX', rows: 80, cols: 8
puts "created #{Airplane.count} airplanes."
Flight.destroy_all
print "Creating flights... "
f1 = Flight.create! flight_number: 'BA256', departure_date: '2021-10-01 04:20', origin: 'SYD', destination: 'MEL', airplane_id: a1.id
f2 = Flight.create! flight_number: 'BA512', departure_date: '2021-10-02 11:20', origin: 'SYD', destination: 'MEL', airplane_id: a1.id
f3 = Flight.create! flight_number: 'BA1024', departure_date: '2021-10-03 16:20', origin: 'SYD', destination: 'SIN', airplane: a2
puts "created #{Flight.count} flights"
Reservation.destroy_all
print "Creating reservations... "
r1 = Reservation.create! flight_id: f1.id, user_id: u1.id, row: 10, col: 2
r2 = Reservation.create! flight: f1, user: u2, row: 10, col: 3
r3 = Reservation.create! flight: f1, user: u3, row: 10, col: 4
r4 = Reservation.create! flight: f2, user: u3, row: 15, col: 1
puts "created #{Reservation.count} reservations."
puts
puts "Association tests:"
puts "Airplane #1 has #{Airplane.first.flights.length} flights (should be 2)"
# You can automatically create an error if you don't get the right answer here!
# (Like JS "throw new Error('abc')")
raise Exception.new('Airplane flights association broken') if Airplane.first.flights.length != 2
# expect( Airplane.first.flights.length ).to eq 2
puts "Flight #1 has #{Flight.first.reservations.length} reservations (should be 3)"
puts "User #3 has #{User.third.reservations.length} reservations (should be 2)"
puts "Flight #1 has airplane name #{Flight.first.airplane.name} (should be '737')"
puts "Reservation #1 has user name #{Reservation.first.user.name} (should be 'Test User 1')"
puts "Reservation #1 has flight number #{Reservation.first.flight.flight_number} (should be 'BA256')"
puts
puts "Done."
| true |
cffc9199a625a255d94816fea4bfbe34822fe660 | Ruby | chlorox416/ruby-oo-relationships-practice-art-gallery-exercise | /tools/console.rb | UTF-8 | 865 | 2.953125 | 3 | [] | no_license | require_relative '../config/environment.rb'
art1 = Artist.new("monet", 10)
art2 = Artist.new("van goh", 20)
art3 = Artist.new("ai", 15)
gallery1 = Gallery.new("sunjet", "new york")
gallery2 = Gallery.new("moon gallery", "brooklyn")
# painting1 = Painting.new(title, price, artist, gallery)
art1.create_painting("starry night", 10, gallery1)
art1.create_painting("blah", 106, gallery1)
art1.create_painting("hello", 103, gallery1)
art1.create_painting("ok", 100, gallery1)
art2.create_painting("david", 102120, gallery1)
art2.create_painting("blah2", 106, gallery1)
art2.create_painting("hello2", 103, gallery1)
art2.create_painting("ok2", 100, gallery1)
art3.create_painting("aaa", 101, gallery1)
art3.create_painting("bbb", 1016, gallery1)
art3.create_painting("ccc", 1013, gallery1)
art3.create_painting("ddd", 1010, gallery1)
binding.pry
puts "Bob Ross rules."
| true |
973e5d094f64e56bd0a02943211b65daf156628a | Ruby | feldpost/bitch_slap | /slap.rb | UTF-8 | 1,134 | 2.671875 | 3 | [] | no_license | class Slap
attr_accessor :sender, :message
ONE_HOUR = 3600 #seconds
def self.create( message )
sender = message.sender.screen_name
message = message.to_s
slap = Slap.new(sender,message)
slap.save
return slap
end
def initialize( sender, message )
@sender = sender
@message = message
@exists = storage.has_key?(sender)
end
def valid?
!exists? && valid_message?
end
def valid_message?
message.match(/@([0-9a-z_]+)/i)
end
def exists?
@exists
end
def outgoing_message
if exists?
d sender, "Steady on there old bean - only once an hour. Try again tomorrow."
elsif not valid?
d sender, "We're all about behavior modification and noticed that you didn't target your last note. Try again."
else
message
end
end
def save
return false unless valid?
storage.store(sender, message, :expires_in => ONE_HOUR)
end
private
def d( recipient, text )
"d #{recipient} #{text}"
end
def storage
@storage ||= Moneta::DataMapper.new(:setup => "sqlite3:///#{File.join(Dir.pwd,'data','slaps.db')}")
end
end | true |
80156845d44f7250fc4e1594e0ef3e0f630835ed | Ruby | griffithchaffee/active_record_seek | /lib/active_record_seek/middleware.rb | UTF-8 | 521 | 2.734375 | 3 | [
"MIT"
] | permissive | module ActiveRecordSeek
class Middleware
attr_accessor(*%w[ name middleware_block ])
def initialize(name:, &middleware_block)
raise(ArgumentError, "#{self.class} expects a block") if !middleware_block
self.name = name.to_s
self.middleware_block = middleware_block
self.class.middleware.push(self)
end
def call(*params, &block)
middleware_block.call(*params, &block)
end
class << self
def middleware
@middleware ||= []
end
end
end
end
| true |
2a24e85bb0f9907a51f84d4e2364fbd3c8f6538f | Ruby | rlishtaba/rb_scope | /lib/rb_scope/api/niScope_values.rb | UTF-8 | 1,149 | 2.578125 | 3 | [] | no_license | module RbScope
module API
# This module reads the file rb_scope/niScope_pairs
# and use the information inside to automatically generate constants
# with values equivalent to the niScope.h #define macro constants.
# The file rb_scope/niScope_pairs is automatically generated by the
# shell script extract_all.sh in ext/rb_scope/generators
module Values
Hash.new.tap{ |pairs|
file_name = File.dirname(__FILE__) + '/niScope_pairs.const'
File.open(file_name, 'r').readlines.tap do |lines|
pairs[lines.shift] = lines.shift until lines.empty?
end
}.each{ |k,v|
begin
self.const_set k.chomp, eval(v) #don't forget to chomp line
rescue Exception => e
#puts "eval error for value %s" % k
end
}
#for safety, redefine these
VI_SUCCESS = 0
VI_NULL = 0
VI_TRUE = 1
VI_FALSE = 0
end
end
end
| true |
c83e6eb041a5c8f4bfd5371deb02d1a3574f65c0 | Ruby | maoueh/buildozer | /lib/buildozer/dsl/validator/package.rb | UTF-8 | 1,006 | 2.78125 | 3 | [
"MIT"
] | permissive | require 'buildozer/dsl/core/package'
require 'buildozer/dsl/exceptions'
module Buildozer
module Dsl
module Validator
class Package
##
# Receive a dsl package and validates that it is
# well-formed.
#
# For now, exceptions are raised when something is wrong.
def self.validate(package)
if not package.kind_of?(Dsl::Core::Package)
raise InvalidDslPackage, "Cannot validate, the argument received is not a dsl package"
end
options = package.options()
validate_architecture(options[:architecture]) if options[:architecture]
end
def self.validate_architecture(architecture)
if architecture == :auto or (architecture.kind_of?(String) and not architecture == "")
return
end
raise InvalidDslPackage, "Invalid package, architecture must be :auto or a non-empty String, currently [#{architecture}]"
end
end
end
end
end
| true |
74112600e67655c414f227e993c013e6b714b39d | Ruby | martinliptak/codility | /13-AbsDistinct.rb | UTF-8 | 143 | 2.8125 | 3 | [
"MIT"
] | permissive | # you can use puts for debugging purposes, e.g.
# puts "this is a debug message"
def solution(a)
a.map! { |e| e.abs }
a.uniq.count
end | true |
944950ce132a298726f5c2336564dd015b5c7d29 | Ruby | bdraco/redlink | /lib/redlink/location.rb | UTF-8 | 662 | 2.671875 | 3 | [
"MIT"
] | permissive | module Redlink
class Location < Redthing
attr_accessor :location_id, :name, :type, :country, :zip_code, :current_weather, :thermostats, :time_zone
def thermostats=(val)
@thermostats = val[:thermostat_info].map do |therm|
Thermostat.new(therm)
end
end
def thermostats
@thermostats
end
def current_weather=(val)
@current_weather = Weather.new(val)
end
def to_s
name
end
def self.all
@all ||= Endpoint.locations.map do |loc|
Location.new(loc)
end
end
def self.first
all[0]
end
def self.last
all[all.length - 1]
end
end
end
| true |
30742c5eb9b0821272d27b5ce0b3374354ffc5fb | Ruby | KeisukeMurata4210/EffectiveRuby | /chapter8/section_44.rb | UTF-8 | 3,001 | 3.21875 | 3 | [] | no_license | # Rubyのガベージコレクタは「マークアンドスウィープ」というプロセスを使っている
# ①オブジェクトグラフを辿って、コードから到達可能なオブジェクトにマークをつける(マークフェーズ)
# ②マークがつけられなかったオブジェクトを解放する(スウィープフェーズ)
# Ruby2.1では「世代別ガベージコレクタ」が導入された
# 1回のマークフェーズを生き延びたオブジェクトは「古いオブジェクト」
# 2回目以降で初めて出てきたオブジェクトは「新しいオブジェクト」
# ①マークフェーズが「メジャー」と「マイナー」の2種類に分かれる。メジャーは全てのオブジェクトにマークをつける、マイナーは新しいオブジェクトのみを対象とする
# ②スウィープフェーズも「即時モード」「遅延モード」の2つがある。「即時モード」はマークのない全てのオブジェクトを解放する
# Rubyのメモリプール:「ヒープ」←「ページ」←「スロット」 スロットがオブジェクト1つ分
GC.stat
{
:count=>10, # ガベージコレクタが合計10回実行された。
:heap_allocated_pages=>132,
:heap_sorted_length=>133, # ヒープに現在あるページ数
:heap_allocatable_pages=>0,
:heap_available_slots=>53803,
:heap_live_slots=>21627, # 今生きているオブジェクトの数
:heap_free_slots=>32176, # 使用済みオブジェクトの数
:heap_final_slots=>0,
:heap_marked_slots=>21225,
:heap_swept_slots=>32578,
:heap_eden_pages=>132,
:heap_tomb_pages=>0,
:total_allocated_pages=>132,
:total_freed_pages=>0,
:total_allocated_objects=>153003, # Rubyプログラムが起動してから作られたオブジェクトが153003個
:total_freed_objects=>131376, # Rubyプログラムが起動してから解放されたオブジェクトが131376個 ↑との差が今生きているオブジェクトの数
:malloc_increase_bytes=>10480,
:malloc_increase_bytes_limit=>16777216,
:minor_gc_count=>6, :major_gc_count=>4, # ガベージコレクタがマイナーモードで6回、メジャーモードで4回実行された
:remembered_wb_unprotected_objects=>257,
:remembered_wb_unprotected_objects_limit=>514,
:old_objects=>20815, :old_objects_limit=>41630, # 古いオブジェクトでマイナーマークフェーズでは処理されないものが20815個。若いオブジェクト=heap_live_slots - old_objects
:oldmalloc_increase_bytes=>10864,
:oldmalloc_increase_bytes_limit=>16777216
}
=begin
<この項目で気づいたこと・学んだこと>
・ヒープのなかのページに、スロットがあり、スロットに1つのオブジェクトが格納される。
・マークしてスウィープする
・古いオブジェクトはマイナーマークフェーズではスルーされる。
=end
| true |
002b9d7c917a0c6aab575a2abf5a5787987ff08d | Ruby | Mimioj101/ruby-project-alt-guidelines-nyc01-seng-ft-071320 | /lib/app/models/movie.rb | UTF-8 | 299 | 2.6875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Movie < ActiveRecord::Base
has_many :reviews
has_many :users, through: :reviews
# def movies
# Movie.all.each do |movie|
# puts movie.title
# end
#end
# def movies
# Movie.map{|movie| movie.title}
# end
end | true |
24d397fbe9bfe344a76bec43ff2d49b794df57fe | Ruby | isaacfinnegan/cmdb-client | /cmdbclient.rb | UTF-8 | 6,223 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | #!ruby
require 'net/http'
require 'net/https'
require 'rubygems'
require 'json'
class CMDBclient
@@mocked = false
def self.mock!
@@mocked = true
end
def initialize(opt)
@delegate = (@@mocked ? CMDBclient::Mock.new(opt) :
CMDBclient::Real.new(opt))
end
def delegate
@delegate
end
def dbg(msg)
if @opt.has_key? 'debug' and @opt['debug'] > 1
puts "DBG(CMDBclient): #{msg}"
end
end
def trim(s, c='/', dir=:both)
case dir
when :both
trim(trim(s, c, :right), c, :left)
when :right
s.sub(Regexp.new(c + '+/'), '')
when :left
s.sub(Regexp.new('^' + c + '+'), '')
end
end
def ltrim(s, c='/')
trim(s, c, :left)
end
def rtrim(s, c='/')
trim(s, c, :right)
end
def method_missing(meth, *args, &block)
@delegate.send(meth, *args, &block)
end
end
class CMDBclient::Real < CMDBclient
def initialize(opt)
@opt = opt
self.dbg "Initialized with options: #{opt.inspect}"
end
def do_request(opt={})
method = [:GET, :PUT].find do |m|
opt.has_key? m
end
method ||= :GET
rel_uri = opt[method]
url = URI.parse(@opt['cmdb']['url'])
url.path = rtrim(url.path) + '/' + ltrim(rel_uri)
url.query = opt[:query] if opt.has_key? :query
self.dbg("#{method.inspect} => #{url.to_s}")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl=true if url.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
reqclass = case method
when :GET
Net::HTTP::Get
when :PUT
Net::HTTP::Put
end
request = reqclass.new(url.request_uri)
self.dbg request.to_s
if @opt['cmdb'].has_key? 'username'
request.basic_auth(@opt['cmdb']['username'],
@opt['cmdb']['password'])
end
request.body = opt[:body].to_json if opt.has_key? :body
response = http.request(request)
self.dbg response.to_s
if response.code[0] != ?2
raise "Error making cmdb request (#{response.code}): " +
error_body(response.body)
end
if response.body
JSON.parse(response.body)
else
true
end
end
def query(type, *condlist)
do_request(:GET => "#{type}", :query => condlist.join('&'))
end
def key_field_of(type)
case type
when 'system'
'fqdn'
else
'id'
end
end
def error_body(body_text)
begin
JSON.parse(body_text)["message"]
rescue
body_text
end
end
def get_or_assign_system_name(serial)
do_request :GET => "pcmsystemname/#{serial}"
end
def update(type, obj, key=nil)
key ||= obj[key_field_of(type)]
do_request(:PUT => "#{type}/#{key}", :body => obj)
end
def tc_post(obj)
# Post the object to trafficcontrol
# obj is something you can call .to_json on
url = URI.parse(@opt['trafficcontrol']['url'])
self.dbg "Posting to #{url.inspect}"
res = Net::HTTP.start(url.host, url.port) do |http|
self.dbg "Connected to #{url.host}:#{url.port}"
req = Net::HTTP::Post.new(url.path)
req.body = obj.to_json
self.dbg "BODY = #{obj.to_json}"
if @opt['trafficcontrol'].has_key? 'username'
self.dbg " using username #{@opt['trafficcontrol']['username']}"
self.dbg " using password #{@opt['trafficcontrol']['password']}"
req.basic_auth @opt['trafficcontrol']['username'], @opt['trafficcontrol']['password']
end
self.dbg "Sending request #{req.inspect}"
http.request(req)
end
self.dbg res.inspect
if res.code[0] == ?2
self.dbg " success (#{res.code})"
true
else
raise "Error posting to TC: #{res}"
end
end
end
class CMDBclient::Mock < CMDBclient
def initialize(opt)
@system_index = 3
@dclist = ['SNV', 'AWSLAB']
@data = {
'm0000001.lab.ppops.net' => {
'fqdn' => 'm0000001.lab.ppops.net',
'roles' => '',
'status' => 'idle',
'environment_name' => 'lab',
'ip_address' => '10.0.0.1',
'created_by' => 'user1',
'serial' => 's-001',
'data_center_code' => 'SNV'
},
'm0000002.lab.ppops.net' => {
'fqdn' => 'm0000002.lab.ppops.net',
'roles' => 'pcm-api-v2::role',
'ip_address' => '10.0.0.1',
'created_by' => 'user2',
'serial' => 's-002',
'data_center_code' => 'AWSLAB'
}
}
end
def query(type, *condlist)
raise "Unimplemented type #{type}" unless type == 'system'
if condlist.empty?
@data.map { |k, v| v }
else
cond = condlist.first
if m = /^fqdn=([^&]+)/.match(cond)
fqdn = m[1]
if @data.has_key? fqdn
[@data[fqdn]]
else
[]
end
else
raise "Unimplemented complex query #{condlist.join('&')}"
end
end
end
def update(type, obj, key=nil)
raise "Unimplemented type #{type}" unless type == 'system'
key ||= obj['fqdn']
raise "404 Not Found" unless @data.has_key? key
@data[key].update(obj)
end
def get_or_assign_system_name(serial)
@data.values.find { |s| s['serial'] == serial } || new_name(serial)
end
def new_name(serial)
fqdn = sprintf('m%07i.lab.ppops.net', @system_index)
@system_index += 1
@data[fqdn] = { 'fqdn' => fqdn,
'serial' => serial
}
end
end
| true |
601b0c44e9e69c51458736f634ee5250576a327d | Ruby | takata/hiitcal | /mail_post.rb | UTF-8 | 776 | 2.703125 | 3 | [] | no_license | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'rubygems'
require 'dotenv'
require 'csv'
require 'mail'
require 'mail-iso-2022-jp'
Dotenv.load
sleeptime = ENV["SLEEPTIME"].to_i
def post(title , description)
mail_from = ARGV[0]
mail_to = ARGV[1]
mail = Mail.new(:charset => 'ISO-2022-JP')
mail.from = mail_from
mail.to = mail_to
mail.subject = title
mail.body = description
mail.deliver
end
CSV(STDIN, :col_sep => "\t").each do |row|
title = row[0].split(/ /)[0] << " " << row[2]
placeenc = URI.encode(row[3].split(/ /)[0])
description = <<"EOS"
#{row[2]}
開始 #{row[0]}
終了 #{row[1]}
場所 #{row[3]}
URL #{row[4]}
地図 https://www.google.co.jp/maps/place/#{placeenc}
EOS
post(title , description)
sleep(sleeptime)
end
| true |
f5edcf1910bec7676de9fa385d9aa1728080d97f | Ruby | Eden-Eltume/120 | /120_Exercises/4_Accessor_Methods/ex10.rb | UTF-8 | 361 | 3.796875 | 4 | [] | no_license | class Person
def name
@first_name + " " + @last_name
end
def name=(name)
full_name_array = splice_name(name)
@first_name = full_name_array.first
@last_name = full_name_array.last
end
private
def splice_name(full_name_string)
full_name_string.split(" ")
end
end
person1 = Person.new
person1.name = 'John Doe'
puts person1.name
| true |
9b2a57b094c36f2521cacf4770202e84e2f162ae | Ruby | VanDeGraf/Chess | /lib/user_interface/console_io.rb | UTF-8 | 223 | 2.71875 | 3 | [] | no_license | class ConsoleIO < UserInterfaceIO
def readline
gets.chomp
end
def write(string)
print(string)
end
def writeline(string)
puts(string)
end
def clear
system('clear') || system('cls')
end
end
| true |
4d6531a2fc2a34abe27a1532d9224fcb89e2e81f | Ruby | henare/linksys_am300_statistics | /dslmodem.rb | UTF-8 | 1,284 | 2.671875 | 3 | [] | no_license | require 'rubygems'
require 'mechanize'
class DSLModem
def initialize(url='http://192.168.1.1/index.stm?title=Status-Modem', username, password)
@url, @username, @password = url, username, password
get_stats_page
end
def get_stats_page
# Get the login page
agent = Mechanize.new
@page = agent.get(@url)
# If we're already logged in (don't ask), then we already have the page we need
return @page if @page.title != "Log In"
# Login
form = @page.forms.first
form.field_with(:name => "username").value = @username
form.field_with(:name => "password").value = @password
form.submit
# Get stats page
@page = agent.get(@url)
end
def statistics
status_table = @page.search("#table1")[1]
{
:bandwidth_downstream => @page.search("#table1")[1].search('b')[3].inner_text.strip.split[0],
:bandwidth_upstream => @page.search("#table1")[1].search('b')[4].inner_text.strip.split[0],
:margin_downstream => @page.search("#table1")[1].search('b')[5].inner_text.strip.split[0],
:margin_upstream => @page.search("#table1")[1].search('b')[6].inner_text.strip.split[0]
}
end
def offline?
@page.search("#table1")[1].search('b')[3].inner_text.strip.split[0] == "0" ? true : false
end
end
| true |
714dee5114a1a5f600156af736cf2014b8b6c820 | Ruby | baloran/tilter | /spec/models/user_spec.rb | UTF-8 | 5,118 | 2.5625 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe 'User', type: :model do
it 'can be created' do
User.create(
username: 'baloran',
display_name: 'bal0ran',
password: 'password',
email: 'baloranandco@gmail.com'
)
found = User.last
expect(found.username).to eq('baloran')
expect(found.display_name).to eq('bal0ran')
expect(found.email).to eq('baloranandco@gmail.com')
end
it 'requires a username, a display name, an email and a password' do
user = User.new
expect(user.valid?).to eq(false)
user.username = 'baloran'
expect(user.valid?).to eq(false)
user.display_name = 'bal0ran'
expect(user.valid?).to eq(false)
user.email = 'baloranandco@gmail.com'
expect(user.valid?).to eq(false)
user.password = 'password'
expect(user.valid?).to eq(true)
end
it 'is automatically assigned its username as display name if none is set' do
user = User.create(
username: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.username).to eq('baloran')
expect(user.display_name).to eq('baloran')
end
it 'can’t have the same email as another user' do
user = User.create(
username: 'baloran',
display_name: 'bal0ran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.valid?).to eq(true)
other_user = User.create(
username: 'stamm',
display_name: 'stammeister',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(other_user.valid?).to eq(false)
end
it 'can’t have the same username as another user' do
user = User.create(
username: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.valid?).to eq(true)
# Here, the uniqueness is handled by ActiveRecord directly and will
# raise an exception as expected.
other_user = User.create(
username: 'baloran',
password: 'password',
email: 'stammeister@gmail.com'
)
expect(other_user.valid?).to eq(false)
end
it 'can have a username between 2 and 40 characters' do
user = User.create(
display_name: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.valid?).to eq(false)
user.username = 'b'
expect(user.valid?).to eq(false)
user.username = (0..100).map { 'X' }.join
expect(user.valid?).to eq(false)
user.username = 'ba'
expect(user.valid?).to eq(true)
user.username = 'baloran'
expect(user.valid?).to eq(true)
end
it 'has a proper error message for username not being valid' do
user = User.create(
display_name: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.errors.messages[:username].first).not_to be_empty
end
it 'can have a display name between 2 and 40 characters' do
user = User.create(
username: 'baloran',
display_name: 'b',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.valid?).to eq(false)
user.display_name = (0..100).map { 'X' }.join
expect(user.valid?).to eq(false)
user.display_name = 'ba'
expect(user.valid?).to eq(true)
user.display_name = 'baloran'
expect(user.valid?).to eq(true)
end
it 'has a proper error message for display name not being valid' do
user = User.create(
username: 'baloran',
display_name: 'b',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.errors.messages[:display_name].first).not_to be_empty
end
it 'requires a valid email' do
user = User.new
user.username = 'baloran'
user.password = 'password'
user.email = 'baloranandco'
expect(user.valid?).to eq(false)
user.email = 'baloranandcogmail.com'
expect(user.valid?).to eq(false)
user.email = 'baloranandco@gmail.com'
expect(user.valid?).to eq(true)
end
it 'has a proper error message for email not being valid' do
user = User.create(
username: 'baloran',
display_name: 'baloran',
password: 'password',
email: 'baloranandco'
)
expect(user.errors.messages[:email].first).not_to be_empty
end
it 'can have a description that has a maximum of 200 characters' do
user = User.create(
username: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com'
)
user.description = ''
expect(user.valid?).to eq(true)
user.description = 'A valid description'
expect(user.valid?).to eq(true)
user.description = (0..500).map { 'X' }.join
expect(user.valid?).to eq(false)
end
it 'has a proper error message for description being too long' do
user = User.create(
username: 'baloran',
password: 'password',
email: 'baloranandco@gmail.com',
description: (0..500).map { 'X' }.join
)
expect(user.errors.messages[:description].first).not_to be_empty
end
it 'has a default avatar if not set' do
user = User.new(
username: 'baloran',
display_name: 'bal0ran',
password: 'password',
email: 'baloranandco@gmail.com'
)
expect(user.valid?).to be(true)
user.save
found = User.last
expect(found.avatar.url).to_not be_empty
end
end
| true |
6eb5b29c59bfe770ba409eb2092e8bcfa909b480 | Ruby | kstephens/cabar | /comp/derby/1.0/lib/ruby/derby.rb | UTF-8 | 1,395 | 2.5625 | 3 | [
"MIT"
] | permissive |
module Derby
EMPTY_ARRAY = [ ].freeze unless defined? EMPTY_ARRAY
EMPTY_HASH = { }.freeze unless defined? EMPTY_HASH
# Mixin to handle:
#
# class Foo
# attr_accessor :foo, :bar
# end
#
# obj = Foo.new(:foo => 'foo', :baz => 'baz')
# obj.foo => 'foo'
# obj.bar => 'nil'
# obj.options => { :baz => 'baz' }
#
module InitializeFromHash
def options
@options
end
def initialize opts = nil
opts ||= EMPTY_HASH
@options = opts.dup
pre_initialize if respond_to?(:pre_initialize)
opts.each do | k, v |
s = :"#{k}="
if respond_to?(s)
send(s, v)
@options.delete(k)
end
end
post_initialize if respond_to?(:post_initialize)
end
end
module DottedHash
def method_missing sel, *args, &blk
sel = sel.to_s
if args.empty? && ! block_given? && key?(sel)
self[sel]
else
super
end
end
end # module
end # module
# Use to add comp/... directories to search path when its too early for
# cabar to require itself.
def cabar_comp_require name, version = nil
path = File.expand_path(File.dirname(__FILE__) + "../../../../../../comp/#{name}/#{version}/lib/ruby")
$:.insert(0, path) unless $:.include?(path)
# $stderr.puts "#{$:.inspect} #{path.inspect}"
require name
end
cabar_comp_require 'cabar_core'
| true |
539ec10c487b523bcff09e54f7582af9464b3cd8 | Ruby | knoxknox/dev-labs | /ractor/src/sidekiq.rb | UTF-8 | 737 | 3.03125 | 3 | [] | no_license | class WorkerPool
attr_reader :workers
def initialize(count)
@workers = create_pool(count)
end
def self.perform(opts)
opts[:klass].new.perform(*opts[:args])
end
def perform_async(klass, *args)
worker, _ = Ractor.select(*workers)
worker.send({ klass: klass, args: args })
end
private
def create_pool(count)
count.times.map { spawn_worker_and_wait }
end
def spawn_worker_and_wait
Ractor.new do
Ractor.yield(:ready)
loop { Ractor.yield WorkerPool.perform(Ractor.receive) }
end
end
end
class PrintMessageJob
def perform(message)
puts "[#{Time.now}] #{message}"
end
end
pool = WorkerPool.new(8)
10.times { |i| pool.perform_async(PrintMessageJob, i) } && sleep(1)
| true |
47cfa8b75489774e75b172df54a85c234ec527e4 | Ruby | Syncleus/Aethyr | /lib/aethyr/core/input_handlers/set.rb | UTF-8 | 2,600 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | require "aethyr/core/actions/commands/setpassword"
require "aethyr/core/actions/commands/set"
require "aethyr/core/actions/commands/showcolors"
require "aethyr/core/actions/commands/setcolor"
require "aethyr/core/registry"
require "aethyr/core/input_handlers/command_handler"
module Aethyr
module Core
module Commands
module Set
class SetHandler < Aethyr::Extend::CommandHandler
def self.create_help_entries
help_entries = []
command = "set"
see_also = ["WORDWRAP", "PAGELENGTH", "DESCRIPTION", "COLORS"]
syntax_formats = ["SET <option> [value]"]
aliases = nil
content = <<'EOF'
There are several settings available to you. To see them all, simply use SET.
To see the values available for a certain setting, use SET <option> without a value.
Example:
To see your color settings, use
SET COLOR
To turn off word wrap, use
SET WORDWRAP OFF
EOF
help_entries.push(Aethyr::Core::Help::HelpEntry.new(command, content: content, syntax_formats: syntax_formats, see_also: see_also, aliases: aliases))
return help_entries
end
def initialize(player)
super(player, ["set"], help_entries: SetHandler.create_help_entries)
end
def self.object_added(data)
super(data, self)
end
def player_input(data)
super(data)
case data[:input]
when /^set\s+colors?\s+(on|off|default)$/i
option = $1
$manager.submit_action(Aethyr::Core::Actions::Setcolor::SetcolorCommand.new(@player, {:option => option}))
when /^set\s+colors?.*/i
$manager.submit_action(Aethyr::Core::Actions::Showcolors::ShowcolorsCommand.new(@player, {}))
when /^set\s+colors?\s+(\w+)\s+(.+)$/i
option = $1
color = $2
$manager.submit_action(Aethyr::Core::Actions::Setcolor::SetcolorCommand.new(@player, {:option => option, :color => color}))
when /^set\s+password$/i
$manager.submit_action(Aethyr::Core::Actions::Setpassword::SetpasswordCommand.new(@player, {}))
when /^set\s+(\w+)\s*(.*)$/i
setting = $1.strip
value = $2.strip if $2
$manager.submit_action(Aethyr::Core::Actions::Set::SetCommand.new(@player, {:setting => setting, :value => value}))
end
end
private
end
Aethyr::Extend::HandlerRegistry.register_handler(SetHandler)
end
end
end
end
| true |
9aba326263094faeac442f8a2d7a7e994b35dd21 | Ruby | xmacinka/capsulecrm | /examples.rb | UTF-8 | 2,294 | 2.96875 | 3 | [
"MIT"
] | permissive | # NOTE: CapsuleCRM::Person and CapsuleCRM::Organisation have virtually identically methods.
# find by id
person = CapsuleCRM::Person.find 123
# or if you don't know what you are searching for Party
something = CapsuleCRM::Party.find 123
something.is?(:person)
something.is?(:organisation)
# find by email
person = CapsuleCRM::Person.find_by_email 'foo@example.com'
# find all
person = CapsuleCRM::Person.find :all, :offset => 10, :limit => 5
# find by search term (searches name, telephone number and searchable custom fields)
person = CapsuleCRM::Person.search 'fred', :offset => 10, :limit => 5
# CapsuleCRM::Person attributes
person.id
person.title
person.first_name
person.last_name
person.job_title
person.about
# update a person object
person.first_name = "Homer"
person.last_name = "Simpson"
person.save # returns true/false
# create a person object
person = CapsuleCRM::Person.new
person.first_name = "Marge"
person.last_name = "Simpson"
person.save # returns true/false
# get the person's organisation
person.organisation # CapsuleCRM::Organisation
# CapsuleCRM::Organisation attributes:
organisation.about
organisation.name
# Contacts: CapsuleCRM::Phone (read-only)
person.phone_numbers # CapsuleCRM::Collection
person.phone_numbers.first.number # 01234 56789
person.phone_numbers.first.type # work
# Contacts: CapsuleCRM::Website (read-only)
party.websites # CapsuleCRM::Collection
party.websites.first.url # http://google.com
party.websites.first.web_address # http://google.com
# Contacts: CapsuleCRM::Email (read-only)
person.emails # CapsuleCRM::Collection
person.emails.first.address # 'foo@example.com'
person.emails.first.type # 'home'
# Contacts: CapsuleCRM::Address (read-only)
person.addresses # CapsuleCRM::Collection
person.addresses.first.street # 10 Somestreet
person.addresses.first.city # Manchester
person.addresses.first.state # Greater Manchester
person.addresses.first.zip # ME10 7TR
person.addresses.first.country # United Kingdom
# CapsuleCRM::CustomFields (read-only)
person.custom_fields # CapsuleCRM::Collection
person.custom_fields.first.label # 'Favourite colour'
person.custom_fields.first.value # 'Blue'
# CapsuleCRM::Tag (read-only)
person.tags # CapsuleCRM::Collection
person.tag_names # ["array", "of all", "tags", "as strings"] | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.