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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9013a9519a297a07b265ab79a9cf1f24710f16a8 | Ruby | JustinData/GA-WDI-Work | /w03/d03/Ann/user.rb | UTF-8 | 486 | 2.9375 | 3 | [] | no_license | class User
def initialize(id, name, address, email)
@id = id
@name = Faker::Name.name
@street_address = Faker::Address.street_address
@email_address = Faker::Internet.email
end
def name
@name
end
def street_address
@street_address
end
def email_address
@email_address
end
def to_s
"Name: #{@name} Street: #{@street_address} Email: #{@email_address}."
end
end
User1 = User.new("0", "Ann", "902 broadway", "ann@gmail.com")
| true |
62ac3b366235f69454f36dab69d6febfccc6c785 | Ruby | george-carlin/abroaders | /spec/support/application_survey_macros.rb | UTF-8 | 2,388 | 2.609375 | 3 | [] | no_license | module ApplicationSurveyMacros
# The apply 'button' is actually a link styled like a button
def self.included(base)
base.include DatepickerMacros
base.extend ClassMethods
base.instance_eval do
# some of these buttons have different text for different survey stages,
# so you'll have to override these let variables where appropriate:
let(:approved_at) { 'card_opened_on' }
let(:decline_btn) { 'No Thanks' }
let(:i_applied_btn) { 'I applied' }
let(:pending_btn) { "I'm waiting to hear back" }
let(:approved_btn) { 'I was approved' }
let(:denied_btn) { 'My application was denied' }
end
end
def i_called_btn(rec)
"I called #{rec.card_product.bank.name}"
end
def i_heard_back_btn(rec = nil)
if rec
"I heard back from #{rec.bank_name} by mail or email"
else
'I heard back from the bank'
end
end
# apply btn is different from the others because it's actually a link
# to another page (styled like a button) rather than a button that changes
# something on the current page: and we want to check that the link is correct,
# so we need to pass in the rec:
def have_find_card_btn(card, present = true)
meth = present ? :have_link : :have_no_link
send(meth, 'Find My Card', href: click_card_recommendation_path(card))
end
def have_no_find_card_btn(card)
have_find_card_btn card, false
end
def decline_reason_wrapper
find('#card_decline_reason').find(:xpath, '..')
end
def set_approved_at_to(date)
raise "error: approved at must be today or in the past" if date > Time.zone.today
set_datepicker_field('#' << approved_at, to: date)
end
module ClassMethods
def it_asks_to_confirm(has_pending_btn:)
example 'it can be confirmed/canceled' do
expect(page).to have_no_button approved_btn
expect(page).to have_no_button denied_btn
expect(page).to have_no_button pending_btn
expect(page).to have_button 'Cancel'
expect(page).to have_button 'Confirm'
# going back
click_button 'Cancel'
expect(page).to have_button approved_btn
expect(page).to have_button denied_btn
expect(page).to has_pending_btn ? have_button(pending_btn) : have_no_button(pending_btn)
expect(page).to have_no_button 'Confirm'
end
end
end
end
| true |
c82239eae70445905bc0703232dd3abc2fdb1095 | Ruby | bmwest/P.E. | /ruby/sum_square_difference.rb | UTF-8 | 375 | 3.84375 | 4 | [] | no_license | def sum_of_squares(x, y)
num = (x..y).to_a
sum = 0
num.each do |n|
sum += (n ** 2)
end
sum
end
def square_of_sum(x, y)
num = (x..y).to_a
sum = 0
num.each do |n|
sum += n
end
sum ** 2
end
x = 1
y = 100
sosq = sum_of_squares(x, y)
sosu = square_of_sum(x, y)
sum_square_difference = sosu - sosq
puts "#{sosu} - #{sosq} = #{sum_square_difference}"
| true |
0d8e37f400678db1298996c251fa7e14a7900b26 | Ruby | GrowMoi/moi | /lib/neo_importer/neuron_node.rb | UTF-8 | 2,081 | 2.71875 | 3 | [
"MIT"
] | permissive | class NeoImporter
class NeuronNode
attr_reader :node, :parent
def initialize(node, parent=nil)
@node = node
@parent = parent
end
def create!
create_neuron!.tap do |neuron|
levels.each do |level|
kinds.each do |kind|
attributes = content_attributes_for(level, kind)
if attributes[:description].present? || attributes[:source].present?
neuron.contents.create!(attributes)
else
# puts "WARN: Discarding content:"
# puts attributes
end
end
end
end
puts "Created: #{@created_neuron.title}, parent: #{@created_neuron.parent.try(:title)}"
@created_neuron
end
private
def content_attributes_for(level, kind)
klass = mapping.fetch(kind)
prefix = "level#{level}_#{klass}"
return {
level: level,
kind: kind,
description: description_for(prefix, level, kind),
source: node.send("#{prefix}_source_link"),
media: node.send("#{prefix}_photo"),
keyword_list: node.send("keywords").to_s.split(",")
}
end
def description_for(prefix, level, kind)
description = ""
# add title just in case
title = node.send("#{prefix}_title")
if title.present?
description = "#{title}\n\n"
end
description + node.send("#{prefix}_description").to_s
end
def create_neuron!
title = node.name
dup_i = 1
while Neuron.exists?(title: title)
title = "#{node.name} (DUP #{dup_i})"
dup_i += 1
end
@created_neuron = Neuron.create!(
title: title,
parent_id: parent.try(:id)
)
end
def levels
1..3
end
def kinds
Content::KINDS
end
def mapping
@mapping ||= {
:"que-es" => "what",
:"por-que-es" => "why",
:"como-funciona" => "how",
:"enlaces" => "links",
:"quien-cuando-donde" => "qcd",
:"videos" => "videos"
}
end
end
end
| true |
4df310c460a07305aa9d676e94bf1c1afc52f471 | Ruby | rab/sport.db | /sportdb-config/lib/sportdb/config/config.rb | UTF-8 | 2,896 | 2.609375 | 3 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | # encoding: utf-8
module SportDb
module Import
class Configuration
##
## todo: allow configure of countries_dir like clubs_dir
## "fallback" and use a default built-in world/countries.txt
## todo/check: rename to country_mappings/index - why? why not?
## or countries_by_code or countries_by_key
def countries
@countries ||= build_country_index
@countries
end
def build_country_index ## todo/check: rename to setup_country_index or read_country_index - why? why not?
CountryIndex.new( Fifa.countries )
end
def clubs
@clubs ||= build_club_index
@clubs
end
####
# todo/fix: find a better way to configure club / team datasets
attr_accessor :clubs_dir
def clubs_dir() @clubs_dir ||= './clubs'; end
CLUBS_REGEX = %r{ (?:^|/) # beginning (^) or beginning of path (/)
(?:[a-z]{1,3}\.)? # optional country code/key e.g. eng.clubs.txt
clubs\.txt$
}x
CLUBS_WIKI_REGEX = %r{ (?:^|/) # beginning (^) or beginning of path (/)
(?:[a-z]{1,3}\.)? # optional country code/key e.g. eng.clubs.wiki.txt
clubs\.wiki\.txt$
}x
def self.find_datafiles( path, pattern )
datafiles = [] ## note: [country, path] pairs for now
## check all txt files as candidates (MUST include country code for now)
candidates = Dir.glob( "#{path}/**/*.txt" )
pp candidates
candidates.each do |candidate|
datafiles << candidate if pattern.match( candidate )
end
pp datafiles
datafiles
end
def self.find_datafiles_clubs( path ) find_datafiles( path, CLUBS_REGEX ); end
def self.find_datafiles_clubs_wiki( path ) find_datafiles( path, CLUBS_WIKI_REGEX ); end
def build_club_index
## unify team names; team (builtin/known/shared) name mappings
## cleanup team names - use local ("native") name with umlaut etc.
## todo/fix: add to teamreader
## check that name and alt_names for a club are all unique (not duplicates)
clubs = ClubIndex.build( clubs_dir )
if clubs.errors?
puts ""
puts "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
puts " #{clubs.errors.size} errors:"
pp clubs.errors
## exit 1
end
clubs
end # method build_club_index
def leagues
read_leagues() if @leagues.nil?
@leagues
end
def read_leagues
#####
# add / read-in leagues config
@leagues = LeagueConfig.new
self ## return self for chaining
end
end # class Configuration
## lets you use
## SportDb::Import.configure do |config|
## config.hello = 'World'
## end
def self.configure
yield( config )
end
def self.config
@config ||= Configuration.new
end
end # module Import
end # module SportDb
| true |
7f5c96d65881ce31b97a031d73ece5faaf6890ec | Ruby | rlister/auger | /lib/auger/config.rb | UTF-8 | 338 | 2.578125 | 3 | [
"MIT"
] | permissive | module Auger
class Config
attr_accessor :projects
def self.load(filename)
config = new
config.instance_eval(File.read(filename), filename)
config
end
def initialize
@projects = []
self
end
def project(name, &block)
@projects << Project.load(name, &block)
end
end
end
| true |
12a69a4d264125eb95a5f3ec9860833d7c141840 | Ruby | shaunakv1/masters_course_work | /cps/ardunio/app/jobs/collect_data.rb | UTF-8 | 1,976 | 3.421875 | 3 | [] | no_license | require 'reading'
require 'serialport'
#params for serial port
port_str = "COM4" #may be different for you
baud_rate = 57600
data_bits = 8
stop_bits = 1
parity = SerialPort::NONE
@@sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity)
def read_sp
reading = ""
check_time = Time.now+10.seconds
while true do
reading = @@sp.read
if !reading.empty? #stop if input is received on serial port
break
end
if Time.now >= check_time #stop reading after 20 seconds
puts "no data received for the command.."
break
end
end
reading.strip!
if (reading_is_valid?(reading))
reading
else
""
end
end
def reading_is_valid? (reading)
valid = true;
valid = false if !reading.start_with?("$")
valid = false if !reading.end_with?("@")
valid = false if reading.count('#') < 3
valid
end
def start_collecting
#$1#22#141@
puts "Starting.."
stations = [1,2]
while true do
stations.each do |stat|
@@sp.write "$##{stat}#temp#moist@"
sleep 1.0
reading = read_sp
puts "Raw:#{reading}"
if !reading.empty?
reading.chop!
reading.slice!(0)
reading.slice!(0)
params = reading.split("#")
#puts "processed: 1:#{params[0]} 2:#{params[1]} 3: #{params[2]}"
puts Time.now
puts "ID = #{params[0]}"
puts "Temperature = #{params[1]}"
puts "Moisture = #{params[2]}"
puts "adding to db.."
reading = Reading.new
reading.station_id = params[0]
reading.temperature = params[1]
reading.moisture = params[2]
reading.created_at = Time.now + 5.hours
reading.save
puts "done.."
puts "------------------------"
end
sleep 5.0
end
end
@@sp.close
puts "Stopping.."
end
start_collecting
| true |
28960ec772ee8c1a9221492c3b978d557dd5a721 | Ruby | markjeee/activefacts | /lib/activefacts/cql/compiler/reading.rb | UTF-8 | 40,842 | 2.5625 | 3 | [
"Zlib"
] | permissive | module ActiveFacts
module CQL
class Compiler < ActiveFacts::CQL::Parser
class Reading
attr_reader :phrases
attr_accessor :qualifiers, :context_note
attr_reader :fact_type, :reading, :role_sequence # These are the Metamodel objects
attr_reader :side_effects
attr_writer :fact_type # Assigned for a bare (existential) objectification fact
attr_accessor :fact # When binding fact instances the fact goes here
attr_accessor :objectified_as # The Reading::RoleRef which objectified this fact type
def initialize role_refs_and_words, qualifiers = [], context_note = nil
@phrases = role_refs_and_words
role_refs.each { |role_ref| role_ref.reading = self }
@qualifiers = qualifiers
@context_note = context_note
end
def role_refs
@phrases.select{|r| r.is_a?(RoleRef)}
end
# A reading that contains only the name of a Concept and no literal or reading text
# refers only to the existence of that Concept (as opposed to an instance of the concept).
def is_existential_type
@phrases.size == 1 and
@phrases[0].is_a?(RoleRef) and
!@phrases[0].literal
end
def display
"#{
@qualifiers && @qualifiers.size > 0 ? @qualifiers.inspect+' ' : nil
}#{
@phrases.map{|p| p.to_s }*" "
}#{
@context_note && ' '+@context_note.inspect
}"
end
def inspect
"#{@qualifiers && @qualifiers.size > 0 ? @qualifiers.inspect+' ' : nil}#{@phrases.map{|p|p.inspect}*" "}#{@context_note && ' '+@context_note.inspect}"
end
def identify_players_with_role_name context
role_refs.each do |role_ref|
role_ref.identify_player(context) if role_ref.role_name
# Include players in an objectification join, if any
role_ref.objectification_join.each{|reading| reading.identify_players_with_role_name(context)} if role_ref.objectification_join
end
end
def identify_other_players context
role_refs.each do |role_ref|
role_ref.identify_player(context) unless role_ref.player
# Include players in an objectification join, if any
role_ref.objectification_join.each{|reading| reading.identify_other_players(context)} if role_ref.objectification_join
end
end
def includes_literals
role_refs.detect{|role_ref| role_ref.literal || (ja = role_ref.objectification_join and ja.detect{|jr| jr.includes_literals })}
end
def bind_roles context
role_names = role_refs.map{ |role_ref| role_ref.role_name }.compact
# Check uniqueness of role names and subscripts within this reading:
role_names.each do |rn|
next if role_names.select{|rn2| rn2 == rn}.size == 1
raise "Duplicate role #{rn.is_a?(Integer) ? "subscript" : "name"} '#{rn}' in reading"
end
role_refs.each do |role_ref|
role_ref.bind context
# Include players in an objectification join, if any
role_ref.objectification_join.each{|reading| reading.bind_roles(context)} if role_ref.objectification_join
end
end
def phrases_match(phrases)
@phrases.zip(phrases).each do |mine, theirs|
return false if mine.is_a?(RoleRef) != theirs.is_a?(RoleRef)
if mine.is_a?(RoleRef)
return false unless mine.key == theirs.key
else
return false unless mine == theirs
end
end
true
end
# This method chooses the existing fact type which matches most closely.
# It returns nil if there is none, or a ReadingMatchSideEffects object if matched.
#
# As this match may not necessarily be used (depending on the side effects),
# no change is made to this Reading object - those will be done later.
def match_existing_fact_type context
raise "Internal error, reading already matched, should not match again" if @fact_type
rrs = role_refs
players = rrs.map{|rr| rr.player}
raise "Must identify players before matching fact types" if players.include? nil
raise "A fact type must involve at least one object type, but there are none in '#{inspect}'" if players.size == 0
player_names = players.map{|p| p.name}
debug :matching, "Looking for existing #{players.size}-ary fact types matching '#{inspect}'" do
debug :matching, "Players are '#{player_names.inspect}'"
# Match existing fact types in objectification joins first:
rrs.each do |role_ref|
next unless joins = role_ref.objectification_join and !joins.empty?
role_ref.objectification_join.each do |oj|
ft = oj.match_existing_fact_type(context)
raise "Unrecognised fact type #{oj.display}" unless ft
if (ft && ft.entity_type == role_ref.player)
role_ref.objectification_of = ft
oj.objectified_as = role_ref
end
end
raise "#{role_ref.inspect} contains objectification joins that do not objectify it" unless role_ref.objectification_of
end
# For each role player, find the compatible types (the set of all subtypes and supertypes).
# For a player that's an objectification, we don't allow implicit supertype joins
player_related_types =
rrs.map do |role_ref|
player = role_ref.player
((role_ref.objectification_of ? [] : player.supertypes_transitive) +
player.subtypes_transitive).uniq
end
debug :matching, "Players must match '#{player_related_types.map{|pa| pa.map{|p|p.name}}.inspect}'"
# The candidate fact types have the right number of role players of related types.
# If any role is played by a supertype or subtype of the required type, there's an implicit subtyping join
candidate_fact_types =
player_related_types[0].map do |related_type|
related_type.all_role.select do |role|
all_roles = role.fact_type.all_role
next if all_roles.size != players.size # Wrong number of players
next if role.fact_type.is_a?(ActiveFacts::Metamodel::ImplicitFactType)
all_players = all_roles.map{|r| r.concept} # All the players of this candidate fact type
next if player_related_types[1..-1]. # We know the first player is compatible, check the rest
detect do |player_types| # Make sure that there remains a compatible player
# player_types is an array of the types compatible with the Nth player
compatible_player = nil
all_players.each_with_index do |p, i|
if player_types.include?(p)
compatible_player = p
all_players.delete_at(i)
break
end
end
!compatible_player
end
true
end.
map{ |role| role.fact_type}
end.flatten.uniq
# If there is more than one possible exact match (same adjectives) with different subyping, the implicit join is ambiguous and is not allowed
debug :matching, "Looking amongst #{candidate_fact_types.size} existing fact types for one matching '#{inspect}'" do
matches = {}
candidate_fact_types.map do |fact_type|
fact_type.all_reading.map do |reading|
next unless side_effects = reading_matches(fact_type, reading)
matches[reading] = side_effects if side_effects
end
end
# REVISIT: Side effects that leave extra adjectives should only be allowed if the
# same extra adjectives exist in some other reading in the same declaration.
# The extra adjectives are then necessary to associate the two role players
# when consumed adjectives were required to bind to the underlying fact types.
# This requires the final decision on fact type matching to be postponed until
# the whole declaration has been processed and the extra adjectives can be matched.
best_matches = matches.keys.sort_by{|match|
# Between equivalents, prefer the one without a join on the first role
(m = matches[match]).cost*2 + ((!(e = m.role_side_effects[0]) || e.cost) == 0 ? 0 : 1)
}
debug :matching_fails, "Found #{matches.size} valid matches#{matches.size > 0 ? ', best is '+best_matches[0].expand : ''}"
if matches.size > 1
first = matches[best_matches[0]]
cost = first.cost
equal_best = matches.select{|k,m| m.cost == cost}
if equal_best.size > 1 and equal_best.detect{|k,m| !m.fact_type.is_a?(Metamodel::TypeInheritance)}
# Complain if there's more than one equivalent cost match (unless all are TypeInheritance):
raise "#{@phrases.inspect} could match any of the following:\n\t"+
best_matches.map { |reading| reading.expand + " with " + matches[reading].describe } * "\n\t"
end
end
if matches.size >= 1
@reading = best_matches[0]
@side_effects = matches[@reading]
@fact_type = @side_effects.fact_type
debug :matching, "Matched '#{@fact_type.default_reading}'"
apply_side_effects(context, @side_effects)
return @fact_type
end
end
debug :matching, "No fact type matched, candidates were '#{candidate_fact_types.map{|ft| ft.default_reading}*"', '"}'"
end
@fact_type = nil
end
# The ActiveFacts::Metamodel::Reading passed has the same players as this Compiler::Reading. Does it match?
# Twisty curves. This is a complex bit of code!
# Find whether the phrases of this reading match the fact type reading,
# which may require absorbing unmarked adjectives.
#
# If it does match, make the required changes and set @role_ref to the matching role.
# Adjectives that were used to match are removed (and leaving any additional adjectives intact).
#
# Approach:
# Match each element where element means:
# a role player phrase (perhaps with adjectives)
# Our phrase must either be
# a player that contains the same adjectives as in the reading.
# a word (unmarked leading adjective) that introduces a sequence
# of adjectives leading up to a matching player
# trailing adjectives, both marked and unmarked, are absorbed too.
# a word that matches the reading's
#
def reading_matches(fact_type, reading)
side_effects = [] # An array of items for each role, describing any side-effects of the match.
intervening_words = nil
residual_adjectives = false
debug :matching_fails, "Does '#{@phrases.inspect}' match '#{reading.expand}'" do
phrase_num = 0
reading_parts = reading.text.split(/\s+/)
# Check that the number of roles matches (skipped, the caller should have done it):
# return nil unless reading_parts.select{|p| p =~ /\{(\d+)\}/}.size == role_refs.size
reading_parts.each do |element|
if element !~ /\{(\d+)\}/
# Just a word; it must match
unless @phrases[phrase_num] == element
debug :matching_fails, "Mismatched ordinary word #{@phrases[phrase_num].inspect} (wanted #{element})"
return nil
end
phrase_num += 1
next
else
role_ref = reading.role_sequence.all_role_ref.sort_by{|rr| rr.ordinal}[$1.to_i]
end
# Figure out what's next in this phrase (the next player and the words leading up to it)
next_player_phrase = nil
intervening_words = []
while (phrase = @phrases[phrase_num])
phrase_num += 1
if phrase.is_a?(RoleRef)
next_player_phrase = phrase
next_player_phrase_num = phrase_num-1
break
else
intervening_words << phrase
end
end
player = role_ref.role.concept
return nil unless next_player_phrase # reading has more players than we do.
# The next player must match:
common_supertype = nil
if next_player_phrase.player != player
# This relies on the supertypes being in breadth-first order:
common_supertype = (next_player_phrase.player.supertypes_transitive & player.supertypes_transitive)[0]
if !common_supertype
debug :matching_fails, "Reading discounted because next player #{player.name} doesn't match #{next_player_phrase.player.name}"
return nil
end
debug :matching_fails, "Subtype join is required between #{player.name} and #{next_player_phrase.player.name} via common supertype #{common_supertype.name}"
end
# It's the right player. Do the adjectives match? This must include the intervening_words, if any.
role_has_residual_adjectives = false
absorbed_precursors = 0
if la = role_ref.leading_adjective and !la.empty?
# The leading adjectives must match, one way or another
la = la.split(/\s+/)
return nil unless la[0,intervening_words.size] == intervening_words
# Any intervening_words matched, see what remains
la.slice!(0, intervening_words.size)
# If there were intervening_words, the remaining reading adjectives must match the phrase's leading_adjective exactly.
phrase_la = (next_player_phrase.leading_adjective||'').split(/\s+/)
return nil if !intervening_words.empty? && la != phrase_la
# If not, the phrase's leading_adjectives must *end* with the reading's
return nil if phrase_la[-la.size..-1] != la
role_has_residual_adjectives = true if phrase_la.size > la.size
# The leading adjectives and the player matched! Check the trailing adjectives.
absorbed_precursors = intervening_words.size
intervening_words = []
elsif intervening_words.size > 0 || next_player_phrase.leading_adjective
role_has_residual_adjectives = true
end
absorbed_followers = 0
if ta = role_ref.trailing_adjective and !ta.empty?
ta = ta.split(/\s+/) # These are the trailing adjectives to match
phrase_ta = (next_player_phrase.trailing_adjective||'').split(/\s+/)
i = 0 # Pad the phrases up to the size of the trailing_adjectives
while phrase_ta.size < ta.size
break unless (word = @phrases[phrase_num+i]).is_a?(String)
phrase_ta << word
i += 1
end
return nil if ta != phrase_ta[0,ta.size]
role_has_residual_adjectives = true if phrase_ta.size > ta.size || i < ta.size
absorbed_followers = i
phrase_num += i # Skip following words that were consumed as trailing adjectives
elsif next_player_phrase.trailing_adjective
role_has_residual_adjectives = true
end
# REVISIT: I'm not even sure I should be caring about role names here.
# Role names are on roles, and are only useful within the fact type definition.
# At some point, we need to worry about role names on readings within fact type derivations,
# which means they'll move to the Role Ref class; but even then they only match within the
# definition that creates that Role Ref.
=begin
if a = (!phrase.role_name.is_a?(Integer) && phrase.role_name) and
e = role_ref.role.role_name and
a != e
debug :matching, "Role names #{e.inspect} for #{player.name} and #{a.inspect} for #{next_player_phrase.player.name} don't match"
return nil
end
=end
residual_adjectives ||= role_has_residual_adjectives
if residual_adjectives && next_player_phrase.binding.refs.size == 1
debug :matching_fails, "Residual adjectives have no other purpose, so this match fails"
return nil
end
# The phrases matched this reading's next role_ref, save data to apply the side-effects:
debug :matching_fails, "Saving side effects for #{next_player_phrase.term}, absorbs #{absorbed_precursors}/#{absorbed_followers}#{common_supertype ? ', join over supertype '+ common_supertype.name : ''}" if absorbed_precursors+absorbed_followers+(common_supertype ? 1 : 0) > 0
side_effects << ReadingMatchSideEffect.new(next_player_phrase, role_ref, next_player_phrase_num, absorbed_precursors, absorbed_followers, common_supertype, role_has_residual_adjectives)
end
if phrase_num != @phrases.size || !intervening_words.empty?
debug :matching_fails, "Extra words #{(intervening_words + @phrases[phrase_num..-1]).inspect}"
return nil
end
if fact_type.is_a?(Metamodel::TypeInheritance)
# There may be only one subtyping join on a TypeInheritance fact type.
ti_joins = side_effects.select{|se| se.common_supertype}
if ti_joins.size > 1 # Not allowed
debug :matching_fails, "Can't have more than one subtyping join on a TypeInheritance fact type"
return nil
end
if ti = ti_joins[0]
# The Type Inheritance join must continue in the same direction as this reading.
allowed = fact_type.supertype == ti.role_ref.role.concept ?
fact_type.subtype.supertypes_transitive :
fact_type.supertype.subtypes_transitive
if !allowed.include?(ti.common_supertype)
debug :matching_fails, "Implicit subtyping join extends in the wrong direction"
return nil
end
end
end
debug :matching, "Matched reading '#{reading.expand}' with #{side_effects.map{|se| se.absorbed_precursors+se.absorbed_followers + (se.common_supertype ? 1 : 0)
}.inspect} side effects#{residual_adjectives ? ' and residual adjectives' : ''}"
end
# There will be one side_effects for each role player
ReadingMatchSideEffects.new(fact_type, self, residual_adjectives, side_effects)
end
def apply_side_effects(context, side_effects)
@applied_side_effects = side_effects
# Enact the side-effects of this match (delete the consumed adjectives):
# Since this deletes words from the phrases, we do it in reverse order.
debug :matching, "Apply side-effects" do
side_effects.apply_all do |se|
# We re-use the role_ref if possible (no extra adjectives were used, no rolename or join, etc).
debug :matching, "side-effect means binding #{se.phrase.inspect} matches role ref #{se.role_ref.role.concept.name}"
se.phrase.role_ref = se.role_ref
changed = false
# Where this phrase has leading or trailing adjectives that are in excess of those of
# the role_ref, those must be local, and we'll need to extract them.
if rra = se.role_ref.trailing_adjective
debug :matching, "Deleting matched trailing adjective '#{rra}'#{se.absorbed_followers>0 ? " in #{se.absorbed_followers} followers" : ""}"
# These adjective(s) matched either an adjective here, or a follower word, or both.
if a = se.phrase.trailing_adjective
if a.size >= rra.size
a.slice!(0, rra.size+1) # Remove the matched adjectives and the space (if any)
se.phrase.wipe_trailing_adjective if a.empty?
changed = true
end
elsif se.absorbed_followers > 0
se.phrase.wipe_trailing_adjective
# This phrase is absorbing non-hyphenated adjective(s), which changes its binding
se.phrase.trailing_adjective = @phrases.slice!(se.num+1, se.absorbed_followers)*' '
se.phrase.rebind context
changed = true
end
end
if rra = se.role_ref.leading_adjective
debug :matching, "Deleting matched leading adjective '#{rra}'#{se.absorbed_precursors>0 ? " in #{se.absorbed_precursors} precursors" : ""}}"
# These adjective(s) matched either an adjective here, or a precursor word, or both.
if a = se.phrase.leading_adjective
if a.size >= rra.size
a.slice!(-rra.size, 1000) # Remove the matched adjectives and the space
a.chop!
se.phrase.wipe_leading_adjective if a.empty?
changed = true
end
elsif se.absorbed_precursors > 0
se.phrase.wipe_leading_adjective
# This phrase is absorbing non-hyphenated adjective(s), which changes its binding
se.phrase.leading_adjective = @phrases.slice!(se.num-se.absorbed_precursors, se.absorbed_precursors)*' '
se.phrase.rebind context
changed = true
end
end
end
end
end
# Make a new fact type with roles for this reading.
# Don't assign @fact_type; that will happen when the reading is added
def make_fact_type vocabulary
fact_type = vocabulary.constellation.FactType(:new)
debug :matching, "Making new fact type for #{@phrases.inspect}" do
@phrases.each do |phrase|
next unless phrase.is_a?(RoleRef)
phrase.role = vocabulary.constellation.Role(fact_type, fact_type.all_role.size, :concept => phrase.player)
phrase.role.role_name = phrase.role_name if phrase.role_name && phrase.role_name.is_a?(String)
end
end
fact_type
end
def make_reading vocabulary, fact_type
@fact_type = fact_type
constellation = vocabulary.constellation
@role_sequence = constellation.RoleSequence(:new)
reading_words = @phrases.clone
index = 0
debug :matching, "Making new reading for #{@phrases.inspect}" do
reading_words.map! do |phrase|
if phrase.is_a?(RoleRef)
# phrase.role will be set if this reading was used to make_fact_type.
# Otherwise we have to find the existing role via the Binding. This is pretty ugly.
unless phrase.role
# Find another binding for this phrase which already has a role_ref to the same fact type:
ref = phrase.binding.refs.detect{|ref| ref.role_ref && ref.role_ref.role.fact_type == fact_type}
role_ref = ref.role_ref
phrase.role = role_ref.role
end
rr = constellation.RoleRef(@role_sequence, index, :role => phrase.role)
phrase.role_ref = rr
if la = phrase.leading_adjective
# If we have used one or more adjective to match an existing reading, that has already been removed.
rr.leading_adjective = la
end
if ta = phrase.trailing_adjective
rr.trailing_adjective = ta
end
if phrase.value_constraint
raise "The role #{rr.inspect} already has a value constraint" if rr.role.role_value_constraint
phrase.value_constraint.constellation = fact_type.constellation
rr.role.role_value_constraint = phrase.value_constraint.compile
end
index += 1
"{#{index-1}}"
else
phrase
end
end
if existing = @fact_type.all_reading.detect{|r|
r.text == reading_words*' ' and
r.role_sequence.all_role_ref_in_order.map{|rr| rr.role.concept} ==
role_sequence.all_role_ref_in_order.map{|rr| rr.role.concept}
}
raise "Reading '#{existing.expand}' already exists, so why are we creating a duplicate?"
end
constellation.Reading(@fact_type, @fact_type.all_reading.size, :role_sequence => @role_sequence, :text => reading_words*" ")
end
end
# When we match an existing reading, we might have matched using additional adjectives.
# These adjectives have been removed from the phrases. If there are any remaining adjectives,
# we need to make a new RoleSequence, otherwise we can use the existing one.
def adjust_for_match
return unless @applied_side_effects
new_role_sequence_needed = @applied_side_effects.residual_adjectives
role_phrases = []
reading_words = []
new_role_sequence_needed = false
@phrases.each do |phrase|
if phrase.is_a?(RoleRef)
role_phrases << phrase
reading_words << "{#{phrase.role_ref.ordinal}}"
if phrase.role_name # ||
# phrase.leading_adjective ||
# phrase.trailing_adjective
debug :matching, "phrase in matched reading has residual adjectives or role name, so needs a new role_sequence" if @fact_type.all_reading.size > 0
new_role_sequence_needed = true
end
else
reading_words << phrase
false
end
end
debug :matching, "Reading '#{reading_words*' '}' #{new_role_sequence_needed ? 'requires' : 'does not require'} a new Role Sequence"
constellation = @fact_type.constellation
reading_text = reading_words*" "
if new_role_sequence_needed
@role_sequence = constellation.RoleSequence(:new)
extra_adjectives = []
role_phrases.each_with_index do |rp, i|
role_ref = constellation.RoleRef(@role_sequence, i, :role => rp.role_ref.role)
if a = rp.leading_adjective
role_ref.leading_adjective = a
extra_adjectives << a+"-"
end
if a = rp.trailing_adjective
role_ref.trailing_adjective = a
extra_adjectives << "-"+a
end
if (a = rp.role_name) && (e = rp.role_ref.role.role_name) && a != e
raise "Can't create new reading '#{reading_text}' for '#{reading.expand}' with alternate role name #{a}"
extra_adjectives << "(as #{a})"
end
end
debug :matching, "Making new role sequence for new reading #{reading_text} due to #{extra_adjectives.inspect}"
else
# Use existing RoleSequence
@role_sequence = role_phrases[0].role_ref.role_sequence
if @role_sequence.all_reading.detect{|r| r.text == reading_text }
debug :matching, "No need to re-create identical reading for #{reading_text}"
return @role_sequence
else
debug :matching, "Using existing role sequence for new reading '#{reading_text}'"
end
end
if @fact_type.all_reading.detect{|r| r.text == reading_text}
raise "Reading '#{@reading.expand}' already exists, so why are we creating a duplicate (with #{extra_adjectives.inspect})?"
end
constellation.Reading(@fact_type, @fact_type.all_reading.size, :role_sequence => @role_sequence, :text => reading_text)
@role_sequence
end
def make_embedded_constraints vocabulary
role_refs.each do |role_ref|
next unless role_ref.quantifier
# puts "Quantifier #{role_ref.inspect} not implemented as a presence constraint"
role_ref.make_embedded_presence_constraint vocabulary
end
if @qualifiers && @qualifiers.size > 0
rc = RingConstraint.new(@role_sequence, @qualifiers)
rc.vocabulary = vocabulary
rc.constellation = vocabulary.constellation
rc.compile
# REVISIT: Check maybe and other qualifiers:
debug :constraint, "Need to make constraints for #{@qualifiers*', '}" if @qualifiers.size > 0
end
end
end
# An instance of ReadingMatchSideEffects is created when the compiler matches an existing fact type.
# It captures the details that have to be adjusted for the match to be regarded a success.
class ReadingMatchSideEffect
attr_reader :phrase, :role_ref, :num, :absorbed_precursors, :absorbed_followers, :common_supertype, :residual_adjectives
def initialize phrase, role_ref, num, absorbed_precursors, absorbed_followers, common_supertype, residual_adjectives
@phrase = phrase
@role_ref = role_ref
@num = num
@absorbed_precursors = absorbed_precursors
@absorbed_followers = absorbed_followers
@common_supertype = common_supertype
@residual_adjectives = residual_adjectives
end
def cost
absorbed_precursors + absorbed_followers + (common_supertype ? 1 : 0)
end
end
class ReadingMatchSideEffects
attr_reader :residual_adjectives
attr_reader :fact_type
attr_reader :role_side_effects # One array of values per RoleRef matched, in order
def initialize fact_type, reading, residual_adjectives, role_side_effects
@fact_type = fact_type
@reading = reading
@residual_adjectives = residual_adjectives
@role_side_effects = role_side_effects
end
def apply_all &b
@role_side_effects.reverse.each{ |role_side_effect| b.call(*role_side_effect) }
end
def cost
c = 0
@role_side_effects.each do |se|
c += se.cost
end
c + (@residual_adjectives ? 1 : 0)
end
def describe
actual_effects =
@role_side_effects.map do |se|
( [se.common_supertype ? "supertype join over #{se.common_supertype.name}" : nil] +
[se.absorbed_precursors > 0 ? "absorbs #{se.absorbed_precursors} preceding words" : nil] +
[se.absorbed_followers > 0 ? "absorbs #{se.absorbed_followers} following words" : nil]
)
end.flatten.compact*','
actual_effects.empty? ? "no side effects" : actual_effects
end
end
class RoleRef
attr_reader :term, :leading_adjective, :trailing_adjective, :quantifier, :function_call, :role_name, :value_constraint, :literal, :objectification_join
attr_reader :player
attr_accessor :binding
attr_accessor :reading # The reading that this RoleRef is part of
attr_accessor :role # This refers to the ActiveFacts::Metamodel::Role
attr_accessor :role_ref # This refers to the ActiveFacts::Metamodel::RoleRef
attr_accessor :objectification_of # If objectification_join is set, this is the fact type it objectifies
attr_reader :embedded_presence_constraint # This refers to the ActiveFacts::Metamodel::PresenceConstraint
attr_writer :leading_adjective
attr_writer :role_name # For assigning subscript when found in identifying roles list
def initialize term, leading_adjective = nil, trailing_adjective = nil, quantifier = nil, function_call = nil, role_name = nil, value_constraint = nil, literal = nil, objectification_join = nil
@term = term
@leading_adjective = leading_adjective
@trailing_adjective = trailing_adjective
@quantifier = quantifier
# @function_call = function_call # Not used or implemented
@role_name = role_name
@value_constraint = value_constraint
@literal = literal
@objectification_join = objectification_join
end
def inspect
"RoleRef<#{
@quantifier && @quantifier.inspect+' ' }#{
@leading_adjective && @leading_adjective.sub(/ |$/,'- ').sub(/ *$/,' ') }#{
@term }#{
@trailing_adjective && ' '+@trailing_adjective.sub(/(.* |^)/, '\1-') }#{
@role_name and @role_name.is_a?(Integer) ? "(#{@role_name})" : " (as #{@role_name})" }#{
@literal && ' '+@literal.inspect }#{
@value_constraint && ' '+@value_constraint.inspect
}#{
@objectification_join ? "(where #{@objectification_join.inspect})" : ""
}>"
end
def to_s
"#{
@quantifier && @quantifier.inspect+' ' }#{
@leading_adjective && @leading_adjective.sub(/ |$/,'- ').sub(/ *$/,' ') }#{
@role_name || @term }#{
@trailing_adjective && ' '+@trailing_adjective.sub(/(.* |^)/, '\1-') }#{
@literal && ' '+@literal.inspect }#{
@value_constraint && ' '+@value_constraint.inspect }"
end
def <=>(other)
( 4*(@term <=> other.term) +
2*((@leading_adjective||'') <=> (other.leading_adjective||'')) +
1*((@trailing_adjective||'') <=> (other.trailing_adjective||''))
) <=> 0
end
def identify_player context
@player = context.concept @term
raise "Concept #{@term} unrecognised" unless @player
context.player_by_role_name[@role_name] = player if @role_name
@player
end
def uses_role_name?
@term != @player.name
end
def key
if @role_name
key = [@term, @role_name] # Defines a role name
elsif uses_role_name?
key = [@player.name, @term] # Uses a role name
else
l = @leading_adjective
t = @trailing_adjective
key = [!l || l.empty? ? nil : l, @term, !t || t.empty? ? nil : t]
key
end
end
def bind context
if role_name = @role_name
# Omit these tests to see if anything evil eventuates:
#if @leading_adjective || @trailing_adjective
# raise "Role reference may not have adjectives if it defines a role name or uses a subscript: #{inspect}"
#end
else
if uses_role_name?
if @leading_adjective || @trailing_adjective
raise "Role reference may not have adjectives if it uses a role name: #{inspect}"
end
role_name = @term
end
end
@binding = (context.bindings[key] ||= Binding.new(@player, role_name))
@binding.refs << self
@binding
end
def unbind context
# The key has changed.
@binding.refs.delete(self)
if @binding.refs.empty?
# Remove the binding from the context if this was the last reference
context.bindings.delete_if {|k,v| v == @binding }
end
@binding = nil
end
def rebind(context)
unbind context
bind context
end
def rebind_to(context, other_role_ref)
debug :binding, "Rebinding #{inspect} to #{other_role_ref.inspect}"
old_binding = binding # Remember to move all refs across
unbind(context)
new_binding = other_role_ref.binding
[self, *old_binding.refs].each do |ref|
ref.binding = new_binding
new_binding.refs << ref
end
old_binding.rebound_to = new_binding
end
# These are called when we successfully match a fact type reading that has relevant adjectives:
def wipe_leading_adjective
@leading_adjective = nil
end
def wipe_trailing_adjective
@trailing_adjective = nil
end
def find_pc_over_roles(roles)
return nil if roles.size == 0 # Safeguard; this would chuck an exception otherwise
roles[0].all_role_ref.each do |role_ref|
next if role_ref.role_sequence.all_role_ref.map(&:role) != roles
pc = role_ref.role_sequence.all_presence_constraint.single # Will return nil if there's more than one.
#puts "Existing PresenceConstraint matches those roles!" if pc
return pc if pc
end
nil
end
def make_embedded_presence_constraint vocabulary
raise "No Role for embedded_presence_constraint" unless @role_ref
fact_type = @role_ref.role.fact_type
constellation = vocabulary.constellation
debug :constraint, "Processing embedded constraint #{@quantifier.inspect} on #{@role_ref.role.concept.name} in #{fact_type.describe}" do
# Preserve the role order of the reading, excluding this role:
constrained_roles = (@reading.role_refs-[self]).map{|rr| rr.role_ref.role}
if constrained_roles.empty?
debug :constraint, "Quantifier over unary role has no effect"
return
end
constraint = find_pc_over_roles(constrained_roles)
if constraint
debug :constraint, "Setting max frequency to #{@quantifier.max} for existing constraint #{constraint.object_id} over #{constraint.role_sequence.describe} in #{fact_type.describe}"
raise "Conflicting maximum frequency for constraint" if constraint.max_frequency && constraint.max_frequency != @quantifier.max
constraint.max_frequency = @quantifier.max
else
role_sequence = constellation.RoleSequence(:new)
constrained_roles.each_with_index do |constrained_role, i|
role_ref = constellation.RoleRef(role_sequence, i, :role => constrained_role)
end
constraint = constellation.PresenceConstraint(
:new,
:vocabulary => vocabulary,
:role_sequence => role_sequence,
:is_mandatory => @quantifier.min && @quantifier.min > 0, # REVISIT: Check "maybe" qualifier?
:max_frequency => @quantifier.max,
:min_frequency => @quantifier.min
)
debug :constraint, "Made new PC min=#{@quantifier.min.inspect} max=#{@quantifier.max.inspect} constraint #{constraint.object_id} over #{(e = fact_type.entity_type) ? e.name : role_sequence.describe} in #{fact_type.describe}"
@quantifier.enforcement.compile(constellation, constraint) if @quantifier.enforcement
@embedded_presence_constraint = constraint
end
constraint
end
end
end
class Quantifier
attr_accessor :enforcement
attr_reader :min, :max
def initialize min, max, enforcement = nil
@min = min
@max = max
@enforcement = enforcement
end
def inspect
"[#{@min}..#{@max}]"
end
end
end
end
end
| true |
73a571791a58f166c5c323100fa1bd458d80071f | Ruby | DannyBen/jossh | /lib/jossh/bin_handler.rb | UTF-8 | 2,805 | 2.578125 | 3 | [
"MIT"
] | permissive | require 'etc'
require 'docopt'
require 'colsole'
require 'fileutils'
module Jossh
class BinHandler
include Colsole
def handle(args)
begin
execute Docopt::docopt(doc, argv: args)
rescue Docopt::Exit => e
puts e.message
end
end
private
def execute(args)
return show_version if args['--version']
return make_hostfile if args['--make-hostfile']
return list_hosts if args['--list']
return edit_hosts if args['--edit-hostfile']
handle_script args['<host>'].dup, args['<script>'], arguments: args['<arguments>']
end
def handle_script(host, script, arguments: nil)
host = standardize_host host
begin
if File.exist? script
ssh_script! host, script, arguments: arguments
elsif File.exist? "#{Dir.home}/jossh/#{script}"
ssh_script! host, "#{Dir.home}/jossh/#{script}", arguments: arguments
else
ssh host, script
end
# :nocov:
rescue => e
abort e.message
end
# :nocov:
end
def standardize_host(str)
if str[0] == ':'
str[0] = ''
return str.to_sym
end
# :nocov:
# We DO have a test for these two cases, requires manual password type
if str =~ /^(.+)@(.+)$/
return { user: $1, host: $2 }
end
return { user: Etc.getlogin, host: str }
# :nocov:
end
def make_hostfile
abort "ssh_hosts.yml already exists" if File.exist?('ssh_hosts.yml')
FileUtils.copy template('ssh_hosts.yml'), './ssh_hosts.yml'
File.exist? './ssh_hosts.yml' or abort "Unable to create ssh_hosts.yml"
say "!txtgrn!Created ssh_hosts.yml"
end
def list_hosts
runner = CommandRunner.new
if runner.active_hostfile
say "!txtgrn!Using: #{runner.active_hostfile}\n"
runner.ssh_hosts.each do |key, spec|
if spec.is_a? Hash
say " :#{key.to_s.ljust(14)} = !txtblu!#{spec[:user]}!txtrst!@!txtylw!#{spec[:host]}"
else
say " :#{key.to_s.ljust(14)} = !txtpur!#{spec.join '!txtrst!, !txtpur!'}"
end
end
else
say "!txtred!Cannot find ssh_hosts.yml or ~/ssh_hosts.yml"
end
end
# :nocov:
def edit_hosts
runner = CommandRunner.new
if runner.active_hostfile
exec "${EDITOR:-vi} #{runner.active_hostfile}"
else
say "!txtred!Cannot find ssh_hosts.yml or ~/ssh_hosts.yml.\nRun 'jossh -m' to create one."
end
end
# :nocov:
def show_version
puts VERSION
end
def doc
return @doc if @doc
@doc = File.read template 'docopt.txt'
end
def template(file)
File.expand_path("../templates/#{file}", __FILE__)
end
end
end
| true |
447f8ca5645a3b6eebefc51e48fb6eb13e9c75ca | Ruby | kharumax/rails-realtime-talkapp | /app/models/user.rb | UTF-8 | 777 | 2.703125 | 3 | [] | no_license | class User < ApplicationRecord
validates :name,presence: true,length: {minimum: 3,maximum: 20}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email,presence: true,format: {with: VALID_EMAIL_REGEX},uniqueness: true
validates :password,presence: true,length: {minimum: 6}
has_secure_password
has_many :entries
has_many :messages
# 相手と自分のルームが存在する場合はそのroom_idの配列を返す、ない場合はFalseを返す
def room_exists?(user)
self_rooms = get_self_rooms
partner_rooms = user.entries.pluck(:room_id)
dup_rooms = self_rooms & partner_rooms
if !dup_rooms.empty?
dup_rooms
else
false
end
end
def get_self_rooms
self.entries.pluck(:room_id)
end
end
| true |
d90b81afcd03efb99fbf33652261d691f0d62011 | Ruby | mmpatel/global_settings | /global_setting.rb | UTF-8 | 802 | 2.75 | 3 | [] | no_license | class GlobalSetting < ActiveRecord::Base
validates :key_name, uniqueness: true, presence: true
validate :has_valid_key_type
def value=(obj)
self.key_type = obj.class.to_s
write_attribute(:key_value, obj)
@key_value = obj
end
def value
return @key_value unless @key_value.nil?
@key_value = case self.key_type.to_s
when "FalseClass"
false
when "Fixnum"
self.key_value.to_i
when "Float"
self.key_value.to_f
when "NilClass"
nil
when "String"
self.key_value
when "TrueClass"
true
end
end
protected
def has_valid_key_type
unless self.key_type.nil? || self.value.class.to_s != self.key_type
errors.add :base, "The class of the key value must be match with key type."
end
end
end | true |
c17d92ef04d0e0de2b4b6348819aadde71c31635 | Ruby | senthilkumarv/retail_analytics | /lib/simple_customer.rb | UTF-8 | 4,828 | 2.625 | 3 | [] | no_license | require 'set'
require 'date'
require 'sqlite3'
require './database'
def p(product, quantity)
{:product => product, :quantity => quantity}
end
def by_description(name, db)
row = db.get_first_row("select * from spree_products where name='#{name}'")
product = {:id => row[0], :name => row[1]}
variant = db.get_first_row("select id, price from spree_variants where product_id=#{product[:id]} and is_master='t'")
product[:variant_id] = variant[0]
product[:price] = variant[1]
product
end
def users(db)
row = db.execute("select id from spree_users").map {|c| c[0]}
end
def value(basket)
sum = 0
basket.each {|i| sum += i[:product][:price]}
sum
end
db = Database.create
phone = by_description("Zen Full Touch Dual Sim Phone - M28", db)
sdcard = by_description("Sandisk 32 GB Micro SD Ultra Card (Class 10)", db)
s3 = by_description("Samsung Galaxy S3 i9300 Mobile Phone - 16GB", db)
linen_kurta = by_description("Fab India Linen Kurta", db)
red_kurta = by_description("Fab India Red Kurta", db)
bracelet = by_description("Multicoloured Bracelet", db)
watch = by_description("Croco Pattern Leather Strap Watch", db)
tikkis = by_description("Kebabs & Tikkis - Tarla Dalal", db)
kitchen_set = by_description("Kitchen Linen Set", db)
biography = by_description("Steve Jobs: The Exclusive Biography", db)
ring = by_description("Ring", db)
tshirt = by_description("Ring", db)
cap = by_description("T shirt", db)
customers = users(db)
customer_frequency_distribution = {1..1 => 0.4, 2..3 => 0.2, 4..5 => 0.1, 6..10 => 0.2}
order_value_frequency_distribution = {1..500 => { :fraction_customers =>0.4, :basket_mix => [[p(tshirt,1)], [p(cap,1)], [p(ring,1), p(bracelet,1)]]},
501..2000 => { :fraction_customers =>0.3, :basket_mix => [[p(kitchen_set,1)], [p(tikkis,1)], [p(biography,1), p(cap, 1)]]},
2001..4000 => { :fraction_customers =>0.2, :basket_mix => [[p(sdcard,1), p(biography,1)], [p(watch,1), p(kitchen_set,1)], [p(linen_kurta,1), p(bracelet,1)]]},
4001..10000 => { :fraction_customers =>0.1, :basket_mix => [[p(linen_kurta,1), p(tshirt,1), p(watch,1)], [p(red_kurta,1), p(ring,1)], [p(s3, 1)]]}}
recency_frequency_distribution = { 0..7 => 0.3, 8..30 => 0.5, 31..80 => 0.2}
num_customers = 100
customers = customers[0..(num_customers - 1)]
ids = Set.new(customers)
transactions = []
transaction_number = 0
customer_frequency_distribution.each_pair do |k,v|
frequency = (v * num_customers).to_i
frequency.times do |f|
num_transactions = (rand(k.end - k.begin) + k.begin).to_i
as_array = ids.to_a
customer_index = as_array[rand(as_array.length).to_i]
num_transactions.times do |i|
transactions << {:id => customer_index, :transaction_id => transaction_number}
transaction_number += 1
end
ids.delete(customer_index)
end
end
ids = Set.new(customers)
order_value_frequency_distribution.each_pair do |k,v|
frequency = (v[:fraction_customers] * num_customers).to_i
frequency.times do |f|
as_array = ids.to_a
customer_index = as_array[rand(as_array.length).to_i]
selected = transactions.select {|t| t[:id] == customer_index}
selected.each do |t|
t[:basket] = v[:basket_mix][rand(v[:basket_mix].length)]
t[:value] = value(t[:basket])
end
ids.delete(customer_index)
end
end
start = Date.new(2012, 5, 1)
stop = Date.new(2012, 8, 1)
transactions.each do |t|
t[:date] = start + rand((stop - start).to_i)
end
ids = Set.new(customers)
recency_frequency_distribution.each_pair do |k,v|
frequency = (v * num_customers).to_i
frequency.times do |f|
as_array = ids.to_a
customer_index = as_array[rand(as_array.length).to_i]
selected = transactions.select {|t| t[:id] == customer_index}
selected.each do |t|
next if (stop - t[:date] >= k.begin && stop - t[:date] <= k.end)
t[:date] = stop - (k.begin + k.end).to_i/2 + rand(4) - 2
end
ids.delete(customer_index)
end
end
handle = File.open("data/op.csv", "w")
handle.puts("CustomerID, OrderValue, Date, TransactionID, ProductID, Quantity")
db.execute( "delete from spree_orders")
db.execute( "delete from spree_line_items")
transactions.each do |t|
db.execute( "insert into spree_orders (id, item_total, total, user_id, payment_total, created_at, updated_at, state) values (?, ?, ?, ?, ?, ?, ?, ?)", t[:transaction_id], t[:value], t[:value], t[:id], t[:value], t[:date].to_s, t[:date].to_s, "complete")
end
transactions.each do |t|
t[:basket].each do |mix|
db.execute( "insert into spree_line_items (order_id, variant_id, quantity, price, created_at, updated_at) values (?, ?, ?, ?, ?, ?)", t[:transaction_id], mix[:product][:variant_id], mix[:quantity], mix[:product][:price], t[:date].to_s, t[:date].to_s)
handle.puts("#{t[:transaction_id]}, #{t[:value]/t[:basket].length}, #{t[:date]}, #{t[:transaction_id]}, #{mix[:product][:id]}, #{mix[:quantity]}")
end
end
handle.close
| true |
cea565af6b22c5b6dd27c1a74a4d3f6e9499c933 | Ruby | mcgain/computationbook | /the_meaning_of_programs/big_step/add.rb | UTF-8 | 193 | 2.859375 | 3 | [
"CC0-1.0"
] | permissive | require_relative '../syntax/add'
require_relative 'number'
class Add
def evaluate(environment)
Number.new(left.evaluate(environment).value + right.evaluate(environment).value)
end
end
| true |
329c1db8e7315ffd21f32cab33f665fe25b6fa76 | Ruby | AshleyRapone/programming_foundations | /small_problems_exercises/Easy7Q5.rb | UTF-8 | 1,938 | 4.65625 | 5 | [] | no_license | # Write a method that takes a String as an argument, and returns a new String that contains
# the original value using a staggered capitalization scheme in which every other character is capitalized,
# and the remaining characters are lowercase.
# Characters that are not letters should not be changed, but count as characters when
# switching between upper and lowercase.
def staggered_case(string)
result = ''
need_upper = true
string.chars.each do |char|
if need_upper
result += char.upcase
else
result += char.downcase
end
need_upper = !need_upper
end
result
end
staggered_case('I Love Launch School!')
staggered_case('ALL_CAPS')
staggered_case('ignore 77 the 444 numbers')
=begin
-Input: string
-set result variable to an empty string ''
-set need upper variable to true
-take string and turn it into array of characters
-iterate through the array of characters
-if need upper is true
-add upcase character to result variable
-else
-add downcase charafcter to result variable
-end
-set need_upper to false
-return result
=end
#or
def staggered_case(string)
swap = []
characters = string.chars
index = 0
while index <= characters.size
if index.even? && characters[index] =~ /['a-z']/
swap << characters[index].upcase
elsif index.odd? && characters[index] =~ /['A-Z']/
swap << characters[index].downcase
else
swap << characters[index]
end
index += 1
end
swap.join
end
staggered_case('I Love Launch School!')
staggered_case('ALL_CAPS')
staggered_case('ignore 77 the 444 numbers')
def staggered_case(string)
staggered = ''
index = 0
while index < string.length
staggered << string[index].upcase if index.even?
staggered << string[index].downcase if index.odd?
index += 1
end
staggered
end
staggered_case('I Love Launch School!')
staggered_case('ALL_CAPS')
staggered_case('ignore 77 the 444 numbers')
| true |
d331de875c215560bd850a503169fe6162f8e879 | Ruby | elizabrock/NSS-futureperfect-CLI | /app/models/project.rb | UTF-8 | 1,362 | 2.59375 | 3 | [
"MIT"
] | permissive | class Project < ActiveRecord::Base
validates_presence_of :name
validates_uniqueness_of :name, message: "must be unique"
default_scope order("completed_at ASC, last_worked_at ASC, id ASC")
scope :finished, where("completed_at IS NOT NULL")
scope :unfinished, where("completed_at IS NULL")
scope :currently_skipped, lambda{ where("skip_until > ?", Time.now) }
scope :not_currently_skipped, lambda{ where("skip_until IS NULL OR skip_until <= ?", Time.now) }
scope :unworkable, lambda{ unfinished.where("skip_until > ? OR last_worked_at >= ?", Time.now, Date.today - 1) }
scope :workable, lambda{ unfinished.not_currently_skipped.where("last_worked_at IS NULL OR last_worked_at < ?", Date.today - 1) }
def complete?
!!completed_at
end
def countdown( countfast = false)
minutes = countfast ? 1 : minutes_to_work
@countdown ||= Countdown.new(minutes)
end
def stop_working! opts = {}
if opts[:forever]
complete
elsif opts[:skipped]
process_skipped
else
process_worked
end
save!
end
private
def complete
self.completed_at = Time.now
end
def process_skipped
self.skip_until = Date.today + 1
end
def process_worked
time_adjustment = (countdown.done?) ? 1 : -1
self.minutes_to_work += time_adjustment
self.last_worked_at = Time.now
end
end
| true |
c64fb52f5897790abcbd50dd74d177618d92c38a | Ruby | Agould94/Crypto_prices_app | /lib/User/portfolio/Portfolio.rb | UTF-8 | 2,053 | 3.484375 | 3 | [
"MIT"
] | permissive | class Portfolio
attr_accessor :name, :coin_value, :total_value, :num, :user
@@all = []
def initialize(currency, num, name = nil)
@name = currency.name
@coin_value = currency.price
@num = num
@user = User.find_by_username(name)
@@all<<self
end
def self.all
@@all
end
def self.total_value
self.all.map{|coin| coin.coin_value.to_f.round(2)*coin.num.to_f.round(2)}.sum
end
def self.find_by_username(name)
self.all.select{|coin| coin if coin.user.username == name}
end
def self.find_by_coin_name(coin_name)
self.all.find{|coin| coin.name == coin_name}
end
def self.find_by_username_and_name(name, coin_name)
self.find_by_username(name).find{|coin| coin.name == coin_name}
end
def add_user(name)
@user = User.find_by_username(name)
end
def self.create(hash, num, name)
self.new(hash, num, name)
end
def self.find_or_create(name, hash, num)
name = self.find_by_name(name) || self.create(hash, num, name)
end
def self.print_portfolio
self.all.map do |coin|
puts "#{coin.name}: #{coin.num} : $#{(coin.num.to_f.round(2))*(coin.coin_value.to_f.round(2))}"
end
end
def self.portfolio_total(name)
t = self.find_by_username(name).map{|coin| coin.num.to_f*coin.coin_value.to_f}.sum
sprintf("%0.02f", t)
end
def self.print_user_portfolio(name)
portfolio = self.find_by_username(name)
if portfolio.length > 0
puts "#{name.capitalize}'s portfolio:"
portfolio.map do |coin|
if coin.num.to_f.round(2) > 0
puts "#{coin.name}: #{coin.num} : $#{sprintf("%0.02f", coin.num.to_f*coin.coin_value.to_f)}"
else
nil
end
end
puts "Portfolio total: $#{self.portfolio_total(name)}"
else
puts "Your portfolio is currently empty"
end
end
end | true |
abf91cd940691c83ee61f0696d41cf8dcbcbf92c | Ruby | mm86/Ruby101 | /Hashes/ex3.rb | UTF-8 | 166 | 3.21875 | 3 | [] | no_license | years = { "a" => 1981, "b" => 1876 }
years.keys.each { |key| puts key }
years.values.each { |val| puts val }
years.each do |key, value|
puts "#{key}, #{value}"
end | true |
39143d6e7d0813257f1aa6aa718550154dddfda4 | Ruby | michaelphines/chirb-mastermind | /spec/mastermind/game_starting_spec.rb | UTF-8 | 1,230 | 2.546875 | 3 | [] | no_license | require File.join(File.dirname(__FILE__), "/../spec_helper")
module Mastermind
describe Game do
context "starting up" do
before(:each) do
@messenger = mock("messenger").as_null_object
@game = Game.new(@messenger)
end
describe "#start" do
it "should generate a random code if one is not given" do
Game.should_receive(:random_code).and_return("random code")
@game.start
@game.instance_variable_get("@secret_code").should == "random code"
end
it "should use the given code" do
code = %w[w w w w]
@game.start(code)
@game.instance_variable_get("@secret_code").should == code
end
it "should send a welcome message" do
@messenger.should_receive(:puts).with("Welcome to Mastermind!")
@game.start(%w[w w w w])
end
it "should prompt for the first guess" do
@messenger.should_receive(:puts).with("Enter guess (bcgryw) or 'exit':")
@game.start(%w[w w w w])
end
end
describe "#over" do
it "should be false" do
@game.should_not be_over
end
end
end
end
end
| true |
ad916ca5a65d710aec6fe3801d56ca6722b47695 | Ruby | nicholaslemay/adventofcode2016 | /day1/part_two/hq_distance_tracker.rb | UTF-8 | 1,062 | 3.25 | 3 | [] | no_license | class HqDistanceTracker
def initialize
@current_direction = :north
@x_axis_position = 0
@y_axis_position = 0
@visited_coordinates = []
end
def distance_from_hq(moves_to_perform)
move = moves_to_perform.first
@current_direction = move.target_direction_after_facing(@current_direction)
1.upto(move.distance) do
move_forward_in_current_direction
return current_distance_from_hq if @visited_coordinates.include?(current_coordinates)
@visited_coordinates << current_coordinates
end
distance_from_hq(moves_to_perform.drop(1))
end
private
def current_coordinates
return [@x_axis_position, @y_axis_position]
end
def move_forward_in_current_direction
@x_axis_position += 1 if (@current_direction == :east)
@x_axis_position -= 1 if (@current_direction == :west)
@y_axis_position += 1 if (@current_direction == :north)
@y_axis_position -= 1 if (@current_direction == :south)
end
def current_distance_from_hq
@y_axis_position.abs + @x_axis_position.abs
end
end
| true |
fcc1cc523eb2a5fdc4d96d3f7347e692c0966bad | Ruby | marcusrussi/yo-tools | /process.rb | UTF-8 | 992 | 2.71875 | 3 | [] | no_license | system('rm -f email\*; rm -f yale\*')
line = ""
emails = []
yale_emails = []
bad_emails = []
f = File.open('bad_emails')
while true
line = f.gets
break if line.nil?
b = line.split(', ')
b.each do |e|
bad_emails << e.strip
end
end
f = File.open('bad_emails_line', 'w')
bad_emails.each do |e|
f.puts e
end
while true
line = gets
break if line.nil?
line = line.strip
if line[0] == '#' || line == ''
next
end
if line.include?('@yale.edu')
yale_emails << line unless yale_emails.include?(line) || bad_emails.include?(line)
else
emails << line.strip unless emails.include?(line.strip) || bad_emails.include?(line)
end
end
count = 1
yale_emails.each_slice(1000) do |e|
f = File.open("yale#{count}", 'w')
e.each do |a|
f.print a
f.print ", "
puts a
end
count += 1
end
count = 1
emails.each_slice(10) do |e|
f = File.open("foreign#{count}", 'w')
e.each do |a|
f.print a
f.print ", "
puts a
end
count += 1
end
| true |
94935a0699507130c2d07ca35c03cfba5d2c56b6 | Ruby | hochardga/DecksterRails | /lib/application/geo.rb | UTF-8 | 240 | 3.3125 | 3 | [
"MIT"
] | permissive | class Geo
attr_accessor :lat, :long
def initialize lat, long
@lat = lat
@long = long
end
def self.parse value
values = value.split ','
Geo.new values[0], values[1]
end
def to_s
"#{@lat},#{@long}"
end
end | true |
b494042bfdc5dd10470f39283dc494a559d8d268 | Ruby | nathanworden/100-Programming-Back-end-Prep | /100 Ruby Basics/13. Debugging/01. Reading Error Messages.rb | UTF-8 | 1,792 | 4.4375 | 4 | [] | no_license | # Reading Error Messages
# You come across the following code. What errors does it raise for the given examples and what exactly do the error messages mean?
def find_first_nonzero_among(numbers)
numbers.each do |n|
return n if n.nonzero?
end
end
# # Examples
find_first_nonzero_among(0, 0, 1, 0, 2, 0)
find_first_nonzero_among(1)
# My Answer:
# Argument Error. when find_first_nonzero_among is defined
# it only has one argument. Then the first time you call
# it you put 6 arguments in. If you want to put 6 arguments in
# then you need to first define it to accept that many arguments
# or have a default value.
# Book Answer:
# Solution
# This method is expecting an array of integers to be passed in as the argument. The example method invocations should look like this:
# find_first_nonzero_among([0, 0, 1, 0, 2, 0])
# find_first_nonzero_among([1])
# Discussion
# The first method invocation (line 9) raises an ArgumentError on line 1:
# example.rb:1:in `find_first_nonzero_among': wrong number of arguments (given 6, expected 1) (ArgumentError)
# The error message tells you that the method find_first_nonzero_among was given 6 arguments but expects only 1 (specified by the parameter numbers).
# The second method invocation (line 10) receives the correct number of arguments, so no error is raised on line 1. However, as soon as the program tries to evaluate line 2 with the given argument, it raises a NoMethodError:
# example.rb:2:in `find_first_nonzero_among': undefined method `each' for 1:Integer (NoMethodError)
# This is because the method parameter numbers is now bound to the provided argument 1, so it tries to evaluate 1.each do ... end, i.e. it tries to call each on the Integer 1. Since integers do not have an each method, this raises a NoMethodError. | true |
41b200967af83b6cb1162c4a35168ea455714667 | Ruby | shkfnly/appacademy | /w2d2/rubychess/lib/chess.rb | UTF-8 | 1,186 | 2.765625 | 3 | [
"MIT"
] | permissive | require 'colorize'
require 'byebug'
require_relative "./chess/tile.rb"
require_relative "./chess/piece.rb"
require_relative "./chess/board.rb"
require_relative "./chess/pieces/bishop.rb"
require_relative "./chess/pieces/king.rb"
require_relative "./chess/pieces/knight.rb"
require_relative "./chess/pieces/pawn.rb"
require_relative "./chess/pieces/queen.rb"
require_relative "./chess/pieces/rook.rb"
require_relative "./chess/pieces/sliding_piece.rb"
require_relative "./chess/pieces/stepping_piece.rb"
require_relative "./chess/game.rb"
require_relative "./chess/player.rb"
module Chess
WHITE_UNICODE_PIECES = {
:K => "\u265A".encode("UTF-8"),
:Q => "\u265B".encode("UTF-8"),
:B => "\u265D".encode("UTF-8"),
:R => "\u265C".encode("UTF-8"),
:N => "\u265E".encode("UTF-8"),
:P => "\u265F".encode("UTF-8")
}
BLACK_UNICODE_PIECES = {
:K => "\u2654".encode("UTF-8"),
:Q => "\u2655".encode("UTF-8"),
:B => "\u2657".encode("UTF-8"),
:R => "\u2656".encode("UTF-8"),
:N => "\u2658".encode("UTF-8"),
:P => "\u2659".encode("UTF-8")
}
class InvalidMoveError < ArgumentError
end
end
b = Chess::Game.new
b.start(b.prompt_player)
| true |
31ea61b72751dd2905d754fc54690378c8093b81 | Ruby | marcbobson2/lessons | /ch10_final/problem3.rb | UTF-8 | 86 | 3.03125 | 3 | [] | no_license | num=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x_array=num.select {|val| val.odd?}
p x_array
| true |
9878453f35a6feaeb99925666afba58930975198 | Ruby | mach1010/odin | /ruby/data_structures/show_nodes.rb | UTF-8 | 1,167 | 3.25 | 3 | [] | no_license |
def levels(current, parents = [current], level_ary = [[current]])
if parents.compact.empty?
level_ary.pop
return level_ary.map {|x| x.map{|y| y ? y.value.to_s : 'x'}}
end
level = []
parents.each do |parent|
if parent
level << (parent.left ? parent.left : nil)
level << (parent.right ? parent.right : nil)
else
2.times {level << nil}
end
parents = []
end
level_ary << level
levels(current, level, level_ary)
end
def print(root)
level_array = levels(root)
base = level_array.last.join.size
return "BST base wider than 80chars, aborting..." if base > 80
level_array.each_with_index do |level, index|
# offset = ( base - level.join.size )/( 2 ** ( index ) )
offset = base / ( 2 ** ( index ) )
level_string = ''
level.each do |x|
index_number = offset - x.size >= 0 ? (offset - x.size) : 0
level_string << ( ' ' * index_number) + x + ( ' ' * (offset) )
end
puts level_string
end
nil
end
# Using algorithms in search to create a BST, you can use the following
# syntax to create a visual BST (probably not more than 6 child nodes deep...)
# print(root_node_here) | true |
65e02dd0d728c619c9efc0cace917f3e30c754c1 | Ruby | 7Joe7/TaskManager | /app/modules/data_helper.rb | UTF-8 | 408 | 2.640625 | 3 | [] | no_license | module DataHelper
def load_data(address, klass)
structure = []
JSON.parse(load_file_text(address), {:symbolize_names => true}).each do |name, pars|
structure << klass.new({name: name.to_s}.merge(pars))
end
structure
end
def save_data(data, address)
hash = {}
data.each { |entry| hash.merge!(entry.to_hash) }
create_file(address, JSON.pretty_generate(hash))
end
end | true |
9ede49f8758f16a5614875a85bf14ca18bac54fc | Ruby | jywei/didactic-enigma | /lib/core_ext/datetime.rb | UTF-8 | 103 | 2.703125 | 3 | [] | no_license | class DateTime
def self.mil(modifier = 0)
(now + modifier.seconds).strftime('%Q').to_i
end
end
| true |
63e74d7794ba739f87132d5abb470d0362561e69 | Ruby | bc-luke/panier | /lib/panier/domain/product_service.rb | UTF-8 | 1,499 | 3.15625 | 3 | [
"MIT"
] | permissive | require 'money'
module Panier
module Domain
##
# The product service provides a means of finding and retrieving products
# from the product catalog.
#
# This is an in-memory implementation, useful for testing, which contains
# only the products from the given input data. A real-world implementation
# would be backed by a database or web service.
#
class ProductService
def initialize
@tax = TaxClass.new('Basic sales tax', 0.1)
@duty = TaxClass.new('Import duty', 0.05)
@products = product_data.map do |row|
Product.new(*row)
end
end
def product_data
[['book', Money.new(1249)],
['music CD', Money.new(1499), [@tax]],
['chocolate bar', Money.new(85)],
['imported box of chocolates', Money.new(1000), [@duty]],
['imported bottle of perfume', Money.new(4750), [@tax, @duty]],
['imported bottle of perfume', Money.new(2799), [@tax, @duty]],
['bottle of perfume', Money.new(1899), [@tax]],
['packet of headache pills', Money.new(975)],
['box of imported chocolates', Money.new(1125), [@duty]]]
end
##
# Finds a product matching the given name and price.
#
# @param [String] name
# @param [Money] price
def find_by_name_and_price(name, price)
@products.find do |product|
product.name == name && product.price == price
end
end
end
end
end
| true |
aed92b8ba449097e5f13af98196e611d81fdf9fe | Ruby | juanriglos/trabajo_final | /app/models/turn.rb | UTF-8 | 1,358 | 2.640625 | 3 | [] | no_license | class Turn < ApplicationRecord
belongs_to :user
has_many :turn_resources
has_many :resources, through: :turn_resources
validates :start_date, presence: true
validates :end_time, presence: true
validate :controlar_que_un_recurso_no_esta_asociado_a_un_turno_en_ese_horario
validate :controlar_fecha_de_fin_mayor_a_fecha_de_inicio
def controlar_que_un_recurso_no_esta_asociado_a_un_turno_en_ese_horario
if self.resources.length > 0
self.resources.each do |recurso|
Turn.all.each do |turno|
turno.resources.each do |recurso_turno|
if recurso_turno.name == recurso.name
if self.start_date >= turno.end_time || self.end_time <= turno.start_date
puts "devuelve true"
return true
else
puts "devuelve false"
return false
end
end
end
end
end
else
errors.add(:base, "No se han seleccionado recursos")
return false
end
end
def controlar_fecha_de_fin_mayor_a_fecha_de_inicio
if self.start_date > self.end_time
return false
else
return true
end
end
end
| true |
5cd2e132bebc3b23cd186b6857abfafef164a4a9 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/cs169/800/feature_try/whelper_source/18125.rb | UTF-8 | 251 | 3.15625 | 3 | [] | no_license | def combine_anagrams(words)
word_cat = {}
words.each do |w|
s = w.downcase.split(//).sort
word_cat[s] ? (word_cat[s].push(w)) : (word_cat[s] = [w])
end
result = []
word_cat.each { |cat, wrds| result.push(wrds) }
return result
end
| true |
3545d30567c93db346782b0b13a2c83f75cb76a2 | Ruby | abe196201/fhss | /app/models/transaction.rb | UTF-8 | 193 | 2.546875 | 3 | [] | no_license | class Transaction
# Methods
def self.amount_for_type(type)
case type
when 'monthly' then 3995
when 'monthly_monitoring' then 2000
when 'purchase' then 700
end
end
end
| true |
da6cba8bafa6505f798a08d85b9127f32b877c79 | Ruby | IanDCarroll/workbookExercises | /Learn_Ruby_the_Hard_Way/ex44/ex44e.rb | UTF-8 | 518 | 3.265625 | 3 | [] | no_license | class Hammer
def override
puts "OTHER override()"
end
def implicit
puts "OTHER implicit()"
end
def altered
puts "OTHER altered()"
end
end
class Child
def initialize
@hammer = Hammer.new
end
def implicit
@hammer.implicit
end
def override
puts "CHILD override()"
end
def altered
puts "CHILD, BEFORE OTHER altered()"
@hammer.altered
puts "CHILD, AFTER OTHER altered()"
end
end
maxwell = Child.new
maxwell.implicit
maxwell.override
maxwell.altered
| true |
6f7237e908be211329248554ef634d36d4a212d1 | Ruby | jhbadger/scripts | /buildOneWayVennCsv | UTF-8 | 1,018 | 2.8125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'optparse'
require 'ostruct'
require 'Btab'
require 'csv'
opt = OpenStruct.new
o = OptionParser.new
o.banner << " btab [..btab...]"
o.on("-v", "--verbose", "Run verbosely") {opt.verbose = true}
begin
o.parse!
rescue
STDERR << $!.message << "\n"
STDERR << o
exit(1)
end
if (ARGV.size < 1)
STDERR << o
exit(1)
end
hits = Hash.new
categories = []
ARGV.each do |btab|
source, target = btab.split("_vs_")
source = source.split(".").first
target = target.split(".").first
categories.push(source) if (!categories.include?(source))
categories.push(target) if (!categories.include?(target))
Btab.new(btab).each do |query|
hits[query.name] = Hash.new if (!hits[query.name])
hits[query.name][target] = query.matches.first.name
hits[query.name][source] = query.name
end
end
print (["Representative"] + categories).to_csv
hits.keys.sort.each do |hit|
row = [hit]
categories.each do |category|
row.push(hits[hit][category])
end
print row.to_csv
end
| true |
71f8eb033c7d5dd1e8402ae7a04545d8177e3a97 | Ruby | TSMMark/homophone | /spec/routing/word_sets_spec.rb | UTF-8 | 2,166 | 2.65625 | 3 | [] | no_license | require 'spec_helper'
describe "short word_set path" do
let(:word_set) do
WordSet.create do |word_set|
word_set.words = %w(wh wha what)
end
end
it "default path helper uses #id" do
expect(word_set_path(word_set)).to eq("/h/#{word_set.id}")
end
it "routes to show" do
expect(:get => "/h/#{word_set.id}").to route_to(
:controller => "word_sets",
:action => "show",
:id => word_set.id.to_s
)
end
describe "slug path helper" do
context "when word_set has a slug" do
before do
Slug.create_for_word_set(word_set)
end
it "uses #to_slug" do
expect(word_set.slug).not_to be_nil
expect(word_set_slug_path(word_set.to_slug)).to eq("/h/#{word_set.to_slug}")
end
end
context "when word_set has no slug" do
it "uses #id" do
expect(word_set.slug).to be_nil
expect(word_set_slug_path(word_set.to_slug)).to eq("/h/#{word_set.id}")
end
end
end
end
describe "vanity word_set path" do
context "when words have weird characters" do
[
[%w(h3l1uM SKY-net 48295), "48295-h3l1um-sky-net", true],
[%w(its' it's its), "it-s-its-its", true],
[%w(porter+robinson porter(robinson)), "porter-robinson-porter-robinson", true]
].each do |words, expected_slug, expected_route|
context "when words are #{words.map(&:inspect).join(", ")}" do
let(:word_set) do
WordSet.create.tap do |word_set|
word_set.words = words
end
end
let(:slug) do
Slug.create_for_word_set(word_set)
end
before do
slug
end
describe "#to_slug" do
it "sorts the elements and generates the slug: #{expected_slug.inspect}" do
expect(word_set.to_slug).to eq(expected_slug)
end
end
it "#{expected_route ? "routes" : "does not route"}" do
expect(:get => word_set_slug_path(word_set.to_slug)).to route_to(
:controller => "word_sets",
:action => "from_slug",
:slug => word_set.to_slug
)
end
end
end
end
end
| true |
e6331d57afa8d70f57e0b86bb3ed14d9ea1cb826 | Ruby | aidenmendez/sweater-weather | /app/poros/short_forecast.rb | UTF-8 | 184 | 3 | 3 | [] | no_license | class ShortForecast
attr_reader :temperature, :conditions
def initialize(temperature = nil, conditions = nil)
@temperature = temperature
@conditions = conditions
end
end | true |
3ff0c375a4976ef1ff5f5709811a9bd210c21c20 | Ruby | medericgb/16-08-2021 | /post-api/main.rb | UTF-8 | 1,287 | 2.71875 | 3 | [] | no_license | require "rest-client"
require "json"
require "csv"
# Get all posts from remote url
posts_url = "https://jsonplaceholder.typicode.com/posts?_start=0&_limit=20"
comments_url = "https://jsonplaceholder.typicode.com/post/5/comments"
list_comments = Array.new
all_comments = Array.new
comments_array = Array.new
for i in 1..20
comment = "https://jsonplaceholder.typicode.com/post/#{i}/comments"
list_comments.push(comment)
end
for comments_link in list_comments
comments = RestClient.get(comments_link)
all_comments.push(JSON.parse(comments))
# puts comments.class
end
posts = RestClient.get(posts_url)
comments = RestClient.get(comments_url)
p all_comments
# Create CSV File for posts
def create_csv_doc(source, file_link)
# Get all headers
@headers = []
JSON.parse(source).each do |h|
h.keys.each do |key|
@headers << key
end
end
# Uniq headers
uniq_headers = @headers.uniq
finalrow = []
JSON.parse(source).each do |h|
final = {}
@headers.each do |key2|
final[key2] = h[key2]
end
finalrow << final
end
CSV.open(file_link , 'w') do |csv|
csv << uniq_headers
finalrow.each do |deal|
csv << deal.values
end
end
end
# create_csv_doc(posts, 'posts.csv')
create_csv_doc(all_comments, 'comments.csv') | true |
0ef09c52b31bcaedfae6ef715117c2901e30642d | Ruby | larrytheliquid/rack-client | /lib/rack/client/http.rb | UTF-8 | 1,759 | 2.734375 | 3 | [
"MIT"
] | permissive | require 'net/http'
class Rack::Client::HTTP
def self.call(env)
new(env).run
end
def initialize(env)
@env = env
end
def run
case request.request_method
when "HEAD"
head = Net::HTTP::Head.new(request.path, request_headers)
http.request(head) do |response|
return parse(response)
end
when "GET"
get = Net::HTTP::Get.new(request.path, request_headers)
http.request(get) do |response|
return parse(response)
end
when "POST"
post = Net::HTTP::Post.new(request.path, request_headers)
post.body = @env["rack.input"].read
http.request(post) do |response|
return parse(response)
end
when "PUT"
put = Net::HTTP::Put.new(request.path, request_headers)
put.body = @env["rack.input"].read
http.request(put) do |response|
return parse(response)
end
when "DELETE"
delete = Net::HTTP::Delete.new(request.path, request_headers)
http.request(delete) do |response|
return parse(response)
end
else
raise "Unsupported method: #{request.request_method.inspect}"
end
end
def http
Net::HTTP.new(request.host, request.port)
end
def parse(response)
status = response.code.to_i
headers = {}
response.each do |key,value|
key = key.gsub(/(\w+)/) do |matches|
matches.sub(/^./) do |char|
char.upcase
end
end
headers[key] = value
end
[status, headers, response.body.to_s]
end
def request
@request ||= Rack::Request.new(@env)
end
def request_headers
headers = {}
@env.each do |k,v|
if k =~ /^HTTP_(.*)$/
headers[$1] = v
end
end
headers
end
end
| true |
d7474ae38fcf758249f9447db1d6eae4121e09ac | Ruby | stuartc/marsbot | /bin/marsbot | UTF-8 | 590 | 2.796875 | 3 | [] | no_license | #!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path("#{File.dirname(__FILE__)}/../lib")
require 'marsbot'
input =
if STDIN.tty?
begin
filename = ARGV[-1]
File.read(filename)
rescue Errno::ENOENT
puts("File doesn't exist")
exit(1)
rescue TypeError
puts('No file name provided')
exit(1)
end
else
$stdin.read
end
begin
puts Marsbot::Parser.parse(input).inspect
rescue ArgumentError
puts 'An error occurred while parsing'
exit(2)
rescue Exception
puts 'An error occurred'
exit(10)
end
| true |
1f1dc12ee97d2f90a0ff25ccad741bb78612ebdd | Ruby | huyphung1602/ddd_example | /app/domains/order_taking/domain_types/unvalidated_order.rb | UTF-8 | 705 | 2.5625 | 3 | [] | no_license | # typed: strict
# Example:
# OrderTaking::DomainTypes::UnvalidatedOrder.new({ id: 1, customer_info: ci, shipping_address: '181 Cao Thang', billing_address: '181 Cao Thang', order_lines: ols})
# ol1 = OrderTaking::DomainTypes::OrderLine.new({ id: 1, order_id: 1, product_code: 'G001', order_quantity: 1.5, price: 0 })
# ol2 = OrderTaking::DomainTypes::OrderLine.new({ id: 1, order_id: 1, product_code: 'W0001', order_quantity: 3, price: 0 })
module OrderTaking::DomainTypes
class UnvalidatedOrder < T::Struct
prop :id, Integer
prop :customer_info, UnvalidatedCustomerInfo
prop :shipping_address, String
prop :billing_address, String
prop :order_lines, T::Array[OrderLine]
end
end
| true |
fe839118c57834b17922968d3b7443912b0bb1eb | Ruby | tommy-russoniello/pantry-buddy | /lib/fdc.rb | UTF-8 | 3,451 | 2.546875 | 3 | [] | no_license | module Fdc
API_HOST = 'api.nal.usda.gov'.freeze
API_KEY = ENV.fetch('FDC_API_KEY')
SEARCH_PATH = '/fdc/v1/foods/search'.freeze
class << self
def get_data_from_upc(upc)
data = send_request(
host: API_HOST,
method: :get,
name: 'UPC lookup',
path: SEARCH_PATH,
query: { query: upc }
)&.dig('foods')&.find { |food| food['gtinUpc'] == upc }
return unless data
nutrients_data = data['foodNutrients'].map do |nutrient_data|
nutrient = nutrient_mappings[nutrient_data['nutrientId'].to_s]
next unless nutrient
value =
case nutrient_data['unitName']
when 'G'
nutrient_data['value']
when 'MG'
nutrient_data['value'] / 1_000
when 'UG'
nutrient_data['value'] / 1_000_000
when 'IU'
international_units_to_grams(nutrient_data['value'], nutrient)
when 'KCAL'
nutrient_data['value']
end
# The FDC API returns nutrient values based on 100 grams of the item
value /= 100 if value
[nutrient, value]
end.compact.sort_by(&:first).to_h
{
fdc_id: data['fdcId'],
name: data['description'],
nutrients: nutrients_data
}
end
private
def international_units_to_grams(value, type)
case type
# One IU of Vitamin A is equivalent to 0.3 micrograms of retinol
when :vitamin_a
value * 0.0000003
# One IU of Vitamin D is equivalent to 0.025 micrograms of cholecalciferol or ergocalciferol
when :vitamin_d
value * 0.000000025
end
end
def nutrient_mappings
@nutrient_mappings ||= {
'1235' => :added_sugar,
'1087' => :calcium,
'1008' => :calories,
'1005' => :carbs,
'1253' => :cholesterol,
'1004' => :fat,
'1079' => :fiber,
'1089' => :iron,
'1090' => :magnesium,
'1292' => :monounsaturated_fat,
'1167' => :niacin,
'1091' => :phosphorus,
'1293' => :polyunsaturated_fat,
'1092' => :potassium,
'1003' => :protein,
'1166' => :riboflavin,
'1258' => :saturated_fat,
'1093' => :sodium,
'2000' => :sugar,
'1165' => :thiamin,
'1257' => :trans_fat,
'1104' => :vitamin_a,
'1175' => :vitamin_b6,
'1178' => :vitamin_b12,
'1162' => :vitamin_c,
'1110' => :vitamin_d,
'1109' => :vitamin_e,
'1185' => :vitamin_k,
'1095' => :zinc
}
end
def send_request(body: nil, headers: {}, host:, method:, name: nil, path: '', query: {})
ActiveSupport::JSON.decode(
RestClient::Request.execute(
headers: headers,
method: method,
payload: body,
url: URI::HTTPS.build(
host: host,
path: path,
query: query.merge(api_key: API_KEY).to_query
).to_s
)
)
rescue RestClient::ExceptionWithResponse => error
error_response =
begin
ActiveSupport::JSON.decode(error.response || '')['message']
rescue JSON::ParserError
error.response
end
message = error_response || error.message
Rails.logger.error("FDC#{' ' if name.present?}#{name} error: #{message}")
nil
rescue JSON::ParserError
nil
end
end
end
| true |
90abd42e36f408046b08fdb4ddc43dbd7538fe2a | Ruby | krlawrence/SVG | /generators/svg-manycircles.rb | UTF-8 | 648 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | puts "<html>"
puts "<head>"
puts "<meta name='description' content='Machine generated SVG using a Ruby script.' />"
puts "<meta name='author' content='Kelvin R. Lawrence' />"
puts "<meta name='created' content='#{Time.now}' />"
puts "</head>"
puts "<body>"
puts"<svg xmlns='http://www.w3.org/2000/svg' version='1.1' width='2000' height='1000'>"
rad = 255
cx = 300
cy = 300
r = b = 0
puts "<g stroke='none'>"
#255.downto 1 do |g|
1.upto 255 do |g|
#fill = "rgb(#{r},#{g},#{b})"
fill = "rgb(#{r},#{g},#{g})"
puts "<circle cx='#{cx}' cy='#{cy}' r='#{rad}' fill='#{fill}'/>"
rad -= 1
end
puts "</g>"
puts "</svg>"
puts "</body>"
puts "</html>"
| true |
616bd6f878c3305814cffcab789169c050dd175a | Ruby | drabelpdx/Epi_W2_vehicles | /lib/vehicle.rb | UTF-8 | 837 | 3.109375 | 3 | [] | no_license | require('pry')
class Vehicle
@@vehicles = []
define_method(:initialize) do |make, model, year|
@make = make
@model = model
@year = year
@id = @@vehicles.length.+(1)
end
define_method(:make) do
@make
end
define_method(:model) do
@model
end
define_method(:id) do
@id
end
define_method(:year) do
@year
end
define_singleton_method(:all) do
@@vehicles
end
define_method(:save) do
@@vehicles.push(self)
end
define_singleton_method(:clear) do
@@vehicles = []
end
define_method(:age) do
current_time = Time.new.year
@age = current_time - @year
end
define_method(:worth_buying?) do
american_made = ["Chevy", "Ford", "GM"]
if american_made.include?(@make) && @age < 15
true
else
false
end
end
end
| true |
a5cec23cb93d55581e031db8bd0ece68e614e075 | Ruby | allizad/pig_latin | /spec/piglatin_spec.rb | UTF-8 | 769 | 3.078125 | 3 | [
"MIT"
] | permissive |
require "./lib/pig_latin.rb"
# require 'pry-byebug'
describe PigLatin do
before do
@glove = "glove"
@egg = "egg"
@yellow = "yellow"
@rhythm = "rhythm"
@integer = 13
@hash = 'wrong'
@array = [1, 2, 3, 4]
end
# test test test
describe '#translate' do
it 'translates a vowel-starting word to its pig latin equivalent' do
expect(PigLatin.translate("egg")).to eq("eggway")
end
it 'translates a consonant-starting word (not y) to it piggy latin equiv' do
expect(PigLatin.translate(@glove)).to eq("oveglay")
end
it 'translates words including y properly' do
expect(PigLatin.translate(@yellow)).to eq("ellowyay")
expect(PigLatin.translate(@rhythm)).to eq("ythmrhay")
end
end
end | true |
509cb830cdef744e695e7b8b5a6e3afb9bfb6e20 | Ruby | milanoid/LRTHW | /ex45/map.rb | UTF-8 | 462 | 3.34375 | 3 | [] | no_license | require_relative 'main_corridor'
require_relative 'bathroom'
require_relative 'death'
class Map
# class variable of type Hash
@@rooms = {
'main_corridor' => MainCorridor.new(),
'bathroom' => Bathroom.new(),
'death' => Death.new()
}
def initialize(start_room)
@start_room = start_room
end
def next_room(room_name)
val = @@rooms[room_name]
return val
end
def opening_room()
return next_room(@start_room)
end
end
| true |
2e46fe7d212565c46676186993fdb3eb3144aca5 | Ruby | guorui9016/ruby | /task9.rb | UTF-8 | 515 | 4.3125 | 4 | [] | no_license | # method take 2 argument
# Interchange value of there argment
# - With using 3rd variable
# - Without using 3rd variable
def interchange_with_3rd_variable(a,b)
puts "a = #{a} and b = #{b}"
temp = a
a = b
b = temp
puts "After interchange, a = #{a} and b = #{b}"
end
def interchange_without_3rd_variable(a,b)
puts "a = #{a} and b = #{b}"
a, b = b, a
puts "After interchange, a = #{a} and b = #{b}"
end
interchange_with_3rd_variable(10, 20)
interchange_without_3rd_variable(10, 20) | true |
cc5eec8fe44d459c9a857b1028ef9d3bb40213d0 | Ruby | BenEddy/ruby_golf | /spec/hole_0_spec.rb | UTF-8 | 688 | 2.84375 | 3 | [] | no_license | require "spec_helper"
require "0/hole_0.rb"
describe HoleZero do
describe ".play" do
it "should display the first fibonacci number" do
when_implemented do
expect(HoleZero.play(1)).to eq("1")
end
end
it "should display the second fibonacci numbers" do
when_implemented do
expect(HoleZero.play(2)).to eq("1,1")
end
end
it "should display the first 10 fibonacci numbers" do
when_implemented do
expect(HoleZero.play(10)).to eq("1,1,2,3,5,8,13,21,34,55")
end
end
it "returns an empty string when 0" do
when_implemented do
expect(HoleZero.play(0)).to eq("")
end
end
end
end
| true |
ec9a15f951503d2f29dc956abd0975387f4070bb | Ruby | eargollo/Quizzer | /test/test_dictionary.rb | UTF-8 | 3,166 | 2.671875 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/test_helper.rb'
class TestDictionary < Test::Unit::TestCase
DB_FILE = File.dirname(__FILE__) + "/fixtures/temp-dictionary.pstore"
DB_WORDS = [["eins", "one"],
["zwei", "two"],
["drei", "three"],
["vier", "four"],
["fuenf", "five"],
["sex", "six"],
["sieben", "seven"],
["acht", "eight"],
["neun", "nine"],
["zehn", "ten"]]
def setup
#Delete database if exists
if File.exists?(DB_FILE)
FileUtils.rm(DB_FILE)
end
end
def teardown
#Delete database if exists
if File.exists?(DB_FILE)
FileUtils.rm(DB_FILE)
end
end
def test_existing
dict = Quizzer::Model::Dictionary.new(File.dirname(__FILE__) + "/fixtures/dictionary.pstore")
assert_equal(10, dict.size)
(0.. DB_WORDS.size - 1).each do |i|
word = dict.retrieve(:id => i)
assert_equal(DB_WORDS[i][0], word.word)
assert_equal(DB_WORDS[i][1], word.meaning)
end
end
def test_initialize
dict = Quizzer::Model::Dictionary.new(DB_FILE)
DB_WORDS.each do |data|
word = dict.insert(:word => data[0], :meaning => data[1])
assert_equal(data[0], word.key)
assert_equal(data[1], word.meaning)
end
assert_equal(DB_WORDS.size, dict.size)
(0.. DB_WORDS.size - 1).each do |i|
word = dict.retrieve(:id => i)
assert_equal(DB_WORDS[i][0], word.word)
assert_equal(DB_WORDS[i][1], word.meaning)
end
assert_raise(RuntimeError) { dict.insert(:word => DB_WORDS[0][0], :meaning => "new meaning") }
assert_not_equal("new meaning", dict.retrieve(:id => 0).meaning)
assert_equal(DB_WORDS[0][1], dict.retrieve(:id => 0).meaning)
dict.insert({:word => DB_WORDS[0][0], :meaning => "zero"}, :duplicate => :replace)
assert_equal("zero", dict.retrieve(:id => 0).meaning)
dict.insert({:word => DB_WORDS[0][0], :meaning => "one"}, :duplicate => :ignore)
assert_equal("zero", dict.retrieve(:id => 0).meaning)
end
def test_csv_good
dict = Quizzer::Model::Dictionary.new(DB_FILE)
dict.insert_csv(File.dirname(__FILE__) + "/fixtures/csv/good.csv")
assert_equal(44, dict.size)
end
def test_csv_duplicate
dict = Quizzer::Model::Dictionary.new(DB_FILE)
assert_equal(0, dict.size)
#Test that either it is all or nothing in case of fail
assert_raise(RuntimeError) { dict.insert_csv(File.dirname(__FILE__) + "/fixtures/csv/with_duplicates.csv") }
assert_equal(0, dict.size)
dict.insert_csv(File.dirname(__FILE__) + "/fixtures/csv/with_duplicates.csv", :duplicate => :ignore)
assert_equal(3, dict.size)
assert_equal("primeiro", dict.retrieve(:id => 0).meaning)
dict.insert_csv(File.dirname(__FILE__) + "/fixtures/csv/with_duplicates.csv", :duplicate => :replace)
assert_equal(3, dict.size)
assert_equal("primero", dict.retrieve(:id => 0).meaning)
end
def test_with_errors
dict = Quizzer::Model::Dictionary.new(DB_FILE)
dict.insert_csv(File.dirname(__FILE__) + "/fixtures/csv/with_errors.csv")
assert_equal(4, dict.size)
end
end | true |
ec620f9c0fa7a124122584cb2bc4f1d3bfdd2b8d | Ruby | DavidMah/tv_renamer | /spec/data_operations_spec.rb | UTF-8 | 975 | 2.84375 | 3 | [] | no_license | require 'data_operations'
class Obj
include DataOperations
end
describe DataOperations do
before :each do
@obj = Obj.new
end
describe "#find_filename" do
it "should return right away if name isn't taken" do
File.should_receive(:exists?).once.with("39").and_return(false)
@obj.find_filename("39").should == "39"
end
it "should count way upwards if names are taken" do
File.should_receive(:exists?).twice.with("39").and_return(true)
(1..3).each do |t|
File.should_receive(:exists?).once.with("39_#{t}").and_return(true)
end
File.should_receive(:exists?).once.with("39_4").and_return(false)
@obj.find_filename("39").should == "39_4"
end
end
describe "#preserve_extensions" do
it "should transfer the extension on the from to the to" do
data = [['a.mkv', 'b'], ['c.mp4', 'd']]
@obj.preserve_extensions(data).should == [['a.mkv', 'b.mkv'], ['c.mp4', 'd.mp4']]
end
end
end
| true |
439683e752f731126a641e21f07e1aba4c8ad3e7 | Ruby | riboseinc/ribose-cli | /spec/acceptance/member_spec.rb | UTF-8 | 2,517 | 2.53125 | 3 | [
"MIT"
] | permissive | require "spec_helper"
RSpec.describe "Space Member" do
describe "list" do
it "retrieves the list of space members" do
command = %w(member list --space-id 123456)
stub_ribose_space_member_list(123456)
output = capture_stdout { Ribose::CLI.start(command) }
expect(output).to match(/| Name | Role Name/)
expect(output).to match(/8332-fcdaecb13e34 | John Doe | Administrator/)
end
end
describe "add" do
it "adds a new member to a space" do
command = %W(
member add
--space-id #{invitation.space_id}
--user-id #{invitation.id1}:#{invitation.role}
--email #{invitation.email1}:0 #{invitation.email2}:1
--message #{invitation.message}
)
stub_ribose_space_invitation_mass_create(
invitation.space_id, build_attr_in_stub_format(invitation)
)
output = capture_stdout { Ribose::CLI.start(command) }
expect(output).to match(/Invitation has been sent successfully!/)
end
end
describe "update" do
it "updates an existing member details" do
command = %w(member update --role-id 135 --member-id 246 --space-id 1234)
stub_ribose_member_role_assign(1234, 246, "135")
output = capture_stdout { Ribose::CLI.start(command) }
expect(output).to match(/Member has been updated with new role!/)
end
end
describe "remove" do
it "removes an existing space member" do
command = %w(member remove --member-id 246 --space-id 1234)
stub_ribose_space_member_delete_api(1234, 246)
output = capture_stdout { Ribose::CLI.start(command) }
expect(output).to match(/The member has been removed from this space/)
end
end
def invitation
@invitation ||= OpenStruct.new(
id1: "123456",
id2: "567890",
role: "123456",
space_id: "123456789",
email1: "invitee-one@example.com",
email2: "invitee-two@example.com",
message: "Your invitation message",
)
end
# This might look compact, but the only purpose for this is to prepare
# the attributes / sequence with the one webmock would be epxecting to
# stub the api request successfully.
#
def build_attr_in_stub_format(invitation)
{
body: invitation.message,
emails: [invitation.email1, invitation.email2],
user_ids: [invitation.id1],
role_ids: {
"#{invitation.email1}": "0",
"#{invitation.email2}": "1",
"#{invitation.id1}": invitation.role,
},
space_id: invitation.space_id,
}
end
end
| true |
afbe4af6aafc9571d0da12b1d46ba8fb22065927 | Ruby | duritong/puppet-hiera | /lib/hiera/scope.rb | UTF-8 | 915 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | class Hiera
class Scope
attr_reader :real
def initialize(real)
@real = real
end
def [](key)
if key == "calling_class"
ans = @real.resource.name.to_s.downcase
elsif key == "calling_module"
ans = @real.resource.name.to_s.downcase.split("::").first
else
ans = @real.lookupvar(key)
end
# damn you puppet visual basic style variables.
return nil if ans == ""
return ans
end
def include?(key)
return true if ["calling_class", "calling_module"].include?(key)
return @real.lookupvar(key) != ""
end
def catalog
@real.catalog
end
def resource
@real.resource
end
def compiler
@real.compiler
end
end
end | true |
8e6c795bbdb533c4dac9a121c70636dea092c40a | Ruby | masacheung/Perilous-Procs | /Phase_1.rb | UTF-8 | 6,952 | 4.4375 | 4 | [] | no_license | # some?
# Write a method some? that accepts an array and a block as arguments.
# The method should return a boolean indicating whether or not at least one of the elements of the array
# returns true when given to the block. Solve this using Array#each.
p "----------"
p "some?"
p "----------"
def some?(array, &proc)
array.each do |ele|
if proc.call(ele)
return true
end
end
false
end
# Examples
p some?([3, 1, 11, 5]) { |n| n.even? } # false
p some?([3, 4, 11, 5]) { |n| n.even? } # true
p some?([8, 2]) { |n| n.even? } # true
p some?(['squash', 'corn', 'kale', 'carrot']) { |str| str[0] == 'p' } # false
p some?(['squash', 'corn', 'kale', 'potato']) { |str| str[0] == 'p' } # true
p some?(['parsnip', 'lettuce', 'pea']) { |str| str[0] == 'p' } # true
# exactly?
# Write a method exactly? that accepts an array, a number (n), and a block as arguments.
# The method should return a boolean indicating whether or not there are exactly n elements
# that return true when given to the block. Solve this using Array#each.
p "----------"
p "exactly?"
p "----------"
def exactly?(array, n, &proc)
count = 0
array.each do |ele|
if proc.call(ele)
count += 1
end
end
count == n
end
# Examples
p exactly?(['A', 'b', 'C'], 2) { |el| el == el.upcase } # true
p exactly?(['A', 'B', 'C'], 2) { |el| el == el.upcase } # false
p exactly?(['A', 'B', 'C'], 3) { |el| el == el.upcase } # true
p exactly?(['cat', 'DOG', 'bird'], 1) { |el| el == el.upcase } # true
p exactly?(['cat', 'DOG', 'bird'], 0) { |el| el == el.upcase } # false
p exactly?(['cat', 'dog', 'bird'], 0) { |el| el == el.upcase } # true
p exactly?([4, 5], 3) { |n| n > 0 } # false
p exactly?([4, 5, 2], 3) { |n| n > 0 } # true
p exactly?([42, -9, 7, -3, -6], 2) { |n| n > 0 } # true
# filter_out
# Write a method filter_out that accepts an array and a block as arguments.
# The method should return a new array where elements of the original array are removed
# if they return true when given to the block. Solve this using Array#each.
p "----------"
p "filter_out"
p "----------"
def filter_out(array, &proc)
ans = []
array.each.with_index do |ele, i|
if !proc.call(ele)
ans << array[i]
end
end
ans
end
# Examples
p filter_out([10, 6, 3, 2, 5 ]) { |x| x.odd? } # [10, 6, 2]
p filter_out([1, 7, 3, 5 ]) { |x| x.odd? } # []
p filter_out([10, 6, 3, 2, 5 ]) { |x| x.even? } # [3, 5]
p filter_out([1, 7, 3, 5 ]) { |x| x.even? } # [1, 7, 3, 5]
# at_least?
# Write a method at_least? that accepts an array, a number (n), and a block as an arguments.
# The method should return a boolean indicating whether or not at least n elements of the array return true
# when given to the block. Solve this using Array#each.
p "----------"
p "at_least?"
p "----------"
def at_least?(array, n, &proc)
count = 0
array.each do |ele|
if proc.call(ele)
count += 1
end
end
count >= n
end
# Examples
p at_least?(['sad', 'quick', 'timid', 'final'], 2) { |s| s.end_with?('ly') }
# false
p at_least?(['sad', 'quickly', 'timid', 'final'], 2) { |s| s.end_with?('ly') }
# false
p at_least?(['sad', 'quickly', 'timidly', 'final'], 2) { |s| s.end_with?('ly') }
# true
p at_least?(['sad', 'quickly', 'timidly', 'finally'], 2) { |s| s.end_with?('ly') }
# true
p at_least?(['sad', 'quickly', 'timid', 'final'], 1) { |s| s.end_with?('ly') }
# true
p at_least?(['sad', 'quick', 'timid', 'final'], 1) { |s| s.end_with?('ly') }
# false
p at_least?([false, false, false], 3) { |bool| bool }
# false
p at_least?([false, true, true], 3) { |bool| bool }
# false
p at_least?([true, true, true], 3) { |bool| bool }
# true
p at_least?([true, true, true, true], 3) { |bool| bool }
# true
# every?
# Write a method every? that accepts an array and a block as arguments.
# The method should return a boolean indicating whether or not all elements of the array return true
# when given to the block. Solve this using Array#each.
p "----------"
p "every?"
p "----------"
def every?(array, &proc)
array.each do |ele|
if !proc.call(ele)
return false
end
end
true
end
# Examples
p every?([3, 1, 11, 5]) { |n| n.even? } # false
p every?([2, 4, 4, 8]) { |n| n.even? } # true
p every?([8, 2]) { |n| n.even? } # true
p every?(['squash', 'corn', 'kale', 'carrot']) { |str| str[0] == 'p' } # false
p every?(['squash', 'pea', 'kale', 'potato']) { |str| str[0] == 'p' } # false
p every?(['parsnip', 'potato', 'pea']) { |str| str[0] == 'p' } # true
# at_most?
# Write a method at_most? that accepts an array, a number (n), and a block as arguments.
# The method should return a boolean indicating whether no more than n elements of the array return true
# when given to the block. Solve this using Array#each.
p "----------"
p "at_most?"
p "----------"
def at_most?(array, n, &proc)
count = 0
array.each do |ele|
if proc.call(ele)
count += 1
end
end
count <= n
end
# Examples
p at_most?([-4, 100, -3], 1) { |el| el > 0 } # true
p at_most?([-4, -100, -3], 1) { |el| el > 0 } # true
p at_most?([4, 100, -3], 1) { |el| el > 0 } # false
p at_most?([4, 100, 3], 1) { |el| el > 0 } # false
p at_most?(['r', 'q', 'e', 'z'], 2) { |el| 'aeiou'.include?(el) } # true
p at_most?(['r', 'i', 'e', 'z'], 2) { |el| 'aeiou'.include?(el) } # true
p at_most?(['r', 'i', 'e', 'o'], 2) { |el| 'aeiou'.include?(el) } # false
# first_index
# Write a method first_index that accepts an array and a block as arguments.
# The method should return the index of the first element of the array that returns true
# when giben to the block. If no element of returns true, then the method should return nil.
# Solve this using Array#each.
p "----------"
p "first_index"
p "----------"
def first_index(array, &proc)
array.each.with_index do |ele, i|
if proc.call(ele)
return i
end
end
return nil
end
# Examples
p first_index(['bit', 'cat', 'byte', 'below']) { |el| el.length > 3 } # 2
p first_index(['bitten', 'bit', 'cat', 'byte', 'below']) { |el| el.length > 3 } # 0
p first_index(['bitten', 'bit', 'cat', 'byte', 'below']) { |el| el.length > 6 } # nil
p first_index(['bit', 'cat', 'byte', 'below']) { |el| el[0] == 'b' } # 0
p first_index(['bit', 'cat', 'byte', 'below']) { |el| el.include?('a') } # 1
p first_index(['bit', 'cat', 'byte', 'below']) { |el| el[0] == 't' } # nil | true |
7a7b5753084deb8e2244333d3e2c0deb5b13f299 | Ruby | pwl-webdev/203_project_ruby_oop | /01_tictactoe/lib/board.rb | UTF-8 | 2,125 | 3.75 | 4 | [] | no_license | class Board
require_relative 'player.rb'
attr_reader :board
def initialize()
@board = [[" ", " "," "],[" ", " "," "],[" ", " "," "]]
end
def reset()
@board = [[" ", " "," "],[" ", " "," "],[" ", " "," "]]
end
def display()
puts " 1 | 2 | 3 "
@board.each_with_index do |x, xi|
print xi+1
x.each_with_index do |y, yi|
print " "+y+" "
if yi < 2
print "|"
end
end
puts""
end
end
def performMove(player)
moveOK = false
while !moveOK
puts "Player '#{player.symbol}' select your move 11 - 33 (ColumnRow)"
answer = gets.chomp
answer = answer.split("")
if answer[0].to_i.between?(1,3) && answer[1].to_i.between?(1,3)
# puts "column #{answer[0]} row #{answer[1]}"
if updateBoard(answer[0].to_i, answer[1].to_i, player.symbol)
moveOK = true
end
end
end
return true
end
def victory?
victory = false
draw = false
symbol = nil
@board.each do |row|
if row.count("x") == 3
victory = true,
symbol = "x"
# puts "row won"
elsif row.count("o") == 3
victory = true
symbol = "o"
# puts "row won"
end
end
3.times do |i|
x = 0
o = 0
3.times do |j|
@board[j-1][i-1] == "x" ? x += 1: nil
@board[j-1][i-1] == "o" ? o += 1: nil
end
if x == 3
victory = true,
symbol = "x"
# puts "column won"
elsif o == 3
victory = true
symbol = "o"
# puts "column won"
end
end
if (@board[0][0] == @board[1][1])&&(@board[1][1] == @board[2][2])&&@board[0][0]!=" "
victory = true
symbol = @board[0][0]
# puts "diagonal won"
end
if (@board[2][0] == @board[1][1])&&(@board[1][1] == @board[0][2])&&@board[2][0]!=" "
victory = true
symbol = @board[2][0]
# puts "diagonal won"
end
x = @board.join
if !(x.include? " ")
draw = true
end
if victory
puts "!!! #{symbol} won the game !!!"
return victory
elsif draw
puts "!!! It's a draw !!!"
return draw
end
end
private
def updateBoard (column, row, symbol)
if @board[row-1][column-1] == " "
@board[row-1][column-1] = symbol
return true
else
return false
end
end
end
| true |
e0e76fdfb468f832f27cf0e87aa287555d769c84 | Ruby | rohan484909/Training | /Ruby Training/TestHase1.rb | UTF-8 | 565 | 3.90625 | 4 | [] | no_license | #declaration of hashes
class Test
student_detail={ 1=>"Rajesh Rai",
2=>"Rakesh Rai",
3=>"Ashi Rai",
4=>"Gulshan Rai"
}#declaration of hash
puts student_detail[3]
puts student_detail[2]
puts student_detail[4]
employee=Hash.new #another declaration of hash
employee[1]="rohan"
employee[2]="Rajesh"
employee[3]="navneet"
employee[4]="rai"
puts "#{employee}"
fruits=Hash.new
fruits.store("red","apple")
fruits.store("yellow","banana")
fruits.store("green","guvava")
puts fruits
end | true |
d7414d2089c080a382e10cf49432bf1100242e7f | Ruby | semliko/blackjack | /round.rb | UTF-8 | 1,503 | 3.5 | 4 | [] | no_license | class Round
attr_reader :player, :dealer, :players, :winner, :deck, :show_cards, :finish_game
def initialize(player, dealer, deck)
@player = player
@dealer = dealer
@deck = deck
@players = [@player, @dealer]
end
def start
2.times { deal_card_to_player }
2.times { deal_card_to_dealer }
end
def player_turn
deal_card_to_player
end
def dealer_turn
deal_card_to_dealer if @dealer.cards_value < 17
end
def deal_card(current_player)
current_player.get_cards(deck.deal_cards(1))
end
def deal_card_to_player
deal_card(player)
end
def deal_card_to_dealer
deal_card(dealer)
end
def exec_user_choice(user_input)
case user_input
when 1
dealer_turn
when 2
player_turn
dealer_turn
when 3
compleate_round
when 0
end_game
end
end
def end_game
@show_cards = true
@finish_game = true
end
def compleate_round
@show_cards = true
end
def winners
new_winners = @players.select { |p| p.cards_value.to_i <= 21 }.max_by(&:cards_value)
if (@dealer.cards_value == @player.cards_value) || !new_winners
@players
else
[new_winners]
end
end
def losers
[@player, @dealer] - winners
end
def round_finished?
players.all? { |p| p.cards.length >= 3 } || (dealer_is_full && player_is_full) || show_cards
end
def dealer_is_full
dealer.cards_value >= 17
end
def player_is_full
player.cards.length >= 3
end
end
| true |
c10e69a3600c69ad10f96ad3030e5f40fe73f93c | Ruby | leonimanuel/reverse-each-word-online-web-sp-000 | /reverse_each_word.rb | UTF-8 | 345 | 3.578125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # def reverse_each_word(sentence)
# sentence_array = sentence.split
# reversed_words = []
# sentence_array.each do |word|
# reversed_words << word.reverse
# end
# reversed_words.join(" ")
# end
def reverse_each_word(sentence)
sentence.split.collect {|word| word.reverse}.join(" ")
end
# print reverse_each_word("hey there bud")
| true |
d4e859cfb71c83e7f919c2151f8d398c93dde34a | Ruby | jose-luis-ramos-olivares/arreglos | /promedio2.rb | UTF-8 | 419 | 3.796875 | 4 | [] | no_license | def compara_arrays(grades, grades1)
average = 0
average1 = 0
lenght = grades.count
lenght1 = grades1.count
grades.each do |grade|
average += grade/lenght.to_f
end
grades1.each do |grade|
average1 += grade/lenght1.to_f
end
if average > average1
print average
else
print average1
end
end
print compara_arrays([1000, 800, 250], [300, 500, 2500]) | true |
03db5e723c5c97ba614d26496422075322b55dd5 | Ruby | dianajyoo/emoticon-translator-dumbo-web-091718 | /lib/translator.rb | UTF-8 | 852 | 3.484375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # require modules here
require 'yaml'
def load_library(file_path)
# code goes here
emoticons = YAML.load_file(file_path)
hash = {"get_emoticon" => {}, "get_meaning" => {}}
emoticons.each do |k, v|
hash["get_emoticon"][v[0]] = v[1]
hash["get_meaning"][v[1]] = k
end
hash
end
def get_japanese_emoticon(file_path, emoticon)
# code goes here
emoticon_hash = load_library(file_path)
if emoticon_hash["get_emoticon"].include?(emoticon)
return emoticon_hash["get_emoticon"][emoticon]
else
return "Sorry, that emoticon was not found"
end
end
def get_english_meaning(file_path, emoticon)
# code goes here
emoticon_hash = load_library(file_path)
if emoticon_hash["get_meaning"].include?(emoticon)
return emoticon_hash["get_meaning"][emoticon]
else
return "Sorry, that emoticon was not found"
end
end
| true |
21cdc487dc393fb4ea94d118f4992d55f648c663 | Ruby | ahmetefeoglu/my-first-ruby-exercise | /check_number.rb | UTF-8 | 92 | 3.28125 | 3 | [] | no_license | arr=[1,3,5,7,9]
number=3
if arr.include?(number)
puts "true"
else
puts "false"
end
| true |
8c84f105d9d7b1bd8b03b1efab85a36fa331c2fa | Ruby | chalmie/Random_Ruby | /fib_checker.rb | UTF-8 | 215 | 3.609375 | 4 | [] | no_license | def fib_checker(num)
fib = [0,1]
while fib.max <= num
next_fib = fib[-1] + fib[-2]
fib << next_fib
end
if fib.include?(num)
return true
else
return false
end
end
p fib_checker(13) | true |
dc53f3523c5ed81e2df21fbd03e11e6db3fe7d32 | Ruby | breadbear/learn_ruby | /01_temperature/temperature.rb | UTF-8 | 89 | 3 | 3 | [] | no_license | def ftoc(f)
(f.to_f - 32.0) * (5.0 / 9.0)
end
def ctof(c)
(c.to_f * 1.8) + 32.0
end
| true |
ef4a6b911dcd17779a3bc46eb48fb705a522aa2d | Ruby | uchihara/word-finder | /lib/word_finder/cell.rb | UTF-8 | 206 | 3.03125 | 3 | [] | no_license | class Cell
attr_reader :char
def initialize char
@char = char
unmark!
end
def marked?
@marked
end
def mark!
@marked = true
end
def unmark!
@marked = false
end
end
| true |
9f67ec2ee2b3de0245d8058155c9b1099135154f | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/filtered-submissions/90f0624e081f43f1846ddbaf32d47afd.rb | UTF-8 | 149 | 3.328125 | 3 | [] | no_license | def compute(x, y)
hamming = 0
x.each_char.with_index do |char, idx|
hamming += 1 unless char == y[idx]
end
return hamming
end | true |
99324c4c39c7c3027096d6f4ab0a7039bf355c1c | Ruby | evanphx/talon | /lib/talon/resolver.rb | UTF-8 | 969 | 2.90625 | 3 | [] | no_license | module Talon
module AST
class Node
attr_accessor :target
end
class Identifier
def resolve_under(res)
@target = res.find(name)
end
end
class Number
def resolve_under(res)
@target = MachineInteger.new(res)
end
end
class Assignment
def resolve_under(res)
res.add_local variable.name, value.resolve_under(res).type
end
end
end
class LocalVariable
def initialize(name, type)
@name = name
@type = type
end
attr_reader :name, :type
end
class MachineInteger
def initialize(res)
@type = res.find('talon.lang.Integer')
end
attr_reader :type
end
class Resolver
def initialize
@locals = {}
end
def add_local(name, type)
@locals[name] = LocalVariable.new(name, type)
end
def find(name)
@locals[name]
end
def resolve(node)
node.resolve_under self
end
end
end
| true |
bcb5606946a380b92f9c33a3112708012daf1807 | Ruby | VladFiliucov/rspec_playground | /spec/lib/count_constraint_spec.rb | UTF-8 | 750 | 3.03125 | 3 | [] | no_license | context "with message count constraints" do
it "allows constraints on message count" do
class Cart
def initialize
@items = []
end
def add_item(id)
@items << id
end
def restock_item(id)
@items.delete(id)
end
def empty
@items.each {|id| restock_item(id)}
end
end
cart = Cart.new
cart.add_item(35)
cart.add_item(178)
expect(cart).to receive(:restock_item).twice
cart.empty
end
it "allows using at_least/at_most" do
post = double('BlogPost')
expect(post).to receive(:like).at_least(3).times
post.like(:user => 'Bob')
post.like(:user => 'Mary')
post.like(:user => 'Ted)')
post.like(:user => 'Jane')
end
end
| true |
6f6a41632fa11fe8bdce1b4cfae66f3b0220f35d | Ruby | MaryBobs/movie_lab | /models/casting.rb | UTF-8 | 888 | 3.078125 | 3 | [] | no_license | require_relative("../db/sql_runner.rb")
class Casting
attr_reader :id
attr_accessor :movie_id, :star_id, :fee
def initialize(options)
@id = options['id'].to_i if options['id']
@movie_id = options['movie_id']
@star_id = options['star_id']
@fee = options['fee']
end
def save()
sql = "INSERT INTO castings
(movie_id, star_id, fee)
VALUES
($1, $2, $3)
RETURNING id"
values = [@movie_id, @star_id, @fee]
@id = SqlRunner.run(sql, values)[0]['id'].to_i
end
def update()
sql = "UPDATE castings SET
(movie_id, star_id, fee) =
($1, $2, $3)
WHERE id = $4"
values = [@movie_id, @star_id, @fee, @id]
SqlRunner.run(sql, values)
end
def self.all()
sql = "SELECT * FROM castings"
result = SqlRunner.run(sql)
return result.map{|casting| Casting.new(casting)}
end
def self.delete_all()
sql = "DELETE FROM castings"
SqlRunner.run(sql)
end
end
| true |
7a7e7bf76fb88b361d7dbd21140f52cd950bd925 | Ruby | aokiji/jenkins_api_client | /lib/jenkins_api_client/job_build.rb | UTF-8 | 2,410 | 2.609375 | 3 | [
"MIT"
] | permissive | module JenkinsApi
class Client
#
# This class represents a build with an assingned id. This includes
# jobs already built or that are currently active.
#
class JobBuild
VALID_PARAMS = ['id', 'name', 'params'].freeze
attr_accessor :id, :name
# Initializes a new [JobBuild]
#
# @param client [Client] the api client object
# @param attr Hash with attributes containing at least name and id, the information not provided
# can be latter retrieved through the json api using the given client
#
# @return [JobBuild] the build item object
def initialize(client, attr = {})
@client = client
attr.each do |name, value|
name = name.to_s
if VALID_PARAMS.include?(name)
instance_variable_set("@#{name.to_s}", value)
end
end
end
# @return Hash with build parameters
#
def params
load_attributes
@params
end
private
# Queries the server for the missing information
#
def load_attributes
if @params.nil?
json = @client.api_get_request("/job/#{@name}/#{@id}", "depth=2")
if json.member?('actions')
@params = json['actions'].find do |action|
if action.is_a?(Hash)
action.member?('parameters')
elsif action.is_a?(Array)
action.first.is_a?(Hash) and action.first.member?('value')
end
end
if @params.nil?
@params = {}
else
@params = @params['parameters'] if @params.is_a?(Hash)
@params = @params.map do |param|
[param['name'], param['value']]
end
@params = Hash[@params]
end
end
end
end
end
end
end
| true |
dbae575b61d4fb2201146d8d40458adbcb86b4b2 | Ruby | faketrees/alpaca | /w3/w3d1/solutions/Simon Kroeger/word_chain2.rb | UTF-8 | 491 | 2.53125 | 3 | [] | no_license | dict, len = Hash.new{|h,k|h[k] = []}, ARGV[0].size
IO.foreach(ARGV[2] || 'words.txt') do |w| w.chomp!
if w.size != len then next else s = w.dup end
(0...w.size).each{|i|s[i]=?.; dict[s] << w; s[i]=w[i]}
end
t, known = {ARGV[1] => 0}, {}
while !known.merge!(t).include?(ARGV[0])
t = t.keys.inject({}){|h, w|(0...w.size).each{|i|
s=w.dup; s[i]=?.; dict[s].each{|l|h[l] = w if !known[l]}};h}
warn 'no way!' or exit if t.empty?
end
puts w = ARGV[0]; puts w while (w = known[w]) != 0
| true |
bccceba83e545590aac1cbce8f324f0b190343c2 | Ruby | bandeirabeto/secretarytest | /app/models/student.rb | UTF-8 | 664 | 2.609375 | 3 | [] | no_license | class Student < ActiveRecord::Base
has_many :classrooms
has_many :courses, class_name: 'Course', dependent: :destroy, through: :classrooms
validates :name,
presence: true,
length: { maximum: 44, minimum: 3 }
validates :register_number,
presence: true,
length: { maximum: 44, minimum: 14 }
validates :status,
presence: true
private
# Internal - Busca todos os estudantes ordenando-os por nome.
#
def self.search_all
all.order(name: :asc)
end
# Internal - Busca apenas estudantes ativos.
#
def self.active
where(status: Status::ACTIVE)
end
end
| true |
3a2afee77105702e2f9ecf75438f3e377de71793 | Ruby | AJ8GH/rspec-udemy | /subjects-examples-context/overwriting_let_spec.rb | UTF-8 | 981 | 3.40625 | 3 | [] | no_license | class ProgrammingLanguage
attr_reader :name
def initialize(name = 'Ruby')
@name = name
end
end
# scope:
# each let is available to all lower level examples - children and descendents
# doesn't work the other way around
# rspec first looks in current scope, then looks at each level above until the top.
# won't look down - i.e. at ancestors
# allows you to isolate variables more for tests and make tests more dry and readable.
describe ProgrammingLanguage do
let(:language) { ProgrammingLanguage.new('Python') }
it 'stores name of language' do
expect(language.name).to eq 'Python'
end
context 'with no argument' do
let(:language) { ProgrammingLanguage.new }
it 'defaults to Ruby' do
expect(language.name).to eq 'Ruby'
end
end
end
# output:
#
# ProgrammingLanguage
# stores name of language
# with no argument
# defaults to Ruby
#
#
# Finished in 0.00183 seconds (files took 0.11931 seconds to load)
# 2 examples, 0 failures
| true |
878ce4edde10e7dbf59be46d8e624cf6c0977754 | Ruby | Sanbornh/object_oriented_programming | /parser.rb | UTF-8 | 1,367 | 4.125 | 4 | [] | no_license | # Accepts a string of the form: "x objects at price",
# with optional input of imported and/or basic tax exempt
# and then returns a hash with the number of items, the price
# the object name, whether it is imported and whether
# it is exempt from basic tax.
# EX: if provided the string : "3 blue water bottle at 10"
# the parer will return : {
# :number=>"3",
# :price=>"10",
# :object=>"blue water bottle",
# :imported=>false,
# :basic_tax_exempt=>false
# }
# Test cases are listed at the bottom.
class Parser
def initialize
@attributes = {}
end
def parse(list_entry)
array = list_entry.split(" ")
if array[0] == "D"
return "D"
else
@attributes[:number] = array[0].to_i
@attributes[:price] = array[array.index("AT") + 1]
@attributes[:object] = array[1..array.index("AT") - 1].join(" ")
if array.include?("IMPORTED")
@attributes[:imported] = true
else
@attributes[:imported] = false
end
if array.include?("EXEMPT")
@attributes[:basic_tax_exempt] = true
else
@attributes[:basic_tax_exempt] = false
end
return @attributes
end
end
end
# parser = Parser.new
# Uncomment these to see how Parser will parse
# puts parser.parse "1 book at 9.99 imported basic tax exempt"
# puts parser.parse "2 chocolate bar at 1.99 basic tax exempt"
# puts parser.parse "3 blue water bottle at 10"
| true |
e26f5ea06f7d036d0c14721cc9454f5d5a250a81 | Ruby | rebeccaswebsite/SQL-bear-organizer-lab-london-web-career-040119 | /lib/sql_queries.rb | UTF-8 | 1,467 | 3.265625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def selects_all_female_bears_return_name_and_age
# selects all of the female bears and returns their name and age
"SELECT name, age FROM bears WHERE gender IS 'F'"
end
def selects_all_bears_names_and_orders_in_alphabetical_order
# selects all of the bears names and orders them in alphabetical order
"SELECT name FROM bears ORDER BY name ASC"
end
def selects_all_bears_names_and_ages_that_are_alive_and_order_youngest_to_oldest
# selects all of the bears names and ages that are alive and order them from youngest to oldest
"SELECT name, age FROM bears WHERE alive IS true ORDER BY age ASC"
end
def selects_oldest_bear_and_returns_name_and_age
# selects the oldest bear and returns their name and age
"SELECT name, age FROM bears ORDER BY age DESC LIMIT 1"
end
def select_youngest_bear_and_returns_name_and_age
# selects the youngest bear and returns their name and age
"SELECT name, age FROM bears ORDER BY age ASC LIMIT 1"
end
def selects_most_prominent_color_and_returns_with_count
# selects the most prominent color and returns it with its count
"SELECT color, COUNT(color) FROM bears GROUP BY color ORDER BY COUNT(*) DESC LIMIT 1"
end
def counts_number_of_bears_with_goofy_temperaments
# counts the number of bears with goofy temperaments
"SELECT COUNT(temperament) FROM bears WHERE temperament = 'goofy'"
end
def selects_bear_that_killed_Tim
# selects the bear that killed Tim
"SELECT * FROM bears WHERE name is null"
end
| true |
bdfddcb7c4acc2b6b02ffee3a57ec75a233263bd | Ruby | hshinde/cheftools | /scripts/aws/newsubnet.rb | UTF-8 | 1,673 | 2.71875 | 3 | [] | no_license | require 'open-uri'
require 'aws-sdk'
require 'pp'
require 'optparse'
options = {}
opts = OptionParser.new do |parser|
parser.banner = "Usage: newvpc.rb [options]"
parser.on('-c', '--cidr CIDR', 'CIDR block, IP range from ') { |v| options[:cidr] = v }
parser.on('-v', '--vpc VPC_ID', 'VPC ID') { |v| options[:vpc_id] = v }
parser.on('-r', '--region REGION', 'REGION') { |v| options[:region] = v }
end.parse!
#pp options
# Raise exception if the mandatory arguments are not specified.
begin
opts.parse!
mandatory = [:cidr, :vpc_id ]
missing = mandatory.select{ |param| options[param].nil? } # the -t and -f switches
unless missing.empty? #
puts "Missing options: #{missing.join(', ')}" #
puts opts #
exit #
end #
rescue OptionParser::InvalidOption, OptionParser::MissingArgument #
puts $!.to_s # Friendly output when parsing fails
puts opts #
exit #
end
# set defaults
options[:region] ||= 'us-west-2';
#pp options
# credentials: creds
Aws.config.update({
region: options[:region]
})
# credentials: creds
# Create AWS client object which will be used for EC operations
ec2client = Aws::EC2::Client.new
subnetresp = ec2client.create_subnet({
vpc_id: options[:vpc_id],
cidr_block: options[:cidr]
});
p subnetresp.subnet[:subnet_id]
| true |
03be995e60a4bd91efd0d91ae44f51065e45e574 | Ruby | Koki-Shimizu/PlanningPokerDomainModel | /gamemaker.rb | UTF-8 | 588 | 2.703125 | 3 | [] | no_license | # To change this template, choose Tools | Templates
# and open the template in the editor.
require "./group"
require "./user"
require "./story"
class Game_Maker
def initialize( product_name )
@product_name = product_name
@group = Group.new( "GroupA" )
end
def make_user( id, name )
user = User.new(id, name)
@group.add_user(user)
end
def set_story( story_summary )
story = Story.new(story_summary)
@group.add_selectable_story(story)
end
def start_planning_poker( story_summary )
return @group.plan(story_summary)
end
end
| true |
117e747fabdccf66cc22cfc7c31fbd5f15c1a5d5 | Ruby | syahmiibrahim/toyrobot | /lib/robot.rb | UTF-8 | 1,310 | 3.8125 | 4 | [] | no_license | class Robot
DEFAULT_LOCATION = 0
DEFAULT_DIRECTION = 'N' #NORTH
def initialize(x = DEFAULT_LOCATION, y = DEFAULT_LOCATION, direction = DEFAULT_DIRECTION)
@orientation = ['N', 'E', 'S', 'W' ]
x < 0 ? @x_location = DEFAULT_LOCATION : @x_location = x
y < 0 ? @y_location = DEFAULT_LOCATION : @y_location = y
valid_direction(direction) ? @direction = direction : @direction = DEFAULT_DIRECTION
end
def x_location
@x_location
end
def x_location=(new_x_location)
@x_location = new_x_location
end
def y_location
@y_location
end
def y_location=(new_y_location)
@y_location = new_y_location
end
def direction
@direction
end
def direction=(new_direction)
@direction = new_direction
end
def valid_direction(direction)
orientation_index(direction) != nil ? true : false
end
def rotate_left
index = orientation_index(direction)
index == 0 ? index = @orientation.length - 1 : index -= 1
@direction = @orientation[index]
end
def rotate_right
index = orientation_index(direction)
index == @orientation.length - 1 ? index = 0 : index += 1
@direction = @orientation[index]
end
def orientation_index(direction)
@orientation.find_index(direction.upcase)
end
private :orientation_index
end
| true |
985a69ac97eac6a4d56d0ff8a30c8e83d9b3f1ef | Ruby | bassdb1/Ruby | /HashBracketNotation.rb | UTF-8 | 680 | 2.796875 | 3 | [] | no_license | grace_hopper = {
full_name: "Grace Hopper",
date_of_birth: "December 9, 1906",
occupations: ["computer scientist", "US Navy rear admiral"],
achievements: ["led the team responsible for releasing some of the first compiled languages", "received more than 40 honorary degrees", "popularized the idea of programming languages written in English and compiled to code understood by computers", "and so much more!"],
source: "https://en.wikipedia.org/wiki/Grace_Hopper"
}
# add the symbol corresponding to the achievements key in the `grace_hopper` hash
puts grace_hopper[:full_name]
puts grace_hopper[:occupations]
puts grace_hopper[:achievements] | true |
c3372c1e9d8f8032dc4bddd32277b35df13deb89 | Ruby | Aifear/free-ruby | /task3.rb | UTF-8 | 991 | 3.921875 | 4 | [] | no_license | #Сложение временных промежутков
def hour(hours)
case hours
when 0
return ""
when 1
return (hours.to_s + " час ")
when 2,3,4
return (hours.to_s + " часа ")
else
return (hours.to_s + " часов ")
end
end
def min(minutes)
case minutes
when 0
return ""
when 1
return (minutes.to_s + " минута ")
when 2,3,4
return (minutes.to_s + " минуты ")
else
return (minutes.to_s + " минут ")
end
end
def sec(seconds)
case seconds
when 0
return ""
when 1
return (seconds.to_s + " секунда ")
when 2,3,4
return (seconds.to_s + " секунды ")
else
return (seconds.to_s + " секунд ")
end
end
#Пользовательский ввод
t1, t2 = ARGV[0].to_i, ARGV[1].to_i
#Подсчеты
time = t1 + t2
hours = time / 3600
time -= hours * 3600
minutes = time / 60
time -= minutes * 60
seconds = time
#Вывод
puts(hour(hours) + min(minutes) + sec(seconds)) | true |
7ed95ac15190b7ce6fe406f917e21a9900844f3a | Ruby | sekoudosso82/ruby_interview_prep | /rubyMetho.rb | UTF-8 | 1,585 | 4.625 | 5 | [] | no_license | # RUBY METHODS
# Prime checker
def prime? (arg)
if arg < 2
return false
end
for i in 2...arg do
if arg%i == 0
return false
end
end
return true
end
or
def prime?(arg)
Prime.prime?(arg)
end
# argument Default value
# assign default values to the variables. It allows us to
# avoid passing a value for every argument, decreasing
# the chance of error.
def take (arr, start_position=1)
arr.slice(start_position, arr.length)
end
take([1,2,3], 1) # [2, 3]
take([1,2,3], 2) # [3]
take([1,2,3]) # [2, 3]
# Ruby - Methods - Variable Arguments
# Consider a method that computes the sum of numbers. Obviously,
# you wouldn't want to write different methods accounting for some
# variable number of arguments
# (e.g.: summing two numbers, three numbers, four numbers, etc.).
# This is where Ruby's * comes into play. Take a look at the
# following code:
def sum(first, *rest)
rest.reduce(first) { |o, x| o + x }
end
> sum(1) # first = 1, rest = [] => 1
> sum(1, 2) # first = 1, rest = [2] => 3
> sum(1, 2, 3) # first = 1, rest = [2, 3] => 6
Write a method named full_name that generates the full
names of people given their first name, followed by some
variable number of middle names, followed by their last name.
def full_name(first, *rest)
rest.reduce(first) { |o, x| o +" "+ x }
end
full_name('Harsha', 'Bhogle') # => "Harsha Bhogle"
full_name('Pradeep', 'Suresh', 'Satyanarayana') # => "Pradeep Suresh Satayanarayana"
full_name('Horc', 'G.', 'M.', 'Moon') # => "Horc G. M. Moon"
# Ruby - Methods - Keyword Arguments
| true |
729ab3b51a86007d846c24acce9b83e62bc52e2b | Ruby | markrickert/PromotionTwoScreensInOne-Example | /app/models/state.rb | UTF-8 | 1,300 | 3.046875 | 3 | [] | no_license | class State
attr_accessor :name
def self.all
[
new("Alabama"),
new("Alaska"),
new("Arizona"),
new("Arkansas"),
new("California"),
new("Colorado"),
new("Connecticut"),
new("Delaware"),
new("Florida"),
new("Georgia"),
new("Hawaii"),
new("Idaho"),
new("Illinois"),
new("Indiana"),
new("Iowa"),
new("Kansas"),
new("Kentucky"),
new("Louisiana"),
new("Maine"),
new("Maryland"),
new("Massachusetts"),
new("Michigan"),
new("Minnesota"),
new("Mississippi"),
new("Missouri"),
new("Montana"),
new("Nebraska"),
new("Nevada"),
new("New Hampshire"),
new("New Jersey"),
new("New Mexico"),
new("New York"),
new("North Carolina"),
new("North Dakota"),
new("Ohio"),
new("Oklahoma"),
new("Oregon"),
new("Pennsylvania"),
new("Rhode Island"),
new("South Carolina"),
new("South Dakota"),
new("Tennessee"),
new("Texas"),
new("Utah"),
new("Vermont"),
new("Virginia"),
new("Washington"),
new("West Virginia"),
new("Wisconsin"),
new("Wyoming")
]
end
def initialize(title)
self.name = title
end
end
| true |
5597ac1bcbef94e947ea22c7ad8e5ed3105853b6 | Ruby | Sam-Serpoosh/twitter_client | /spec/tweet/parser_spec.rb | UTF-8 | 2,580 | 2.765625 | 3 | [] | no_license | require_relative "../../lib/tweet/parser"
require_relative "./data"
module Twitter
describe Parser do
let(:all_tweets) { Data.timeline }
let(:friends) { Data.friends }
let(:parser) { Parser.new(Factory.new) }
context "tweets" do
it "parses a collection of tweets" do
tweets = parser.get_tweets(all_tweets)
tweets.count.should == 20
tweets.first.screen_name.should == "masihjesus"
tweets.first.text.should include "little bit"
end
it "returns empty tweet when there's error" do
tweet_response = %Q{ { "errors": "something went wrong" } }
tweets = parser.get_tweets(tweet_response)
tweets.first.should be_empty
end
end
context "create_cursor_for" do
it "parses the cursor" do
cursor = parser.create_cursor_for(friends)
cursor.next_cursor.should == 1421369440215956700
cursor.has_next?.should be_true
end
it "returns 'last cursor' if there is any error" do
friends_response = %Q{ { "errors": "somethign went wrong" } }
cursor = parser.create_cursor_for(friends_response)
cursor.has_next?.should be_false
end
end
context "#any_error?" do
it "knows when there is error in response" do
response = { "errors" => "something went wrong" }
parser.any_error?(response).should be_true
end
it "won't detect errors if resonse is not hash" do
response = "bla bla"
parser.any_error?(response).should be_false
end
end
context "friends" do
it "parses a collection of users" do
users = parser.users_from(friends)
users.count.should == 20
users.last.id.should == 588743
users.last.screen_name.should == "Bob"
end
it "parses users directly from json" do
users = parser.users_from(Data.one_friend)
users.count.should == 1
users.first.screen_name.should == "Bob"
end
it "returns empty when there is no users data" do
users = parser.users_from("{}")
users.should be_empty
end
end
context "authentication" do
let(:auth_response) { Data.auth_data }
it "returns ok when authentication is success" do
auth_result = parser.authentication_result(auth_response)
auth_result.should == "Authenticated"
end
it "returns 'Not Valid' when authentication is failure" do
auth_result = parser.authentication_result("{}")
auth_result.should == "Not Valid"
end
end
end
end
| true |
a13c85e036cda8946ca033191b49006a7e47930b | Ruby | mattlistor/module-one-final-project-guidelines-nyc-web-071519 | /app/models/customer.rb | UTF-8 | 3,000 | 3.328125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Customer < ActiveRecord::Base
has_many :orders
has_many :books, through: :orders
def name
"#{self.first_name}" + " #{self.last_name}"
end
def get_orders
Order.all.select{|o| o.customer_id == self.id}
end
def get_books
self.get_orders.map{|o| o.get_books_from_order}.flatten
end
def sort_books
self.get_books.sort_by{|b| b.title}.uniq
end
def print_books
puts "|| #{self.name}'s Orders:"
puts "|| -------------------------"
x = 1
self.sort_books.map do |b|
puts "|| #{x}. #{b.title}"
x += 1
end
nil
end
def print_customer_info
puts "|| Name: #{self.name}"
puts "|| Email: #{self.email}"
puts "|| Address: #{self.home_address}"
end
def num_books
self.sort_books.count
end
def num_orders
self.get_orders.count
end
def recommend_book_by_genre
customers_books = self.sort_books
#gets a list of all the genres and titles
# select instead of map (activerecord)
genre_list = customers_books.map{|b| b.genre}
#makes a list of books that the user doesnt own and a list of their genres
books_to_choose_from = Book.all.reject{|b| customers_books.include?(b)}
books_to_choose_from_genre_list = books_to_choose_from.map{|b| b.genre}
#counts each genre and makes a tallied hash ({"Mystery" => 5, etc...})
genre_count_hash = {}
genre_list.each {|genre| genre_count_hash[genre] = 0}
genre_list.each {|genre| genre_count_hash[genre] += 1}
#creates a hash of the most common genre(s) with their amounts
genre_count_hash.delete_if{|genre, amount| amount < genre_count_hash.values.max}
#creates an array of the most common genres
favorite_genre_list = genre_count_hash.keys
#picks a random book to possibly recommend
#binding.pry
if (favorite_genre_list & books_to_choose_from_genre_list) == []
puts "|| There are no books to recommend by your favorite genre!".upcase
nil
else
#chooses what genre we're going to recommend out of all the favorite genres
chosen_genre = favorite_genre_list[rand(0..(favorite_genre_list.length-1))]
#creates a list of books that the user doesn't own that also has the chosen favorite genre
books_with_chosen_genre = books_to_choose_from.select{|b| b.genre == chosen_genre}
#chooses a random book out of that list to recommend
book_recommendation = books_with_chosen_genre[rand(0..(books_with_chosen_genre.length-1))]
#binding.pry
#print out the info for that random book
puts "|| #{self.name}, here is another #{chosen_genre} book:".upcase
puts "||"
book_recommendation.print_book_info
nil
end
end
end | true |
e491f4c1cadd1c4d716ff711cfa8ebca1fb9d07f | Ruby | OrlandyAriel/prct10 | /lib/referencia/referencia.rb | UTF-8 | 982 | 3.171875 | 3 | [
"MIT"
] | permissive | class ReferenciaBase
include Comparable
attr_accessor:m_autores, :m_titulo, :m_anio
def initialize(a_autores, a_titulo, a_anio)
@m_autores,@m_titulo,@m_anio = a_autores,a_titulo,a_anio
end
#Uso 3 criterios para comparar, primero comprueba si los autores son iguales
#si lo son, comprobaría el título, y si este también lo es mirará el año.
def <=>(other)
if(other==nil)
nil
else
t_comparaciones=self.m_autores <=> other.m_autores
if(t_comparaciones == 0)
t_comparaciones=self.m_titulo <=> other.m_titulo
if (t_comparaciones ==0)
t_comparaciones=self.m_anio <=> other.m_anio
if(t_comparaciones == 0)
t_comparaciones
else
t_comparaciones
end
else
t_comparaciones
end
else
t_comparaciones
end
end
end
end | true |
b049ce339de3b5c8ebf46d4890dd3dd71682c662 | Ruby | kschumy/hotel | /old_version/lib/bookings_manager_old_f_ed_up_version.rb | UTF-8 | 3,288 | 3.34375 | 3 | [] | no_license | # # QUESTION: is it better to check if valid date immediately or wait until making
# # reservation?
#
# module Hotel
# class BookingsManager
# # attr_reader :room, :reservations
#
# def initialize
# @rooms = []
# @reservations = []
# load_rooms
# end
#
# # Throws ArgumentError if input_check_in or input_check_out are not Dates.
# def reserve_room(input_check_in, input_check_out)
# return book_a_new_reservation(input_check_in, input_check_out)
# end
#
# #
# def get_reservations_on_date(date)
# Hotel.has_valid_date_or_error(date)
# return find_reservations_on_date(date)
# end
#
#
# def get_available_rooms(start_date, end_date)
# return @rooms.select { |room| room if room.is_available?(start_date, end_date)}
# end
#
# #
# def get_reservation_cost(reservation_id)
# has_valid_reservation_id_or_error(reservation_id)
# return find_reservation_by_id(reservation_id).get_cost
# end
#
# # Returns a list of room numbers.
# def rooms
# return @rooms.dup
# end
#
# # Returns a list of reservations.
# def reservations
# return @reservations.dup
# end
#
# private
#
#
# def load_rooms
# (1..NUM_OF_ROOMS).each { |num| @rooms << Hotel::Room.new(num) }
# end
#
# def book_a_new_reservation(input_check_in, input_check_out)
# reservation_info = {
# id: @reservations.length + 1,
# room_number: find_available_room(input_check_in, input_check_out),
# check_in: input_check_in,
# check_out: input_check_out
# }
# new_reservation = Hotel::Reservation.new(reservation_info)
# add_reservation_to_room(new_reservation)
# @reservations << new_reservation
# return new_reservation
# end
#
# def add_reservation_to_room(new_reservation)
# @rooms[new_reservation.room_number - 1].add_reservation(new_reservation)
# end
#
# # Provided date must be a valid Date.
# # Returns the reservations that overlap with the provided date. If no
# # reservations overlap with date, returns an empty ArrayList. All
# # reservations with check-out dates on provided date are excluded.
# def find_reservations_on_date(date)
# return @reservations.select { |reservation| reservation if
# is_date_between_dates?(date, reservation) }
# end
#
# # Provided id must be a valid id for reservations.
# # Returns the reservation with the provided id.
# def find_reservation_by_id(id)
# return @reservations[id - 1]
# end
#
# def find_available_room(start_date, end_date)
# return @rooms.find { |room| room if room.is_available?(start_date, end_date)}.number
# end
#
# # Provided date must be a valid Date.
# # Return 'true' if date is between check-in (inclusive) and check-out
# # (exclusive) of the provided reservation.
# def is_date_between_dates?(date, reservation)
# return date >= reservation.check_in && date < reservation.check_out
# end
#
# #
# def has_valid_reservation_id_or_error(id)
# if id.class != Integer || !id.between?(1, @reservations.length)
# raise ArgumentError.new("Invalid id #{id}")
# end
# end
#
# end
# end
| true |
0b544df2255b4c84df39abf0d9b3ba53c19725ca | Ruby | jasonpilz/ctci-6th-edition-ruby | /lib/chapter_01/1.07.rb | UTF-8 | 153 | 2.59375 | 3 | [] | no_license | # frozen_string_literal: true
module One
module Seven
module_function
def call(input)
input.transpose.map(&:reverse)
end
end
end
| true |
926a983a022126b9275847455afcb99d8205d471 | Ruby | masked-rpgmaker/RGSS3 | /MBS/sprites-below-player.rb | UTF-8 | 1,396 | 2.546875 | 3 | [] | no_license | #==============================================================================
# MBS - Imagens debaixo do player
#------------------------------------------------------------------------------
# por Masked
#==============================================================================
#==============================================================================
# ** Sprite_Character
#------------------------------------------------------------------------------
# Este sprite é usado para mostrar personagens. Ele observa uma instância
# da classe Game_Character e automaticamente muda as condições do sprite.
#==============================================================================
class Sprite_Character < Sprite_Base
#--------------------------------------------------------------------------
# * Inicialização do objeto
# viewport : camada
# character : personagem (Game_Character)
#--------------------------------------------------------------------------
def initialize(viewport, character = nil)
super(nil)
@character = character
@balloon_duration = 0
update
end
#--------------------------------------------------------------------------
# * Atualização da tela
#--------------------------------------------------------------------------
alias mbs_upd update
def update
mbs_upd
self.z = 10
end
end
| true |
1b5cb008d29e4559b84faf923deadc7b35cec8c6 | Ruby | andrewls/mysql-replayer | /lib/mysql_replayer/prepared_statement_cache.rb | UTF-8 | 2,211 | 2.921875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module MysqlReplayer
class PreparedStatementCache
def initialize(db)
@db = db
# probably the simplest way to manage these is just by using the SQL
# strings as keys in a big hash
@statements = {}
# In a twist of fate that's also super weird, we have no guarantee of
# a prepared statement being called by the same thread that originally
# prepared it, so we need an easy way to determine if the statement
# we prepared is in fact a match for the statement we're trying to execute.
# We also then need to be able to extract the arguments that were passed
# into the query.
#
# We do this by turning _all_ ? in the original prepared statements into
# capture groups that match any character with an optional spaces after
# (in case the ? is at the end of the line). By doing this, we can extract
# the arguments that were added in the logs.
# Not gonna lie, it's a _brutally_ messy system, it'd be way easier
# to just execute these without using prepared statements. Good thing
# I'm committed to science and such.
@regexes = {}
end
def prepare(sql)
@statements[sql] ||= @db.prepare(sql)
@regexes[sql] = Regexp.compile(
Regexp.escape(
sql.gsub(/\s+/, ' ')
).gsub('\ \?', '\ (.+)').gsub('\ ', '\s+')
)
end
def execute(sql, metrics)
# This one is trickier. We first have to find if we have a prepared
# statement that matches it.
found = false
prepared_statement, match = @statements.keys.each do |prepared|
if (match = @regexes[prepared].match(sql)).present?
found = true
break [prepared, match]
end
end
# If we found a prepared statement that matches, execute it using
# all the captured data
if found && match
metrics[:executed_as_query] = false
@statements[prepared_statement].execute(*match.captures.map { |s| s.gsub!(/\A["']|["']\z/, '') })
else
# Fall back to just querying on the db.
metrics[:executed_as_query] = true
@db.query(sql)
end
end
end
end
| true |
82c411f8ff1bf852fb977a10557a90b46bea1975 | Ruby | ylee12/ruby_reference | /enumerable_reduce.rb | UTF-8 | 449 | 3.734375 | 4 | [] | no_license | [1,2,3].reduce do |accumulator, current|
puts "Accumulator: #{accumulator}, Current: #{current}"
accumulator + current
end
puts()
puts "Second pass ..."
[1,2,3].reduce(0) do |accumulator, current|
puts "Accumulator: #{accumulator}, Current: #{current}"
accumulator + current
end
puts()
puts "Third pass ..."
[1,2,3].reduce(1) do |accumulator, current|
puts "Accumulator: #{accumulator}, Current: #{current}"
accumulator + current
end | true |
9072d9b3b15986bffbaf487b31924d5824053a60 | Ruby | SergeiHrenovsky/summer-2018 | /2309/2/rap-battles/versus.rb | UTF-8 | 8,446 | 2.984375 | 3 | [] | no_license | require 'terminal-table'
# This method smells of :reek:IrresponsibleModule
# This method smells of :reek:TooManyInstanceVariables
# This method smells of :reek:TooManyMethods
# rubocop:disable Style/GlobalVars
# rubocop:disable Metrics/MethodLength
# rubocop:disable Lint/UnneededCopDisableDirective
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/EmptyElse
# rubocop:disable Metrics/ClassLength
class AllRapers
attr_reader :all_rapers, :sum_batles, :bad_words, :all_words, :sort_bw, :one_raper_words, :sort_raper_word
def initialize
@all_rapers = {}
@sum_batles = {}
@all_words = {}
@bad_words = {}
@sort_bw = []
@one_raper_words = {}
@sort_raper_word = []
end
def create_all_rapers
spis_rapers
end
def create_sum_batles
count_sum_battles
end
def create_all_words
count_sum_battles
end
def create_search_bad_words
search_bad_words
end
def create_sort_bad_words
sort_bad_words
end
def create_sort_words
sort_words
end
def create_count_words_raper(namee)
count_words_raper(namee)
end
private
# This method smells of :reek:FeatureEnvy
# rubocop:disable Style/EmptyElse
# rubocop:disable Lint/UselessAssignment
def format_text(val)
text = read_file(' ' + val)
text.gsub!(/[,-.!?&:;()1234567890%»]/, ' ')
text = text.downcase
text = text.split
end
# rubocop:enable Lint/UselessAssignment
# rubocop:enable Style/EmptyElse
# This method smells of :reek:NestedIterators
# rubocop:disable Style/EmptyElse
def count_words_raper(namee)
if @all_rapers.include? namee
@all_rapers[namee].each do |val|
format_text(val).each do |word|
unless read_file('предлоги').include? word
if @one_raper_words.include? word
@one_raper_words[word] += 1
else
@one_raper_words[word] = 1
end
end
end
end
else
nil
end
end
# rubocop:enable Style/EmptyElse
# rubocop:enable Metrics/AbcSize
# rubocop:enable Lint/UnneededCopDisableDirective
# rubocop:enable Metrics/MethodLength
def sort_words
@one_raper_words.each { |key, value| @sort_raper_word.push([value, key]) }
@sort_raper_word.sort! { |first, last| last <=> first }
@sort_raper_word.delete_at(0)
end
# This method smells of :reek:UtilityFunction
def list_all_files
Dir['*']
end
# This method smells of :reek:UtilityFunction
def read_file(file)
IO.read(file)
end
# This method smells of :reek:UtilityFunction
def open_file(name_file)
File.open(name_file)
end
# This method smells of :reek:TooManyStatements
# This method smells of :reek:FeatureEnvy
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/MethodLength
# rubocop:disable Style/For
# rubocop:disable Style/Next
# rubocop:disable Style/IfUnlessModifier
def spis_rapers
list_all_files.each do |battle|
if battle.length > 15
if battle.include? 'против' then vs = 'против' end
if battle.include? 'VS' then vs = 'VS' end
if battle.include? 'vs' then vs = 'vs' end
if battle.include? vs
namee = battle[0...battle.index(vs) - 1]
battle = battle[1...battle.size]
variable_name(namee, battle)
end
end
end
end
# rubocop:enable Style/IfUnlessModifier
# This method smells of :reek:FeatureEnvy
# rubocop:disable Style/IfUnlessModifier
def variable_name(namee, battle)
open_file('варианты_имен').each do |names|
names.chomp!
if names.include? namee then namee = names.split(', ')[0] end
end
add_name(namee, battle)
end
# rubocop:enable Style/IfUnlessModifier
def add_name(namee, line)
if @all_rapers.include?(namee)
@all_rapers[namee] += [line]
else
@all_rapers[namee] = [line]
end
end
def count_sum_battles
keys = @all_rapers.keys
keys.each do |key|
sum = @all_rapers[key].size
@sum_batles[key] = sum
end
end
# This method smells of :reek:FeatureEnvy
def format_text_battle(battle)
text = read_file(battle)
text.downcase!
text.gsub!(/[^a-z а-я ё 1-9 0 * \n]/, ' ')
end
# This method smells of :reek:TooManyStatements
# rubocop:disable Style/AndOr
def search_bad_words
files = list_all_files
for key in @all_rapers.keys
@bad_words[key] = 0
@all_words[key] = 0
files.each do |line|
if line.include? key and line.index(key) == 1
for word in format_text_battle(line).split
test_for_a_bad_word(word, key)
end
end
end
end
end
# rubocop:enable Style/AndOr
def add_bad_word(namee)
@bad_words[namee] += 1
end
def add_all_words(namee)
@all_words[namee] += 1
end
# This method smells of :reek:DuplicateMethodCall
# This method smells of :reek:TooManyStatements
# This method smells of :reek:NestedIterators
# rubocop:disable Style/OneLineConditional
def test_for_a_bad_word(word, namee)
add_all_words(namee)
mat = read_file('маты')
not_mats = read_file('не маты')
if word.include? '*'
add_bad_word(namee)
else
mat.split.each do |bad_word|
if word.include? bad_word
not_mats.split.each do |good_word|
if word.include? good_word then else add_bad_word(namee) end
end
end
end
end
end
def sort_bad_words
@bad_words.each { |key, value| @sort_bw.push([value, key]) }
@sort_bw.sort! { |first, last| last <=> first }
end
end
# rubocop:enable Style/OneLineConditional
# rubocop:enable Metrics/ClassLength
# rubocop:enable Style/Next
# rubocop:enable Style/For
# rubocop:enable Metrics/MethodLength
# rubocop:enable Metrics/AbcSize
$rapers = AllRapers.new
$rapers.create_all_rapers
$rapers.create_sum_batles
$rapers.create_search_bad_words
$rapers.create_sort_bad_words
# This method smells of :reek:TooManyStatements
# This method smells of :reek:FeatureEnvy
# rubocop:disable Metrics/MethodLength
# rubocop:disable Metrics/AbcSize
# rubocop:disable Style/HashSyntax
def build_table(lines)
rows = []
ind = 0
while lines != 0
raper = $rapers.sort_bw[ind][1]
num_battles = $rapers.sum_batles[raper]
num_bad_words = $rapers.bad_words[raper]
bw_on_battle = (num_bad_words.to_f / num_battles.to_f).round(2)
word_on_raund = $rapers.all_words[raper] / num_battles / 3
rows << [raper, "#{num_battles} батлов", "#{num_bad_words} нецензурных слов",
"#{bw_on_battle} слова на баттл", "#{word_on_raund} слова в раунде"]
ind += 1
lines -= 1
end
table = Terminal::Table.new :rows => rows
puts table
end
# rubocop:enable Style/HashSyntax
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/BlockLength
# rubocop:disable Style/IfInsideElse
# rubocop:disable Lint/UnusedBlockArgument
# rubocop:disable Metrics/BlockNesting
# rubocop:disable Style/IfUnlessModifier
marker = 30
arguments = ARGV
arguments.each do |arg|
if arg == '--help'
help = IO.read('help')
help = help.split("\n")
help.each do |line|
puts line
end
elsif arg.include? '--top-bad-words='
num_bad_words = arg[16..arg.size]
num_bad_words = num_bad_words.to_i
build_table(num_bad_words)
else
if arg.include? '--top-words='
marker = arg[12..arg.size]
marker = marker.to_i
elsif arg.include? '--name='
name_r = arg[7..arg.size]
if arguments.index(arg) != arguments.size - 1
name_r += " #{arguments.last}"
end
if $rapers.create_count_words_raper(name_r).nil?
puts "Рэпер #{name_r} не известен мне. Зато мне известны:"
$rapers.all_rapers.each { |key, value| puts key.to_s }
else
$rapers.create_count_words_raper(name_r)
$rapers.create_sort_words
$rapers.sort_raper_word.each do |word|
puts "#{word[1]} - #{word[0]} раз"
marker -= 1
if marker.zero?
break
end
end
end
end
end
end
# rubocop:enable Style/IfUnlessModifier
# rubocop:enable Metrics/BlockNesting
# rubocop:enable Lint/UnusedBlockArgument
# rubocop:enable Style/IfInsideElse
# rubocop:enable Metrics/BlockLength
# rubocop:enable Style/GlobalVars
| true |
34a870042c1fa42a35b1e9849493a13f652fbc65 | Ruby | pipivybin/simple-loops-online-web-prework | /simple_looping.rb | UTF-8 | 811 | 4.21875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # REMEMBER: print your output to the terminal using 'puts'
def loop_iterator(number_of_times)
phase = "Welcome to Flatiron School's Web Development Course!"
number = 0
loop do
puts phase
number += 1
break if number == number_of_times
end
end
def times_iterator(number)
number.times do
puts "Welcome to Flatiron School's Web Development Course!"
end
end
def while_iterator(number)
start = 0
while start < number
puts "Welcome to Flatiron School's Web Development Course!"
start += 1
end
end
def until_iterator(number)
start = 0
until start == number
puts "Welcome to Flatiron School's Web Development Course!"
start += 1
end
end
def for_iterator(number)
for element in 1..number
puts "Welcome to Flatiron School's Web Development Course!"
end
end
| true |
2ff7519e3b8830e57a21f884c2ae20658d7e99f3 | Ruby | PetushovaE/my-collect-wdf-000 | /lib/my_collect.rb | UTF-8 | 401 | 3.140625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def my_collect(languages)
# 1st version:
# new_array = []
# counter = 0
# while counter < languages.length
# new_array << yield(languages[counter])
# counter += 1
# end
# empty_array
# end
# 2nd version:
new_collection = []
counter = 0
while counter < languages.length
new_collection << yield(languages[counter])
counter += 1
end
new_collection
end
| true |
ed9ef3f240dfd2a37b2845243533c69b29e1ec75 | Ruby | DBuckley0126/deli-counter-online-web-ft-090919 | /deli_counter.rb | UTF-8 | 623 | 3.90625 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
# binding.pry
def line(array)
if array.empty?
puts "The line is currently empty."
else
string = "The line is currently:"
array.each_with_index do |name, index|
string << " #{index + 1}. #{name}"
end
puts string
end
end
def take_a_number(queue_array, name)
next_position = queue_array.length + 1
queue_array << name
puts "Welcome, #{name}. You are number #{next_position} in line."
end
def now_serving (queue_array)
if queue_array.empty?
puts "There is nobody waiting to be served!"
else
puts "Currently serving #{queue_array[0]}."
queue_array.shift
end
end
| true |
f5e4e5fd55470f2a8eba366759f4059f75390735 | Ruby | shadabahmed/leetcode-problems | /nested-list-weight-sum.rb | UTF-8 | 286 | 3.453125 | 3 | [] | no_license | # @param {NestedInteger[]} nested_list
# @return {Integer}
def depth_sum(nested_list, depth = 1)
nested_list.reduce(0) do |sum, elem|
if elem.is_a?(Array)
sum += depth_sum(elem, depth + 1)
else
sum += elem * depth
end
end
end
p depth_sum [[1,1],2,[1,1]] | true |
ef32afdb52a11a13d1ec84c5cc1d17262ded282d | Ruby | kwin555/ruby-code-and-algorithm-practice | /ruby_class_bug.rb | UTF-8 | 303 | 3.75 | 4 | [] | no_license | class Person
attr_reader :age
def initialize(first_name, last_name, age)
@first_name = first_name
@last_name = last_name
@age = age
end
def full_name
"#{@first_name} #{@last_name}"
end
end
person = Person.new('Yukihiro', 'Matsumoto', 47)
puts person.full_name
puts person.age
| true |
32ec07e3ccd284f353f06559648634e0b2533bc0 | Ruby | mjuettne/optimizer22 | /app/models/cmas_import.rb | UTF-8 | 1,295 | 2.65625 | 3 | [] | no_license | class CmasImport
include ActiveRecord::Model
require 'roo'
attr_accessor :file
def initialize(attributes={})
attributes.each { |name, id, exp_ret, std_dev, skew, kurt, _yield| send("#{name}=", id, exp_ret, std_dev, skew, kurt, _yield) }
end
def persisted?
false
end
def open_spreadsheet
case File.extname(file.original_filename)
when ".csv" then Csv.new(file.path, nil, :ignore)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path)
else raise "Unknown file type: #{file.original_filename}"
end
end
def load_imported_items
spreadsheet = open_spreadsheet
header = spreadsheet.row(1)
(1..spreadsheet.last_row).map do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
item = Item.find_by_id(row["id"]) || Item.new
item.attributes = row.to_hash
item
end
end
def imported_items
@imported_items ||= load_imported_items
end
def save
if imported_items.map(&:valid?).all?
imported_items.each(&:save!)
true
else
imported_items.each_with_index do |item, index|
item.errors.full_messages.each do |msg|
errors.add :base, "Row #{index + 6}: #{msg}"
end
end
false
end
end
end | true |
a7e8e48c78e534d07931704213328a18168e25f1 | Ruby | etdev/algorithms | /4_custom/bubble_sort.rb | UTF-8 | 1,695 | 3.6875 | 4 | [
"MIT"
] | permissive | require_relative "./testable"
class BubbleSort
include Testable
def solution(arr)
return [] unless (arr && arr.is_a?(Array))
return arr if arr.size < 2
swapped = true
until !swapped
swapped = false
0.upto(arr.size-2) do |i|
a, b = arr[i], arr[i+1]
if b < a
arr[i], arr[i+1] = b, a
swapped = true
end
end
end
arr
end
def test_cases
puts "Setting up test data..."
test_case_1_hundred = generate_test_case(100)
test_case_1_hundred_sorted = test_case_1_hundred.sort
test_case_1_thousand = generate_test_case(1000)
test_case_1_thousand_sorted = test_case_1_thousand.sort
test_case_10_thousand = generate_test_case(10_000)
test_case_10_thousand_sorted = test_case_10_thousand.sort
[
{ name: "empty array", in: { a: [] }, out: [] },
{ name: "nil", in: { a: nil }, out: [] },
{ name: "non-array", in: { a: "invalid" }, out: [] },
{ name: "array with single integer", in: { a: [12000] }, out: [12000] },
{ name: "array w/ large negative element", in: { a: [5, -20000000000000] }, out: [-20000000000000, 5] },
{ name: "simple 6-element array", in: { a: [2, 4, 3, 1, 6, 5] }, out: [1, 2, 3, 4, 5, 6] },
{ name: "1 hundred element array", in: { a: test_case_1_hundred }, out: test_case_1_hundred_sorted },
{ name: "1 thousand element array", in: { a: test_case_1_thousand }, out: test_case_1_thousand_sorted },
{ name: "10 thousand element array", in: { a: test_case_10_thousand }, out: test_case_10_thousand_sorted }
]
end
def generate_test_case(n)
([0] * n).map{ rand(n) }
end
end
BubbleSort.new.test
| true |
b5e695bfa578d30ef79fd8118d8ff8eb6e55b623 | Ruby | feigningfigure/WDI_NYC_Apr14_String | /w02/d01/Christopher_Bajorin/homework/part_2_pair_programming_bot/pair_programmer.rb | UTF-8 | 1,098 | 2.765625 | 3 | [] | no_license | require 'sinatra'
require 'sinatra/reloader'
require_relative 'styles'
# buttons aren't working.
get '/' do
<<-HTML
<link rel="stylesheet" type="text/css" href="/styles.css">
<h1>Does The Test Pass?</h1>
<input type="submit" value=" YES " href="http://localhost:4567/yespass"><br>
<input type="submit" value=" NO " href="http://localhost:4567/nopass">
HTML
end
get '/nopass' do
<<-HTML
<h1>write just enough code for the test to pass</h1>
<input type="submit" value=" DONE " href="http://localhost:4567/">
HTML
end
get '/yespass' do
<<-HTML
<h1>Do you need to refactor?</h1>
<input type="submit" value=" YES " href="http://localhost:4567/yespass/yesrefactor"><br>
<input type="submit" value=" NO " href="http://localhost:4567/nopass/norefactor">
HTML
end
get '/yespass/yesrefactor' do
<<-HTML
<h1>Refactor the code.</h1>
<input type="submit" value=" DONE " href="http://localhost:4567/">
HTML
end
get '/yespass/norefactor' do
<<-HTML
<h1>Congratulations</h1>
<input type="submit" value=" DONE " href="http://localhost:4567/">
HTML
end
| true |
7ebf84409db87cde85da90d3fbb379323d849338 | Ruby | Atilla106/multiboard | /lib/weather.rb | UTF-8 | 1,877 | 2.921875 | 3 | [] | no_license | require 'json'
require 'net/http'
require 'time'
class Weather
attr_reader :weather, :weather_icon, :temperature, :min_temperature, :max_temperature, :wind_speed, :sunrise, :sunset, :morning_forecast, :afternoon_forecast
def initialize
owp_current
owp_forecast
end
def to_s
"#{@weather} #{weather_icon} #{@temperature} #{@wind_speed} #{@sunrise} #{@sunset} #{@min_temperature} #{@max_temperature}"
end
private
def owp_current
data = query("weather", q: "Cergy")
@weather = data["weather"][0]["main"]
@temperature = (data["main"]["temp"] - 273.15).to_i
@wind_speed = data["wind"]["speed"]
@sunrise = Time.at(data["sys"]["sunrise"])
@sunset = Time.at(data["sys"]["sunset"])
@weather_icon = icon(data["weather"][0])
end
def owp_forecast
data = query("forecast/daily", q: "Cergy", cnt: 4)
@min_temperature = (data["list"][0]["temp"]["min"] - 273.15).to_i
@max_temperature = (data["list"][0]["temp"]["max"] - 273.15).to_i
@morning_forecast = []
@afternoon_forecast = []
data["list"][1..3].each do |day|
@morning_forecast << (day["temp"]["min"] - 273.15).to_i
@afternoon_forecast << (day["temp"]["max"] - 273.15).to_i
end
end
def icon(weather)
urls = {
"Clear Sky" => "clear-sky.png",
"Clouds" => "clouds.png",
"Thunderstorm" => "thunderstorm.png",
"Drizzle" => "drizzle.png",
"Rain" => "rain.png",
"Snow" => "snow.png",
}
weather["main"] = "Clear Sky" if weather["id"] == 800
urls[weather["main"]] || "unknwown.png"
end
def query(url, options = {})
token = File.read("owm_token").chomp
options.merge!({ :mode => "json", :appid => token })
uri = URI("http://api.openweathermap.org/data/2.5/#{url}")
uri.query = URI.encode_www_form(options)
JSON.parse(Net::HTTP.get(uri)) rescue {}
end
end
| true |
e75ef294ba77871360a907a1f78e5c69d5d71ebf | Ruby | h4hany/yeet-the-leet | /algorithms/Easy/1441.build-an-array-with-stack-operations.rb | UTF-8 | 1,798 | 3.828125 | 4 | [] | no_license | #
# @lc app=leetcode id=1441 lang=ruby
#
# [1441] Build an Array With Stack Operations
#
# https://leetcode.com/problems/build-an-array-with-stack-operations/description/
#
# algorithms
# Easy (69.57%)
# Total Accepted: 23K
# Total Submissions: 33.1K
# Testcase Example: '[1,3]\r\n3\r'
#
# Given an array target and an integer n. In each iteration, you will read a
# number from list = {1,2,3..., n}.
#
# Build the target array using the following operations:
#
#
# Push: Read a new element from the beginning list, and push it in the
# array.
# Pop: delete the last element of the array.
# If the target array is already built, stop reading more elements.
#
#
# You are guaranteed that the target array is strictly increasing, only
# containing numbers between 1 to n inclusive.
#
# Return the operations to build the target array.
#
# You are guaranteed that the answer is unique.
#
#
# Example 1:
#
#
# Input: target = [1,3], n = 3
# Output: ["Push","Push","Pop","Push"]
# Explanation:
# Read number 1 and automatically push in the array -> [1]
# Read number 2 and automatically push in the array then Pop it -> [1]
# Read number 3 and automatically push in the array -> [1,3]
#
#
# Example 2:
#
#
# Input: target = [1,2,3], n = 3
# Output: ["Push","Push","Push"]
#
#
# Example 3:
#
#
# Input: target = [1,2], n = 4
# Output: ["Push","Push"]
# Explanation: You only need to read the first 2 numbers and stop.
#
#
# Example 4:
#
#
# Input: target = [2,3,4], n = 4
# Output: ["Push","Pop","Push","Push","Push"]
#
#
#
# Constraints:
#
#
# 1 <= target.length <= 100
# 1 <= target[i] <= 100
# 1 <= n <= 100
# target is strictly increasing.
#
#
#
# @param {Integer[]} target
# @param {Integer} n
# @return {String[]}
def build_array(target, n)
end
| true |
6d6af4602b25e842e7d1829e178d994c2ddb46cb | Ruby | evanaaron26/weekend_work | /week3_work/sum_of_range.rb | UTF-8 | 1,216 | 4.6875 | 5 | [] | no_license | # Complete the method called sum_of_range, which will accept an array containing
# two numbers, and return the sum of all of the whole numbers within the range of those
# numbers, inclusive.
# number = 0
def sum_of_range(array)
#here I set range to 0 in order to count the range of array
range = 0
#here I used the each method to determined the difference in the 2
#array variables and made that sum equal to the variable total
total = (array[0]..array[1]).each {|n| print n, ''}
#here total was iterated thru an each loop and added to variable #range. This was done in order to calcuate total of all variables
#in the range of two points in the array.
total.each do |sum|
range = sum + range
p range
end
# output is calculating range of the 2 array variables but not
#adding them together. Not sure why not.
end
# Driver code - don't touch anything below this line.
puts "TESTING sum_of_range..."
puts
result = sum_of_range([1, 4])
puts "Your method returned:"
puts result
puts
if result == 10
puts "PASS!"
else
puts "F"
end
result = sum_of_range([4, 1])
puts "Your method returned:"
puts result
puts
if result == 10
puts "PASS!"
else
puts "F"
end | true |
ff1d01dcc4f08a9b5351516ab831fa60b2f848b3 | Ruby | tlowrimore/ghost_phone | /lib/ghost_phone.rb | UTF-8 | 2,929 | 2.953125 | 3 | [] | no_license | require 'pathname'
require 'logger'
require 'ghost_phone/message'
require 'ghost_phone/serial'
require 'ghost_phone/sound'
require 'ghost_phone/state_manager'
module GhostPhone
SERIAL_PORT = '/dev/serial0'
BAUD_RATE = 115200
# -----------------------------------------------------
# Class Methods
# -----------------------------------------------------
def self.root
Pathname.new File.expand_path('../', __dir__)
end
def self.logger
@logger ||= begin
formatter = Logger::Formatter.new
level = ENV['LOG_LEVEL'] || :info
Logger.new(STDOUT, level: level).tap do |logger|
logger.formatter = proc do |severity, datetime, progname, msg|
formatter.call(severity, datetime, progname, msg.dump)
end
end
end
end
def self.start
return if @runner
@runner = Runner.new
Signal.trap("INT") do
logger.info '--- shutting down'
@runner.stop
@runner = nil
exit
end
Signal.trap("TERM") do
logger.warn '--- terminating!'
@runner.stop
@runner = nil
exit
end
@runner.start
end
# -----------------------------------------------------
# Runner
# -----------------------------------------------------
class Runner
def initialize
@state_manager = GhostPhone::StateManager.new
@serial = GhostPhone::Serial.new(SERIAL_PORT, BAUD_RATE)
@sound = nil
@message = nil
end
def start
GhostPhone.logger.info "--- starting serial monitor"
@serial.monitor { |value| update(value) }
end
def stop
@serial.stop
@sound.shutdown if @sound
@message.shutdown if @message
end
def update(value)
GhostPhone.logger.debug "--- updating state with: '#{value}'"
event, key = value[0], value[1]
state = @state_manager.update(event, key)
GhostPhone.logger.debug "--- current state: #{state.inspect}"
play_dial_tone if state.ready?
play_tone(key) if state.play_tone?
stop_tone if state.stop_tone?
record_message(state.file_name) if state.recording?
stop_recording if state.hangup?
end
# -----------------------------------------------------
# Private Methods
# -----------------------------------------------------
private
def play_dial_tone
play_tone(GhostPhone::Sound::DIAL_TONE)
end
def play_tone(key)
stop_tone
@sound = GhostPhone::Sound.new(key)
@sound.play
end
def stop_tone
@sound.stop if @sound
end
def record_message(file_name)
return unless @message.nil?
@message = GhostPhone::Message.new(file_name)
@message.record
end
def stop_recording
return if @message.nil?
@message.stop
@message = nil
end
end
end
| true |
3d8343cdd1d9153e1a8fbd14ac7cb24b0349991d | Ruby | galejscott/OO-Get-Swole-london-web-051319 | /tools/console.rb | UTF-8 | 838 | 3.078125 | 3 | [] | no_license | # You don't need to require any of the files in lib or pry.
# We've done it for you here.
require_relative '../config/environment.rb'
# test code goes here
#gym
uber = Gym.new("Uber")
twitter = Gym.new("Twitter")
airbnb = Gym.new("AirBnb")
#lifter
bill = Lifter.new("Bill", 3000000000)
warren = Lifter.new("Warren", 900000000)
jeff = Lifter.new("jeff", 1500000000)
#membership
uberbill = Membership.new(200, uber, bill)
twitterbill = Membership.new(300, twitter, bill)
airbnbbill = Membership.new(100, airbnb, bill)
twitterwarren = Membership.new(300, twitter, warren)
uberwarren = Membership.new(200, uber, warren)
airbnbwarren = Membership.new(100, airbnb, warren)
airbnbjeff = Membership.new(100, airbnb, jeff)
uberjeff = Membership.new(200, uber, jeff)
twitterjeff = Membership.new(300, twitter, jeff)
binding.pry
puts "Gains!"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.