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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1b9cb7d7a23219fe6e61e41c8d086384e18f7516 | Ruby | jch/whatcodecraves.com | /app/models/post.rb | UTF-8 | 3,806 | 3 | 3 | [] | no_license | require 'date'
require 'pathname_extensions'
# A blog post is a directory with an index.text document found within `root_path`.
class Post
class Error < StandardError
attr_reader :post
def initialize(post, message)
@post = post
super("#{post.permalink}: #{message}")
end
end
class << self
# @!attribute [rw] root_path
# Pathname to directory to store and retrieve posts.
# Default `Rails.root`.
# @return [Pathname]
attr_writer :root_path
def root_path
@root_path ||= Rails.root + 'posts'
@root_path ||= Pathname.new(@root_path.expand_path)
end
def last_modified
root_path.atime
end
# @param [Integer] count number of recent posts to return
# @return [Array] count most recent posts
def recent(count = 6)
all.slice(0, count)
end
# @return [Array] posts found under `root_path`
def all
root_path.search('index.text').sort {|a,b| b <=> a}.map do |path|
new(path.dirname)
end
end
end
include Comparable
# @!attribute [r] permalink
# @return [String] relative canonical url
attr_reader :permalink
# @param [String] uri file path or uri path. e.g.
# /YYYY/MM/DD/dasherized-title
# /home/jch/articles/2011/11/14/articles_path/index.html
def initialize(uri)
@permalink = normalized_permalink(uri)
@renderer = Redcarpet::Markdown.new(Redcarpet::Render::XHTML, {
no_intra_emphasis: true,
fenced_code_blocks: true
})
end
# Raw file contents of an index file
#
# @param [Pathname] dir directory to look for file
# @return [String] index file contents. nil if not found
def raw
return nil unless directory
@raw ||= directory.children.detect {|path|
path.basename.to_s =~ /index.text/i
}.read
rescue Errno::ENOENT => e
nil
end
# Normalizes directory names in `root_path` to find
# a matching directory for the given permalink
#
# @return [Pathname] directory that holds permalink, nil if not found
def directory
# concatenate relative path to root_path
dir, base = (self.class.root_path + permalink.gsub(/^\//, '')).split
normalized = base.to_s.upcase
match = nil
dir.find do |path|
if path.basename.to_s.dasherize.upcase == normalized
match = path
Find.prune # stop find
end
end
@directory ||= match
rescue Errno::ENOENT => e
nil
end
# @return [Boolean] whether post directory exists with content
def exists?
!raw.nil?
end
# @return [String] title of post, first h1 line
def title
raw.split("\n").detect {|line|
line =~ /\s/
}.strip.gsub(/^#\s*/, '').gsub(/\s*#/, '')
rescue => e
raise Error.new(self, e.message)
end
# @return [String] publish date based on permalink
def date
Date.strptime permalink.match(%r{^/\d{4}/\d{2}/\d{2}})[0], '/%Y/%m/%d'
end
# @return [Datetime] last modified date
def updated_at
directory.mtime
end
# @return [String] html excerpt of the post
def description
@parsed_html ||= Nokogiri::HTML(html)
@parsed_html.css('body').children.slice(1..-1).map(&:to_s).map(&:strip).join('')
end
# @return [String] html of entire post
def html
@html ||= @renderer.render(raw)
end
# Compares posts by permalink
def <=>(post)
permalink <=> post.permalink
end
protected
# Normalize a directory path to a permalink string
#
# @param [Pathname, String] path
# @return [String] permalink
def normalized_permalink(path)
path.to_s.
gsub(self.class.root_path.to_s, ''). # relative path
gsub(/[_,!@#\$^*?]/, '-'). # dasherize
gsub(/index\.html$/, ''). # remove trailing index.html
gsub(/\/$/, ''). # remove trailing /
downcase
end
end
| true |
18c0484f5e53c60364d1f7ec3dc1944db2534d3f | Ruby | josei/tron3000 | /code/entities/homing.rb | UTF-8 | 562 | 2.65625 | 3 | [
"MIT"
] | permissive | module Homing
def self.included klass
klass.class_eval do
follow nil
homing_strategy :best
homing_method do case @homing_strategy
when :best; method(:best_angle)
when :closest; method(:closest_angle)
end
end
end
end
def update
super
if follow
diff = (@angle - @homing_method.call(follow.x, follow.y)).normalize_angle
self.angle += 4 if diff < -4
self.angle -= 4 if diff > 4
end
end
end | true |
0d61a665de2df8336a8cb7f32509095b9bb51ebb | Ruby | tengyuma/cs229t-percy | /lectures/otl2tex | UTF-8 | 11,052 | 2.96875 | 3 | [] | no_license | #!/usr/bin/ruby
# Converts an outline file (otl) into a latex file.
# Input: <file.otl>
# Output: <file.tex>
# Format of an OTL file:
# !format TSI
# !documentclass[12pt]{article}
# !preamble \usepackage{mystyle}
# !include- macros.otl (- means don't include again if already included)
# !verbatim: include stuff directly in latex without wrapping in outline
# !escape: for typing text. Certain characters get escaped automatically like quotes and underscores.
# !comment: always hide.
# !preliminary: mark the subtree as preliminary.
# !showPreliminary: show preliminary subtrees.
# !ruby: execute these Ruby commands.
# $filePrefix is the prefix of the otl file.
ContinuePattern = /^ / # Continuation of line
DefaultStyleSpec = "TSI"
def indent(i) " " * (i > 0 ? i : 0) end
def blank(s) s.gsub(/./, " ") end
def escape(s, startInMath) # return s, inMath
inMath = []
# Don't escape anything in math mode (stuff between \[,\] or $,$)
t = (0...s.size).map { |i| s[i..i] }
t.each_index { |i|
prevInMath = (i == 0 ? startInMath : inMath[i-1])
next if inMath[i] != nil
if t[i] == "\\" && t[i+1] == "[" then
inMath[i] = inMath[i+1] = true
elsif t[i] == "\\" && t[i+1] == "]" then
inMath[i] = inMath[i+1] = false
elsif t[i] == "$" then
inMath[i] = (not prevInMath)
else # Continue on
inMath[i] = prevInMath
end
}
inQuote = false
t.each_index { |i|
next if inMath[i]
# Turn " into `` and ''
if t[i] == "\"" then
t[i] = inQuote ? "''" : "``"
inQuote = (not inQuote)
end
t[i] = "$"+t[i]+"$" if ["|", "<", ">"].member?(t[i]) # Escape symbols which are not in math
t[i] = "\\"+t[i] if ["_", "%"].member?(t[i])
}
return t.join(""), inMath.last
end
class Style
attr_accessor :id, :before, :after, :begin, :end
def initialize(*strs)
@id = strs[0]
@before = strs[1]
@after = strs[2]
@begin = strs[3]
@end = strs[4]
end
end
class StyleDB
def initialize
@map = {}
[ Style.new("N" , "", "\n\n"),
Style.new("T1" , "\\begin{center} \\Large ", " \\end{center}"),
Style.new("T2" , "\\begin{center} ", " \\end{center}"),
Style.new("R" , "\\newpage \\begin{center} \\Large ", " \\end{center}"),
Style.new("S1", "\\section{", "}"),
Style.new("S2", "\\subsection{", "}"),
Style.new("S3", "\\subsubsection{", "}"),
Style.new("s1", "\\section*{", "}"),
Style.new("s2", "\\subsection*{", "}"),
Style.new("s3", "\\subsubsection*{", "}"),
Style.new("P" , "\\paragraph{", "}"),
Style.new("I" , "\\item ", "", "\\begin{itemize}", "\\end{itemize}"),
Style.new("E" , "\\item ", "", "\\begin{enumerate}", "\\end{enumerate}")
].each { |style|
@map[style.id] = style
}
end
def get(id)
@map[id] || raise("Invalid ID: #{id}")
end
end
Styles = StyleDB.new
# A list of styles
class StyleList
def initialize(str)
@styles = []
n = 0
str.each_byte { |c| c = c.chr
if c =~ /[SsT]/ then
n += 1
c += n.to_s
end
@styles << Styles.get(c)
}
end
def get(i) @styles[[i, @styles.size-1].min] end
def update(indent, s)
styles = @styles[0...indent] + [@styles.last] * [indent-@styles.size, 0].max
StyleList.new(styles.map { |style| style.id[0..0] }.join("") + s)
end
def to_s; @styles.map { |style| style.id[0..0] }.join("") end
end
############################################################
class Node
attr_reader :value, :children, :source
def initialize(value, source)
@value = value
@source = source
@children = []
end
def addChild(childNode); @children.push(childNode) end
def removeFirstChild; @children.shift end
def removeLastChild; @children.pop end
def firstChild; @children.first end
def lastChild; @children.last end
end
# Return a list of nodes
# Each node is ["value", [children]]
def readForest(inFile)
oldIndent = 0
lineNum = 0
getSource = lambda {inFile+":"+lineNum.to_s}
rootNode = Node.new(nil, getSource.call)
path = [rootNode] # Path to current node
IO.foreach(inFile) { |s|
lineNum += 1
s = s.rstrip
next if s == ""
t = s.gsub(/\t/, "")
currIndent = s.size - t.size
(oldIndent+1).upto(currIndent) { |i|
node = path.last
node.addChild(Node.new(nil, getSource.call)) unless node.children.size > 0
path.push(node.lastChild) # Indent one level
}
(oldIndent-1).downto(currIndent) { |i|
path.pop
}
path.last.addChild(Node.new(t, getSource.call))
oldIndent = currIndent
}
rootNode.children # Return nodes
end
def getFreeFile(prefix, suffix)
i = 0
while true
f = "#{prefix}#{i}#{suffix}"
return f unless File.exists? f
i += 1
end
end
def evalRuby(lines, verbose)
#lines.each { |line| puts line }
begin
#puts "EVAL at #{$0}"
#puts "CURRDIR " + `pwd`
#puts "LOAD " + $LOAD_PATH.inspect
puts if verbose
puts "EVAL " + lines.inspect if verbose
x = eval lines.join("\n")
x = [""] if x == nil || x == true
puts "RESULT " + x.inspect if verbose
x
rescue SyntaxError => e
["Execution failed:", "\\begin{verbatim}"] + lines + e.message.split("\n") + ["\\end{verbatim}"]
end
end
def flatten(nodes)
nodes.map { |node|
[node.value]+flatten(node.children)
}.flatten.compact
end
$showPreliminary = false
def writeForest(out, forest, currIndent, styleList, includedFiles, escapeStuff)
began = false
restoreStyleList = nil # If go into a temporary style, restore to this right after
tmpDone = false # Whether we're done printing stuff in a temporary style and ready to switch back
finishStyle = lambda {
if began
style = styleList.get(currIndent)
#puts "GOT style #{style.id}"
out.puts indent(currIndent) + style.end if style.end
end
began = false
}
inMath = false
forest.each_index { |i|
node, nextNode = forest[i], forest[i+1]
value = node.value
# Render URLs specially
# If we have:
# <title>
# http://...
# then fold the URL into the <title> as a link
subnode = node.firstChild
if subnode && subnode.value =~ /^(ftp|http|https):\/\/.+$/
value = "\\href{#{subnode.value}}{#{value}}"
node.removeFirstChild
end
# Source a file.
if value =~ /^!(include|INCLUDE)(-?)\s+(.+)/ then
out.puts "% " + value
$3.split.each { |f|
next if $2 && includedFiles.has_key?(f) # Skip if already included
includedFiles[f] = true
if f =~ /\.otl$/ then
styleList, escapeStuff = writeForest(out, readForest(f), currIndent, styleList, includedFiles, escapeStuff)
else
IO.foreach(f) { |s| out.puts s }
end
}
next
end
# If showing preliminary, strip out "!preliminary"
value = $1 if $showPreliminary && value =~ /^!preliminary ?(.*)$/
# Assume that the format doesn't switch while we're in the middle of this
if value =~ /^!(verbatim|VERBATIM)\s*(.*)$/ then
out.puts $2
node.children.each { |childNode| out.puts childNode.value }
elsif value =~ /^!(preamble|PREAMBLE)\s*(.*)$/ then
# Do nothing
elsif value =~ /^!showPreliminary$/ then
$showPreliminary = true
elsif value =~ /^!(comment|COMMENT)\s*(.*)$/ then
out.puts "% " + $2
elsif (not $showPreliminary) && value =~ /^!(preliminary|PRELIMINARY)\s*(.*)$/ then
out.puts "% " + $2
elsif value =~ /^!(escape|ESCAPE)\s+(.+)$/ then
escapeStuff = ($2 == "1" || $2 == "true")
elsif value =~ /^!(tmp)?(format|FORMAT)\s*[= ]\s*(\w+)$/ then
# Clean up last format, go to new format
finishStyle.call
if restoreStyleList == nil && $1 # Jump back here right after
restoreStyleList = styleList
doneTmp = false
end
styleList = styleList.update(currIndent, $3)
#puts "styleList: #{styleList}"
elsif value =~ /^!ruby(-verbose)?\s*(.*)$/ then
inLines = [$2] + flatten(node.children)
outLines = evalRuby(inLines, $1 != nil)
outLines = [outLines] unless outLines.is_a?(Array)
outLines.each { |line| out.puts line }
else
currIsContinue = value =~ ContinuePattern
nextIsContinue = nextNode && nextNode.value =~ ContinuePattern
# Restore from temporary style
if restoreStyleList && (not currIsContinue) # In a temporary style
if (not tmpDone) # First time, do nothing (go with temporary style)
tmpDone = true
else # Second time, restore before print stuff out
#puts "restore #{styleList} -> #{restoreStyleList}"
finishStyle.call
styleList = restoreStyleList
restoreStyleList = nil
end
end
style = styleList.get(currIndent)
if not began then
if style.begin
out.print indent(currIndent) + style.begin
out.print ' % ' + node.source
out.puts ""
end
began = true
end
i = currIndent
t = value
if not t
raise "No value (too much or too little indent) at #{node.source}"
end
t, inMath = escape(t, inMath) if escapeStuff
out.print indent(i)
if currIsContinue
out.print blank(style.before) + t.sub(ContinuePattern, "")
else
out.print style.before + t
end
if not nextIsContinue
out.print style.after
end
out.print ' % ' + node.source
out.puts ""
writeForest(out, node.children, currIndent+1, styleList, includedFiles, escapeStuff)
end
}
# Finish
if began
style = styleList.get(currIndent)
if style.end
node = forest.last
out.print indent(currIndent) + style.end
out.print ' % ' + node.source if node.source
out.puts ""
end
end
[styleList, escapeStuff]
end
############################################################
def main
if ARGV.size != 1 then
puts "Converts an OTL file into a tex file with the same prefix."
puts "Usage: <otl file>"
exit 1
end
inFile = ARGV[0]
$filePrefix = inFile.sub(/\.otl$/, "");
outFile = $filePrefix + ".tex"
out = open(outFile, "w")
forest = readForest(inFile)
documentclassArgs = "[12pt]{article}"
forest = forest.map { |node|
if node.value =~ /^!documentclass(.*)$/
documentclassArgs = $1
nil
else
node
end
}.compact
out.puts <<EOF
%%% THIS FILE IS AUTOMATICALLY GENERATED. DON'T MODIFY, OR YOUR CHANGES MIGHT BE OVERWRITTEN!
\\documentclass#{documentclassArgs}
\\usepackage{fullpage,amsmath,amssymb,graphicx,color,bbm,url,stmaryrd,ifthen}
\\usepackage[colorlinks=true]{hyperref}
\\usepackage[utf8]{inputenc}
EOF
# Print premable
forest.each { |node|
out.puts $2 if node.value =~ /^!(preamble|PREAMBLE)\s*(.*)$/
}
out.puts <<EOF
\\begin{document}
EOF
includedFiles = {}
writeForest(out, forest, 0, StyleList.new(DefaultStyleSpec), includedFiles, true)
out.puts <<EOF
\\end{document}
EOF
out.close()
end
main
| true |
01cd58ca3d8d050a8ffc6ddd6b879cd37e1a3331 | Ruby | claeusdev/algorithms | /leetcode/Leetcode 26. Remove Duplicates from Sorted Array.rb | UTF-8 | 1,835 | 4.3125 | 4 | [
"MIT"
] | permissive | # Given a sorted array, remove the duplicates
# in place such that each element appear only once
# and return the new length.
#
# Do not allocate extra space for another array,
# you must do this in place with constant memory.
#
# For example,
# Given input array nums = [1,1,2],
#
# Your function should return length = 2,
# with the first two elements of nums being 1 and 2 respectively.
# It doesn't matter what you leave beyond the new length.
# O(n) time complexity
def remove_duplicates(nums)
return if nums.empty?
# `i` is a counter that increments when elements are unique
# `j` is the index in the array, it can start at 1 since i is first compared at 0
i = 0
j = 1
while j < nums.size
if nums[i] != nums[j]
i += 1
# i should point to the most recent unique for the next comparison
# therefore `i + 1` (note `i` increments just before) should have `j`'s current value
nums[i] = nums[j]
end
j += 1
end
# add 1 to include the last value checked, which will never be compared as `i`
i + 1
end
p remove_duplicates([1, 1, 2]) # => 2
# equivalent
def remove_duplicates(nums)
return if nums.empty?
count = 0
(1...nums.size).each do |index|
next if nums[count] == nums[index]
count += 1
nums[count] = nums[index]
end
count + 1
end
p remove_duplicates([1, 1, 2]) # => 2
# to actually remove duplicate elements, adjust the first implementation
# to build a new array of uniques, or alternatively:
def remove_duplicates(nums)
i = 0
j = 1
while j < nums.size
if nums[i] == nums[j]
# found a repeat -> cut away the duplicate + reset the search
nums = j == nums.size - 1 ? nums[0..i] : nums[j..-1]
i = 0
j = 1
else
i += 1
j += 1
end
end
nums.size
end
p remove_duplicates([1, 1, 2]) # => 2
| true |
00f7d123d0b443a2ed8990d7b37e54df1dd0e026 | Ruby | mindfire-solutions/survey | /app/models/survey/survey_evaluation_item.rb | UTF-8 | 3,252 | 2.5625 | 3 | [
"MIT"
] | permissive | #app/models/survey/survey_evaluation_item.rb
module Survey
class SurveyEvaluationItem < ActiveRecord::Base
set_table_name "survey_evaluation_items"
attr_accessible :parent_id, :evaluation_id, :question_id, :answer_text, :level, :children_attributes
attr_accessible :question_set_item_id
belongs_to :evaluation, :class_name => "SurveyEvaluation", :foreign_key => :evaluation_id
has_many :children, :class_name => "SurveyEvaluationItem", :dependent => :destroy, :foreign_key => "parent_id"
belongs_to :parent, :class_name => "SurveyEvaluationItem"
belongs_to :question, :class_name => "SurveyQuestion", :foreign_key => :question_id
belongs_to :set_item, :class_name => "SurveyQuestionSetItem", :foreign_key => :question_set_item_id
accepts_nested_attributes_for :children, :reject_if => proc { |attributes| attributes['answer_text'].blank? }
validates :question_id, :presence => true
validates :answer_text, :presence => true
validates :level, :presence => true
validate :validate_question
before_save :add_evaluation_id
def validate_question
x = true
if question.question_type == "Text Box"
question.survey_question_validations.each do |ques_val|
validation = ques_val.validation
validation_method = validation.title
validation_params = []
validation_params << answer_text
validation_params << ques_val.validation_param_1 unless validation.param_1_caption.nil?
validation_params << ques_val.validation_param_2 unless validation.param_2_caption.nil?
unless self.send validation_method, validation_params
x = false
errors.add( :answer_text, "Invalid entry!")
end
end
end
x
end
def is_not_blank?( param_list )
input_text = param_list[0]
!input_text.blank?
end
def is_number?( param_list )
input_text = param_list[0]
begin
Float( input_text )
rescue
false # not numeric
else
true # numeric
end
end
def range( param_list )
input_text = param_list[0]
range_from = param_list[1].to_i
range_to = param_list[2].to_i
input_text.length > range_from && input_text.length < range_to
end
def max_char( param_list )
input_text = param_list[0]
size = param_list[1].to_i
input_text.length <= size
end
def equal_to( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text == compare_to
end
def not_equal_to( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text != compare_to
end
def greater_than( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text > compare_to
end
def greater_than_equal_to( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text >= compare_to
end
def less_than( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text < compare_to
end
def less_than_equal_to( param_list )
input_text = param_list[0]
compare_to = param_list[1]
input_text <= compare_to
end
private
def add_evaluation_id
self.parent_id = 0 if parent.nil?
if evaluation.blank? && !parent.nil?
self.evaluation_id = parent.evaluation_id
end
end
end
end
| true |
890543a0ebffaba650d000d7c021270bbf95ee97 | Ruby | gregors/boilerpipe-ruby | /lib/boilerpipe/filters/terminating_blocks_finder.rb | UTF-8 | 1,509 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | # Finds blocks which are potentially indicating the end of an article
# text and marks them with INDICATES_END_OF_TEXT. This can be used
# in conjunction with a downstream IgnoreBlocksAfterContentFilter.
module Boilerpipe::Filters
class TerminatingBlocksFinder
def self.process(doc)
doc.text_blocks.each do |tb|
next unless tb.num_words < 15
if tb.text.length >= 8 && finds_match?(tb.text.downcase)
tb.labels << :INDICATES_END_OF_TEXT
elsif tb.link_density == 1.0 && tb.text == 'comment'
tb.labels << :INDICATES_END_OF_TEXT
end
end
doc
end
def self.finds_match?(text)
text.start_with?('comments') ||
text =~ /^\d+ (comments|users responded in)/ || # starts with number
text.start_with?('© reuters') ||
text.start_with?('please rate this') ||
text.start_with?('post a comment') ||
text.include?('what you think...') ||
text.include?('add your comment') ||
text.include?('add comment') ||
# TODO add this and test
# text.include?('leave a reply') ||
# text.include?('leave a comment') ||
# text.include?('show comments') ||
# text.include?('Share this:') ||
text.include?('reader views') ||
text.include?('have your say') ||
text.include?('reader comments') ||
text.include?('rätta artikeln') ||
text == 'thanks for your comments - this feedback is now closed'
end
end
end
| true |
e80055239e8f2803fcdb280fcac647b66d9445f7 | Ruby | johnto20/tealeaf_course | /Intro_to_programming/loops_and_iterators/exercise_3.rb | UTF-8 | 150 | 3.34375 | 3 | [] | no_license | array1 = ["John", "Jim", "Andrew","Adelaide", "Sarah", "Johnny"]
array1.each_with_index do |name, index|
puts "#{index}" + ". " + "#{name}"
end | true |
c62ed7f72a2929106634e714bf02cf203598911e | Ruby | siakaramalegos/assignment_rspec_ruby_tdd | /spec/stock_spec.rb | UTF-8 | 887 | 3.5 | 4 | [] | no_license | require_relative '../lib/stock.rb'
describe '#stock' do
it 'should raise an error if an argument is not given' do
expect{stock}.to raise_error(ArgumentError)
end
# TODO: Better way to do this? arg.to be_Array?
it 'should only accept an array as an argument' do
expect{stock(1)}.to raise_error("Oops, need an array")
expect{stock('hi')}.to raise_error("Oops, need an array")
end
it 'should raise an error if less than 2 days given' do
expect{stock([1])}.to raise_error("Oops, need more days")
end
it 'should return [0,1] if only given 2 days' do
expect(stock([25, 42])).to eq([0, 1])
end
it 'should return a buy day that is before the sell day' do
expect(stock([25, 16, 4])).to eq([0, 1])
end
it 'should pick the best buy and sell day combination' do
expect(stock([44, 30, 24, 32, 35, 30, 40, 38, 15])).to eq([2, 6])
end
end | true |
cc10e44ec9cd5f17d182b85092ea6c4e9b69c36f | Ruby | josephelias-techversant/Calender | /Ruby/sample.rb | UTF-8 | 622 | 4 | 4 | [] | no_license | #Sample code to prompt user to enter his name
puts "Enter your name: "
first_name = gets.chomp
puts "Hi #{first_name}, welcome to Ruby!"
#The below lines will create a file or over write the exisitng file
File.open('file2.txt', 'a+') do |f|
f.puts "This is JavaTpoint"
f.write "You are reading Ruby tutorial.\n"
f << "Please visit our website.\n"
end
#Reading contents from the file
puts "Reading contents"
File.open('file2.txt', 'r+') do |f|
arr = f.readlines
puts arr.inspect
end
puts "Reading to upcase"
File.readlines("file2.txt").each do |line|
puts line.upcase
end
| true |
83563d9f0d5257ed408cf6b12ce93731cef52ea8 | Ruby | levbrie/rails_tutorial_app | /app/controllers/users_controller.rb | UTF-8 | 3,345 | 2.6875 | 3 | [] | no_license | class UsersController < ApplicationController
# before filter arranges for a method to be called before the given actions
# following and followers actions in the signed_in_user filter enables us
# to set title, find user, and retrieve followed_users or followers using defs
before_filter :signed_in_user,
only: [:index, :edit, :update, :destroy, :following, :followers]
# 2nd before filter to call the correct_user method and make sure only the
# current user can only edit his account and nothing else
before_filter :correct_user, only: [:edit, :update]
# add before filter restricting destroy action to admins
before_filter :admin_user, only: :destroy
def index
# pull all the users out of the database and assign them to @users i.v.
# @users = User.all
# for pagination, we replace above with:
@users = User.paginate(page: params[:page]) # paginate users in index
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
# adding an @user variable to the new action
def new
if signed_in?
redirect_to root_path, notice: "Please sign out in order to create a new user."
else
@user = User.new
end
end
def create
if signed_in?
redirect_to user_path(current_user), notice: "Please sign out in order to create a new user."
else
@user = User.new(params[:user])
if @user.save
sign_in @user # signs in the user upon signup
flash[:success] = "Welcome to the Sample App!"
# Handle a successful save.
redirect_to @user
else
render 'new'
end
end
end
# RESTful edit action that starts by finding the user
def edit
# no longer needed: @user = User.find(params[:id])
end
def update
# no longer needed because of correct_user before filter:
# @user = User.find(params[:id])
if @user.update_attributes(params[:user])
# Handle a successful update.
# we sign in user as part of a successful profile update because
# remember token gets reset when user is saved, this also prevents
# hijacked sessions from continuing after user info is changes
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
if current_user?(@user)
redirect_to users_path, notice: "Admin cannot delete himself"
else
# use method chaining to combine find and destroy into one line
@user.destroy
flash[:success] = "User destroyed."
redirect_to users_path
end
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.followed_users.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
# everything after this is private?
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
# used to make sure only admins can destroy users
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
| true |
82d3873b5f8df92276316d9492b202158455633d | Ruby | emanon001/atcoder-ruby | /joi2014yo/d/main.rb | UTF-8 | 831 | 2.984375 | 3 | [] | no_license | N = gets.to_i
R = gets.chomp.chars
MOD = 10 ** 4 + 7
def r_to_k(r)
case r
when 'J' then 0
when 'O' then 1
when 'I' then 2
end
end
dp = Array.new(N + 1) { Array.new(1 << 3, 0) }
dp[0][1] = 1
N.times do |i|
r = R[i]
(1..7).each do |bits|
next if dp[i][bits] == 0
next_value = Array.new(1 << 3, 0)
# 鍵を持つ人を選ぶ
3.times do |key|
next if bits[key] == 0
# 次の日に参加する人を決める
(1..7).each do |next_bits|
next if next_bits[key] == 0
next if next_bits[r_to_k(r)] == 0
next_value[next_bits] = dp[i][bits] if next_value[next_bits] == 0
end
end
(1..7).each do |next_bits|
count = next_value[next_bits]
dp[i + 1][next_bits] = (dp[i + 1][next_bits] + count) % MOD
end
end
end
puts dp[N].reduce(&:+) % MOD | true |
5df0211c754c9be3349a98273be4c0f76f19c134 | Ruby | volunteermatch/vm-contrib | /archive/api-examples-v2/generate_credentials/generate_credentials.rb | UTF-8 | 789 | 2.984375 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'base64'
require 'digest/sha2'
if ARGV.length == 2
account_name, api_key = ARGV
else
puts "Usage: #{$0} account_name api_key"
exit 1
end
class VolunteerMatchApi
attr_reader :nonce, :creation_time, :digest
def initialize (account_name, api_key)
@account_name = account_name
@api_key = api_key
@nonce = Digest::SHA2.hexdigest(rand.to_s)[0, 20]
@creation_time = Time.now.utc.strftime("%Y-%m-%dT%H:%m:%S%z")
@digest = Base64.encode64(Digest::SHA2.digest(nonce + creation_time + @api_key)).chomp
end
end
api = VolunteerMatchApi.new(account_name, api_key)
puts "Account Name: #{account_name}"
puts "Nonce: #{api.nonce}"
puts "Digest: #{api.digest}"
puts "Creation Time: #{api.creation_time}"
| true |
1e3dba1b1f3eea147c678aa34e953d9870d134ac | Ruby | EzraMoore65/raylib-ruby | /examples/textures/textures_raw_data.rb | UTF-8 | 2,566 | 2.765625 | 3 | [
"MIT"
] | permissive | # /*******************************************************************************************
# *
# * raylib [textures] example - Load textures from raw data
# *
# * NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM)
# *
# * This example has been created using raylib 1.3 (www.raylib.com)
# * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
# *
# * Copyright (c) 2015 Ramon Santamaria (@raysan5)
# *
# ********************************************************************************************/
# Ported to ruby by Aldrin Martoq (@aldrinmartoq)
require 'raylib'
# Initialization
screen_w = 800
screen_h = 450
RayWindow.init screen_w, screen_h, 'ruby raylib [textures] example - texture from raw data'
# NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
# Load RAW image data (512x512, 32bit RGBA, no file header)
fudesumi_raw = RayImage.load_raw 'resources/fudesumi.raw', 384, 512, :uncompressed_r8g8b8a8, 0
fudesumi = fudesumi_raw.to_texture2d # Upload CPU (RAM) image to GPU (VRAM)
fudesumi_raw.unload # Unload CPU (RAM) image data
# Generate a checked texture by code (1024x1024 pixels)
width = 1024
height = 1024
# Dynamic memory allocation to store pixels data (Color type)
pixels = FFI::MemoryPointer.new RayColor, width * height
array = []
(0...height).each do |y|
(0...width).each do |x|
if ((x / 32 + y / 32) / 1).even?
color = RayColor[:orange]
else
color = RayColor[:gold]
end
array << color.r
array << color.g
array << color.b
array << color.a
end
end
pixels.write_array_of_uchar array
# Load pixels data into an image structure and create texture
checked_image = RayImage.load_ex pixels, width, height
checked = checked_image.to_texture2d
checked_image.unload # Unload CPU (RAM) image data
# Main game loop
until RayWindow.should_close? # Detect window close button or ESC key
# Update
# TODO: Update your variables here
# Draw
RayDraw.drawing do
RayDraw.clear_background :raywhite
checked.draw screen_w / 2 - checked.width / 2, screen_h / 2 - checked.height / 2, RayColor.fade(:white, 0.5)
fudesumi.draw 430, -30, :white
RayDraw.text 'CHECKED TEXTURE ', 84, 100, 30, :brown
RayDraw.text 'GENERATED by CODE', 72, 164, 30, :brown
RayDraw.text 'and RAW IMAGE LOADING', 46, 226, 30, :brown
end
end
# De-Initialization
fudesumi.unload # Texture unloading
checked.unload # Texture unloading
RayWindow.close # Close window and OpenGL context
| true |
93ddba4d2d4b454cc1a7fcb8d1e184e023ff2fe5 | Ruby | MatthewShepherd/phase-0-tracks | /ruby/vampires2.rb | UTF-8 | 343 | 3.546875 | 4 | [] | no_license | # Request user input
# name
# age and year
# garlic bread?
# health insurance?
p "what is your name?"
user_name = gets.chomp
p "how old are you?"
age = gets.chomp
p "what year were you born?"
year = gets.chomp
"would you liike garlic bread(y/n)?"
bread = gets.chomp
"health insurance?(y/n)"
insur = gets.chomp
| true |
7c972a71394208fea7933aba2b55bf028cc29102 | Ruby | pedrogglima/scrap-cbf | /lib/scrap_cbf/errors.rb | UTF-8 | 1,551 | 3.015625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class ScrapCbf
# Base error for all ScrapCbf errors.
class BaseError < ::StandardError; end
# Raised when a required method is not implemented.
class MethodNotImplementedError < BaseError; end
# Raised when a argument is not included in a predefined range of values.
class OutOfRangeArgumentError < BaseError
def initialize(argument, range)
message = "#{argument} must be in the range of : #{range}"
super(message)
end
end
# Raised when a argument is required but it is missing.
class MissingArgumentError < BaseError
def initialize(argument)
message = "missing argument: #{argument}"
super(message)
end
end
# Raised when the scraping data is not included in a predefined range.
class InvalidNumberOfEntitiesError < BaseError
def initialize(entity, number)
message = "an invalid number of #{entity} entities was found: #{number}"
super(message)
end
end
# Raised when the scraping data from a table
# have the size of the Table's header different than the Table's rows.
class RowSizeError < BaseError
def initialize(row_length, header_length)
message = "row length: #{row_length} doesn't match with " \
"header length: #{header_length}"
super(message)
end
end
# Raised when a method is not found on a class.
class MethodMissingError < BaseError
def initialize(klass_name, method)
message = "method '#{method}' missing on class #{klass_name}"
super(message)
end
end
end
| true |
fdcfc7374cadb4c0dce204c987b545af091b58bb | Ruby | Dyoon3102/phase-0-tracks | /ruby/hashes.rb | UTF-8 | 1,750 | 3.9375 | 4 | [] | no_license | # Initialize an empty hash to start collecting client information.
client = {}
puts "Please key in corresponding information."
puts ""
# Prompt user to input corresponding information.
puts "Client's name:"
name = gets.chomp
# Convert input to value of key
client[:name] = name
puts ""
# Prompt user to input corresponding information.
puts "Client's age:"
age = gets.chomp.to_i
# Convert input to value of key
client[:age] = age
puts ""
# Prompt user to input corresponding information.
puts "Number of children? (0 if none):"
child_num = gets.chomp.to_i
# Convert input to value of key
client[:child_num] = child_num
puts ""
# Prompt user to input corresponding information.
puts "Choice of decor theme:"
decor_theme = gets.chomp
# Convert input to value of key
client[:decor_theme] = decor_theme
puts ""
# Prompt user to input corresponding information.
puts "Likes chandaliers? (y/n)"
like_chandalier = gets.chomp.downcase
if like_chandalier == "y"
like_chandalier = true
else
like_chandalier = false
end
# Convert input to value of key
client[:like_chandalier] = like_chandalier
puts ""
# Prompt user to input corresponding information.
puts "Allergic to lime-green paint? (y/n)"
allergy = gets.chomp.downcase
if allergy == "y"
allergy = true
else
allergy = false
end
# Convert input to value of key
client[:allergy] = allergy
puts ""
# Print the hash
puts client
puts ""
# Give the user opportunity to update a key
puts "Please type in the key you would like to change. If none, please type none."
key_change = gets.chomp
puts ""
# Update the value of the key and end program with hash print
if key_change == "none"
else
puts "Enter new value."
new_value = gets.chomp
client[key_change.to_sym] = new_value
end
puts ""
puts client | true |
5c4833030c09c5c5ac4d02baa6ab0bf684ce28f3 | Ruby | aagooden/Pizza | /pizza.rb | UTF-8 | 1,166 | 3.71875 | 4 | [] | no_license | def crust()
["Thick Crust", "Thin Crust", "Pan Crust", "Stuffed Crust"]
end
def meats()
["Pepperoni", "Sausage", "Ham", "Chicken"]
end
def veggies()
["Peppers", "Onions", "Mushrooms", "Peas"]
end
def special_sauce()
["Tomato Sauce", "Ranch Sauce", "Itallian Sauce", "Fruit Sauce"]
end
def special_tops()
["Extra Cheese", "Extra Sauce", "Pineapple"]
end
def size()
["Small", "Medium", "Large", "Extra Large"]
end
def owe_calc(s)
if s == "Small"
8
elsif s == "Medium"
10
elsif s == "Large"
12
else
15
end
end
owe = 0.0
puts "How many pizzas would you like"
num_p = gets.chomp
num_p = num_p.to_i
for x in 1..num_p
p_size = size.sample
puts "Pizza #{x}"
puts "#{p_size}, #{crust.sample}, #{meats.sample}, #{veggies.sample}, #{special_sauce.sample}, #{special_tops.sample}\n"
puts " "
owe = owe + owe_calc(p_size)
end
delivery = num_p * 2
delivery = delivery.to_f
tax = owe * 0.06
tax = tax.to_f
owe = owe.to_f
puts
puts "Pizza Charge = $#{sprintf("%.02f", owe)}"
puts "Delivery = $#{sprintf("%.02f", delivery)}"
puts "Tax = $#{sprintf("%.02f", tax)}"
puts " "
puts "Your Total is $#{(sprintf("%.02f",(owe + delivery + tax)))}"
| true |
c386cac69dbaa2373698b64ddd393fd398175c20 | Ruby | jnunemaker/gemwhois | /lib/rubygems/commands/whois_command.rb | UTF-8 | 1,295 | 2.890625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | require 'rubygems/gemcutter_utilities'
require 'crack'
require 'unindent'
class Gem::Commands::WhoisCommand < Gem::Command
include Gem::GemcutterUtilities
def description
'Perform a whois lookup based on a gem name so you can see if it is available or not'
end
def arguments
"GEM name of gem"
end
def usage
"#{program_name} GEM"
end
def initialize
super 'whois', description
end
def execute
whois get_one_gem_name
end
def whois(gem_name)
response = rubygems_api_request(:get, "api/v1/gems/#{gem_name}.json") do |request|
request.set_form_data("gem_name" => gem_name)
end
with_response(response) do |resp|
json = Crack::JSON.parse(resp.body)
puts <<-STR.unindent
gem name: #{json['name']}
owners: #{json['authors']}
info: #{json['info']}
version: #{json['version']}
downloads: #{json['downloads']}
STR
end
end
def with_response(resp)
case resp
when Net::HTTPSuccess
block_given? ? yield(resp) : say(resp.body)
else
if resp.body == 'This rubygem could not be found.'
puts '','Gem not found. It will be mine. Oh yes. It will be mine. *sinister laugh*',''
else
say resp.body
end
end
end
end | true |
4f16528c70399d5e4733acc079da200a2d824565 | Ruby | Porti2/Appium | /LoginStaff_Valido.rb | UTF-8 | 1,525 | 2.734375 | 3 | [] | no_license | # Importamos las librerias o scripts necesarias
require '../Login.rb'
puts "** Test 3: Login Satff Válido **\n--------------------------"
Login.login('Paco.cid','1234abcd')
# Realizamos un 'Click' en el boton para iniciar la sesión.
$driver.find_element(:id, "com.Intelinova.TgApp:id/btn_login_staff").click
# Indicamos que espere a que aparezca el centro (Gimnasio) y lo seleccionamos.
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { $driver.find_element(:id, "com.Intelinova.TgApp:id/container_info").displayed? }
$driver.find_element(:id, "com.Intelinova.TgApp:id/container_info").click
puts "\t"+Time.now.strftime("%d/%m/%Y %H:%M:%S")+" --> Inicia sesión correctamente."
# Indicamos que espere a que aparezca las ventanas de informacion y las cerramos.
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { $driver.find_element(:id, "com.Intelinova.TgApp:id/iv_closeView").displayed? }
$driver.find_element(:id, "com.Intelinova.TgApp:id/iv_closeView").click
# Indicamos que si existe un titulo en la Toolbar es que ha iniciado sesion correctamente y damos por finalizado correctamente el Test.
# Si este titulo no existiera dariamos como NO finalizado el Test.
if ($driver.find_element(:id, "com.Intelinova.TgApp:id/toolbar_title").displayed?)
puts "\t"+Time.now.strftime("%d/%m/%Y %H:%M:%S")+" --> Aparece la pantalla principal. Test finalizado con exito."
else
puts "\t"+ Time.now.strftime("%d/%m/%Y %H:%M:%S")+" --> ¡¡Error!! El test NO ha finalizado correctamente."
end | true |
ffde1c2368c5fa6d3e8e307360c630d40ff31e0d | Ruby | oshou/procon | /HackerRank/Algorithms/sock_merchant.rb | UTF-8 | 179 | 3.109375 | 3 | [] | no_license | n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)
counts = {}
arr.uniq.each do |v|
counts[v] = arr.count(v)
end
pairs = 0
counts.map { |k, v| pairs += v / 2 }
puts pairs
| true |
85476bd160b947e21ebf45a48575fb1ded3ed0ae | Ruby | PrateekAlakh/Ruby-Programmes | /Proc_floor.rb | UTF-8 | 79 | 2.9375 | 3 | [] | no_license | a=[1.2,2.3,3.4,4.5,5.6,6.7]
fl=Proc.new do |n|
n.floor
end
p a.collect!(&fl)
| true |
3c318eb85764a75f610d44936b017e3de3f4e5c0 | Ruby | wendy0402/jsm | /spec/jsm/states_spec.rb | UTF-8 | 2,007 | 2.859375 | 3 | [
"MIT"
] | permissive | describe Jsm::States do
let(:states) { Jsm::States.new }
describe '.add_state' do
it 'register new state' do
states.add_state(:x)
expect(states.list[0].name).to eq(:x)
end
it 'can register more than one state' do
states.add_state(:x)
states.add_state(:y)
expect(states.list.map(&:name)).to match_array([:x, :y])
end
it 'can register initial state' do
states.add_state(:x, initial: true)
expect(states.list[0].name).to eq(:x)
expect(states.list[0].initial).to eq(true)
end
it 'can register initial state with others states' do
states.add_state(:w, initial: true)
states.add_state(:x)
states.add_state(:y)
expect(states.list.map(&:name)).to match_array([:w, :x, :y])
end
context 'exception' do
before do
states.add_state(:x, initial: true)
end
it 'register same state twice' do
expect{ states.add_state(:x) }.to raise_error(Jsm::NotUniqueStateError, "state x has been defined")
end
it 'register initial state twice' do
expect { states.add_state(:y, initial: true) }.to raise_error(Jsm::InvalidStateError, 'can not set initial state to y. current initial state is x')
end
end
end
describe '.initial_state' do
before do
states.add_state(:x, initial: true)
states.add_state(:y)
end
it 'value is the state with initial true' do
expect(states.initial_state.name).to eq(:x)
end
end
describe 'has_state?' do
context 'list has states' do
before do
states.add_state(:x, initial: true)
states.add_state(:y)
end
it 'return true if state present' do
expect(states.has_state?(:x)).to be_truthy
end
it 'return false if state doesnt present' do
expect{ states.has_state?(:z).to be_falsey }
end
end
context 'list doesnt have any state' do
it { expect( states.has_state?(:y)).to be_falsey }
end
end
end
| true |
ae0eca544070ed1e741ab843dc5e7a237c73353c | Ruby | kaspernj/attr_args_shorthand | /lib/attr_args_shorthand.rb | UTF-8 | 920 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | class AttrArgsShorthand
def self.set(object, arguments, args = {})
arguments.each do |key, value|
object.instance_variable_set("@#{key}", value)
unless object.respond_to?(key)
object.define_singleton_method(key) do
instance_variable_get("@#{key}")
end
end
unless object.respond_to?("#{key}=")
object.define_singleton_method("#{key}=") do |value|
instance_variable_set("@#{key}", value)
end
end
end
end
def self.set_attrs(clazz, args)
args.each do |arg|
clazz.__send__(:define_method, arg) do
instance_variable_get("@#{arg}")
end
clazz.__send__(:define_method, "#{arg}=") do |value|
instance_variable_set("@#{arg}", value)
end
end
end
def self.set_args(object, args)
args.each do |key, value|
object.instance_variable_set("@#{key}", value)
end
end
end
| true |
3a5344c73eda3b157bcfa9ac3c631658546fd25c | Ruby | marcandre/backports | /lib/backports/2.5.0/string/undump.rb | UTF-8 | 2,411 | 2.984375 | 3 | [
"MIT"
] | permissive | unless String.method_defined? :undump
class String
def undump
# Making sure to return a String and not a subclass
string = to_s
raise 'string contains null byte' if string["\0"]
raise 'non-ASCII character detected' unless string.ascii_only?
match = string.match(/\A(".*?"?)(?:\.force_encoding\("([^"]*)"\))?\z/) or
raise %(invalid dumped string; not wrapped with '"' nor '"...".force_encoding("...")' form)
string = match[1]
encoding = match[2]
# Ruby 1.9.3 does weird things to encoding during gsub
encoding ||= string.encoding.to_s
# Unescaped have an even number of backslashes in front of them
# because the double-quote is included, the unescaped quotes are where the size is odd
nb_unescaped_quote = string.scan(/\\*"/).select { |s| s.size.odd? }.size
raise 'unterminated dumped string' if nb_unescaped_quote == 1
if string[-1] != '"' || nb_unescaped_quote > 2
raise %(invalid dumped string; not wrapped with '"' nor '"...".force_encoding("...")' form)
end
string = string[1...-1]
if RUBY_VERSION >= '1.9'
# Look-arounds are not supported in ruby 1.8. Using a string with Regexp avoids the SyntaxError in 1.8.7
# \xY, \x3Y and finishing with \x
regex = Regexp.new("(?<!\\)(?:\\\\)*\\x(?![0-9a-f]{2})".gsub('\\', '\\\\\\\\'), Regexp::IGNORECASE)
raise 'invalid hex escape' if string[regex]
end
# The real #undump ignores the \C, \c and \M escapes
# Code injection is avoided by:
# * only allowing \u to have {}, so \\\\#{injection} will not eval the injection
# * only allowing the first character after the \\ to not be alpha/num/space, so \\\\#@inst_var_access is ignored
# To reduce the number of calls to eval a little, we wrap everything in a (...)+ so that consecutive escapes are
# handled at the same time.
result = string.gsub(/(\\+(u\{[\w ]+\}|[^cCM]\w*))+/) do |s|
begin
eval("\"#{s}\"") # "body"
rescue SyntaxError => e
raise RuntimeError, e.message, e.backtrace
end
end
if encoding
begin
Encoding.find(encoding)
rescue ArgumentError
raise "dumped string has unknown encoding name"
end
result = result.force_encoding(encoding)
end
result
end
end
end
| true |
9e22fb124a31cfc8e2f69335afc65f53b5cbfe44 | Ruby | callahanbrothers/larry | /spec/models/twitter_account_spec.rb | UTF-8 | 4,328 | 2.53125 | 3 | [] | no_license | require "rails_helper"
RSpec.describe TwitterAccount, type: :model do
let(:user) { User.create(uid: "123", token: "token", secret: "secret") }
let(:twitter_params) { {
uid: "123",
screen_name: "screen_name",
profile_image_url: "profile_image_url",
followers_count: "followers_count",
friends_count: "friends_count",
statuses_count: "statuses_count"
}
}
subject { TwitterAccount.new(twitter_params) }
it "can belong to a User" do
subject.user = user
expect(subject.user).to eq(user)
end
it "has many friends" do
subject.save
expect{
subject.friends << TwitterAccount.create(twitter_params)
subject.friends << TwitterAccount.create(twitter_params)
}.to change(subject.friends, :count).by(2)
end
it "has many followers" do
subject.save
expect{
subject.followers << TwitterAccount.create(twitter_params)
subject.followers << TwitterAccount.create(twitter_params)
}.to change(subject.followers, :count).by(2)
end
describe "#uid" do
it "is required" do
subject.uid = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Uid can't be blank")
end
end
describe "#screen_name" do
it "is required" do
subject.screen_name = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Screen name can't be blank")
end
end
describe "#profile_image_url" do
it "is required" do
subject.profile_image_url = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Profile image url can't be blank")
end
end
describe "#followers_count" do
it "is required" do
subject.followers_count = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Followers count can't be blank")
end
end
describe "#friends_count" do
it "is required" do
subject.friends_count = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Friends count can't be blank")
end
end
describe "#statuses_count" do
it "is required" do
subject.statuses_count = nil
subject.valid?
expect(subject.errors.full_messages.first).to eq("Statuses count can't be blank")
end
end
describe ".create_from_twitter_object" do
let(:twitter_obj) { Hashie::Mash.new({
"id" => "123",
"screen_name" => "screen name",
"profile_image_url" => "profile image url",
"followers_count" => 11,
"friends_count" => 22,
"statuses_count" => 33
})
}
it "creates a twitter account from the passed in twitter object" do
expect{TwitterAccount.create_from_twitter_object(twitter_obj)}.to change(TwitterAccount, :count).by(1)
end
it "sets the #uid to the integer form of the uid from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.uid).to eq(twitter_obj.id)
end
it "sets the #screen_name to the screen_name from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.screen_name).to eq(twitter_obj.screen_name)
end
it "sets the #profile_image_url to the profile_image_url from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.profile_image_url).to eq(twitter_obj.profile_image_url)
end
it "sets the #followers_count to the followers_count from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.followers_count).to eq(twitter_obj.followers_count)
end
it "sets the #friends_count to the friends_count from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.friends_count).to eq(twitter_obj.friends_count)
end
it "sets the #statuses_count to the statuses_count from the passed in twitter object" do
twitter_account = TwitterAccount.create_from_twitter_object(twitter_obj)
expect(twitter_account.statuses_count).to eq(twitter_obj.statuses_count)
end
end
end | true |
f1c2d7f1d9c5fe9f568b674a6d29931a2aebb863 | Ruby | mahichy/Ruby_Blockss | /05/bonus.rb | UTF-8 | 837 | 3.984375 | 4 | [] | no_license | # def n_times(number)
# 1.upto(number) do |c|
# yield(c)
# end
# end
# n_times(5) do |n|
# puts "#{n} situps"
# puts "#{n} pushups"
# puts "#{n} chinups"
# end
def deal(number_of_cards)
faces = ["Jack", "Queen", "King", "Ace"]
suits = ["Hearts", "Diamonds", "Spades", "Clubs"]
if block_given?
number_of_cards.times do
random_face = faces.sample
random_suit = suits.sample
score = yield random_face, random_suit
puts "You scored a #{score}!"
end
else
puts "No deal!"
end
end
deal(10) do |face, suit|
puts "Dealt a #{face} of #{suit}"
face.length + suit.length
end
def progress
0.step(100, 10) do |number|
yield number
end
end
progress { |percent| puts percent }
def greet
yield "Larry", 18
end
greet { |name, age| puts "Hello, #{name}. You don't look #{age}!" } | true |
f0aa8bfd9ee84a60c424c465d58939b509d260ce | Ruby | analyticalCat/playground | /todolists/app/models/profile.rb | UTF-8 | 626 | 2.625 | 3 | [] | no_license | class Profile < ActiveRecord::Base
belongs_to :user
validate :first_last_name_not_null
def first_last_name_not_null
if first_name.nil? and last_name.nil?
errors.add(:first_name, "and last name cannot both be null")
end
end
validates :gender, inclusion: { in: ["male", "female"]}
validate :no_sue_for_male
def no_sue_for_male
if gender == "male" and first_name == "Sue"
errors.add(:gender, "cannot have first name as 'Sue'")
end
end
def self.get_all_profiles(miny, maxy)
Profile.where("birth_year BETWEEN :mi and :ma", mi: miny, ma: maxy).order(:birth_year)
end
end
| true |
baee2c8c4ac64ef5575c482ead0ca4ffbdaeec7f | Ruby | louiechristie/WDI_LDN_5_Assignments | /louiechristie/w9d3/code_test/Card.rb | UTF-8 | 2,094 | 3.65625 | 4 | [] | no_license | class Card
attr_accessor :card_number
attr_accessor :card_type
def initialize(card_number)
@card_number = card_number.gsub(/\s+/, "") #strip out white space
@card_type = "Unknown" if !valid_type_of_card?
end
def check()
valid? ? "valid" : "invalid"
end
def valid?
is_a_number? && valid_type_of_card? && valid_luhn_number?
end
def is_a_number?
begin
!!Integer(@card_number)
rescue ArgumentError, TypeError
false
end
end
def valid_type_of_card?
puts "type: "
puts @card_number[0]
case @card_number[0].to_i
when 3
check_is_amex?
when 4
check_is_visa?
when 5
check_is_mastercard?
when 6
check_is_discover?
else
false
end
end
def check_is_amex?
if (@card_number[0..1] == "34" || @card_number[0..1] == "37") && @card_number.length == 15
@card_type = "AMEX"
return true
else
return false
end
end
def check_is_visa?
if @card_number.length == 13 || @card_number.length == 16
@card_type = "VISA"
return true
else
return false
end
end
def check_is_mastercard?
if @card_number.length == 16
@card_type = "MasterCard"
return true
else
return false
end
end
def check_is_discover?
if @card_number[0..3] == "6011" && @card_number.length == 16
@card_type = "Discover"
return true
else
return false
end
end
def valid_luhn_number?
@card_number.reverse!
array = []
for i in 0..(@card_number.length-1)
if i % 2 == 0
array << @card_number[i].to_i
else
array << double_and_sum_digits(@card_number[i].to_i)
end
end
array.reverse!
puts "array"
puts array.inspect
number = array.reduce{ |sum, x| sum + x }
puts "number"
puts number
number % 10 == 0
end
def double_and_sum_digits(num)
double = num * 2
string = double.to_s
result = string.split('').reduce{ |sum, x| sum.to_i + x.to_i }.to_i
end
end | true |
1799d5227d656713c4a291aa0d89ce3c66135fe4 | Ruby | IlyaUmanets/improve_your_code | /lib/improve_your_code/code_comment.rb | UTF-8 | 1,626 | 2.703125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'yaml'
require_relative 'smell_detectors/base_detector'
module ImproveYourCode
class CodeComment
CONFIGURATION_REGEX = /
:improve_your_code: # prefix
(\w+) # smell detector e.g.: UncommunicativeVariableName
(
:? # legacy separator
\s*
(\{.*?\}) # optional details in hash style e.g.: { max_methods: 30 }
)?
/x
SANITIZE_REGEX = /(#|\n|\s)+/ # Matches '#', newlines and > 1 whitespaces.
DISABLE_DETECTOR_CONFIGURATION = '{ enabled: false }'
MINIMUM_CONTENT_LENGTH = 2
LEGACY_SEPARATOR = ':'
attr_reader :config
def initialize(comment:, line: nil, source: nil)
@original_comment = comment
@line = line
@source = source
@config = Hash.new { |hash, key| hash[key] = {} }
@original_comment.scan(CONFIGURATION_REGEX) do |detector_name, _option_string, options|
@config.merge! detector_name => YAML.safe_load(options || DISABLE_DETECTOR_CONFIGURATION,
[Regexp])
end
end
def descriptive?
sanitized_comment.split(/\s+/).length >= MINIMUM_CONTENT_LENGTH
end
private
attr_reader :original_comment, :source, :line
def sanitized_comment
@sanitized_comment ||= original_comment
.gsub(CONFIGURATION_REGEX, '')
.gsub(SANITIZE_REGEX, ' ')
.strip
end
end
end
| true |
1a7584f3a8a282305cfc40882338814a246a6895 | Ruby | majestrate/BitMessageForum | /lib/bmf.rb | UTF-8 | 1,996 | 2.609375 | 3 | [] | no_license | require 'thread'
module BMF
require_relative "bmf/lib/bmf.rb"
require_relative "bmf/lib/alert.rb"
def self.puts_and_alert msg
puts msg
Alert.instance << msg
end
def self.sync
new_messages = MessageStore.instance.update
Alert.instance.add_new_messages(new_messages)
AddressStore.instance.update
rescue Errno::ECONNREFUSED => ex
puts_and_alert "Background sync. Couldn't connect to PyBitmessage server. Is it running with the API enabled? "
rescue JSON::ParserError => ex
puts_and_alert "Couldn't background sync. It seems like PyBitmessage is running but refused access. Do you have the correct info in config/settings.yml? "
rescue Exception => ex
puts_and_alert "Background Sync failed with #{ex.message}"
end
def self.boot
puts "Doing initial sync before starting..."
sync
Alert.instance.pop_new_messages # don't show new message alert on bood.
Thread.new do
while(1) do
sync_interval = Settings.instance.sync_interval.to_i
sync_interval = 60 if sync_interval == 0
sleep(sync_interval)
begin
sync
rescue Exception => ex
msg = "Background sync faild with #{ex.message}"
Alert.instance << msg
puts msg
puts ex.backtrace.join("\n")
end
end
end
BMF.run! do |server|
settings = Settings.instance
if (settings.https_server_key_file && settings.https_server_key_file != "") &&
(settings.https_server_certificate_file && settings.https_server_certificate_file != "")
puts "Requiring https..."
ssl_options = {
:cert_chain_file => settings.https_server_certificate_file,
:private_key_file => settings.https_server_key_file,
:verify_peer => false
}
server.ssl = true
server.ssl_options = ssl_options
else
puts "NOT requiring https. Traffic is unencrypted..."
end
end
end
end
| true |
e1e2dbcb6a249d3704594c3248ccad35aa0bd65f | Ruby | vkothari-systango/mars_rover | /mars_rover_input.rb | UTF-8 | 737 | 3.234375 | 3 | [] | no_license | require_relative "./mars_rover"
puts "Enter Top(upper-right) coordinates of the plateau separated by spaces:"
upper_right_coordinate = gets
starting_position = []
instructions = []
inputs = []
for i in 0...2
puts "Enter Rover's starting position(two integers and a letter) separated by spaces:"
starting_position[i] = gets
puts "Enter series of instructions for rover in the form of [L]eft [R]ight [M]ove:"
instructions[i] = gets
inputs.push({
top_coordinates: upper_right_coordinate,
starting_position: starting_position[i],
instructions: instructions[i]
})
end
inputs.each do |input|
result = MarsRover.get_updated_rover_position input
puts "Updated rover position: #{result}" if result.present?
end | true |
e8c00aab1507d50dcecbadc8f8452fd34da0fa02 | Ruby | alanryoung01/badges-and-schedules-onl01-seng-pt-090820 | /conference_badges.rb | UTF-8 | 557 | 3.421875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Write your code here.
def badge_maker(name)
return "Hello, my name is #{name}."
end
def batch_badge_creator(attendees)
people = []
attendees.each do |name|
people.push("Hello, my name is #{name}.")
end
return people
end
def assign_rooms(att)
people = []
counter = 1
att.each do |name|
people.push("Hello, #{name}! You'll be assigned to room #{counter}!")
counter += 1
end
return people
end
def printer(att)
batch_badge_creator(att).each do |badge|
puts badge
end
assign_rooms(att).each do |assign|
puts assign
end
end
| true |
d4a56f009d5e16a97f68853d518d0831f30f0d4b | Ruby | DanS/design_patterns | /composite_pattern/spec/baker_spec.rb | UTF-8 | 1,242 | 2.703125 | 3 | [] | no_license | require "baker.rb"
describe "cake making tasks" do
it "should mix dry ingredients" do
adi = AddDryIngredientsTask.new
adi.name.should == "Add dry ingredients"
adi.get_time_required.should == 1.0
end
it "should add the wet ingredients" do
awi = AddLiquidsTask.new
awi.name.should == "Adding liquids glug glug glug"
awi.get_time_required.should == 1.3
end
describe "Make Batter Task" do
it "should make batter by instantiating subTasks" do
genericTask = Task.new('generic task')
AddDryIngredientsTask.should_receive(:new).and_return(genericTask)
AddLiquidsTask.should_receive(:new).and_return(genericTask)
MixTask.should_receive(:new).and_return(genericTask)
MakeBatterTask.new
end
it "should have a time equal to the sum of all subtasks times" do
sum = AddDryIngredientsTask.new.get_time_required +
AddLiquidsTask.new.get_time_required +
MixTask.new.get_time_required
mbt = MakeBatterTask.new
mbt.get_time_required.should == sum
end
it "should have subtasks that know their parent" do
mbt = MakeBatterTask.new
mbt.sub_tasks.each do |task|
task.parent.should == mbt
end
end
end
end | true |
7388e63ae5b11e50f3498a4eff30d0533a39ac23 | Ruby | emrancub/Basic-Ruby-Programming-Practice | /chapter_3.1/arry_iteration.rb | UTF-8 | 328 | 4.0625 | 4 | [] | no_license | # iterating through arrays
[1, "test", 2, 3, 4].each{|element| puts element.to_s + "X"}
# each iterations through an array element
[1, 2, 3, 4].collect {|element| puts element*2}
# array acess using loop and add new letter with a array
a = [1, 'test', 2, 3, 4]
i = 0
while (i<a.length)
puts a[i].to_s + "X"
i+=1
end | true |
b1aed24d9df6ce9e86b196b61348d2dfc9778213 | Ruby | brandontricci/debut | /inclass/arrayask.rb | UTF-8 | 210 | 3.875 | 4 | [] | no_license | puts "enter the array elements (type 'exit' to get out)"
input = gets.chomp
arr = []
while input != 'exit'
arr << input.to_i
input = gets.chomp
end
puts arr.count
puts "times u have entered array items!!" | true |
4921217f95f36d26a70285297f7700592dc480f1 | Ruby | kjchiu/cobra | /app/services/sos_calculator.rb | UTF-8 | 2,490 | 2.71875 | 3 | [] | no_license | class SosCalculator
def self.calculate!(stage)
players = Hash[stage.players.map{ |p| [p.id, p] }]
# calculate points and cache values for sos calculations
points = {}
games_played = {}
opponents = {}
points_for_sos = {}
corp_points = {}
runner_points = {}
stage.eligible_pairings.each do |p|
points[p.player1_id] ||= 0
points[p.player1_id] += p.score1 || 0
points[p.player2_id] ||= 0
points[p.player2_id] += p.score2 || 0
games_played[p.player1_id] ||= 0
games_played[p.player1_id] += p.round.weight
games_played[p.player2_id] ||= 0
games_played[p.player2_id] += p.round.weight
opponents[p.player1_id] ||= []
opponents[p.player1_id] << { id: p.player2_id, weight: p.round.weight }
opponents[p.player2_id] ||= []
opponents[p.player2_id] << { id: p.player1_id, weight: p.round.weight }
points_for_sos[p.player1_id] ||= 0
points_for_sos[p.player1_id] += p.score1 || 0
points_for_sos[p.player2_id] ||= 0
points_for_sos[p.player2_id] += p.score2 || 0
corp_points[p.player1_id] ||= 0
corp_points[p.player1_id] += p.score1_corp || 0
corp_points[p.player2_id] ||= 0
corp_points[p.player2_id] += p.score2_corp || 0
runner_points[p.player1_id] ||= 0
runner_points[p.player1_id] += p.score1_runner || 0
runner_points[p.player2_id] ||= 0
runner_points[p.player2_id] += p.score2_runner || 0
end
# filter out byes from sos calculations
opponents.each do |k, i|
opponents[k] = i.select { |player| player[:id] }
end
sos = {}
opponents.each do |id, o|
if o.any?
sos[id] = o.sum do |player|
player[:weight] * points_for_sos[player[:id]].to_f / games_played[player[:id]]
end.to_f / o.inject(0) { |i, player| i += player[:weight] if player[:id] }
else
sos[id] = 0.0
end
end
extended_sos = {}
opponents.each do |id, o|
if o.any?
extended_sos[id] = o.sum do |player|
player[:weight] * sos[player[:id]]
end.to_f / o.inject(0) { |i, player| i += player[:weight] if player[:id] }
else
extended_sos[id] = 0.0
end
end
players.values.map do |p|
Standing.new(p,
points: points[p.id],
sos: sos[p.id],
extended_sos: extended_sos[p.id],
corp_points: corp_points[p.id],
runner_points: runner_points[p.id]
)
end.sort
end
end
| true |
b3338fb2e1ae6bcdd7d2adb5eed4c7650b2fcc3b | Ruby | cblair/portal | /app/models/job.rb | UTF-8 | 2,972 | 2.59375 | 3 | [] | no_license | class Job < ActiveRecord::Base
require 'spawn'
require 'delayed_job_runner'
attr_accessible :description, :finished, :user_id
belongs_to :user
has_one :delayed_job
def submit_job(current_user, ar_module, options)
jobs = Job.where(:user_id => current_user.id)
if jobs.count > 1000
puts "WARN: user #{current_user.email} has exceeded maximum jobs"
return false
end
self.user = current_user
self.waiting = true
job_type = Portal::Application.config.job_type
if job_type == "threads"
self.submit_job_threads(ar_module, options)
elsif job_type == "delayed_job"
self.submit_job_delayed_job(ar_module, options)
end
end
##############################################################################
## Jobs - thread mode functions (obsolete)
##############################################################################
def submit_job_threads(ar_module, options)
self.started = true
self.save
#spawn_block do
Thread.new do
#ensure we have a new connection with the db pool; each thread needs a new
# connection
begin
ActiveRecord::Base.connection_pool.with_connection do
#wait for a few seconds before we start
sleep 5
#If ar_module is a doc, gets passed to "submit_job" in doc model?
ar_module.submit_job(self, options)
end
rescue ActiveRecord::ConnectionTimeoutError
puts "WARN: Job #{self.id} waiting to start job on DB connection, sleeping 10 seconds..."
sleep 10
retry
end
end
self.finished = true
self.save
return true
end
##############################################################################
## Jobs - Delayed Job mode functions (current)
##############################################################################
def submit_job_delayed_job(ar_module, options)
self.started = true
self.save
#Submit job to delayed_job
puts "INFO: Starting DelayedJobRunner on #{ar_module.class.name}..."
#Typical submit...
#delayed_job_object = ar_module.delay.submit_job(self, options)
#~OR, using enqueue...
delayed_job_object = Delayed::Job.enqueue DelayedJobRunner.new(self, ar_module, options)
delayed_job_object.job_id = self.id
delayed_job_object.save
end
##############################################################################
## Other helpers
##############################################################################
#Makes job text displayable for the web
def safe_html(key)
s = self[key]
if s != nil
s = s.gsub(/[<>]/, '') #drop <> chars
s = s.gsub(/\n/, '<br />') #turn newlines into breaks
else
s = ""
end
s
end
def get_error_or_output
retval = ""
if self.last_error
retval = self.safe_html(:last_error)
else
retval = self.safe_html(:output)
end
retval
end
end
| true |
7f8513517965e7c8d93a4985b9809027e6cc0261 | Ruby | tmacram/Ruby- | /ex13ec3.rb | UTF-8 | 636 | 3.625 | 4 | [] | no_license | first, second, third = ARGV
puts "Maybe you can guess maybe you cannot, whaddya think the first one is?"
print "? "
response = STDIN.gets.chomp()
puts "You guessed #{response} and the correct answer was #{first}, sorry :("
puts "Alright another try, this variable is an animal but smells lika a...."
print "? "
response2 = STDIN.gets.chomp()
puts "That's right a #{second}! Well you said #{response2}, but that is not here nor there"
puts "Just say something already, youre upchuck.."
print "? "
response3 = STDIN.gets.chomp()
puts "It was actually #{third}, I said it right there in the prompt. I didn't say #{response3}, did I?" | true |
df7c6548dc457732a64667c9e8f9adf2cd97525c | Ruby | Polo94/testdrivendev | /00_hello/hello.rb | UTF-8 | 125 | 3.5625 | 4 | [] | no_license | #write your code here
def hello
"Hello!"
end
def greet(someone)
"Hello, #{someone}!"
end
puts greet("Alice"),greet("Bob") | true |
982e559fc0471eb0807abac65741ef5930e36cf6 | Ruby | ABBennett/chillow | /lib/truck.rb | UTF-8 | 191 | 2.515625 | 3 | [] | no_license | require_relative 'box'
require_relative "capacity_module"
class Truck
include Capacity
attr_reader :array
def initialize(capacity)
@capacity = capacity
@array = []
end
end
| true |
4621c87fac4d70494e4cedb3fdf8f2bd63d9d4d8 | Ruby | richardtemple/dice_game | /lib/draw/die.rb | UTF-8 | 542 | 3.1875 | 3 | [
"MIT"
] | permissive | require 'gosu'
class Die
attr_accessor :value, :image, :selected, :locked
def initialize()
@selected = false
@locked = false
@new_lock = false
roll
end
def roll
@value = rand(6) + 1
@image = Gosu::Image.new("./media/#{@value}.png") # code smell
end
def clicked
@selected = !@selected unless @locked
end
def lock
if @locked
@new_lock = false
else
@locked = true
@new_lock = true
end
end
def new_lock?
@new_lock
end
def reset
@new_lock = false
@selected = false
@locked = false
end
end | true |
1e4aa892e13dad89084303f0e44ab3fa9b0c970d | Ruby | adoan91/essential-ruby | /string-manip.rb | UTF-8 | 298 | 4.59375 | 5 | [] | no_license | # Method for getting user input
def get_input
print "Enter a string: "
return gets.chomp.to_s
end
str = get_input
print("String entered (str): #{str}\n")
print("Capitalizing of str: #{str.upcase}\n")
print("Length of string str: #{str.length}\n")
print("Reverse of string str: #{str.reverse}\n") | true |
3c93531a061337a6bd6442e45293eb9c646f0d7d | Ruby | phump81/bank_test | /spec/unit/account_spec.rb | UTF-8 | 730 | 2.921875 | 3 | [] | no_license | require 'account'
require 'timecop'
describe Account do
let(:account) { Account.new }
let(:deposit) { account.deposit(1000) }
let(:withdraw) { account.withdraw(500) }
it "adds deposit to balance" do
deposit
expect(account.instance_variable_get(:@balance)).to eq(1000)
end
it "deducts withdrawal from balance" do
deposit
withdraw
expect(account.instance_variable_get(:@balance)).to eql(500)
end
it "adds the withdrawal to the transactions" do
deposit
withdraw
expect(account.instance_variable_get(:@balance)).to eq(500)
end
it "displays a nicely formatted statement" do
expect { account.statement }.to output(/"date || credit || debit || balance"/).to_stdout
end
end
| true |
462985f616cb2704c012a25568f1b3c66b2e76ca | Ruby | guillaumejounel/CodeWars | /Ruby/top_3_words.rb | UTF-8 | 776 | 4.125 | 4 | [] | no_license | #Returns the top 3 words from a string. Words should be lowercased and may contain a '
def top_3_words(text)
rank = {}
words = text.downcase.scan(/[a-z]+['[a-z]+]*/)
words.uniq.map{|w| rank[w] = words.count(w)}
rank.sort_by{|k,v| [-v, k]}[0..2].to_h.keys
end
#Really interesting challenge as I don't often use Hash.
#For each unique word, I create a hash entry with this format : "word" => <nb of use>
#Then I just need to sort this hash and extract the first 3 keys.
#best solution: (much more readable)
def top_3_words(text)
text.scan(/[A-Za-z']+/)
.select { |x| /[A-Za-z]+/ =~ x }
.group_by { |x| x.downcase }
.sort_by { |k,v| -v.count }
.first(3)
.map(&:first)
end
#I did not know "group_by", it avoids creating a Hash
| true |
fde1005b994355fce659f937e39cccddc651663a | Ruby | bdurand/lumberjack | /lib/lumberjack/template.rb | UTF-8 | 5,354 | 3.15625 | 3 | [
"MIT"
] | permissive | # frozen_string_literals: true
module Lumberjack
# A template converts entries to strings. Templates can contain the following place holders to
# reference log entry values:
#
# * :time
# * :severity
# * :progname
# * :tags
# * :message
#
# Any other words prefixed with a colon will be substituted with the value of the tag with that name.
# If your tag name contains characters other than alpha numerics and the underscore, you must surround it
# with curly brackets: `:{http.request-id}`.
class Template
TEMPLATE_ARGUMENT_ORDER = %w[:time :severity :progname :pid :message :tags].freeze
MILLISECOND_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%3N"
MICROSECOND_TIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%6N"
PLACEHOLDER_PATTERN = /:(([a-z0-9_]+)|({[^}]+}))/i.freeze
# Create a new template from the markup. The +first_line+ argument is used to format only the first
# line of a message. Additional lines will be added to the message unformatted. If you wish to format
# the additional lines, use the :additional_lines options to specify a template. Note that you'll need
# to provide the line separator character in this template if you want to keep the message on multiple lines.
#
# The time will be formatted as YYYY-MM-DDTHH:MM:SSS.SSS by default. If you wish to change the format, you
# can specify the :time_format option which can be either a time format template as documented in
# +Time#strftime+ or the values +:milliseconds+ or +:microseconds+ to use the standard format with the
# specified precision.
#
# Messages will have white space stripped from both ends.
#
# @param [String] first_line The template to use to format the first line of a message.
# @param [Hash] options The options for the template.
def initialize(first_line, options = {})
@first_line_template, @first_line_tags = compile(first_line)
additional_lines = options[:additional_lines] || "#{Lumberjack::LINE_SEPARATOR}:message"
@additional_line_template, @additional_line_tags = compile(additional_lines)
# Formatting the time is relatively expensive, so only do it if it will be used
@template_include_time = first_line.include?(":time") || additional_lines.include?(":time")
self.datetime_format = (options[:time_format] || :milliseconds)
end
# Set the format used to format the time.
#
# @param [String] format The format to use to format the time.
def datetime_format=(format)
if format == :milliseconds
format = MILLISECOND_TIME_FORMAT
elsif format == :microseconds
format = MICROSECOND_TIME_FORMAT
end
@time_formatter = Formatter::DateTimeFormatter.new(format)
end
# Get the format used to format the time.
#
# @return [String]
def datetime_format
@time_formatter.format
end
# Convert an entry into a string using the template.
#
# @param [Lumberjack::LogEntry] entry The entry to convert to a string.
# @return [String] The entry converted to a string.
def call(entry)
return entry unless entry.is_a?(LogEntry)
first_line = entry.message.to_s
additional_lines = nil
if first_line.include?(Lumberjack::LINE_SEPARATOR)
additional_lines = first_line.split(Lumberjack::LINE_SEPARATOR)
first_line = additional_lines.shift
end
formatted_time = @time_formatter.call(entry.time) if @template_include_time
format_args = [formatted_time, entry.severity_label, entry.progname, entry.pid, first_line]
tag_arguments = tag_args(entry.tags, @first_line_tags)
message = (@first_line_template % (format_args + tag_arguments))
message.rstrip! if message.end_with?(" ")
if additional_lines && !additional_lines.empty?
tag_arguments = tag_args(entry.tags, @additional_line_tags) unless @additional_line_tags == @first_line_tags
additional_lines.each do |line|
format_args[format_args.size - 1] = line
line_message = (@additional_line_template % (format_args + tag_arguments)).rstrip
line_message.rstrip! if line_message.end_with?(" ")
message << line_message
end
end
message
end
private
def tag_args(tags, tag_vars)
return [nil] * (tag_vars.size + 1) if tags.nil? || tags.size == 0
tags_string = ""
tags.each do |name, value|
unless value.nil? || tag_vars.include?(name)
value = value.to_s
value = value.gsub(Lumberjack::LINE_SEPARATOR, " ") if value.include?(Lumberjack::LINE_SEPARATOR)
tags_string << "[#{name}:#{value}] "
end
end
args = [tags_string.chop]
tag_vars.each do |name|
args << tags[name]
end
args
end
# Compile the template string into a value that can be used with sprintf.
def compile(template) # :nodoc:
tag_vars = []
template = template.gsub(PLACEHOLDER_PATTERN) do |match|
var_name = match.sub("{", "").sub("}", "")
position = TEMPLATE_ARGUMENT_ORDER.index(var_name)
if position
"%#{position + 1}$s"
else
tag_vars << var_name[1, var_name.length]
"%#{TEMPLATE_ARGUMENT_ORDER.size + tag_vars.size}$s"
end
end
[template, tag_vars]
end
end
end
| true |
1491b6ac2dd125a251717295339798c24a8470d2 | Ruby | taijinlee/sift-ruby | /examples/client.rb | UTF-8 | 1,948 | 2.515625 | 3 | [] | no_license | #!/usr/bin/env ruby
#
# A simple example of how to use the API.
require 'rubygems'
require 'sift'
require 'multi_json'
TIMEOUT = 5
if ARGV.length.zero?
puts "Please specify an Plugin key"
puts "usage:"
puts " ruby client.rb <Plugin KEY>"
puts
exit
end
plugin_key = ARGV[0];
class MyLogger
def warn(e)
puts "[WARN] " + e.to_s
end
def error(e)
puts "[ERROR] " + e.to_s
end
def fatal(e)
puts "[FATAL] " + e.to_s
end
def info(e)
puts "[INFO] " + e.to_s
end
end
def handle_response(response)
if response.nil?
puts 'Error: there was an HTTP error calling through the API'
else
puts 'Successfully sent request; was ok? : ' + response.ok?.to_s
puts 'API error message : ' + response.api_error_message.to_s
puts 'API status code : ' + response.api_status.to_s
puts 'HTTP status code : ' + response.http_status_code.to_s
puts 'original request : ' + response.original_request.to_s
puts 'json : ' + response.json.to_s
end
end
Sift.logger = MyLogger.new
client = Sift::Client.new(plugin_key, "#{Sift::Client::SIGNUP_ENDPOINT + Sift.current_client_signup_api_path}")
properties = {
# These fields are required and need to be
# unique per client
"$shopify_url" => "acme.myshopify.com",
"$shopify_id" => "12345",
"$email" => "bugsy@bunny.com",
# These are optional
"$name" => "Bugs Bunny Club",
"$domain" => "acmeclubs.com",
"$shop_owner" => "Bugs Bunny",
"$address1" => "123 Rabbit Rd",
"$city" => "Carrotsville",
"$province" => "New Mexico",
"$province_code" => "NM",
"$country" => "United States",
"$zip" => "87002",
"$plan_name" => "enterprise",
"$timezone" => "PDT"
}
handle_response client.signup(plugin_key, properties, TIMEOUT) | true |
6a046deb434b9c7b363f270b6a4c0aa3a3a05ca5 | Ruby | RobinBailey84/gym_project | /models/member.rb | UTF-8 | 1,325 | 2.90625 | 3 | [] | no_license | require_relative('../db/sql_runner')
class Member
attr_accessor(:id, :name, :gold_membership)
def initialize(options)
@id = options['id'].to_i if options['id']
@name = options['name']
@gold_membership = options['gold_membership']
end
def save()
sql = "INSERT INTO members (name, gold_membership) VALUES ($1, $2) returning id"
values = [@name, @gold_membership]
results = SqlRunner.run(sql, values)
@id = results.first()['id'].to_i
end
def self.all()
sql = "SELECT * FROM members"
results = SqlRunner.run(sql)
return results.map{|member| Member.new(member)}
end
def update()
sql = "UPDATE members SET (name, gold_membership) = ($1, $2) WHERE id = $3"
values = [@name, @gold_membership, @id]
SqlRunner.run(sql, values)
end
def self.delete_all()
sql = "DELETE FROM members"
SqlRunner.run(sql)
end
def delete()
sql = "DELETE FROM members WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def self.find(id)
sql = "SELECT * FROM members WHERE id = $1"
values = [id]
member = SqlRunner.run(sql, values)
result = Member.new(member.first)
return result
end
def check_membership()
if @peak_time == true && @gold_membership == false
return true
end
return false
end
end
| true |
c7eb948b01fec05b11b5dbdadf94e556313fb387 | Ruby | djfletcher/AAScavengerHunt | /part1.rb | UTF-8 | 789 | 2.796875 | 3 | [] | no_license | require 'httparty'
require 'nokogiri'
page = HTTParty.get('https://scottduane.github.io/TopSecretClue/')
doc = Nokogiri::HTML(page)
links = doc.css('a')
valid_links = []
links.each do |a|
address = a['href']
response = HTTParty.get(address)
if response.code == 200
valid_links << address
end
end
def parse_page(page)
doc = Nokogiri::HTML(page)
links = doc.css('a')
end
def follow_link(url, valid_links)
response = HTTParty.get(url)
if response.code == 200
valid_links << url
follow_link()
end
end
# doc.css('a')[2000..-1].map.with_index do |a, index|
# address = a['href']
# if index % 1000 == 0
# puts index
# end
# response = HTTParty.get(address)
# if response.code == 200
# valid_links << address
# end
# end
p valid_links
| true |
b65c98c4a149b80379a92c787d14a17687eefc28 | Ruby | pjsmueller/Ruckus | /db/seeds.rb | UTF-8 | 1,160 | 2.53125 | 3 | [
"MIT"
] | permissive | require 'faker'
50.times do
User.create(username: Faker::Internet.user_name, f_name: Faker::Name.first_name, l_name: Faker::Name.last_name, password: "pass")
end
movies = Movie.now_playing
movies.each do |movie|
Movie.create(api_id: movie.id )
end
100.times do
Review.create(title: Faker::Hipster.word, body: Faker::Hacker.say_something_smart, user_id: User.all.sample.id, movie_id: Movie.all.sample.id)
end
150.times do
Comment.create(body: Faker::Hacker.say_something_smart, user_id: User.all.sample.id, review_id: Review.all.sample.id)
end
types = ["Review", "Comment", "Movie"]
300.times do
ids = [Review.all.sample.id, Movie.all.sample.id, Comment.all.sample.id]
picked_type = types.sample
if picked_type == "Review"
Rating.create(user_id: User.all.sample.id, rateable_type: picked_type, rateable_id: ids[0], score: rand(1..5))
elsif picked_type == "Comment"
Rating.create(user_id: User.all.sample.id, rateable_type: picked_type, rateable_id: ids[1], score: rand(1..5))
elsif picked_type == "Movie"
Rating.create(user_id: User.all.sample.id, rateable_type: picked_type, rateable_id: ids[2], score: rand(1..5))
end
end
| true |
50a9cf4f145c94b1699903de8cfbd8c0d21e34c8 | Ruby | imac18078/collections_practice_vol_2-001-prework-web | /collections_practice.rb | UTF-8 | 1,347 | 3.390625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # your code goes here
def begins_with_r(array)
array.all? do |x|
x.start_with?("r")
end
end
def contain_a(array)
array.select do |x|
x.match("a")
end
end
def first_wa(array)
array.find do |x|
x[0].match("w") && x[1].match("a")
end
end
def remove_non_strings(array)
array.select do |x|
x.class == String
end
end
def count_elements(array)
new_array = []
hash = {}
hash.default = 0
array.each do |x|
hash[x] += 1
end
new_hash = {}
hash.each do |x, y|
new_hash = x
new_hash[:count] = y
new_array << new_hash
end
new_array
end
def merge_data(keys, data)
hash = {}
hash.default = 0
new_array = []
data.each do |x|
x.each do |y,z|
hash = z
new_array << hash
end
end
idx = 0
answer = []
keys.each do |x|
answer[idx] = x.merge(new_array[idx])
idx += 1
end
answer
end
def find_cool(cool)
array = []
cool.each do |x|
x.each do |y, z|
if z == "cool"
array << x
else
nil
end
end
end
array
end
def organize_schools(schools)
location = {}
location.default = 0
hash = {}
hash.default = 0
schools.each do |x, y|
y.each do |a, b|
hash = {}
hash[b] = [x]
location = location.merge(hash) do |k, o, n|
(o << n).flatten
end
end
end
location
end | true |
19d583dca59eed45513cb1b92fe0a12a0e3bc272 | Ruby | keblodev/sassificator | /lib/sassificator.rb | UTF-8 | 9,239 | 2.6875 | 3 | [
"MIT"
] | permissive | # Created by: Roman Fromrome
# https://github.com/rimaone
#TODO:
# - mediaquery inside of a mediaquery - done partically (only for one tree level deep)
# - images formating pattern setting
# - add convertor: all #_colors_ to rgb
# - MAJOR: formatting is done only for output sass_string, but not for sass_obj. Move formatting options applyment to object creation
# - write tests
# - had issue with [] brackets - test
# - had issue with asset-url asigning - test - background: asset-url('#{$brand}offersButton_on.png',image',image) 100% 50% no-repeat;
# background: asset-url('#{$brand}//offersButton_on.png) 100% 50% no-repeat;
# - issue with assigning same roles one after onother
class Sassificator
attr_accessor :colors_to_vars
##
#
# @param [Boolean] alphabethize_output true : Alphatehise the rules in output string
# @param [Boolean] colors_to_vars true : sets all color to sass variables to the top of output string
# @param [Boolean] fromat_image_declarations true : formats images declarations to asset-url (for now at least - TODO: will be unified for any format)
# @param [Boolean] download_images true : downloads images to specified @output_path
# @param [String] image_assets_path Image asstes path in application
# @param [String] output_path Output path must be specified if download_images is set to true
#
def initialize( param = {})
@alphabethize_output = (param[:alphabethize_output] != false) != false
@colors_to_vars = (param[:colors_to_vars] != false) != false
@fromat_image_declarations = (param[:fromat_image_declarations] != false) != false
@download_images = (param[:download_images] != false) != false
@image_assets_path = param[:image_assets_path] ? param[:image_assets_path] : ''
@output_path = param[:output_path] ? param[:output_path] : "#{ENV['HOME']}/Desktop/sassificator_output/"
end
##
#
# Returns a hash containing sass_object and sass_formated string
# REQUIRES A PROPERLY FROMATED INPUT CSS
#
# @param [String] css A PROPERLY FROMATED INPUT CSS STRING | for now it's NOT working with media_query's inside of media_querys
#
def get_sass_str_and_sass_obj(input_css_str)
selectors_hash = css_to_hash input_css_str # 1. convert plain css to hash obj
css_stack = objectize_css(selectors_hash) # 2. convert recieved hash to sass obj with relatons
sassed_css_string = sass_obj_to_str(css_stack) # 3. get formatted string out sass_obj
Hash[:sass_obj => css_stack, :sass_string => sassed_css_string]
end
private
class CssNode
attr_accessor :rule, :children, :parent, :uninitialized
def initialize( param = {})
@rule = param[:rule] ? param[:rule] : ''
@children = param[:children] ? param[:children] : {}
@parent = param[:parent] ? param[:parent] : nil
@parent = nil unless param[:parent]
@uninitialized = param[:uninitialized] ? param[:uninitialized] : {}
end
end
def remove_white_spaces_and_new_lines(line)
line.gsub(/\n/,'').gsub(/\t/,'').gsub(/\s+(?=\})/,'').gsub(/(?<=\{)\s+/,'')
end
def prepare_input_css(input_css)
## 1. reduses double :: pseudo selectors to :
## 2. removes empty rules
input_css.gsub(/::/,':').gsub(/^.+{[\s\t\n]{0,}}/,'')
end
def css_to_hash (input_css)
input_css = prepare_input_css(input_css)
selectors_arr = remove_white_spaces_and_new_lines(input_css).gsub(/@media/,"\n@media").gsub(/(?<={{1}).+}(?=[\s\t\n]{0,}}{1})/,'').gsub(/(?<={{1}).+}(?=[\s\t\n]{0,}}{1})/,'').scan(/[^{^}]+(?=\{)/).map {|line| line.sub(/^\s+/,'').sub(/\s+$/,'')}
rules_arr = remove_white_spaces_and_new_lines(input_css).gsub(/@media/,"\n@media").scan(/(((?<={{1}).+}(?=[\s\t\n]{0,}}{1})|(?<=\{)[^}]+\}{0,}[\\t\\n\s]{0,}(?=\}))|((?<=\{)[^}]+\}{0,}[\\t\\n\s]{0,}(?=\}))|(?<={{1}).+}(?=[\s\t\n]{0,}}{1}))/).map {|item| item.compact.uniq.join} #super-mega reg-exp that scans for normal rules as well as inlined media-query rule + make a single_string_items out of matched array groups
return_hash = {}
selectors_arr.each_with_index do |selector, index|
unless return_hash[selector]
return_hash[selector] = rules_arr[index.to_i]
else
return_hash[selector] = return_hash[selector] + ' ' + rules_arr[index.to_i]
end
end
return_hash.each do |key,val|
unless val.scan(/[^{^}]+(?=\{)/).size.zero?
return_hash[key] = css_to_hash val
end
end
return_hash
end
def objectize_css (uninitialized_childrens_hash, parent_node = nil)
childrens_stack = {}
uninitialized_childrens_hash.each { |selector,rule|
#TODO: optimize pattern mathcing = thei are both matching same string
match = /^[&.#\"\'\[\]=a-zA-Z-_0-9]{1,}(?=\s(?=[^,]{0,}$))/.match(selector).to_s #checks for childrens in selector
sub_pat = /^[\.#]{0,1}[a-zA-Z-_0-9]{1,}(?=(\.|:|\[|#))/.match(selector).to_s #deals with pseudo elements
#TODO : optimize this
unless sub_pat.empty?
unless selector.match(/,/)
match = sub_pat
selector = selector.sub( Regexp.new('^'+match) ,match+' &')
end
end
unless match.empty?
unless node = childrens_stack[match]
node = CssNode.new
childrens_stack[match] = node
end
node.uninitialized[selector.sub( Regexp.new('^'+match.sub( /\[/ ,'\[').sub(/\]/, '\]')+' ') ,'')] = rule
node.parent = parent_node
else
if node = childrens_stack[selector]
node.rule = node.rule + "\n\t" + rule.gsub(/;\s/,";\n\t")
else
node = CssNode.new
if rule.is_a?(Hash)
node.children = objectize_css( rule, node )
else
node.rule = "\n\t"+rule.gsub(/;\s/,";\n\t")
end
childrens_stack[selector] = node
end
node.rule = node.rule.split(';').sort().join(';') + ';' if @alphabethize_output && !node.rule.empty? #alphabetize
node.parent = parent_node
end
}
childrens_stack.each { |node_selector,node|
unless childrens_stack[node_selector].uninitialized.empty?
childrens_stack[node_selector].children = objectize_css( childrens_stack[node_selector].uninitialized, node )
childrens_stack[node_selector].uninitialized = []
end
}
childrens_stack
end
def sass_obj_to_str (css_stack)
sassed_str = format_sass sass_stack_to_s(css_stack)
sassed_str
end
def sass_stack_to_s (css_stack)
str = ''
css_stack.each { |node_key,node|
unless node.children.empty?
chldrn = node.children
children_stack = sass_stack_to_s(chldrn)
end
str = str +"\n"+ node_key + " {\t" + ( node.rule ? node.rule : '') + ( children_stack ? children_stack.gsub(/^/,"\t") : '' ) +"\n\t}"
}
str
end
def format_sass (sassed_str)
formated_sass_with_images = @fromat_image_declarations ? format_images(sassed_str) : sassed_str
formated_sass_with_color = @colors_to_vars ? format_color(formated_sass_with_images) : sassed_str
formated_sass_with_color
end
def format_images (sassed_str)
require 'net/http'
formated_rule = sassed_str
#TODO - move this to optional feature (file downloading)
#TODO: optimise this - connect to global path
path = @output_path
Dir.mkdir(path) unless Dir.exist?(path)
FileUtils.rm_rf(Dir.glob("#{@output_path}/*"))
sassed_str.scan(/(url\((((http[s]{0,1}:\/\/)([a-z0-9].+\.[a-z]+).+)(\/.+)))\)/).each do |match|
#TODO: optimize this - move mathched to variables for clarification of match
formated_rule = formated_rule.sub(Regexp.new(match[0].gsub(/\(/,'\(').gsub(match[5],'')),'asset-url(\''+@image_assets_path)
.sub( Regexp.new(match[5]),match[5].sub(/\//,'')+'\'')
#TODO - move this to optional feature (file downloading)
Net::HTTP.start(match[4]) do |http|
#TODO - test get_url
# forms relative url
get_url = match[1].sub(Regexp.new("(http:\/\/||https:\/\/){1}#{match[4]}"),'')
begin
http.read_timeout = 20
resp = http.get(get_url)
open(path+match[5], 'wb') do |file|
begin
file.write(resp.body)
ensure
file.close()
end
end
rescue
p "Fail on getting image #{match[1]}"
end
end
end
formated_rule
end
def format_color(sassed_str)
#TODO: resolve the match for colors in format #sdsd
formated_rule = sassed_str
color_hash = {}
sassed_str.scan(/rgba\([0-9\,\s\.]+\)|rgb\([0-9\,\s\.]+\)|#[0-9A-Za-z]+(?=;)/).each do|m|
unless color_hash[m]
color_hash[m] = '$color_'+color_hash.size.to_s
formated_rule = formated_rule.gsub( Regexp.new(m.gsub(/\(/,'\(').gsub(/\)/,'\)').gsub(/\./,'\.')), color_hash[m] )
end
end
color_hash.invert.to_a.reverse_each {|m|
formated_rule = m.join(":")+";\n" + formated_rule
}
formated_rule
end
def format_mixin
#TODO: combine similar rules blocks in mixins.. in some way..?
end
end | true |
001dde2a81e15576f02ef14377e7655ba022558f | Ruby | Russian-AI-Cup-2015/ruby-cgdk | /my_strategy.rb | UTF-8 | 425 | 2.78125 | 3 | [] | no_license | require './model/car'
require './model/game'
require './model/move'
require './model/world'
class MyStrategy
# @param [Car] me
# @param [World] world
# @param [Game] game
# @param [Move] move
def move(me, world, game, move)
move.engine_power = 1.0
move.throw_projectile = true
move.spill_oil = true
if world.tick > game.initial_freeze_duration_ticks
move.use_nitro = true
end
end
end | true |
42b907bbaf8f1b2e9ba5f759828386e9752a49fd | Ruby | David-Kirsch/ruby-oo-practice-relationships-domains-nyc01-seng-ft-071320 | /app/models/shows.rb | UTF-8 | 551 | 3.375 | 3 | [] | no_license | class Show
@@all = []
attr_reader :name
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def show_characters
ShowCharacter.all.select {|show_char| show_char.show == self}
end
def characters
self.show_characters.map {|character| character}
end
def shows
show_characters.map {|char| char.show}.uniq
end
def on_the_big_screen
Movie.all.select do |movie|
movie.name == self.name
end
end
end | true |
209e7492c833fb0e1a5fb643359f24696b645d53 | Ruby | jtruong2/battleship | /lib/battleship.rb | UTF-8 | 3,644 | 2.9375 | 3 | [] | no_license | require 'pry'
require_relative 'player'
require_relative 'computer'
require_relative 'grid'
class Battleship
attr_reader :player,
:computer,
:grid
def initialize
@player = Player.new
@computer = Computer.new
@grid = Grid.new
@player_ship1_count = 0
@player_ship2_count = 0
@computer_ship1_count = 0
@computer_ship2_count = 0
@start = nil
end
def intro
display_intro
response = gets.chomp.downcase
case response
when 'p' then ship_layout
when 'i' then puts instructions
when 'q' then puts 'Goodbye!' + "\u{1F590}" ; exit 1
else puts "Invalid response! \n\n\n Go (b)ack" ; go_back
end
end
def ship_layout
place_computer_ships
place_player_ships
fire_shot
end
def fire_shot
@start = Time.now
until (@player_ship1_count == 2 && @player_ship2_count == 3) || (@computer_ship1_count == 2 && @computer_ship2_count == 3) do
player.fire_missile
player_fires_at_computer
computer.fire_missile
computer_fires_at_player
end
gameover
end
def display_intro
puts 'Welcome to BATTLESHIP' + "\u{1F6F3}"
puts 'Would you like to (p)lay, read the (i)nstructions, or (q)uit'
end
def go_back
go_back = gets.chomp.upcase
if go_back == 'B'
intro
end
end
def instructions
puts File.read("/Users/jimmytruong/turing/1module/projects/battleship/instructions/instructions.md")
go_back
end
def place_computer_ships
computer.generate_ship1
computer.generate_ship2
end
def place_player_ships
player.find_ship1_coordinate1
player.find_ship1_coordinate2
player.find_ship2_coordinate1
player.find_ship2_coordinate2
end
def player_fires_at_computer
hit = "\u{1F4A5}"; miss = "\u{274C}"
if computer.ship1.include?(player.current_shot)
puts "You hit their Destroyer" + "\u{1F4A5}"
grid.player_grid(player.current_shot, hit)
@computer_ship1_count += 1
puts "You sank their Destroyer" + "\u{1F604}" if @computer_ship1_count == 2
elsif computer.ship2.include?(player.current_shot)
puts "You hit their Cruiser!" + "\u{1F4A5}"
grid.player_grid(player.current_shot, hit)
@computer_ship2_count += 1
puts "You sank their Cruiser" + "\u{1F604}" if @computer_ship2_count == 3
else
puts "Miss, computer ships"
grid.player_grid(player.current_shot, miss)
end
end
def computer_fires_at_player
hit = "\u{1F4A5}"; miss = "\u{274C}"
if player.ship1.include?(computer.current_shot)
puts "They hit your Destroyer" + "\u{1F4A5}"
grid.computer_grid(computer.current_shot, hit)
@player_ship1_count += 1
puts "They sank your Destroyer" + "\u{1F62B}" if @player_ship1_count == 2
elsif player.ship2.include?(computer.current_shot)
puts "They hit your Cruiser" + "\u{1F4A5}"
grid.computer_grid(computer.fire_missile, hit)
@player_ship2_count += 1
puts "They sank your Cruiser" + "\u{1F62B}" if @player_ship2_count == 3
else
puts "Miss, player ships"
grid.computer_grid(computer.current_shot, miss)
end
end
def gameover
if @computer_ship1_count == 2 && @computer_ship2_count == 3
puts "\u{1F3C6}" + " Congratulations, You are VICTORIOUS! " + "\u{1F3C6}"
else
puts "So Sad!! You lost!" + "\u{1F62B}"
end
finish = Time.now
diff = finish - @start
puts "\u{23F1}" + " Total time of gameplay: #{diff}"
puts "\u{1F52B}" + " Number of shots fired: #{player.fire.length}"
exit 1
end
end
battleship = Battleship.new
battleship.intro.pry
| true |
3343e9b8cab4bc27730c4b43e169ababe77fceda | Ruby | cjlofts/testrepo1 | /lol.rb | UTF-8 | 238 | 4.0625 | 4 | [] | no_license | # write some code that asks for 2 inputs
# then returns the product
puts "Enter the first number:"
num_1 = gets.chomp.to_f
puts "Enter the second number:"
num_2 = gets.chomp.to_f
puts "the two numbers multiplied are #{num_1 * num_2}" | true |
eae282fcfc6be75d6201198377210a94f15ca391 | Ruby | nramadas/ChessOld | /lib/pieces.rb | UTF-8 | 2,626 | 3.75 | 4 | [] | no_license | class Piece
DIAGONAL = [[-1, -1], [-1, 1], [1, -1], [1, 1]]
STRAIGHT = [[-1, 0], [1, 0], [0, -1], [0, 1]]
KNIGHT = [[-1, -2], [-2, -1], [-2, 1], [-1, 2],
[1, 2], [2, 1], [2, -1], [1, -2]]
attr_reader :token
attr_accessor :coordinates, :player_type
def initialize(coordinates, player_type)
@coordinates, @player_type = coordinates, player_type
@token = ""
end
private
def move(move_type, start_coord, times = 10)
possible_moves = []
row, col = start_coord
move_type.each do |pair|
move = { :coord => start_coord, :prev_move => nil }
x, y = row, col
do_counter = 0
until (x + pair[0] < 0 || x + pair[0] > 7 ||
y + pair[1] < 0 || y + pair[1] > 7)
do_counter += 1
temp = move
move = { :coord => [x + pair[0], y + pair[1]],
:prev_move => temp }
possible_moves << move
x, y = x + pair[0], y + pair[1]
break if do_counter == times
end
end
possible_moves
end
end
class Pawn < Piece
def initialize(coordinates, player_type)
super
@token = "\u2659"
@coordinates_at_start = coordinates
end
def get_moves
if @coordinates == @coordinates_at_start
possible_moves = move(STRAIGHT, @coordinates, 2) +
move(DIAGONAL, @coordinates, 1)
else
possible_moves = move(STRAIGHT, @coordinates, 1) +
move(DIAGONAL, @coordinates, 1)
end
if @player_type == :player1
possible_moves.delete_if { |move| move[:coord][0] <= @coordinates[0] }
else
possible_moves.delete_if { |move| move[:coord][0] >= @coordinates[0] }
end
possible_moves
end
end
class Rook < Piece
def initialize(coordinates, player_type)
super
@token = "\u2656"
end
def get_moves
move(STRAIGHT, @coordinates)
end
end
class Bishop < Piece
def initialize(coordinates, player_type)
super
@token = "\u2657"
end
def get_moves
move(DIAGONAL, @coordinates)
end
end
class Knight < Piece
def initialize(coordinates, player_type)
super
@token = "\u2658"
end
def get_moves
move(KNIGHT, @coordinates, 1)
end
end
class King < Piece
def initialize(coordinates, player_type)
super
@token = "\u2654"
end
def get_moves
move(STRAIGHT, @coordinates, 1) + move(DIAGONAL, @coordinates, 1)
end
end
class Queen < Piece
def initialize(coordinates, player_type)
super
@token = "\u2655"
end
def get_moves
move(STRAIGHT, @coordinates) + move(DIAGONAL, @coordinates)
end
end | true |
70c2fd9550c48e9db7b1575a96d3c7ed1bc5797b | Ruby | artzte/itcostus | /app/models/category_matcher.rb | UTF-8 | 349 | 2.671875 | 3 | [
"MIT"
] | permissive | class CategoryMatcher < ActiveRecord::Base
def regexp
@regexp ||= Regexp.new self.value, Regexp::IGNORECASE
@regexp
end
def keywords
@keywords ||= self.value.split.uniq
@keywords
end
def self.dump
dumped = all
puts "["
dumped.each{|cm| puts " [\"#{cm.category}\",\"#{cm.regex}\"], "}
puts "]"
end
end | true |
13a30d28d41c099b7a6c1515162a6bb88e638b05 | Ruby | fujin/foodcritic | /lib/foodcritic/helpers.rb | UTF-8 | 6,815 | 2.796875 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'xmlsimple'
module FoodCritic
# Helper methods that form part of the Rules DSL.
module Helpers
# Create a match from the specified node.
#
# @param [Nokogiri::XML::Node] node The node to create a match for
# @return [Hash] Hash with the matched node name and position with the recipe
def match(node)
pos = node.xpath('descendant::pos').first
{:matched => node.respond_to?(:name) ? node.name : '', :line => pos['line'], :column => pos['column']}
end
# Does the specified recipe check for Chef Solo?
#
# @param [Nokogiri::XML::Node] ast The AST of the cookbook recipe to check.
# @return [Boolean] True if there is a test for Chef::Config[:solo] in the recipe
def checks_for_chef_solo?(ast)
! ast.xpath(%q{//if/aref[count(descendant::const[@value = 'Chef' or @value = 'Config']) = 2 and
count(descendant::ident[@value='solo']) > 0]}).empty?
end
# Searches performed by the specified recipe.
#
# @param [Nokogiri::XML::Node] ast The AST of the cookbook recipe to check.
# @return [Boolean] True if the recipe performs a search
def searches(ast)
ast.xpath("//fcall/ident[@value = 'search']")
end
# Find Chef resources of the specified type.
# TODO: Include blockless resources
#
# @param [Nokogiri::XML::Node] ast The AST of the cookbook recipe to check
# @param [String] type The type of resource to look for (or nil for all resources)
def find_resources(ast, type = nil)
ast.xpath(%Q{//method_add_block[command/ident#{type.nil? ? '' : "[@value='#{type}']"}]})
end
# Return the type, e.g. 'package' for a given resource
#
# @param [Nokogiri::XML::Node] resource The resource AST
# @return [String] The type of resource
def resource_type(resource)
resource.xpath('string(command/ident/@value)')
end
# Retrieve the name attribute associated with the specified resource.
#
# @param [Nokogiri::XML::Node] resource The resource AST to lookup the name attribute under
def resource_name(resource)
resource.xpath('string(command//tstring_content/@value)')
end
# Retrieve a single-valued attribute from the specified resource.
#
# @param [String] name The attribute name
# @param [Nokogiri::XML::Node] resource The resource AST to lookup the attribute under
# @return [String] The attribute value for the specified attribute
def resource_attribute(name, resource)
resource_attributes(resource)[name]
end
# Retrieve all attributes from the specified resource.
#
# @param [Nokogiri::XML::Node] resource The resource AST
# @return [Hash] The resource attributes
def resource_attributes(resource)
atts = {:name => resource_name(resource)}
resource.xpath('do_block/descendant::command').each do |att|
if att.xpath('descendant::symbol').empty?
att_value = att.xpath('string(descendant::tstring_content/@value)')
else
att_value = att.xpath('string(descendant::symbol/ident/@value)').to_sym
end
atts[att.xpath('string(ident/@value)')] = att_value
end
atts
end
# Retrieve all resources of a given type
#
# @param [Nokogiri::XML::Node] ast The recipe AST
# @return [Hash] The matching resources
def resources_by_type(ast)
result = Hash.new{|hash, key| hash[key] = Array.new}
find_resources(ast).each{|resource| result[resource_type(resource)] << resource}
result
end
# Retrieve the attributes as a hash for all resources of a given type.
#
# @param [Nokogiri::XML::Node] ast The recipe AST
# @return [Hash] An array of resource attributes keyed by type.
def resource_attributes_by_type(ast)
result = {}
resources_by_type(ast).each do |type,resources|
result[type] = resources.map{|resource| resource_attributes(resource)}
end
result
end
# Retrieve the recipes that are included within the given recipe AST.
#
# @param [Nokogiri::XML::Node] ast The recipe AST
# @return [Hash] include_recipe nodes keyed by included recipe name
def included_recipes(ast)
# we only support literal strings, ignoring sub-expressions
included = ast.xpath(%q{//command[ident/@value = 'include_recipe' and count(descendant::string_embexpr) = 0]/
descendant::tstring_content})
Hash[included.map{|recipe|recipe['value']}.zip(included)]
end
# The name of the cookbook containing the specified file.
#
# @param [String] file The file in the cookbook
# @return [String] The name of the containing cookbook
def cookbook_name(file)
File.basename(File.absolute_path(File.join(File.dirname(file), '..')))
end
# The dependencies declared in cookbook metadata.
#
# @param [Nokogiri::XML::Node] ast The metadata rb AST
# @return [Array] List of cookbooks depended on
def declared_dependencies(ast)
deps = ast.xpath("//command[ident/@value='depends']/descendant::args_add/descendant::tstring_content")
# handle quoted word arrays
var_ref = ast.xpath("//command[ident/@value='depends']/descendant::var_ref/ident")
deps += ast.xpath(%Q{//block_var/params/ident#{var_ref.first['value']}/ancestor::method_add_block/
call/descendant::tstring_content}) unless var_ref.empty?
deps.map{|dep| dep['value']}
end
# If the provided node is the line / column information.
#
# @param [Nokogiri::XML::Node] node A node within the AST
# @return [Boolean] True if this node holds the position data
def position_node?(node)
node.respond_to?(:length) and node.length == 2 and node.respond_to?(:all?) and node.all?{|child| child.respond_to?(:to_i)}
end
# Recurse the nested arrays provided by Ripper to create an intermediate Hash for ease of searching.
#
# @param [Nokogiri::XML::Node] node The AST
# @return [Hash] The friendlier Hash.
def ast_to_hash(node)
result = {}
if node.respond_to?(:each)
node.drop(1).each do |child|
if position_node?(child)
result[:pos] = {:line => child.first, :column => child[1]}
else
if child.respond_to?(:first)
result[child.first.to_s.gsub(/[^a-z_]/, '')] = ast_to_hash(child)
else
result[:value] = child unless child.nil?
end
end
end
end
result
end
# Read the AST for the given Ruby file
#
# @param [String] file The file to read
# @return [Nokogiri::XML::Node] The recipe AST
def read_file(file)
Nokogiri::XML(XmlSimple.xml_out(ast_to_hash(Ripper::SexpBuilder.new(IO.read(file)).parse)))
end
end
end
| true |
c3c819989577c062bc204b64840064343cdabca3 | Ruby | pacuum/vtc_payment | /lib/vtc_payment/mobile_card/crypt.rb | UTF-8 | 1,067 | 2.734375 | 3 | [
"MIT"
] | permissive | require "openssl"
require "digest"
require "base64"
module VtcPayment
module MobileCard
class Crypt
class << self
def encrypt( input, seed )
input = input.to_s.strip;
# it seems openssl automatically pad the string in the same way as php sample code
# encrypt
cipher = OpenSSL::Cipher.new 'des-ede3' # tripledes-ebc
cipher.encrypt
cipher.key = md5_key(seed)
encrypted = cipher.update(input) + cipher.final
return Base64.encode64(encrypted).gsub("\n", "");
end
# generate a 24 byte key from the md5 of the seed
def md5_key(seed)
Digest::MD5.hexdigest(seed).to_s[0,24]
end
def decrypt( encoded, seed )
encrypted = Base64.decode64(encoded)
key = md5_key(seed)
cipher = OpenSSL::Cipher.new 'des-ede3' # tripledes-ebc
cipher.decrypt
cipher.key = key
plain = cipher.update(encrypted) + cipher.final
plain
end
end
end
end
end
| true |
32da5df5c75213e7ebf7c904d8d86d64d16f75a3 | Ruby | gushul/parse_result_list | /parser_json.rb | UTF-8 | 7,015 | 2.78125 | 3 | [] | no_license | class ImportRaytingWorker
require 'rubyXL'
require 'json'
def self.perform
debug_file = open("output.txt", 'w')
result_file = open("result.json", 'w')
debug_file.write("Begin\n")
workbook = RubyXL::Parser.parse("rating_2016.xlsm")
worksheet = workbook.worksheets[0]
total = 0
worksheet.each { |row| total +=1}
debug_file.write("total is #{total}\n" )
index = 1
cell = worksheet.sheet_data[index][0]
result = []
debug_file.write("Before while\n")
while index < total
#sheet_data = worksheet.sheet_data[index]
cell = worksheet.sheet_data[index][0] if worksheet.sheet_data[index]
current = cell && cell.value
if current == "Институт / факультет"
cell = worksheet.sheet_data[index][5] if worksheet.sheet_data[index]
current_inst = cell && cell.value
debug_file.write("Institute: #{current_inst}\n")
result_inst = Hash.new
result_inst[:institute_title] = current_inst
result_inst[:specialities] = []
result.push(result_inst)
index +=1
next
elsif current == "Направление подготовки / специальность"
cell = worksheet.sheet_data[index][5] if worksheet.sheet_data[index]
spec_title = cell && cell.value
debug_file.write("speciality: #{spec_title}\n")
spec = Hash.new
spec[:title] = spec_title
index +=2
cell = worksheet.sheet_data[index][1] if worksheet.sheet_data[index]
description = cell && cell.value
debug_file.write("set: #{description}\n")
spec[:description] = description
index +=1
cell = worksheet.sheet_data[index][2] if worksheet.sheet_data[index]
plan = cell && cell.value
debug_file.write("plan: #{plan}\n")
spec[:plan] = plan
index +=1
cell = worksheet.sheet_data[index][2] if worksheet.sheet_data[index]
submitted = cell && cell.value
debug_file.write("submitted: #{submitted}\n")
spec[:submitted] = submitted
index +=1
cell = worksheet.sheet_data[index][2] if worksheet.sheet_data[index]
contest = cell && cell.value
debug_file.write("contest: #{contest}\n")
spec[:contest] = contest
index +=4
cell = worksheet.sheet_data[index][7] if worksheet.sheet_data[index]
exam_1 = cell && cell.value
exam_1 = "" if exam_1 == nil
spec[:exam_1] = exam_1
cell = worksheet.sheet_data[index][8] if worksheet.sheet_data[index]
exam_2 = cell && cell.value
exam_2 = "" if exam_2 == nil
spec[:exam_2] = exam_2
cell = worksheet.sheet_data[index][9] if worksheet.sheet_data[index]
exam_3 = cell && cell.value
exam_3 = "" if exam_3 == nil
spec[:exam_3] = exam_3
cell = worksheet.sheet_data[index][10] if worksheet.sheet_data[index]
exam_4 = cell && cell.value
exam_4 = "" if exam_4 == nil
spec[:exam_4] = exam_4
index +=1
cell = worksheet.sheet_data[index][1] if worksheet.sheet_data[index]
rating = cell && cell.value
if rating == "Рейтинг"
index +=1
spec[:ratings] = []
spec[:names] = []
index = get_set_ratings(index, worksheet, debug_file, spec)
result_inst[:specialities].push(spec)
result.pop
result.push(result_inst)
end
end
index += 1
end
debug_file.close
result_file.write(result.to_json )
result_file.close
end
def self.get_set_ratings(index, worksheet, debug_file, spec)
i = 0
rate_titles = ["Без вступительных испытаний", "Общий конкурс"]
debug_file.write("Рейтинг:\n")
while i < 2
cell = worksheet.sheet_data[index][2]
title = cell && cell.value
if worksheet.sheet_data[index+1]
cell = worksheet.sheet_data[index+1][2]
next_cell = cell && cell.value
if(rate_titles.include?(title) && next_cell.is_a?(Integer))
debug_file.write("#{title}:\n")
rating = Hash.new
rating[:title] = title
rating[:list] = []
index +=1
index = get_rating_data(index, worksheet, debug_file, rating, spec)
spec[:ratings].push(rating)
else
index +=1
end
end
i +=1
end
index
end
def self.get_rating_data(index, worksheet, debug_file, rating, spec)
until_cell = worksheet.sheet_data[index][3]
while until_cell
submit = Hash.new
cell = worksheet.sheet_data[index][2]
position = cell && cell.value
submit[:position] = position
cell = worksheet.sheet_data[index][3]
id = cell && cell.value
submit[:id] = id
cell = worksheet.sheet_data[index][4]
name = cell && cell.value
submit[:name] = name
last_name = name.split.first
spec[:names].push(last_name)
cell = worksheet.sheet_data[index][5]
total = cell && cell.value
submit[:total] = total
cell = worksheet.sheet_data[index][5]
achiev = cell && cell.value
submit[:achiev] = achiev
cell = worksheet.sheet_data[index][7] if worksheet.sheet_data[index]
exam_1 = cell && cell.value
exam_1 = "" if exam_1 == nil
submit[:exam_1] = exam_1
cell = worksheet.sheet_data[index][8] if worksheet.sheet_data[index]
exam_2 = cell && cell.value
exam_2 = "" if exam_2 == nil
submit[:exam_2] = exam_2
cell = worksheet.sheet_data[index][9] if worksheet.sheet_data[index]
exam_3 = cell && cell.value
exam_3 = "" if exam_3 == nil
submit[:exam_3] = exam_3
cell = worksheet.sheet_data[index][10] if worksheet.sheet_data[index]
exam_4 = cell && cell.value
exam_4 = "" if exam_4 == nil
submit[:exam_4] = exam_4
cell = worksheet.sheet_data[index][11] if worksheet.sheet_data[index]
doc_original = cell && cell.value
submit[:doc_original] = doc_original
cell = worksheet.sheet_data[index][12] if worksheet.sheet_data[index]
doc_original = cell && cell.value
submit[:agreement] = doc_original
cell = worksheet.sheet_data[index][13] if worksheet.sheet_data[index]
doc_original = cell && cell.value
submit[:decision] = doc_original
cell = worksheet.sheet_data[index][14] if worksheet.sheet_data[index]
privilege = cell && cell.value
submit[:privilege] = privilege
cell = worksheet.sheet_data[index][15] if worksheet.sheet_data[index]
benefit = cell && cell.value
submit[:benefit] = benefit
debug_file.write("student: #{position}, #{id}, #{name}, #{total} \n")
rating[:list].push(submit)
until_cell = nil
index +=1
until_cell = worksheet.sheet_data[index][3] if worksheet.sheet_data[index]
end
index
end
end
ImportRaytingWorker.perform
| true |
e10cebbeeb5da74d2d30a6057675152833616ef9 | Ruby | sirisak-amivoice/aohs_old | /app/models/dsrresult_log.rb | UTF-8 | 730 | 2.53125 | 3 | [] | no_license | class DsrresultLog < ActiveRecord::Base
belongs_to :voice_log
def rec_text
extract_result
return @ret_txt
end
def rec_stime
extract_result
return @ret_stime.to_f.round(4)
end
def rec_etime
extract_result
return @ret_etime.to_f.round(4)
end
private
def extract_result
if defined? @result
return true
end
@ret_txt = ""
@ret_stime = nil
@ret_etime = nil
raw_result = self.result.to_s
raw_result.split("|").each do |rr|
ele = rr.split(":")
@ret_txt << ele.first
@ret_stime = ele[1] if @ret_stime.nil?
@ret_etime = ele[1]
end
end
end
| true |
975aeff134e2af095e0ea02de604551e57cf3e33 | Ruby | yous/Yous-Webtoon | /bin/getList.rb | UTF-8 | 879 | 2.6875 | 3 | [] | no_license | # encoding: utf-8
require 'logger'
require 'site'
logger = Logger.new(STDERR)
logger.level = Logger::INFO
trap("QUIT") {
logger.close
exit
}
sites = [SiteNaver.new, SiteDaum.new]
count = 0
while true
if count % (6 * 24) == 0
sites.each do |site|
begin
site.getList :all => true
logger.info "#{site.site} ALL"
rescue Exception => e
logger.error "#{site.site} ALL\n#{e.backtrace[0]}: #{e.message} (#{e.class})\n#{e.backtrace.drop(1).map {|msg| "\tfrom #{msg}"}.join("\n")}"
end
end
else
sites.each do |site|
begin
site.getList :all => false
logger.info site.site
rescue Exception => e
logger.error "#{site.site}\n#{e.backtrace[0]}: #{e.message} (#{e.class})\n#{e.backtrace.drop(1).map {|msg| "\tfrom #{msg}"}.join("\n")}"
end
end
end
sleep(60 * 10)
count += 1
end
| true |
6960f055e24a123dd581487ee5535f07cee48f15 | Ruby | andolu/final | /createdb.rb | UTF-8 | 1,436 | 2.5625 | 3 | [] | no_license | # Set up for the application and database. DO NOT CHANGE. #############################
require "sequel" #
connection_string = ENV['DATABASE_URL'] || "sqlite://#{Dir.pwd}/development.sqlite3" #
DB = Sequel.connect(connection_string) #
#######################################################################################
# Database schema - this should reflect your domain model
DB.create_table! :rides do
primary_key :id
String :title
String :description, text: true
String :date
String :location
end
DB.create_table! :rsvps do
primary_key :id
foreign_key :ride_id
foreign_key :user_id
Boolean :going
String :comments, text: true
end
DB.create_table! :users do
primary_key :id
String :name
String :email
String :password
end
rides_table = DB.from(:rides)
rides_table.insert(title: "Fabulous Farmer's Market",
description: "We are excited to take our amazing senior community members on a visit to the local farmer's market.!",
date: "June 13",
location: "Paulus Park")
rides_table.insert(title: "Local Library Visit",
description: "If books are your best friends, you will love a trip to the library.",
date: "June 14",
location: "Ela Area Public Library")
| true |
887db45dd111f5927dbafe62f2e0bf8411c2b79f | Ruby | AIexey-L/http_profiler | /profiler.rb | UTF-8 | 2,123 | 2.53125 | 3 | [] | no_license | require 'net/http'
require 'progress_bar'
require 'benchmark'
require 'bundler/setup'
Bundler.require(:default)
rows = []
main_samples = []
samples_different = %w[dme lon mos pari novos vosto kras shan ber amster]
samples_two_lwtters = %w[dm mo sa ne no sh am]
main_samples << samples_different
main_samples << samples_two_lwtters
bar = ProgressBar.new(main_samples.flatten.count)
def format(time)
time.to_a.last.ceil(3)
end
main_samples.each do |sample_collection|
sample_collection.each do |sample|
time_party_suggest = Benchmark.measure do
HTTParty.get("https://suggest.kupibilet.ru/suggest.json?term=#{sample}")
end
time_net_suggest = Benchmark.measure do
Net::HTTP.get_response(URI("https://suggest.kupibilet.ru/suggest.json?term=#{sample}"))
end
time_party_hinter_old = Benchmark.measure do
HTTParty.get("https://hinter.kupibilet.ru/suggest.json?term=#{sample}")
end
time_net_hinter_old = Benchmark.measure do
Net::HTTP.get_response(URI("https://hinter.kupibilet.ru/suggest.json?term=#{sample}"))
end
time_party_hinter_new = Benchmark.measure do
HTTParty.get("https://hinter.kupibilet.ru/hinter.json?str=#{sample}")
end
time_net_hinter_new = Benchmark.measure do
Net::HTTP.get_response(URI("https://hinter.kupibilet.ru/hinter.json?str=#{sample}"))
end
rows << [
sample,
"#{format(time_party_suggest)}\n#{format(time_net_suggest)}",
"#{format(time_party_hinter_old)}\n#{format(time_net_hinter_old)}",
"#{format(time_party_hinter_new)}\n#{format(time_net_hinter_new)}"
]
rows << :separator
bar.increment!
end
table = Terminal::Table.new :headings => %w[
string
suggest_prod
hinter_old_format_staging
hinter_new_format_staging
],
:rows => rows
puts table
rows = []
end
| true |
d46a4dbfc7270f66667ca3b93ec06e7487afd758 | Ruby | bugoodby/bugoodbylib | /script/rb/01.command_line.rb | UTF-8 | 437 | 3.640625 | 4 | [
"Unlicense"
] | permissive | #!/bin/ruby
def main()
puts "count = #{ARGV.length}"
puts "--- method 1 ---\n"
for arg in ARGV
puts arg
end
puts "--- method 2 ---\n"
ARGV.each {|arg|
puts arg
}
puts "--- method 3 ---\n"
ARGV.each_with_index {|arg, i|
puts i.to_s << " : " << arg
}
puts "--- method 4 ---\n"
i = 0
while i < ARGV.length
print i.to_s + " : " + ARGV[i] + "\n"
i = i + 1
end
end
main()
| true |
a959ac50269f00897b29d3e4bbc879edbe5afec7 | Ruby | jcellomarcano/movies-backend-manager-ruby | /lambdabuster.rb | UTF-8 | 22,314 | 3.390625 | 3 | [
"MIT"
] | permissive | require 'json'
require 'set'
require 'date'
require_relative 'classes'
def create_order(movies,type,user)
if type == :rent
my_name="rentar"
verb_in_past="rentado"
my_price="rent_price"
action="rent_order"
store="rented_movies"
else
my_name="comprar"
verb_in_past="comprado"
my_price="price"
action="buy_order"
store="owned_movies"
end
puts "¿Que pelicula quiere #{my_name}?"
puts "Inserta el nombre de la pelicula"
movie_name = gets.chomp
# puts movie_name
# puts movies
movie=movies.scan(:name) { |x| x == movie_name}
puts "Movie length #{movie.length}"
if movie.length == 0
puts "\nSorry, no se encontró la pelicula :("
while true
puts "\n---------- * -----------"
puts "Que accion quiere realizar?"
puts "1. Intentar con otro nombre"
puts "2. Volver al menu inicial"
puts "3. Consultar peliculas"
puts "4. Salir"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
resp=create_order(movies,type,user)
break
when 2
resp=1
break
when 3
consult_movies(movies)
break
when 4
puts "\nGracias por usar Lambdabuster"
puts "Nos vemos en la proxima :D"
exit(0)
else
puts "\nPrueba una opcion valida :3"
end
end
else
my_movie=nil
# puts movie
movie.each do |x|
puts "\nPelicula encontrada: #{x.name}"
puts "Duracion: #{x.runtime}"
puts "Categorias: #{x.categories}"
puts "Fecha de lanzamiento: #{x.release_date}"
puts "Directors: #{x.directors}"
puts "Actores: #{x.actors}"
puts "Precio de compra: #{x.price}"
puts "Precio para rentar: #{x.rent_price}"
my_movie=x
end
while true
puts "\n---------- * -----------"
puts "Elige el metodo de pago que mejor se adapte:"
puts "1. Dolares"
puts "2. Bolivares"
puts "3. Euros"
puts "4. Bitcoin"
option = gets.chomp.to_i
# puts my_movie
currency=my_movie.method(my_price).call.dolars
case option
when 1
break
when 2
puts "Precio: #{currency.in(:bolivares).to_s}"
break
when 3
puts "Precio: #{currency.in(:euros).to_s}"
break
when 4
puts "Precio: #{currency.in(:bitcoin).to_s}"
break
else
puts "\nPrueba una opcion valida"
end
end
puts "Precio: #{currency.to_s}"
while true
puts "\n---------- * -----------"
puts "1. Continuar"
puts "2. Volver al menu inicial"
option = gets.chomp.to_i
case option
when 1
transaction=Transaction.new(my_movie,type)
transaction.method(action).call(transaction)
if type == :rent
user.rented_movies << my_movie
else
user.owned_movies << my_movie
end
user.transactions<<transaction
puts "\nLa pelicula se ha #{verb_in_past} con exito!!"
puts "Ya la tienes disponible en tu perfil"
puts "Que la disfrutes :D"
break
when 2
break
else
puts "\nPrueba una opcion valida"
end
end
end
end
#JSON READER
def readJson(path)
@directorsList = {}
@actorsList = {}
@moviesList = SearchList.new()
@moviesChecker = {}
@personsList = {}
@categories = Set.new
begin
file = File.read(path)
data_hash = JSON.parse(file)
result = true
# "try" block
for director in data_hash['directors']
if @directorsList.keys.include? director['name']
throw "The Director: #{director['name']} has been registered before"
else
auxDir = Director.new(director['name'],Date.parse(director['birthday']), director['nationality'])
@directorsList[director['name']] = auxDir
@personsList[director['name']] = auxDir
end
end
for actor in data_hash['actors']
if @actorsList.keys.include?actor['name']
throw "The Actor: #{actor['name']} has been registered before"
else
auxAct = Actor.new(actor['name'],Date.parse(actor['birthday']), actor['nationality'])
@actorsList[actor['name']] = auxAct
if @personsList.keys.include?actor['name']
throw "The Actor: #{actor['name']} has been registered as director"
else
@personsList[actor['name']] = auxAct
end
end
end
for movie in data_hash['movies']
# puts movie
if @moviesChecker.keys.include?movie['name']
throw "The Movie: #{movie['name']} has been registered before"
else
# puts loadMovie(movie)
auxMov = loadMovie(movie)
@moviesList << auxMov
@moviesChecker[movie['name']]= auxMov
for category in movie['categories']
@categories << category
end
end
end
rescue StandardError => e# optionally: `rescue Exception => ex`
result = false
puts e
raise "Error to load JSON"
ensure # will always get executed
# puts "Movies #{@moviesList}"
if result
return @directorsList,@actorsList,@moviesList,@categories,@personsList
else
return false
end
end
# puts directorsList
end
def loadMovie(movieObj)
# puts "We are in load"
# puts movieObj
begin
movie = Movie.new(
movieObj['name'],
Integer(movieObj['runtime']),
movieObj['categories'],
Date.parse(movieObj['release_date']),
movieObj['directors'],
movieObj['actors'],
Float(movieObj['price']),
Float(movieObj['rent_price']),
movieObj['premiere'],
Integer(movieObj['discount'])
)
if Integer(movieObj['discount']) > 0
movie = Discount.new(movie)
end
if movieObj['premiere'] == true
movie = Premiere.new(movie)
end
rescue StandardError => e
puts e
ensure
return movie
end
movie
end
# CONSULT MOVIES
def create_comparison_condition()
while true
puts "\n---------- * -----------"
puts "¿Con qué comparación?"
puts "1. Menor"
puts "2. Menor o igual"
puts "3. Igual"
puts "4. Mayor o igual"
puts "5. Mayor"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
resp="<"
break
when 2
resp="<="
break
when 3
resp="=="
break
when 4
resp=">="
break
when 5
resp=">"
break
else
puts "\nPrueba una opcion valida :S"
end
end
resp
end
def create_coincidence_condition()
while true
puts "\n---------- * -----------"
puts "¿Con qué comparación?"
puts "1. Coincidencia exacta"
puts "2. Coincidencia parcial"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
resp = "=="
break
when 2
resp = "include?"
break
else
puts "\nPrueba una opcion valida"
end
end
resp
end
def create_result_menu(searchlist)
while true
puts "\n---------- * -----------"
puts "1. Aplicar otro filtro"
puts "2. Buscar"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
movies=searchlist
break
when 2
if searchlist.length > 0
puts "\n**Resultado**"
puts searchlist
else
puts "\n**No se encontro resultado para este filtro"
end
break
else
puts "\nPrueba una opcion valida :3"
end
end
option
end
def consult_movies(movies)
while true
puts "\n---------- * -----------"
puts "Que accion quiere realizar?"
puts "1. Mostrar todas las peliculas"
puts "2. Filtrar"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
if movies.length > 0
puts "\n**Resultado**"
puts movies
else
puts "\n**No se encontro resultado para este filtro"
end
when 2
while true
puts "\n---------- * -----------"
puts "¿Que filtro quieres aplicar?"
puts "1. Nombre"
puts "2. Año"
puts "3. Nombre del director"
puts "4. Nombre del actor"
puts "5. Duracion"
puts "6. Categorias"
puts "7. Precio de compra"
puts "8. Precio de alquiler"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
puts "\nInserte el nombre:"
my_name = gets.chomp
my_method=create_coincidence_condition()
resp=movies.scan(:name) { |x| x.method(my_method).call my_name }
op=create_result_menu(resp)
if op == 2
break
end
when 2
puts "\nInserte el año:"
# puts movies
my_year = gets.chomp.to_i
my_method=create_comparison_condition()
resp=movies.scan(:release_date) { |x| x.year.method(my_method).call my_year }
op=create_result_menu(resp)
if op == 2
break
end
when 3
puts "\nInserte el nombre del director:"
my_name = gets.chomp
my_method=create_coincidence_condition()
if my_method == "=="
resp=movies.scan(:directors) { |x| x.include? my_name }
else
resp=movies.scan(:directors) { |x| x.any? { |s| s.include? my_name } }
end
op=create_result_menu(resp)
if op == 2
break
end
when 4
puts "\nInserte el nombre del actor:"
my_name = gets.chomp
my_method=create_coincidence_condition()
if my_method == "=="
puts "igualdad total"
if movies.directors.include? my_name
resp=movies.scan(:actors) { |x| x.include? my_name }
else
resp=movies.scan(:actors) { |x| x.any? { |s| s.include? my_name } }
end
puts resp
else
resp=movies.scan(:actors) { |x| x.any? { |s| s.include? my_name } }
puts resp
end
op=create_result_menu(resp)
if op == 2
break
end
when 5
puts "\nInserte la duracion:"
duration = gets.chomp.to_i
my_method=create_comparison_condition()
resp=movies.scan(:runtime) { |x| x.method(my_method).call duration }
op=create_result_menu(resp)
if op == 2
break
end
when 6
filter_categories=Set.new()
while true
puts "\n---------- * -----------"
puts "Seleccione una categoria:"
counter=1
my_categories.each do |x|
puts "#{counter}. #{x}"
my_list_of_categies<<x
counter=counter+1
end
option = gets.chomp.to_i
if option > my_categories.length
puts "\nElige una opcion valida"
else
my_category=my_list_of_categies[option-1]
resp=movies.scan(:categories).select {|x| x.include? my_category}
while true
puts "\n---------- * -----------"
puts "Quieres seleccionar otra categoria?"
puts "1. Si"
puts "2. No"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
op=1
break
when 2
op=2
break
else
puts "\nElige una opcion valida"
end
end
if op == 2
op2=create_result_menu(resp)
if op2 == 2
break
end
end
end
end
op=create_result_menu(resp)
if op == 2
break
end
when 7
puts "\nInserte el precio de compra:"
my_price = gets.chomp.to_i
my_method=create_comparison_condition()
resp=movies.scan(:price) { |x| x.method(my_method).call my_price }
op=create_result_menu(resp)
if op == 2
break
end
when 8
puts "\nInserte el precio de renta:"
my_price = gets.chomp.to_i
my_method=create_comparison_condition()
resp=movies.scan(:rent_price) { |x| x.method(my_method).call my_price }
op=create_result_menu(resp)
if op == 2
break
end
else
puts "\nPrueba una opcion valida :3"
end
#movies=resp
end
break
else
puts "\nPrueba una opcion valida"
end
end
end
def myUser (user, moviesList, personsList)
puts "RentedList #{user.rented_movies.length}"
if user.owned_movies.length == 0 && user.rented_movies.length == 0
puts "No has realizado transacciones en #{"Lambdabuster"}"
puts "Listado de Peliculas alquiladas: " + "\n" + "#{user.rented_movies}"
puts "Listado de Peliculas compradas: " + "\n" + "#{user.owned_movies}"
puts "Vuela a consultar despues de haber rentado o adquirido una"
return
end
#menu for select option
while true
puts "\n---------- * -----------"
puts "¿Quieres consultar alguna de tus películas?"
puts "1. Si"
puts "2. No"
option = gets.chomp.to_i
case option
when 1
while true
puts "\n---------- * -----------"
puts "Ingresa el nombre de la película: \n"
puts "Si deseas salir, escribe: salir"
movie = gets.chomp
case movie
when "salir"
break
else
a = SearchList.new
b = SearchList.new
if user.owned_movies.length == 0 && user.rented_movies.length != 0
b = user.rented_movies.scan(:name) {|x| x == movie}
elsif user.owned_movies.length != 0 && user.rented_movies.length == 0
a = user.owned_movies.scan(:name) {|x| x == movie}
else
b = user.rented_movies.scan(:name) {|x| x == movie}
a = user.owned_movies.scan(:name) {|x| x == movie}
end
if ( a.length == 0 ) && (b.length == 0)
puts "Lo siento, no tienes esta pelicula, puedes intentar buscar otra"
break
else
userMovie = (moviesList.scan(:name) {|name| name == movie}).head
puts "\n#{userMovie}\n"
while true
puts "\n¿Quieres conocer acerca de algun actor o director de esta peli?"
puts "Si"
puts "No"
response = gets.chomp
case response
when "Si"
while true
puts "Ingrese nombre de actor o director"
response2 = gets.chomp
aux = false
while (! userMovie.actors.include? response2) && (! userMovie.directors.include? response2)
aux = true
puts "Persona no encontrada"
end
if not aux
puts "\n #{personsList[response2]}"
break
else
break
end
end
when "No"
break
else
puts "Ingresa una seleccion válida"
end
end
end
end
end
when 2
break
else
puts "Porfavor, escoge una selección válida"
end
end
end
class Main
# FUNCTIONS
def self.get_path
puts "\nPor favor ingrese la direccion desde donde se cargaran los archivo"
path = gets.chomp
end
@user = User.new
@directorsList = {}
@actorsList = {}
@moviesList = SearchList.new()
@moviesChecker = {}
@personsList = {}
@categories = Set.new
# MAIN
puts "**************************"
puts "Bienvenido a Lambdabuster\n"
while true
puts "\n---------- * -----------"
path = self.get_path()
charge_data = readJson(path) #Funcion que carga los datos
if charge_data == false
puts "\nLo sentimos, no pudimos cargar los datos :("
puts "\nAsegurate de haber colocado la ruta retaliva"
puts "y la estructura del archivo correcta para el programa"
puts "\nOpciones:"
puts "1. Reintentar"
puts "2. Salir"
option = gets.chomp.to_i
if option != 1
exit(0)
end
else
puts "\nDatos cargados con exito :D"
@directorsList = charge_data[0]
@actorsList = charge_data[1]
@moviesList = charge_data[2]
@personsList = charge_data[4]
@categories = charge_data[3]
break
end
end
while true
puts "\n---------- * -----------"
puts "Que accion quiere realizar?"
puts "1. Crear nueva orden de alquiler"
puts "2. Crear nueva orden de compra"
puts "3. Mi Usuario"
puts "4. Consultar catálogo"
puts "5. Salir"
puts ""
puts "Inserta el numero de la opcion"
option = gets.chomp.to_i
case option
when 1
#puts "1. Crear nueva orden de alquiler"
create_order(@moviesList,:rent,@user)
when 2
#puts "2. Crear nueva orden de compra"
create_order(@moviesList,:buy,@user)
when 3
#puts "3. Mi Usuario"
myUser(@user,@moviesList,@personsList)
when 4
#puts "4. Consultar catálogo"
consult_movies(@moviesList)
when 5
puts "\nGracias por usar Lambdabuster"
puts "Nos vemos en la proxima :D"
exit(0)
else
puts "\nPrueba una opcion valida :3"
end
end
end | true |
22a26fd3295f7ca1189e44b0a9a35044dd4ee8c4 | Ruby | p3ban3/megacalcio | /mega.rb | UTF-8 | 1,638 | 2.59375 | 3 | [] | no_license | require "sinatra"
require './config'
# squadre = DB.carica "squadre"
enable :sessions
get "/migrate" do
DataMapper.auto_migrate!
"db pronto"
end
get "/" do
erb :index
end
get "/typography" do
erb :typography
end
get "/squadre" do
squadre.to_s
end
get "/users/new" do
erb :users_new
end
post "/users" do
user = User.new username: params[:username], password: params[:password]
if user.save
# loggarlo
redirect "/"
else
erb :users_new
end
end
get "/login" do
erb :login
end
post "/login" do
user = User.first username: params[:username], password: params[:password]
if user
session[:user_id] = user.id
redirect "/"
else
erb :login
end
end
def current_user
# TODO: ottimizzazione da fare
User.get session[:user_id]
end
def logged?
current_user
end
post '/logout' do
session[:user_id] = nil
redirect "/"
end
get "/squadre/new" do
erb :squadre_new
end
get "/squadre/*" do |id|
@squadra = Squadra.get id
erb :squadra
end
post '/squadre' do
squadra = Squadra.new nome: params[:nome], user_id: current_user.id
squadra.save
redirect "/squadre/#{squadra.id}"
end
get "/asta" do
"..."
end
get "/classifica" do
erb :classifica
end
set(:probability) { |value| condition { rand <= value } }
get '/win_a_car', :probability => 0.1 do
"You won!"
erb :win_a_car
end
get '/win_a_car' do
erb :win_a_car
end
=begin
exit
squadra1 = Squadra.new("p3ban3").hash
squadra2 = Squadra.new("Can3x").hash
puts Dado.new(squadra1, squadra2).risultato
puts "---"
puts squadra1
puts squadra2
squadre = [squadra1, squadra2]
DB.salva "squadre", squadre
=end | true |
a174d6a2a5f2d15724e7330f1e31c4bc2e75a2d5 | Ruby | invibelabs/iron-workers | /mandrill_mailer/mandrill_mailer.rb | UTF-8 | 563 | 2.625 | 3 | [
"MIT"
] | permissive | require "mandrill"
puts "Starting Mandrill Mailer"
mandrill_api_key = params["mandrill_api_key"]
from_email = params["from_email"]
from_name = params["from_name"]
subject = params["subject"]
content = params["content"]
to_email = params["to_email"]
mandrill = Mandrill::API.new mandrill_api_key
puts "Building email message"
message = {
text: content,
subject: subject,
from_email: from_email,
from_name: from_name,
to: [{
email: to_email
}]
}
puts "Sending Email"
result = mandrill.messages.send(message)
puts result
puts "Email Sent"
| true |
50728d737e20e643bdd62060fcd91b43be8e1ac9 | Ruby | Vellimir/ParallelDots-Ruby-API | /lib/config.rb | UTF-8 | 406 | 2.75 | 3 | [] | no_license | require 'parseconfig'
def set_api_key( api_key )
file = File.open( 'paralleldots_key.conf', 'w' )
config = ParseConfig.new( file )
config.add( "PD", api_key )
config.write( file )
file.close
puts "API Key Set.\nKey Value: %s"%api_key
end
def get_api_key
begin
config = ParseConfig.new( "paralleldots_key.conf" )
return config[ "PD" ]
rescue
puts "No API Key Found."
return
end
end
| true |
231e0d740504a0eb2ea4a1185bcf29121b1f4e9a | Ruby | markevan100/exercisms | /ruby/collatz-conjecture/collatz_conjecture.rb | UTF-8 | 277 | 3.09375 | 3 | [] | no_license | module CollatzConjecture
def self.steps(num)
raise ArgumentError if num < 1
counter = 0
loop do
break if num == 1
counter += 1
if num % 2 == 0
num = num / 2
else
num = (3 * num) + 1
end
end
counter
end
end
| true |
8582f2a0c5c0b4fdae431a9f2dd9a41c4638a7fe | Ruby | benizi/dotfiles | /bin/git.encryptedjs | UTF-8 | 2,998 | 2.515625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'base64'
def encrypting?
!!(__FILE__ =~ /encrypt$/)
end
def contents
@contents ||= $stdin.read
end
def lines
@lines ||= contents.lines.to_a
end
def password
`git config filter.encryptedjs.password || true`.chomp
end
def encrypted?
!!((lines[0] || '') =~ /^benizi/)
end
def done?
encrypting? == encrypted?
end
if done? || password.empty?
# Already processed or no password
$stdout.write(contents)
exit
end
MARKER = '//OK'
def prep(contents)
encrypting? ? mark(contents) : from_js_source(contents)
end
def mark(contents)
[MARKER, contents].join("\n")
end
def from_js_source(contents)
contents.lines.to_a[1..-2].map do |line|
line.sub(/^"/, '').sub(/\\n" \+/, '')
end.join
end
def find_salt(input)
cipher = Base64.decode64(input)
return if cipher.size * 2 < input.size
marker = 'Salted__'
return unless cipher.start_with?(marker)
@salt = cipher[marker.size, 8].unpack("H*")[0].upcase
end
def dumpsalt(input, out)
input.tap do
return unless find_salt(input)
out.puts("SALT=#{@salt}")
end
end
def showsalt(input)
dumpsalt(input, $stderr)
end
def putsalt(input)
dumpsalt(input, $stdout)
end
def use_salt?
encrypting? && ENV.has_key?('SALT')
end
def command
op = encrypting? ? '-e' : '-d'
salt = use_salt? ? %Q{ -S #{ENV['SALT']}} : ''
%Q{openssl enc #{op} -a -blowfish -pass #{password}} + salt
end
def post(result)
encrypting? ? to_js_source(result) : unmark(result)
end
def to_js_source(result)
ret = []
ret << 'benizi.source ='
ret += result.lines.map { |line| %Q{"#{line.chomp}\\n" +} }
ret << '"";'
ret.map { |line| line + "\n" }.join
end
def unmark(result)
first_line = result.lines.first.chomp
abort "Bad decode (First line: #{first_line})" unless first_line == MARKER
result.lines.drop(1).join
end
def process(input)
IO.popen(command, 'r+') do |io|
io.write input
io.close_write
io.read
end
end
STAGES = %i[prep process post puts]
SALT_FNS = %i[showsalt putsalt]
def sym_list(s)
String === s ? s.split(/\W+/).map(&:downcase).map(&:to_sym) : s
end
def setup_salt!(list)
return unless ENV['SHOWSALT'] || (SALT_FNS & list).any?
to_add = [:prep] + (encrypting? ? [:process] : []) + [:showsalt]
to_find = Hash[to_add.reverse.each_cons(2).to_a]
to_add.each do |s|
next if list.include?(s)
after = to_find[s]
pos = list.find_index(after)
list.insert(pos ? pos + 1 : 0, s)
end
end
def stages
list = sym_list(ENV['ONLY'] || STAGES)
list << :puts if (STAGES & list).any? && !list.include?(:puts)
setup_salt!(list)
salt_fn = list.include?(:puts) ? :showsalt : :putsalt
list.map! { |s| SALT_FNS.include?(s) ? salt_fn : s }
list.uniq.select { |s| should_run?(s) }
end
def in?(var, stage, default = '')
sym_list(ENV.fetch(var, default)).include?(stage.to_sym)
end
def should_run?(stage)
!in?('SKIP', stage)
end
def run_stages(input)
stages.reduce(input) { |ret, fn| send(fn, ret) }
end
run_stages(contents)
| true |
4a99cbb7c32a08fa0d2bd070099d6c4f421cbfb5 | Ruby | renuo/hashcode2017-jamp | /app/file_reader.rb | UTF-8 | 3,698 | 2.875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative './world.rb'
require_relative './video.rb'
require_relative './endpoint.rb'
require_relative './request.rb'
require_relative './connection.rb'
require_relative './cache_server.rb'
class FileReader
def initialize(file_path)
@file = File.read(file_path)
end
def puts(whatever)
end
def world
lines = @file.split(/\n/)
first_line = lines[0].split
videos_count = first_line[0].to_i
endpoints_count = first_line[1].to_i
requests_count = first_line[2].to_i
cache_servers_count = first_line[3].to_i
cache_servers_capacity = first_line[4].to_i
videos_sizes = lines[1].split
videos = Array.new(videos_count) do |i|
Video.new(i, videos_sizes[i].to_i)
end
data_center = CacheServer.new(nil, nil, true)
data_center.videos = videos
cache_servers = Array.new(cache_servers_count) do |c|
CacheServer.new(c, cache_servers_capacity)
end
line_count = 1
endpoints = Array.new(endpoints_count) do |i|
line_count += 1
puts "parsing endpoint #{i}: #{lines[line_count]}"
endpoint_line = lines[line_count].split
endpoint = Endpoint.new(i)
connections = []
endpoint_line[1].to_i.times do |_j| #
line_count += 1
puts "parsing line #{line_count}: #{lines[line_count]}"
connection_line = lines[line_count].split
cache_server = cache_servers[connection_line[0].to_i]
latency = connection_line[0].to_i
puts "cache_server:#{cache_server.id}"
puts "endpoint:#{endpoint.id}"
connection = Connection.new(latency, cache_server, endpoint)
puts "creating a connection: #{connection}"
connections << connection
end
connections << Connection.new(endpoint_line[0].to_i, data_center, endpoint)
endpoint.connections = connections
endpoint
end
requests_count.times do |_r|
line_count += 1
puts "parsing request line: #{lines[line_count]}"
request_line = lines[line_count].split
video = videos[request_line[0].to_i]
endpoint = endpoints[request_line[1].to_i]
request = Request.new(video, endpoint, request_line[2].to_i)
endpoint.requests << request
end
World.new(data_center, cache_servers, endpoints)
end
def fake_world
data_center = CacheServer.new(nil, nil, true)
videos = []
videos << Video.new(0, 50)
videos << Video.new(1, 50)
videos << Video.new(2, 80)
videos << Video.new(3, 30)
videos << Video.new(3, 110)
data_center.videos = videos
cache_servers = []
cache_servers << CacheServer.new(0, 100)
cache_servers << CacheServer.new(1, 100)
cache_servers << CacheServer.new(2, 100)
endpoints = []
endpoint0 = Endpoint.new(0)
connections = []
connections << Connection.new(100, cache_servers[0], endpoint0)
connections << Connection.new(200, cache_servers[1], endpoint0)
connections << Connection.new(200, cache_servers[2], endpoint0)
connections << Connection.new(1000, data_center, endpoint0)
endpoint0.connections = connections
requests = []
requests << Request.new(videos[3], endpoint0, 1500)
requests << Request.new(videos[4], endpoint0, 500)
requests << Request.new(videos[1], endpoint0, 1000)
endpoint0.requests = requests
endpoints << endpoint0
endpoint1 = Endpoint.new(1)
connections = [Connection.new(500, data_center, endpoint1)]
endpoint1.connections = connections
requests = []
requests << Request.new(videos[0], endpoint1, 1000)
endpoint1.requests = requests
endpoints << endpoint1
World.new(data_center, cache_servers, endpoints)
end
end
| true |
2c2f1428d3ceb42375bf9a99671f0596f3de3096 | Ruby | JoeJones76/programming-univbasics-nds-green-grocer-part-2-chicago-web-021720 | /lib/grocer_part_2.rb | UTF-8 | 2,535 | 3.3125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative './part_1_solution.rb'
def consolidate_cart(cart)
hash = {}
cart.each do |item_hash|
item_hash.each do |name, price_hash|
if hash[name].nil?
hash[name] = price_hash.merge({:count => 1})
else
hash[name][:count] += 1
end
end
end
hash
end
def apply_coupons(cart, coupons)
hash = cart
coupons.each do |coupon_hash|
# add coupon to cart
item = coupon_hash[:item]
if !hash[item].nil? && hash[item][:count] >= coupon_hash[:num]
temp = {"#{item} W/COUPON" => {
:price => coupon_hash[:cost],
:clearance => hash[item][:clearance],
:count => 1
}
}
if hash["#{item} W/COUPON"].nil?
hash.merge!(temp)
else
hash["#{item} W/COUPON"][:count] += 1
#hash["#{item} W/COUPON"][:price] += coupon_hash[:cost]
end
hash[item][:count] -= coupon_hash[:num]
end
end
hash
end
def apply_clearance(cart)
cart.each do |item, price_hash|
if price_hash[:clearance] == true
price_hash[:price] = (price_hash[:price] * 0.8).round(2)
end
end
cart
end
def checkout(items, coupons)
cart = consolidate_cart(items)
cart1 = apply_coupons(cart, coupons)
cart2 = apply_clearance(cart1)
total = 0
cart2.each do |name, price_hash|
total += price_hash[:price] * price_hash[:count]
end
total > 100 ? total * 0.9 : total
end
items = [
{"AVOCADO" => {:price => 3.00, :clearance => true}},
{"AVOCADO" => {:price => 3.00, :clearance => true}},
{"AVOCADO" => {:price => 3.00, :clearance => true}},
{"AVOCADO" => {:price => 3.00, :clearance => true}},
{"AVOCADO" => {:price => 3.00, :clearance => true}},
{"KALE" => {:price => 3.00, :clearance => false}},
{"BLACK_BEANS" => {:price => 2.50, :clearance => false}},
{"ALMONDS" => {:price => 9.00, :clearance => false}},
{"TEMPEH" => {:price => 3.00, :clearance => true}},
{"CHEESE" => {:price => 6.50, :clearance => false}},
{"BEER" => {:price => 13.00, :clearance => false}},
{"PEANUTBUTTER" => {:price => 3.00, :clearance => true}},
{"BEETS" => {:price => 2.50, :clearance => false}},
{"SOY MILK" => {:price => 4.50, :clearance => true}}
]
coupons = [
{:item => "AVOCADO", :num => 2, :cost => 5.00},
{:item => "AVOCADO", :num => 2, :cost => 5.00},
{:item => "BEER", :num => 2, :cost => 20.00},
{:item => "CHEESE", :num => 2, :cost => 15.00}
]
checkout(items, coupons)
| true |
b61b7b2e9724070289c6281a7cd2b825341b2035 | Ruby | stuartwakefield/testality | /lib/testality/request.rb | UTF-8 | 2,561 | 3.09375 | 3 | [
"MIT"
] | permissive | require "json"
module Testality
class Request
def initialize(socket)
puts "New request"
@socket = socket
puts "Parsing request"
@request = parse_request @socket
puts "Parsing headers"
# Parse headers
@headers = parse_headers @socket
puts "Parsing body"
# Parse body
@body = parse_body @headers, @socket
puts "Parsed"
end
def parse_request(socket)
# Get the request information (parse HTTP, perhaps there is a library
# that exists to do this already...)
str = socket.gets
str.strip!
req = {}
regexp = /^(\w+)\s(.+)\s(.+)$/
req[:verb] = str[regexp, 1]
req[:uri] = str[regexp, 2]
req[:path] = parse_path(req[:uri])
req[:querystring] = parse_querystring(req[:uri])
req[:get] = parse_querystring_params(req[:querystring])
# protocol = request[regexp, 3]
return req
end
def parse_path(uri)
path = uri
split = uri.index("?")
if split != nil
if split == 1
path = uri[0]
else
path = uri[0..(split - 1)]
end
end
return path
end
def parse_querystring(uri)
qs = ""
split = uri.index("?")
if split != nil
qs = uri[(split + 1)..(uri.length - 1)]
end
return qs
end
def parse_querystring_params(querystring)
map = {}
puts querystring
querystring.lines("&") do |line|
puts "Parsing parameter pair"
# Will not handle params without a value
index = line.index("=")
param = line[0..(index - 1)]
value = line[(index + 1)..(line.length - 1)]
map[param] = value
end
return map
end
def parse_headers(socket)
headers = {}
loop do
line = socket.gets
if line.index("\r\n") == 0
break
end
index = line.index(":")
param = line[0..(index - 1)]
value = line[index + 1..(line.length - 1)]
param.strip!
value.strip!
headers[param] = value
end
return headers
end
def parse_body(headers, socket)
body = nil
if headers["Content-Length"]
length = Integer(headers["Content-Length"])
body = socket.read length
# The response is json
if headers["Content-Type"].index("application/json") != nil
puts "Parsing json"
body = JSON.parse(body)
end
end
return body
end
def has_body
@body != nil
end
def get_body
@body
end
def get_headers
@headers
end
def on(verb, path)
if @request[:verb] == verb and @request[:path] == path
yield(self)
end
end
def get_socket
@socket
end
end
end
| true |
20fc03a16f282f3b23be8e774acf39d180f48b59 | Ruby | bishma-stornelli/ANN | /one-neuron/prueba.rb | UTF-8 | 214 | 2.6875 | 3 | [] | no_license | #!/usr/bin/ruby
require 'rubygems'
require 'gruff'
g = Gruff::Dot.new
g.title = "Mi gráfica de prueba"
g.data("Java", [24, 25, 18])
g.data("C", [17.5, 17, 16.5])
g.labels = {0 => '2003'}
g.write('prueba.png') | true |
aa08bb512b3adb75f900bd9de943c7bcded3cbbb | Ruby | asciidoctor/kramdown-asciidoc | /lib/kramdown-asciidoc/api.rb | UTF-8 | 6,750 | 2.71875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Kramdown
module AsciiDoc
DEFAULT_PARSER_OPTS = {
auto_ids: false,
hard_wrap: false,
html_to_native: true,
input: 'GFM',
}
DEFAULT_PREPROCESSORS = [
(Preprocessors.method :extract_front_matter),
(Preprocessors.method :replace_toc),
(Preprocessors.method :trim_before_leading_comment),
]
# Converts a Markdown string to an AsciiDoc string and either returns the result or writes it to a file.
#
# @param markdown [String, IO] the Markdown source to convert to AsciiDoc.
# @param opts [Hash] additional options to configure the behavior of the converter.
# @option opts [Boolean] :auto_ids (false) controls whether converter automatically generates an explicit ID for any
# section title (aka heading) that doesn't already have an ID assigned to it.
# @option opts [String] :auto_id_prefix (nil) the prefix to add to an auto-generated ID.
# @option opts [String] :auto_id_separator ('-') the separator to use in auto-generated IDs.
# @option opts [Boolean] :lazy_ids (false) controls whether to drop the ID if it matches the auto-generated ID value.
# @option opts [Symbol] :wrap (:preserve) the line wrapping behavior to apply (:preserve, :ventilate, or :none).
# @option opts [Integer] :heading_offset (0) the heading offset to apply to heading levels.
# @option opts [Boolean] :auto_links (true) whether to allow raw URLs to be recognized as links.
# @option opts [Hash] :attributes ({}) additional AsciiDoc attributes to add to header of output document; reserved
# attributes, like stem, may be overridden; some attributes may impact conversion, such as idprefix and idseparator
# @option opts [String] :imagesdir (nil) the prefix to remove from image references found in the Markdown document;
# if not specified, the value of the imagesdir attribute is used
# @option opts [Symbol] :encode (true) whether to reencode the source to UTF-8.
# @option opts [Array<Proc>] :preprocessors ([]) a list of preprocessors functions to execute on the cleaned Markdown source.
# @option opts [Array<Proc>] :postprocessors ([]) a list of functions through which to run the output document.
# @option opts [Proc] :postprocess (nil) a function through which to run the output document (if :postprocessors is falsy).
# @option opts [String, Pathname] :to (nil) the path to which to write the output document.
#
# @return [String, nil] the converted AsciiDoc or nil if the :to option is specified.
def self.convert markdown, opts = {}
if markdown.respond_to? :read
markdown = markdown.read
encode = true
else
encode = opts[:encode]
end
unless encode == false || (markdown.encoding == UTF_8 && !(markdown.include? CR))
markdown = markdown.encode UTF_8, universal_newline: true
end
markdown = markdown.rstrip
markdown = markdown.slice 1, markdown.length while markdown.start_with? LF
parser_opts = DEFAULT_PARSER_OPTS.merge opts
attributes = (parser_opts[:attributes] = (parser_opts[:attributes] || {}).dup)
((opts.fetch :preprocessors, DEFAULT_PREPROCESSORS) || []).each do |preprocessor|
markdown = preprocessor[markdown, attributes]
end
asciidoc = (kramdown_doc = ::Kramdown::Document.new markdown, parser_opts).to_asciidoc
(opts[:postprocessors] || Array(opts[:postprocess])).each do |postprocessor|
asciidoc = (postprocessor.arity == 1 ? postprocessor[asciidoc] : postprocessor[asciidoc, kramdown_doc]) || asciidoc
end
asciidoc += LF unless asciidoc.empty?
if (to = opts[:to])
if ::Pathname === to || (!(to.respond_to? :write) && (to = ::Pathname.new to.to_s))
to.dirname.mkpath
to.write asciidoc, encoding: UTF_8
else
to.write asciidoc
end
nil
else
asciidoc
end
end
# Converts a Markdown file to AsciiDoc and writes the result to a file or the specified destination.
#
# @param markdown_file [String, File] the Markdown file or file path to convert to AsciiDoc.
# @param opts [Hash] additional options to configure the behavior of the converter.
# @option opts [Boolean] :auto_ids (false) controls whether converter automatically generates an explicit ID for any
# section title (aka heading) that doesn't already have an ID assigned to it.
# @option opts [String] :auto_id_prefix (nil) the prefix to add to an auto-generated ID.
# @option opts [String] :auto_id_separator ('-') the separator to use in auto-generated IDs.
# @option opts [Boolean] :lazy_ids (false) controls whether to drop the ID if it matches the auto-generated ID value.
# @option opts [Symbol] :wrap (:preserve) the line wrapping behavior to apply (:preserve, :ventilate, or :none).
# @option opts [Integer] :heading_offset (0) the heading offset to apply to heading levels.
# @option opts [Boolean] :auto_links (true) whether to allow raw URLs to be recognized as links.
# @option opts [Hash] :attributes ({}) additional AsciiDoc attributes to add to header of output document; reserved
# attributes, like stem, may be overridden; some attributes may impact conversion, such as idprefix and idseparator
# @option opts [String] :imagesdir (nil) the prefix to remove from image references found in the Markdown document;
# if not specified, the value of the imagesdir attribute is used
# @option opts [Array<Proc>] :preprocessors ([]) a list of preprocessors functions to execute on the cleaned Markdown source.
# @option opts [Array<Proc>] :postprocessors ([]) a list of functions through which to run the output document.
# @option opts [Proc] :postprocess (nil) a function through which to run the output document (if :postprocessors is falsy).
# @option opts [String, Pathname] :to (nil) the path to which to write the output document.
#
# @return [String, nil] the converted document if the :to option is specified and is falsy, otherwise nil.
def self.convert_file markdown_file, opts = {}
if ::File === markdown_file
markdown = markdown_file.read
markdown_file = markdown_file.path
encode = true
else
markdown = ::File.read markdown_file, mode: 'r:UTF-8', newline: :universal
encode = false
end
if (to = opts[:to])
to = ::Pathname.new to.to_s unless ::Pathname === to || (to.respond_to? :write)
elsif !(opts.key? :to)
to = (::Pathname.new markdown_file).sub_ext '.adoc'
raise ::IOError, %(input and output cannot be the same file: #{markdown_file}) if to.to_s == markdown_file.to_s
end
convert markdown, (opts.merge to: to, encode: encode)
end
CR = ?\r
LF = ?\n
TAB = ?\t
UTF_8 = ::Encoding::UTF_8
private_constant :CR, :LF, :TAB, :UTF_8
end
end
| true |
7f75860a8d54621e3943dc644deda712da426c43 | Ruby | CultureHQ/adequate_serialization | /lib/adequate_serialization/attribute.rb | UTF-8 | 3,131 | 2.765625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module AdequateSerialization
def self.dump(object)
if object.is_a?(Hash)
object
elsif object.respond_to?(:as_json)
object.as_json
else
object
end
end
module Attribute
class Simple
attr_reader :name
def initialize(name)
@name = name
end
def serialize_to(_serializer, response, model, _includes)
response[name] = AdequateSerialization.dump(model.public_send(name))
end
end
class Synthesized
attr_reader :name, :block
def initialize(name, &block)
@name = name
@block = block
end
def serialize_to(serializer, response, model, _includes)
response[name] =
AdequateSerialization.dump(serializer.instance_exec(model, &block))
end
end
class IfCondition
attr_reader :attribute, :condition
def initialize(attribute, condition)
@attribute = attribute
@condition = condition
end
def name
attribute.name
end
def serialize_to(serializer, response, model, includes)
return unless model.public_send(condition)
attribute.serialize_to(serializer, response, model, includes)
end
end
class UnlessCondition
attr_reader :attribute, :condition
def initialize(attribute, condition)
@attribute = attribute
@condition = condition
end
def name
attribute.name
end
def serialize_to(serializer, response, model, includes)
return if model.public_send(condition)
attribute.serialize_to(serializer, response, model, includes)
end
end
class Optional
attr_reader :attribute
def initialize(attribute)
@attribute = attribute
end
def name
attribute.name
end
def serialize_to(serializer, response, model, includes)
return unless includes.include?(attribute.name)
attribute.serialize_to(serializer, response, model, includes)
end
end
class Config
attr_reader :attribute, :options
def initialize(attribute, options)
@attribute = attribute
@options = options
end
def to_attribute
nested = nested_attribute_from(attribute, options)
nested ? Config.new(nested, options).to_attribute : attribute
end
private
def nested_attribute_from(attribute, options)
if options.delete(:optional)
Optional.new(attribute)
elsif if_option
IfCondition.new(attribute, if_option)
elsif unless_option
UnlessCondition.new(attribute, unless_option)
end
end
def if_option
@if_option ||= options.delete(:if)
end
def unless_option
@unless_option ||= options.delete(:unless)
end
end
def self.from(name, options = {}, &block)
attribute =
if block
Synthesized.new(name, &block)
else
Simple.new(name)
end
Config.new(attribute, options).to_attribute
end
end
end
| true |
8faaaf41a81acaa54eef92f83e9db80b6d37f2d1 | Ruby | drewswinburne/landlord | /ar_exercise/exercise.rb | UTF-8 | 6,406 | 3.3125 | 3 | [] | no_license | ### NOTE: Make sure you've loaded the seeds.sql file into your DB before starting
### this exercise
require "pg" # postgres db library
require "active_record" # the ORM
require "pry" # for debugging
ActiveRecord::Base.establish_connection(
:adapter => "postgresql",
:database => "landlord"
)
class Tenant < ActiveRecord::Base
belongs_to :apartment
end
class Apartment < ActiveRecord::Base
has_many :tenants
end
################################################
#### NOTE: DON'T MODIFY ABOVE THIS LINE ####
################################################
################################################
# FINDING / SELECTING
################################################
# Hint, the following methods will help: `where`, `all`, `find`, `find_by`
# Use Active record to do the following, and store the results **in a variable**
# example: get every tenant in the DB
all_tenants = Tenant.all
# get the first tenant in the DB
first = Tenant.first
# get all tenants older than 65
seniors = Tenant.select do |x|
x[:age] >= 65
end
# get all apartments whose price is greater than $2300
gentrification = Apartment.select {|x| x.monthly_rent > 2300}
# get the apartment with the address "6005 Damien Corners"
omen = Apartment.find_by_address("6005 Damien Corners")
# get all tenants in that apartment
# coven = Tenant.where(:apartment_id => omen[:id])
# Use `each` and `puts` to:
# Display the name and ID # of every tenant
all_tenants.each do |tenant|
puts "#{tenant.name} has id #{tenant.id}"
end
# Iterate over each apartment, for each apartment, display it's address and rent price
all_apartments = Apartment.all
all_apartments.each do |apt|
puts "#{apt.address} has a rent of $#{apt.monthly_rent}."
end
# Iterate over each apartment, for each apartment, display it's address and all of it's tenants
all_apartments.each do |apt|
puts "#{apt.address}'s tenants are: "
all_tenants.each do |tenant|
if tenant[:apartment_id] == apt[:id]
puts "#{tenant.name}"
end
end
#{all_tenants.where(:apartment_id => apt.id)}."
end
################################################
# CREATING / UPDATING / DELETING
################################################
# Hint, the following methods will help: `new`, `create`, `save`, `uddate`, `destroy`
# Create 3 new apartments, and save them to the DB
# Create at least 9 new tenants and save them to the DB. (Make sure they belong to an apartment)
# Note: you'll use this little bit of code as a `seeds.rb` file later on.
this = Apartment.create(:address =>"1234 this lane", :monthly_rent => 700, :sqft => 1400, :num_beds => 2, :num_baths => 1)
that = Apartment.create(:address =>"5678 that lane", :monthly_rent =>700, :sqft => 1400, :num_beds => 2, :num_baths => 1)
cool = Apartment.create(:address =>"420 cool st", :monthly_rent =>666, :sqft => 2100, :num_beds => 3, :num_baths =>2)
a = Tenant.create(name: "Adam", age: 30, gender: "Male", apartment_id: 3)
b = Tenant.create(name: "Dan", age: 31, gender: "Male", apartment_id: 2)
c = Tenant.create(name: "Fran", age: 32, gender: "Male", apartment_id: 3)
d = Tenant.create(name: "Frank", age: 33, gender: "Male", apartment_id: 1)
e = Tenant.create(name: "Francis", age: 34, gender: "Male", apartment_id: 2)
f = Tenant.create(name: "Francine", age: 35, gender: "Female", apartment_id: 2)
g = Tenant.create(name: "Francois", age: 36, gender: "Male", apartment_id: 1)
h = Tenant.create(name: "Frankford", age: 37, gender: "Male", apartment_id: 3)
i = Tenant.create(name: "France", age: 65, gender: "Male", apartment_id: 3)
binding.pry
# Birthday!
# It's Kristin Wisoky's birthday. Find her in the DB and change her age to be 1 year older
# Note: She's in the seed data, so she should be in your DB
kris = Tenant.where(name:"Kristin Wisoky").update(:age => 24)
# Rennovation!
# Find the apartment "62897 Verna Walk" and update it to have an additional bedroom
# Make sure to save the results to your database
rennovate = Apartment.where(address: "62897 Verna Walk")
rennovate.update(:num_beds => rennovate[0][:num_beds]+=1)
# Rent Adjustment!
# Update the same apartment that you just 'rennovated'. Increase it's rent by $400
# to reflect the new bedroom
rennovate.update(:monthly_rent => rennovate[0][:monthly_rent]+=1)
# Millenial Eviction!
# Find all tenants who are under 30 years old
# Delete their records from the DB
millenials = Tenant.select {|x| x.age < 30}
millenials.each do |y|
Tenant.destroy(y[:id])
end
def menuscreen tenants, apartments
puts "###################################################"
puts "Welcome to landlord.ly, the premier landlording app"
puts "###################################################"
puts "1. list all tenants"
puts "2. list all apartments"
puts "3. view apartments with current tenants"
puts "4. search apartment by tenant"
puts "5. remove tenant from apartment"
puts "6. add new tenant"
puts "9. exit"
menu = gets.chomp.to_i
case menu
when 1
tenants.each do |name|
puts "#{name.name}"
end
puts ""
menuscreen tenants, apartments
when 2
apartments.each do |apt|
puts "#{apt.address}"
end
puts ""
menuscreen tenants, apartments
when 3
apartments.each do |apt|
tenants.each do |name|
if apt.id == name.apartment_id
puts "#{apt.address}, occupied by #{name.name}\n"
end
end
end
puts ""
menuscreen tenants, apartments
when 4
puts "enter tenant name"
search = gets.chomp
apartments.each do |apt|
tenants.each do |name|
if search == name.name && apt.id == name.apartment_id
puts "#{name.name} lives at #{apt.address}\n"
end
end
end
puts ""
menuscreen tenants, apartments
when 5
puts "removing tenant: enter tenant name"
search = gets.chomp
tenants.each do |name|
if search == name.name
name.apartment_id = nil #there's gotta be a better way to do this
end
end
puts "#{search} has been removed"
puts ""
menuscreen tenants, apartments
when 6
puts "new tenant name"
newname = gets.chomp
puts "new tenant id"
newid = gets.chomp
puts "new tenant age"
newage = gets.chomp
puts "new tenant apartment_id"
newapt = gets.chomp
tenants << Tenant.new(newid, newname, newage, newapt)
puts "#{newname} has been added"
puts ""
menuscreen tenants, apartments
when 9
puts "enjoy your idle wealth!!"
else
puts "not a valid response\n\n"
menuscreen tenants, apartments
end
end
menuscreen all_tenants, all_apartments
#lkasjdfj
| true |
72486b4c215735a375f041e2382022865aa1c283 | Ruby | arturcp/arenah-rails | /app/models/sheet/character_attribute.rb | UTF-8 | 1,758 | 2.625 | 3 | [] | no_license | # frozen_string_literal: true
module Sheet
class CharacterAttribute
include EmbeddedModel
attr_accessor :name, :order, :type, :master_only, :description,
:formula, :action, :base_attribute_group, :base_attribute_name,
:abbreviation, :table_name, :cost, :prefix, :content, :points,
:total, :images
# Attributes that are not stored in the database
attr_accessor :equipment_modifier, :base_attribute, :unit
# Public: returns the value of the attribute
#
# This method is used to be called on a formula. When an attribute is
# used as a variable, it must provide a value to be used in the math.
#
# Returns a number according to these rules:
#
# * If the attribute has a cost, it will be the attribute value.
# * Else, if there are points on it, the points will be summed up with
# the based attribute value and the modifiers
# * At last, if no rule was matched, it returns the content.
def value
if cost
cost.to_i
elsif points
points.to_i + base_attribute.try(:value).to_i + equipment_modifier.to_i
elsif content
content.to_i
else
points.to_i
end
end
def to_s
"#{points} / #{value}"
end
def to_params(options = {})
params = {
attribute_name: name,
points: points,
value: total || value,
equipment_modifier: equipment_modifier,
type: type
}.merge(options)
params[:base_attribute_group] = base_attribute_group if base_attribute_group.present?
params[:base_attribute_name] = base_attribute_name if base_attribute_name.present?
params
end
private
def nested_attributes
%w(images)
end
end
end
| true |
87f767f3ad26922725d31d37456cea42cc794ce4 | Ruby | kmicinski/micinski-dissertation | /location_privacy/data/scripts/main.rb | UTF-8 | 4,982 | 2.828125 | 3 | [] | no_license | #! /usr/bin/env ruby
require 'rubygems'
require 'optparse'
require 'pathname'
require './dataset'
require './data'
require './applist'
require './plotter'
THIS_FILE = Pathname.new(__FILE__).realpath.to_s
HOME = File.dirname(__FILE__) + "/.."
class Array
# Process each element of an array using a separate process.
# @param [Array<T>] An array to process in a mapped fashion
# @param block A block taking two parameters, the object of the
# array and an index of the pid
# @return [Array<Fixnum>] An array of pids (children).
def process_each
pids = Array.new
self.each do |x|
pids << fork
if !pids[-1]
yield x, pids[-1]
exit
end
end
pids
end
#Sequential implementation
# def process_each
# self.each { |x| yield x; sleep 5}
# []
# end
end
# Main data processor: collects, processes, and plots data from files
# given for selected apps
class MainProcessor
attr_accessor :plot_set_int, :plot_edit_dist, :plot_add_dist, :build_cache
def initialize
@plot_set_int = false
@plot_edit_dist = false
@plot_add_dist = false
end
# Make all plots for an app. Calculate the metric and vary this
# over a set of cutoff points (alpha) from `start` to `max`, varying
# by `inc`
#
# @param app The app which should be plotted
# @param [Fixnum] start The number at which to start plotting
# @param [Fixnum] max The maximum number of data points
# @param [Fixnum] inc The increment for each successive plot
# @param [Symbol] tp The metric to use
def plot_up_to_max(app,tp)
max = app::MAX_ALPHA
start = app::MIN_ALPHA
inc = app::ALPHA_INC
alphas = []
i = start
while (i <= max)
alphas << i
i += inc
end
# Paralleize using `fork`, keeping pids in this array
pids = Array.new
puts "forking a new process for each alpha value"
# Plot for edit distance
alphas.process_each do |alpha|
cl = app.new(HOME+"/"+app::NAME, $cities, Data::SKEWS, i, tp)
cl.alpha = alpha
cl.process()
puts "done plotting"
case tp.to_sym
when :set_int
ylab = "Set intersection size as % of original set size"
when :add_dist
ylab = "Additional distance to destination (km)"
when :edit_dist
ylab = "Edit distance"
end
plotter = Plotter.new("Location trunction (km)", ylab,
Data::APPS_TO_NAMES[cl.name.to_sym],
"location")
plotter.range=(0..i)
cl.plot_medians_across_cities(plotter)
end.each { |x| Process.wait x }
end
# Make all the available plots.
def generate_plots(app)
# Plot edit distances for varying values of alpha
puts "spawning separate processes for each metric"
%w[plot_edit_dist plot_add_dist plot_set_int].process_each{ |x|
if(instance_variable_get("@#{x}")) then
puts "Generating plots for #{app}"
plot_up_to_max(app, x.match(/plot_(.*)/)[1])
end
}.each { |x| Process.wait x }
puts "all metrics done"
end
# Generate plots for each of the apps given in the options list.
#
# @param [Array<String>] apps The set of apps to process.
def process(apps)
apps.each { |app|
puts "Generating plots and data for #{app}"
klass = Kernel.const_get(app.capitalize)
if @build_cache
raise ArgumentException unless klass
cl = klass.new(HOME+"/"+klass::NAME, $cities,
Data::SKEWS, 0, nil, false).build_cache
else
generate_plots(klass)
end
}
end
end
main = MainProcessor.new
apps = []
OptionParser.new do |opts|
opts.banner = "Usage: ruby #{THIS_FILE}"
opts.on("--app app", "the test on which to begin") do |x|
apps = [x]
end
opts.on("--build-cache", "build caches of data") do
main.build_cache = true
end
opts.on("--all-apps") do
apps = ['gasbuddy','restaurant_finder','walmart','tdbank','webmd','hospitals']
end
opts.on("--plot metric", "make plots for `metric`") do |x|
main.instance_variable_set("@plot_#{x.gsub('-','_')}".to_sym, true)
end
opts.on("--all-plots", "plot all metrics") do
main.instance_variables.grep(/plot_/).each { |var|
main.instance_variable_set(var, true)
}
end
opts.on_tail("-h", "--help", "show this message") do
puts opts
exit
end
end.parse!
apps.each do |app|
# Load the set of cities from the dataset
$cities = Hash.new
Dir.glob("../#{app}/**/").each { |dirent|
subdir = dirent.split("/")[-1]
if !(subdir =~ /([a-z_]+)\z/)
next
end
Dir.glob("../#{app}/#{subdir}/**/").each { |s|
sampdir = s.split("/")[-1]
if !(sampdir =~ /[a-z]+_([0-9]+)\z/)
next
end
if ($cities[subdir] == nil) then
$cities[subdir] = Integer($1)
elsif ($cities[subdir] < Integer($1))
$cities[subdir] = Integer($1)
end
}
}
main.process([app])
end
| true |
663fd8143c3b04d9ad0ddd7f632ef2baaa90b81c | Ruby | Steven-Galvin/Contacts | /spec/address_spec.rb | UTF-8 | 3,012 | 3.046875 | 3 | [] | no_license | require "address"
require "rspec"
require "pry"
describe Address do
describe('#street') do
it('returns the street of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.street()).to(eq('123 Test St.'))
end
end
describe('#city') do
it('returns the city of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.city()).to(eq('Portland'))
end
end
describe('#state') do
it('returns the state of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.state()).to(eq('OR'))
end
end
describe('#zipcode') do
it('returns the zipcode of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.zipcode()).to(eq('97236'))
end
end
describe('#type') do
it('returns the type of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.type()).to(eq('Home'))
end
end
describe('#id') do
it('returns the ID of the address') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(test_address.id()).to(eq(1))
end
end
describe('.all') do
it('returns an empty array') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
expect(Address.all()).to(eq([]))
end
end
describe('#save') do
it('adds an address and all attributes to the address array') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
test_address.save
expect(Address.all()).to(eq([test_address]))
end
end
describe('.clear') do
it('returns an empty array') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
test_address.save
expect(Address.clear()).to(eq([]))
end
end
describe('.find') do
it('returns an address by an id number') do
test_address = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
test_address.save
test_address2 = Address.new({:street => '123 Test St.', :city => 'Portland', :state => "OR", :zipcode => "97236", :type => "Home"})
test_address2.save
expect(Address.find(2)).to(eq(test_address2))
end
end
end
| true |
947382ec7f9412c825314ba333bef177601ddb7d | Ruby | nkeszler/Boris-Bikes | /spec/garage_spec.rb | UTF-8 | 640 | 2.953125 | 3 | [] | no_license | require 'garage'
describe Garage do
let(:garage) {Garage.new}
it "Should initialize with a capacity of 200 bikes" do
expect(garage.capacity).to eq(200)
end
it "Should accept all bikes from a van" do
van = Van.new
5.times do
bike = Bike.new
bike.break
van.dock(bike)
end
garage.get_all_broken_bikes(van)
expect(garage.bike_count).to eq(5)
expect(van.bike_count).to eq(0)
end
it "Should fix all broken bikes" do
5.times do
bike = Bike.new
bike.break
garage.dock(bike)
end
garage.fix_bikes
expect(garage.broken_bikes.count).to eq(0)
expect(garage.available_bikes.count).to eq(5)
end
end | true |
7e4bf22805039bc5b15944154a516696eb99591e | Ruby | textmate/ruby.tmbundle | /Support/vendor/rcodetools/test/data/attic/unit_test_rbtest-output.rb | UTF-8 | 79 | 2.703125 | 3 | [
"LicenseRef-scancode-boost-original",
"Ruby",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | =begin test_bar
assert_equal("BAR", bar("bar"))
=end
def bar(s)
s.upcase
end
| true |
726eebc612147bf06c9df4411ae09b18393a603a | Ruby | ashirahattia/cs169-pgm | /app/models/match.rb | UTF-8 | 4,067 | 3.265625 | 3 | [
"MIT"
] | permissive | require 'munkres'
class Match < ActiveRecord::Base
belongs_to :group
belongs_to :project
@@big_number = 999999999999999
def self.generate_preference_list(group)
group_preferences = [group[:first_choice], group[:second_choice],
group[:third_choice], group[:fourth_choice],
group[:fifth_choice], group[:sixth_choice],
group[:seventh_choice]]
return group_preferences
end
# Creates a cost matrix in which each row corresponds to a group and each
# column corresponds to a project. Each cell represents a group's ranking
# for that project, where if a project is not ranked by the group, then
# it is given a cost of 100.
def self.generate_cost_matrix
cost_matrix = Array.new
@all_groups.each do |group|
project_list = self.generate_preference_list(group)
row = Array.new
@all_projects.each do |project|
if project_list.include?(project.id)
rank = project_list.index(project.id) + 1
row << rank
else
row << @@big_number
end
end
cost_matrix << row
end
return cost_matrix
end
# Fill in cost matrix with dummy groups to create an nxn cost matrix
# since there will probably be more projects than groups
def self.fill_dummy_groups(cost_matrix)
num_projects = cost_matrix[0].length
while num_projects > cost_matrix.length
dummy_row = self.make_dummy_arr(num_projects)
cost_matrix << dummy_row
end
return cost_matrix
end
# Helper method for fill_in_dummy_groups
def self.make_dummy_arr(length)
return Array.new(length, @@big_number)
end
# Converts results matrix to matches and filters out dummy groups created
def self.convert_matrix_to_matches(results_matrix)
results_matrix.each do |group_index, project_index|
if group_index < @all_groups.length
Match.create(:group_id => @all_groups[group_index].id, :project_id => @all_projects[project_index].id)
end
end
end
def self.powerize_matrix(matrix, x)
matrix.each do |row|
row.length.times.each do |i|
row[i] **= x
end
end
end
def self.exponentiate_matrix(matrix, x)
matrix.each do |row|
row.length.times.each do |i|
row[i] = x**row[i]
end
end
end
def self.force_matches
groups_to_delete = []
projects_to_delete = []
@all_groups.each do |group|
project = group.force_matched_project
if project
groups_to_delete << group
projects_to_delete << project
Match.create(:group_id => group.id, :project_id => project.id)
end
end
groups_to_delete.each do |group|
@all_groups.delete(group)
end
projects_to_delete.each do |project|
@all_projects.delete(project)
end
end
def self.algorithm(function_type, x)
@all_groups = Group.all.to_a
@all_projects = Project.all.to_a
if (@all_groups.length == 0) or (@all_projects.length == 0) # if it's 0, the page will crash.
return
end
Match.delete_all
self.force_matches # must go before creating cost matrix!
cost_matrix = self.generate_cost_matrix
if function_type == :power
self.powerize_matrix(cost_matrix, x)
elsif function_type == :exponential
self.exponentiate_matrix(cost_matrix, x)
end
cost_matrix = self.fill_dummy_groups(cost_matrix)
m = Munkres.new(cost_matrix)
self.convert_matrix_to_matches(m.find_pairings)
end
end
| true |
da4ad99e70c6f3c0206b1aa9ebdb003c3e0eb68a | Ruby | snoble/relational_streams | /example.rb | UTF-8 | 728 | 2.75 | 3 | [] | no_license | require './relational_stream'
require './relational_event'
require 'redis'
redis = Redis.new
x = InputRStream.new("x", [:a])
x.each! {|n| puts "#{n[:a]} added to x"}
y = x.select {|n| n[:a].even?}
y.each! {|n| puts "#{n[:a]} filtered to y"}
another_x = InputRStream.new("another_x", [:a])
j = x.join(another_x, redis, 'join')
jj = j.select_first(redis, 'select first')
j.each! {|nn| puts "joined #{nn[:right][:b]} from x and another_x on key #{nn[:right][:a]}"}
jj.each! {|nn| puts "first join of key #{nn[:right][:a]} from x and another_x"}
x.push({:a => 2})
.push({:a => 3})
another_x
.push({:a => 3, :b => 3})
.push({:a => 2, :b => 2})
.push({:a => 3, :b => 33})
.push({:a => 4, :b => 4})
x.push({:a => 4})
| true |
0ada2e6b1f0023be134c031ff7e62e985bb7c590 | Ruby | StephenOey/LS_Ruby | /RB 100/Intro_to_Programming_with_Ruby/Flow_Control/true.rb | UTF-8 | 132 | 3.984375 | 4 | [] | no_license |
if a = 5 #this is assigning a value to a rather than checking with ==
puts "how can this be"
else
puts "it is not true"
end | true |
353f6f08c6da881a257358aea9a0ae4023531ad6 | Ruby | hazemosman/germanizer | /db_base.rb | UTF-8 | 2,988 | 2.9375 | 3 | [] | no_license | # TODO Change into active record
require 'sqlite3'
require_relative 'verb'
class DBBase
def initialize
@db = SQLite3::Database.new('dbfile')
@db.results_as_hash = true
end
def drop_tables
puts 'Dropping pronouns table...'
@db.execute 'Drop table if exists pronouns'
@db.execute 'Drop table if exists tenses'
@db.execute 'Drop table if exists verbs'
end
def create_tables
create_pronouns_table
create_tenses_table
create_verbs_table
end
def get_pronouns
@db.execute('Select * from pronouns')
end
def insert_veb(verb)
@db.execute(%q{Insert into verbs(tense_id, infinitive, ich, du, er, sie_she, es, wir, ihr, sie, sie_formal)
values(?,?,?,?,?,?,?,?,?,?,?)},
verb.tense_id, verb.infinitive, verb.ich, verb.du, verb.er, verb.sie_she, verb.es, verb.wir, verb.ihr, verb.sie, verb.sie_formal)
end
def get_tenses
return @db.execute %q{
Select * from tenses
}
end
# Private Methods
private
def create_pronouns_table
puts 'Creating pronouns table...'
@db.execute %q{
Create table pronouns (
id integer primary key Autoincrement,
description varchar(50),
nominative varchar(10),
accusative varchar(10),
dative varchar(10)
)
}
i = 0
sql = 'Insert into pronouns(description,nominative,accusative,dative) values('
puts 'Inserting pronouns...'
@db.execute"#{sql}'I','ich','mich','mir')"
@db.execute"#{sql}'you (informal)','du','dich','dir')"
@db.execute"#{sql}'he','er','ihn','ihm')"
@db.execute"#{sql}'she','sie','sie','ihr')"
@db.execute"#{sql}'it','es','es','ihm')"
@db.execute"#{sql}'we','wir','uns','uns')"
@db.execute"#{sql}'you (all)','ihr','euch','euch')"
@db.execute"#{sql}'they','sie','sie','ihnen')"
@db.execute"#{sql}'you (formal)','Sie','Sie','Ihnen')"
end
def create_tenses_table
puts 'Creating tenses table...'
@db.execute %q{
Create table tenses (
id integer primary key Autoincrement,
description varchar(10),
tense varchar(10)
)
}
i = 0
sql = "Insert into tenses(description,tense) values("
puts 'Inserting tenses...'
@db.execute"#{sql}'present','Präsens')"
@db.execute"#{sql}'preterite', 'Imperfekt, Präteritum')"
@db.execute"#{sql}'perfect','Perfekt')"
@db.execute"#{sql}'past perfect','Plusquamperfekt')"
@db.execute"#{sql}'future','Futur I')"
@db.execute"#{sql}'future perfect','Futur II')"
end
def create_verbs_table
puts 'Creating verbs table...'
@db.execute %q{
Create table verbs (
id integer primary key Autoincrement,
tense_id integer,
infinitive varchar(20),
ich varchar(20),
du varchar(20),
er varchar(20),
sie_she varchar(20),
es varchar(20),
wir varchar(20),
ihr varchar(20),
sie varchar(20),
sie_formal varchar(20),
foreign key(tense_id) references tenses(id)
)
}
end
end | true |
267e8a023c78c65bd229f51f75bf7406f6cfb54c | Ruby | nbdavies/phase-0 | /week-4/errors.rb | UTF-8 | 8,558 | 4.4375 | 4 | [
"MIT"
] | permissive | # Analyze the Errors
# I worked on this challenge by myself.
# I spent [#] hours on this challenge.
# --- error -------------------------------------------------------
cartmans_phrase = "Screw you guys " + "I'm going home."
# This error was analyzed in the README file.
# --- error -------------------------------------------------------
def cartman_hates(thing)
while true
puts "What's there to hate about #{thing}?"
end
end
# This is a tricky error. The line number may throw you off.
# 1. What is the name of the file with the error?
# errors.rb
# 2. What is the line number where the error occurs?
# 170
# 3. What is the type of error message?
# syntax error
# 4. What additional information does the interpreter provide about this type of error?
# unexpected end-of-input, expecting keyword_end
# Write your reflection below as a comment.
# 5. Where is the error in the code?
# The method cartman_hates opens a WHILE loop, but then doesn't have a corresponding END command. To the interpreter, this means that the method itself doesn't have an end, and realizes something's wrong when it reaches the end of the file without ever finding the END.
# 6. Why did the interpreter give you this error?
# "end" on line 16 is treated as the end of the while loop, rather than the end of the method, since the interpreter doesn't interpret indentation as being meaningful.
# --- error -------------------------------------------------------
# south_park
# 1. What is the line number where the error occurs?
# 37
# 2. What is the type of error message?
# Name Error
# 3. What additional information does the interpreter provide about this type of error?
# undefined local variable or method `south_park' for main:Object (NameError)
# 4. Where is the error in the code?
# south_park hasn't been defined as a method or as a variable.
# 5. Why did the interpreter give you this error?
# When we reference south_park without assigning it a class or defining it, or setting its value, Ruby doesn't know what to do with it.
# --- error -------------------------------------------------------
# cartman()
# 1. What is the line number where the error occurs?
# 52
# 2. What is the type of error message?
# NoMethodError
# 3. What additional information does the interpreter provide about this type of error?
# undefined method `cartman' for main:Object
# 4. Where is the error in the code?
# Based on the parentheses, Ruby thinks we are trying to call a method called cartman. But we haven't defined that method anywhere.
# 5. Why did the interpreter give you this error?
# For anything that we're trying to use as a method, the interpreter would try to find the corresponding definition of that method, and if it can't find one, that's a problem. This is like the previous error, except in this case there's a little more context telling Ruby that what's missing is a method in particular.
# --- error -------------------------------------------------------
def cartmans_phrase (you_hate_kyle)
puts "I'm not fat; I'm big-boned!"
end
cartmans_phrase('I hate Kyle')
# 1. What is the line number where the error occurs?
# 67
# 2. What is the type of error message?
# ArgumentError
# 3. What additional information does the interpreter provide about this type of error?
# in `cartmans_phrase': wrong number of arguments (1 for 0)
# 4. Where is the error in the code?
# On line 71, the code is calling method cartmans_phrase with an argument of 'I hate Kyle', but that method doesn't have an argment defined.
# 5. Why did the interpreter give you this error?
# In general, the number of arguments passed into a method can't differ from what it is written to accept. That can get fuzzy with optional arguments and sponge arguments.
# --- error -------------------------------------------------------
def cartman_says(offensive_message)
puts offensive_message
end
cartman_says("I hate Kyle")
# 1. What is the line number where the error occurs?
# 86
# 2. What is the type of error message?
# ArgumentError
# 3. What additional information does the interpreter provide about this type of error?
# in `cartman_says': wrong number of arguments (0 for 1)
# 4. Where is the error in the code?
# This is the opposite of the example above. The method cartman_says is expecting an argument, and it was called without one.
# 5. Why did the interpreter give you this error?
# The number of arguments passed in needs to match the number of arguments that the method expects. (With some exceptions I noted above.)
# --- error -------------------------------------------------------
def cartmans_lie(lie, name='Kylie Minogue')
puts "#{lie}, #{name}!"
end
cartmans_lie('A meteor the size of the earth is about to hit Wyoming!')
# 1. What is the line number where the error occurs?
# 105
# 2. What is the type of error message?
# ArgumentError
# 3. What additional information does the interpreter provide about this type of error?
# in `cartmans_lie': wrong number of arguments (1 for 2)
# 4. Where is the error in the code?
# When calling method cartmans_lie on line 109, only one argument is passed in, while the method expects two.
# 5. Why did the interpreter give you this error?
# The number of arguments passed in needs to match the number of arguments the method expects.
# --- error -------------------------------------------------------
"Respect my authoritay!" * 5
# 1. What is the line number where the error occurs?
# 124
# 2. What is the type of error message?
# TypeError
# 3. What additional information does the interpreter provide about this type of error?
# String can't be coerced into Fixnum
# 4. Where is the error in the code?
# We're starting with an integer 5, and multiplying it by...a string??
# 5. Why did the interpreter give you this error?
# If the interpreter knew how to turn "Respect my authoritay" into a number, than it could have completed the multiplication. But it doesn't know how to do that. This would work written the other way around though, which I'll do instead.
# --- error -------------------------------------------------------
amount_of_kfc_left = 20/0.1
# 1. What is the line number where the error occurs?
# 139
# 2. What is the type of error message?
# ZeroDivisionError
# 3. What additional information does the interpreter provide about this type of error?
# divided by 0
# 4. Where is the error in the code?
# The code was attempting to divide a number by zero, which mathematically speaking would be infinity.
# 5. Why did the interpreter give you this error?
# Fortunately, the interpreter knows better than to try to calculate infinity, and returns an error instead.
# --- error -------------------------------------------------------
# require_relative "cartmans_essay.md"
# 1. What is the line number where the error occurs?
# 155
# 2. What is the type of error message?
# LoadError
# 3. What additional information does the interpreter provide about this type of error?
# in `require_relative': cannot load such file -- /Users/ndavies/phase-0/week-4/cartmans_essay.md
# 4. Where is the error in the code?
# The code is telling Ruby to load file "cartmans_essay.md", which doesn't exist where it's expected to be (on my PC, in the same directory as errors.rb).
# 5. Why did the interpreter give you this error?
# The code is telling Ruby to load a file that doesn't exist.
# --- REFLECTION -------------------------------------------------------
# Write your reflection below as a comment.
=begin
Which error was the most difficult to read?
The one where the root cause of the error wasn't on the line number in the error message was the most challenging to figure out.
How did you figure out what the issue with the error was?
I had a sense that the line number in the error message was only relevant because it was the last line of code in the file. That got me looking at whether there were any methods in the file missing an end statement.
Were you able to determine why each error message happened based on the code?
Yes! They were mostly pretty intuitive.
When you encounter errors in your future code, what process will you follow to help you debug?
I would do a couple things:
Start by looking at the line number indicated. That may not always be the right place to look but it's a safer assumption than trying to spot-check the entire file.
Take the standard error message, and if it's not familiar, google it to try to find other examples of code that caused that error. That would give me a better idea of what problem I should look for in my own code.
=end | true |
7d4d2e8b5fcf33af4fef68a742baff8de5f0a2cb | Ruby | atruby-team/internship-18-summer | /at-tanvo/Exercise1.rb | UTF-8 | 381 | 3.4375 | 3 | [] | no_license | add = ->(*arr) { arr.inject { |i, y| i + y } }
sub1 = ->(*arr) { arr.inject { |i, y| i - y } }
multi = ->(*arr) { arr.inject { |i, y| i * y } }
div = lambda { |*arr|
if arr.slice(1, arr.length).include? 0
'Khong chia duoc'
else
arr.inject { |i, y| i / y }
end
}
puts add.call(5, 4, 3, 4, 5, 6, 7)
puts sub1.call(9, 4, 5)
puts multi.call(5, 4)
puts div.call(20, 5, 2)
| true |
54f277609de4428435a2819349f174fcec67219b | Ruby | stocker5076/capistrano | /Back/first/funcionPares.rb | UTF-8 | 126 | 3.5 | 4 | [] | no_license | def function3
even_numbers =[]
for x in 1..100
even_numbers << x if x.even?
end
puts even_numbers.inspect
end
function3 | true |
3d7749ef9e4d87bde55cbab7740b7bbdaf81ec01 | Ruby | christianotieno/codility | /cyclic_rotation.rb | UTF-8 | 213 | 3.21875 | 3 | [] | no_license | # https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/
def solution(a, k)
# a.rotate(k)
return [] if a.empty?
k.times do
removed_val = a.pop
a.insert(0, removed_val)
end
a
end
| true |
0bf1c64f257bfa1c216bd11278fd22884eba6454 | Ruby | betesh/hanoi | /spec/hanoi_spec.rb | UTF-8 | 792 | 3.15625 | 3 | [
"MIT"
] | permissive | require File.expand_path("../../hanoi", __FILE__)
def expect_invalid_input_error(input, message)
begin
hanoi = Hanoi.new(input)
rescue InvalidInputError => e
e.message.should eq(message)
end
end
describe "invalid inputs" do
it "should raise an error if input is not an Integer" do
expect_invalid_input_error("abc", "ring_count must be a positive integer, not 'abc'!")
end
it "should raise an error if input is a negative Integer" do
expect_invalid_input_error(-3, "ring_count must be a positive integer, not '-3'!")
end
it "should raise an error if input is zero" do
expect_invalid_input_error(0, "ring_count must be a positive integer, not '0'!")
end
end
describe "playing the game" do
it "should play and win" do
Hanoi.new(4).play!
end
end
| true |
c16dbb94f7e8678c7590d42c8fd40cb7fdeb8f61 | Ruby | mahinourElsheikh/ice_cube | /spec/examples/yearly_rule_spec.rb | UTF-8 | 3,960 | 2.890625 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/../spec_helper'
describe IceCube::YearlyRule, 'interval validation' do
it 'converts a string integer to an actual int when using the interval method' do
rule = IceCube::Rule.yearly.interval("2")
expect(rule.validations_for(:interval).first.interval).to eq(2)
end
it 'converts a string integer to an actual int when using the initializer' do
rule = IceCube::Rule.yearly("3")
expect(rule.validations_for(:interval).first.interval).to eq(3)
end
it 'raises an argument error when a bad value is passed' do
expect {
Rule.yearly("invalid")
}.to raise_error(ArgumentError, "'invalid' is not a valid input for interval. Please pass a postive integer.")
end
it 'raises an argument error when a bad value is passed using the interval method' do
expect {
Rule.yearly.interval("invalid")
}.to raise_error(ArgumentError, "'invalid' is not a valid input for interval. Please pass a postive integer.")
end
end
describe IceCube::YearlyRule do
it 'should update previous interval' do
t0 = Time.utc(2013, 5, 1)
rule = Rule.yearly(3)
rule.interval(1)
expect(rule.next_time(t0 + 1, t0, nil)).to eq(t0 + (IceCube::ONE_DAY * 365))
end
it 'should be able to specify complex yearly rules' do
start_time = Time.local(2010, 7, 12, 5, 0, 0)
schedule = IceCube::Schedule.new(start_time)
schedule.add_recurrence_rule IceCube::Rule.yearly.month_of_year(:april).day_of_week(:monday => [1, -1])
one_year = 365 * IceCube::ONE_DAY
expect(schedule.occurrences(start_time + one_year).size).to eq(2)
end
it 'should produce the correct number of days for @interval = 1' do
start_time = Time.now
schedule = IceCube::Schedule.new(start_time)
schedule.add_recurrence_rule IceCube::Rule.yearly
#check assumption
expect(schedule.occurrences(start_time + 370 * IceCube::ONE_DAY).size).to eq(2)
end
it 'should produce the correct number of days for @interval = 2' do
start_time = Time.now
schedule = IceCube::Schedule.new(start_time)
schedule.add_recurrence_rule IceCube::Rule.yearly(2)
#check assumption
expect(schedule.occurrences(start_time + 370 * IceCube::ONE_DAY)).to eq([start_time])
end
it 'should produce the correct days for @interval = 1 when you specify months' do
start_time = Time.utc(2010, 1, 1)
schedule = IceCube::Schedule.new(start_time)
schedule.add_recurrence_rule IceCube::Rule.yearly.month_of_year(:january, :april, :november)
months_of_year = [Time.utc(2010,1,1), Time.utc(2010,4,1), Time.utc(2010,11,1)]
expect(schedule.occurrences(Time.utc(2010, 12, 31))).to eq months_of_year
end
it 'should produce the correct days for @interval = 1 when you specify days' do
start_time = Time.utc(2010, 1, 1)
schedule = IceCube::Schedule.new(start_time)
schedule.add_recurrence_rule IceCube::Rule.yearly.day_of_year(155, 200)
days_of_year = [Time.utc(2010, 6, 4), Time.utc(2010, 7, 19)]
expect(schedule.occurrences(Time.utc(2010, 12, 31))).to eq days_of_year
end
it 'should produce the correct days for @interval = 1 when you specify negative days' do
schedule = IceCube::Schedule.new(Time.utc(2010, 1, 1))
schedule.add_recurrence_rule IceCube::Rule.yearly.day_of_year(100, -1)
days_of_year = [Time.utc(2010, 4, 10), Time.utc(2010, 12, 31)]
expect(schedule.occurrences(Time.utc(2010, 12, 31))).to eq days_of_year
end
it 'should handle negative offset day of year for leap years' do
schedule = IceCube::Schedule.new(Time.utc(2010, 1, 1))
schedule.add_recurrence_rule IceCube::Rule.yearly.day_of_year(-1)
days_of_year = [Time.utc(2010, 12, 31),
Time.utc(2011, 12, 31),
Time.utc(2012, 12, 31),
Time.utc(2013, 12, 31),
Time.utc(2014, 12, 31)]
expect(schedule.occurrences(Time.utc(2014, 12, 31))).to eq days_of_year
end
end
| true |
b2353a43c53cc74219db5e0bc372a0813dc65c5f | Ruby | theoandtheb/CRM | /CRM.rb | UTF-8 | 3,411 | 3.375 | 3 | [] | no_license | require_relative 'contact'
require_relative 'rolodex'
def sleepForSleepsSake
sleep 0.1
end
def intCheck(x,y)
$selectr = gets.chomp.to_i
unless $selectr.between?(x,y)
until $selectr.between?(x,y)
print "\nLet\'s try that again.\n\nEnter a number: "
$selectr = gets.chomp.to_i
end
end
end
class CRM
attr_accessor :name
def initialize(name)
@name = name
@rolodex = Rolodex.new
print "Welcome to #{name}"
sleep 1.4
end
def self.run(name)
crm = CRM.new(name)
crm.mainMenu
crm.selectOption
end
def mainMenu
print "\n\nMAIN MENU\n"
2 * sleepForSleepsSake
print "_______________________________\n\n"
sleepForSleepsSake
print "[1] Add a new contact\n"
sleepForSleepsSake
print "[2] Modify an existing contact\n"
sleepForSleepsSake
print "[3] Delete a contact\n"
sleepForSleepsSake
print "[4] Display all contacts\n"
sleepForSleepsSake
print "[5] Display an attribute\n"
sleepForSleepsSake
print "[6] Exit\n\n"
end
def selectOption
sleep 0.6
print "Please enter the number from the list above and press enter."
sleep 0.8
print " I'll wait."
3.times { sleepForSleepsSake }
print " => "
intCheck(1,6)
selectr = $selectr
call_option(selectr)
end
def call_option(selectr)
5.times { sleepForSleepsSake }
puts "\e[H\e[2J"
case $selectr
when 1
addNewContact
when 2
modifyContact
when 3
deleteContact
when 4
displayContacts
when 5
displayAttribute
when 6
return
end
end
def addNewContact
print "ADDING A NEW CONTACT\n______________\n\n"
5.times { sleepForSleepsSake }
print "Enter First Name: "
first_name = gets.chomp
sleepForSleepsSake
print "\n\nEnter Last Name: "
last_name = gets.chomp
sleepForSleepsSake
print "\n\nEnter Email Address: "
email = gets.chomp
unless email.include? "@"
print "\n\nPlease Enter Valid Email Address: "
email = gets.chomp
end
sleepForSleepsSake
print "\n\nEnter a Note: "
note = gets.chomp
contact = Contact.new(first_name, last_name, email, note)
@rolodex.addContact(contact)
4.times { sleepForSleepsSake }
print "\n\nAdding contact and returning to the main menu. "
6.times { sleepForSleepsSake }
print "Please wait."
3.times { sleepForSleepsSake }
print "\n\nProcessing"
sleep (rand/5)
print "."
sleep (rand/5)
print "."
sleep (rand/5)
print "."
sleep (2*rand)
print "."
sleep (3*rand)
print "."
sleep (rand/20)
print "."
sleep (rand/20)
print "."
4.times { sleepForSleepsSake }
puts "\e[H\e[2J"
mainMenu
selectOption
end
def findUser
print "\nPlease specify the contact ID would you like to address: "
modId = gets.chomp.to_i
unless modId >= 1000
until modId >= 1000
"\nLet\'s try that again.\n\nEnter the contact ID of the contact you wish to modify: : "
modId = gets.chomp.to_i
end
end
modId
end
def modifyContact
modId = findUser
@rolodex.modify(modId)
mainMenu
selectOption
end
def deleteContact
modId = findUser
@rolodex.delete(modId)
mainMenu
selectOption
end
def displayContacts
@rolodex.displayContacts
mainMenu
selectOption
end
def displayAttribute
@rolodex.displayAttribute
mainMenu
selectOption
end
end
puts "\e[H\e[2J"
sleep 1
CRM.run("G.U.S.S.") | true |
2a39b60f1ade656d4b48e8e47be1b9369fe2654d | Ruby | tomofumi-run/cherry_book | /lib/4章/4.7.14.rb | UTF-8 | 257 | 3.578125 | 4 | [] | no_license | #ミュータブル(変更可),イミュータブル(変更不可)=integer,float,symbol,true,false,nilなど
#[]や<<を使った文字列の操作
a = 'abcde'
a[2] #c
a[1,3] #bcd
a[-1] #e
a[0] = 'x' #'xbcde'
a[1,3] = 'y' #'xye'
a << 'pqr' #'xyepqr' | true |
7b56f621d5f8753439e95bed231bd4f37c1c3cf2 | Ruby | nvdai2401/metaprogramming-ruby-2 | /class_definitions/singleton_class.rb | UTF-8 | 325 | 2.875 | 3 | [] | no_license | an_object = Object.new
singleton_class = class << an_object
self
end
def an_object.my_singleton_method; end
p singleton_class.class
p singleton_class.singleton_class
p singleton_class.singleton_class.superclass
p singleton_class.singleton_class.ancestors
p singleton_class.instance_methods.grep(/my_/)
| true |
95d7fd5c99aa78c45943238f532b49636a187a1f | Ruby | dvc94ch/go2nix | /lib/go2nix.rb | UTF-8 | 3,355 | 2.53125 | 3 | [] | no_license | require 'go2nix/go'
require 'go2nix/revision'
require 'go2nix/vcs'
require 'erubis'
require 'go2nix/nix'
require 'set'
module Go2nix
TEMPLATE_PATH = File.expand_path("../nix.erb", __FILE__)
def self.snapshot(gopath, tags, til, imports, revs=[], processed_imports=Set.new)
imports.each do |import|
next if Go::Package.standard?(import)
repo_root = Go::RepoRoot.from_import(import)
next if repo_root.nil?
vcs = repo_root.vcs
root = repo_root.root
repo = repo_root.repo
src = File.join(gopath, "src", root)
if processed_imports.include?(import)
next
else
processed_imports << import
end
puts root
system("GOPATH=#{gopath.shellescape} go get #{import.shellescape} 2>/dev/null")
rev = nil
if til.nil?
rev = vcs.current_rev(src)
else
rev = vcs.find_revision(src, til)
vcs.tag_sync(src, rev)
end
date = vcs.revision_date(src, rev)
puts " rev: #{rev}"
puts " date: #{date}"
puts ""
doc = Go::Package.from_import(gopath, root, tags).first.doc
pkgs = Go::Package.from_import(gopath, "#{root}...", tags)
new_imports = Go::Package.all_imports(pkgs)
deps = deps_from_imports(new_imports)
deps.delete(root)
revs << Revision.new(
:root => root,
:repo => repo,
:doc => doc,
:rev => rev,
:vcs => vcs.cmd,
:deps => deps
)
snapshot(gopath, tags, til, deps, revs, processed_imports)
end
revs
end
def self.deps_from_imports(imports)
deps = []
imports.each do |import|
next if Go::Package.standard?(import)
repo_root = Go::RepoRoot.from_import(import)
next if repo_root.nil?
deps << repo_root.root
end
deps.uniq!
deps.sort!
end
def self.render_nix(revisions)
NixRenderer.render(revisions)
end
class NixRenderer
attr_reader :revisions
def self.render(revisions)
new(revisions).render
end
def initialize(revisions)
@revisions = revisions
end
def render
template = File.open(TEMPLATE_PATH, &:read)
renderer = Erubis::Eruby.new(template)
renderer.result(binding)
end
private
def usesGit?
revisions.any? {|rev| rev.vcs == "git" && !rev.root.start_with?("github.com") }
end
def fetchers
fetchers = []
if revisions.any? {|rev| rev.root.start_with?("github.com") }
fetchers << "fetchFromGitHub"
end
if revisions.any? {|rev| rev.vcs == "git" && !rev.root.start_with?("github.com") }
fetchers << "fetchgit"
end
if revisions.any? {|rev| rev.vcs == "hg" }
fetchers << "fetchhg"
end
if revisions.any? {|rev| rev.vcs == "bzr" }
fetchers << "fetchbzr"
end
fetchers
end
def sha256(rev)
if rev.root.start_with?("github.com")
Nix.prefetch_github(owner(rev), repo(rev), rev.rev)
elsif rev.vcs == "git"
Nix.prefetch_git(rev.repo, rev.rev)
elsif rev.vcs == "hg"
Nix.prefetch_hg(rev.repo, rev.rev)
elsif rev.vcs == "bzr"
Nix.prefetch_bzr(rev.repo, rev.rev)
end
end
def owner(rev)
rev.root.split("/")[1]
end
def repo(rev)
rev.root.split("/")[2]
end
end
end
| true |
58d29d9edccc299bfb97dff3606913852fda0cb5 | Ruby | vyklimavicius/cartoon-collections-dumbo-web-career-021819 | /cartoon_collections.rb | UTF-8 | 412 | 3.328125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | def roll_call_dwarves(array)
array.each_with_index do |name,idx|
puts "#{idx+1} #{name}"
end
end
def summon_captain_planet(array)
array.collect do |ele|
ele.capitalize << "!"
end
end
def long_planeteer_calls(array)
array.any? do |word|
word.length > 4
end
end
def find_the_cheese(array)
array.find do |word|
word == "cheddar" || word == "gouda" || word == "camembert"
end
end
| true |
da96d4daf59b78594e9fb6a855f74ff0eb0c830f | Ruby | Account-onmi-2xplanet/rails-mister-cocktail | /app/controllers/cocktails_controller.rb | UTF-8 | 1,358 | 2.8125 | 3 | [] | no_license | class CocktailsController < ApplicationController
def index
@cocktails = Cocktail.all
@phrases = ["Frank Sinatra said, 'Alcohol may be man's worst enemy, but the Bible says love your enemy.'",
"Irish Quote:'When we drink, we get drunk. When we get drunk, we fall asleep. When we fall asleep, we commit no sin. When we commit no sin, we go to Heaven. So, let's all get drunk and go to heaven.'",
"Irish Quote:'What butter or whiskey does not cure cannot be cured.'",
"Irish Quote:'May you always have a clean shirt, A clear conscience,And enough coins in your pocket to buy a pint.'",
"Sergei Lukyanenko: 'It's about waking up in the morning with everything around you looking gray. Gray sky, gray sun, gray city, gray people, gray thoughts. And the only way out is to have another drink. Then you feel better. Then the colors come back.'"
].sample
end
def show
@cocktail = Cocktail.find(params[:id])
end
def new
@cocktail = Cocktail.new
end
def create
@cocktail = Cocktail.new(cocktail_params)
@cocktail.save
# no need for app/views/cocktails/create.html.erb
redirect_to cocktail_path(@cocktail)
end
private
def cocktail_params
params.require(:cocktail).permit(:name, :photo)
end
end
| true |
b284b40defcbad3324a22c18543de2f4e432f699 | Ruby | walidwahed/ls | /120-oop/lesson_4-exercises/easy2/05.rb | UTF-8 | 392 | 3.984375 | 4 | [] | no_license | # Question 5
# There are a number of variables listed below. What are the different types and how do you know which is which?
excited_dog = "excited dog" # local variable
@excited_dog = "excited dog" # instance variable
@@excited_dog = "excited dog" # class variable
# You know which is which by the '@'s prefixed to the variable name. One is an instance variable, two is a class variable. | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.