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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1b949e901b629f30c235f2370e9aad73cf6df738 | Ruby | glecklernola/ruby | /loop.rb | UTF-8 | 489 | 3.859375 | 4 | [] | no_license | puts "1 bird on a wire - ha ha ha!"
# for n in 2...100
# puts "#{n} birds on a wire - ha ha ha!"
# end
# 5.times do |i|
# puts "#{i + 2} birds on a wire - ha ha ha!"
# end
# 3. times do
# puts "She loves me, yeah yeah yeah!"
# end
# 2.upto(10) { |n| puts "#[n} birds on a wire - ha ha ha }
x=2
# while x is < 10
# puts "#{x} birds on a wire - ha ha ha!"
# x = x + 1
# # x +=1
# until x == 10
# puts "#{x} birds on a wire - ha ha ha!"
# x += 1
end
| true |
4a2fc3abbe617ec4aeecbe082ac5eef079cfc1df | Ruby | wilsonokibe/BasicRuby | /name_raise/bin/main.rb | UTF-8 | 280 | 3.59375 | 4 | [] | no_license | require_relative '../lib/name.rb'
begin
puts "Enter firstname"
firstname = gets.chomp
puts "Enter lastname"
lastname = gets.chomp
name = Name.new(firstname, lastname)
puts "Your name is: #{name.names}"
rescue NameException => detail
puts "#{detail.message}"
end
| true |
b7e7937767356ac24668912df932bdc0c6d7a9fc | Ruby | rdblakemore/linguistics | /lib/linguistics.rb | UTF-8 | 6,355 | 2.609375 | 3 | [] | no_license | #!/usr/bin/ruby
# coding: utf-8
require 'loggability'
# An interface for extending core Ruby classes with natural-language methods.
module Linguistics
extend Loggability
Loggability.level = 0
# Loggability API -- set up a logger for Linguistics objects
log_as :linguistics
# Release version
VERSION = '2.0.4'
# VCS version
REVISION = %q$Revision$
# The list of Classes to add linguistic behaviours to.
DEFAULT_EXT_CLASSES = [ String, Numeric, Array ]
vvec = lambda {|version| version.split('.').collect {|v| v.to_i }.pack('N*') }
abort "This version of Linguistics requires Ruby 1.9.2 or greater." unless
vvec[RUBY_VERSION] >= vvec['1.9.2']
require 'linguistics/monkeypatches'
require 'linguistics/iso639'
require 'linguistics/inflector'
include Linguistics::ISO639
### Language modules and the inflector classes that act as their interfaces
@languages = {}
@inflector_mixins = {}
class << self
# The Hash of loaded languages keyed by 3-letter bibliographic ISO639-2 code
attr_reader :languages
# The Hash of anonymous inflector modules that act as the mixin interface to
# a language module's inflector, keyed by the language module they belong to
attr_reader :inflector_mixins
end
### Return the library's version string
def self::version_string( include_buildnum=false )
vstring = "%s %s" % [ self.name, VERSION ]
vstring << " (build %s)" % [ REVISION[/: ([[:xdigit:]]+)/, 1] || '0' ] if include_buildnum
return vstring
end
### Register a module as providing linguistic functions for the specified +language+ (a two-
### or three-letter ISO639-2 language codes as a Symbol)
def self::register_language( language, mod )
language_entry = LANGUAGE_CODES[ language.to_sym ] or
raise "Unknown ISO639-2 language code '#{language}'"
self.log.info "Registering %s for language %p" % [ mod, language_entry ]
language_entry[:codes].each do |lang|
self.languages[ lang.to_sym ] = mod
end
# Load in plugins for the language
Gem.find_files( "linguistics/#{language}/*.rb" ).each do |extension|
next if extension.include?( '/spec/' ) # Skip specs
extension.sub!( %r{.*/linguistics/}, 'linguistics/' )
self.log.debug " trying to load #{language_entry[:eng_name]} extension %p" % [ extension ]
begin
require extension
rescue LoadError => err
self.log.debug " failed (%s): %s %s" %
[ err.class.name, err.message, err.backtrace.first ]
else
self.log.debug " success."
end
end
end
### Try to load the module that implements the given language, returning
### the Module object if successful.
def self::load_language( lang )
unless mod = self.languages[ lang.to_sym ]
self.log.debug "Trying to load language %p" % [ lang ]
language = LANGUAGE_CODES[ lang.to_sym ] or
raise "Unknown ISO639-2 language code '#{lang}'"
self.log.debug " got language code %p" % [ language ]
# Sort all the codes for the specified language, trying the 2-letter
# versions first in alphabetical order, then the 3-letter ones
msgs = []
mod = nil
language[:codes].sort.each do |code|
next if code == ''
begin
require "linguistics/#{code}"
self.log.debug " loaded linguistics/#{code}!"
mod = self.languages[ lang.to_sym ]
self.log.debug " set mod to %p" % [ mod ]
break
rescue LoadError => err
self.log.error " require of linguistics/#{code} failed: #{err.message}"
msgs << "Tried 'linguistics/#{code}': #{err.message}\n"
end
end
if mod.is_a?( Array )
raise LoadError,
"Failed to load language extension %s:\n%s" %
[ lang, msgs.join ]
end
end
return mod
end
### Add linguistics functions for the specified languages to Ruby's core
### classes. The interface to all linguistic functions for a given language
### is through a method which is the same the language's international 2- or
### 3-letter code (ISO 639). You can also specify a Hash of configuration
### options which control which classes are extended:
###
### [<b>:classes</b>]
### Specify the classes which are to be extended. If this is not specified,
### the Class objects in Linguistics::DEFAULT_EXT_CLASSES (an Array) are
### extended.
### [<b>:monkeypatch</b>]
### Monkeypatch directly (albeit responsibly, via a mixin) the specified
### +classes+ instead of adding a single language-code method.
def self::use( *languages )
config = languages.pop if languages.last.is_a?( Hash )
config ||= {}
classes = Array(config[:classes]) if config[:classes]
classes ||= DEFAULT_EXT_CLASSES
self.log.debug "Extending %d classes with %d language modules." %
[ classes.length, languages.length ]
# Mix the language module for each requested language into each
# specified class
classes.each do |klass|
self.log.debug " extending %p" % [ klass ]
languages.each do |lang|
mod = load_language( lang ) or
raise LoadError, "failed to load a language extension for %p" % [ lang ]
self.log.debug " using %s language module: %p" % [ lang, mod ]
if config[:monkeypatch]
klass.send( :include, mod )
else
inflector = make_inflector_mixin( lang, mod )
self.log.debug " made an inflector mixin: %p" % [ inflector ]
klass.send( :include, inflector )
end
end
end
return classes
end
### Create a mixin module/class pair that act as the per-object interface to
### the given language +mod+'s inflector.
def self::make_inflector_mixin( lang, mod )
language = LANGUAGE_CODES[ lang.to_sym ] or
raise "Unknown ISO639-2 language code '#{lang}'"
unless mixin = self.inflector_mixins[ mod ]
self.log.debug "Making an inflector mixin for %p" % [ mod ]
bibcode, alpha2code, termcode = *language[:codes]
inflector = Class.new( Linguistics::Inflector ) { include(mod) }
self.log.debug " created inflector class %p for [%p, %p, %p]" %
[ inflector, bibcode, termcode, alpha2code ]
mixin = Module.new do
define_method( bibcode ) do
inflector.new( bibcode, self )
end
alias_method termcode, bibcode unless termcode.nil? || termcode.empty?
alias_method alpha2code, bibcode unless alpha2code.nil? || alpha2code.empty?
end
self.inflector_mixins[ mod ] = mixin
end
return mixin
end
end # module Linguistics
Loggability.level = 0
| true |
fdcebf1c56238c0c8dc2665a85c1d94c4695346e | Ruby | krypt/FuzzBert | /spec/test_spec.rb | UTF-8 | 511 | 2.703125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'rspec'
require 'fuzzbert'
describe FuzzBert::Test do
describe "new" do
it "takes a mandatory proc argument" do
-> { FuzzBert::Test.new }.should raise_error
FuzzBert::Test.new( lambda { |data| data }).should be_an_instance_of(FuzzBert::Test)
end
end
describe "#run" do
it "executes the block passed on creation with the data passed to it" do
value = "test"
t = FuzzBert::Test.new( lambda { |data| data })
t.run(value).should == value
end
end
end
| true |
f2fd62eecd21b33bde85a42f8a4d9ba88367ec98 | Ruby | xiy/os-client-tools | /express/spec/rhc/helpers_spec.rb | UTF-8 | 4,428 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
require 'rhc/helpers'
require 'rhc/core_ext'
require 'highline/import'
require 'rhc/config'
describe RHC::Helpers do
before(:each) do
mock_terminal
RHC::Config.initialize
@tests = HelperTests.new()
end
subject do
Class.new(Object) do
include RHC::Helpers
end.new
end
its(:openshift_server) { should == 'openshift.redhat.com' }
context 'with LIBRA_SERVER environment variable' do
before do
ENV['LIBRA_SERVER'] = 'test.com'
# need to reinit config to pick up env var
RHC::Config.initialize
end
its(:openshift_server) { should == 'test.com' }
after { ENV['LIBRA_SERVER'] = nil }
end
context "Formatter" do
it "should print out a section without any line breaks" do
@tests.section_no_breaks
$terminal.read.should == "section 1 "
end
it "should print out a section with trailing line break" do
@tests.section_one_break
$terminal.read.should == "section 1\n"
end
it "should print out 2 sections with matching bottom and top margins generating one space between" do
@tests.sections_equal_bottom_top
$terminal.read.should == "section 1\n\nsection 2\n"
end
it "should print out 2 sections with larger bottom margin generating two spaces between" do
@tests.sections_larger_bottom
$terminal.read.should == "section 1\n\n\nsection 2\n"
end
it "should print out 2 sections with larger top margin generating two spaces between" do
@tests.sections_larger_top
$terminal.read.should == "section 1\n\n\nsection 2\n"
end
it "should print out 4 sections with the middle two on the same line and a space between the lines" do
@tests.sections_four_on_three_lines
$terminal.read.should == "section 1\n\nsection 2 section 3\n\nsection 4\n"
end
it "should show the equivilance of paragaph to section(:top => 1, :bottom => 1)" do
@tests.section_1_1
section_1_1 = $terminal.read
@tests.reset
@tests.section_paragraph
paragraph = $terminal.read
section_1_1.should == paragraph
@tests.reset
@tests.section_1_1
@tests.section_paragraph
$terminal.read.should == "\nsection\n\nsection\n\n"
end
it "should show two line with one space between even though an outside newline was printed" do
@tests.outside_newline
$terminal.read.should == "section 1\n\nsection 2\n"
end
end
class HelperTests
include RHC::Helpers
def initialize
@print_num = 0
end
def next_print_num
@print_num += 1
end
def output
say "section #{next_print_num}"
end
def output_no_breaks
say "section #{next_print_num} "
end
def section_no_breaks
section { output_no_breaks }
end
def section_one_break
section { output }
end
def sections_equal_bottom_top
section(:bottom => 1) { output }
section(:top => 1) { output }
end
def sections_larger_bottom
section(:bottom => 2) { output }
section(:top => 1) { output }
end
def sections_larger_top
section(:bottom => 1) { output }
section(:top => 2) { output }
end
def sections_four_on_three_lines
section { output }
section(:top => 1) { output_no_breaks }
section(:bottom => 1) { output }
section(:top => 1) { output }
end
def outside_newline
section(:bottom => -1) { output }
say "\n"
section(:top => 1) { output }
end
def section_1_1
section(:top => 1, :bottom => 1) { say "section" }
end
def section_paragraph
paragraph { say "section" }
end
# call section without output to reset spacing to 0
def reset
section {}
end
end
end
describe Object do
context 'present?' do
specify('nil') { nil.present?.should be_false }
specify('empty array') { [].present?.should be_false }
specify('array') { [1].present?.should be_true }
specify('string') { 'a'.present?.should be_true }
specify('empty string') { ''.present?.should be_false }
end
context 'blank?' do
specify('nil') { nil.blank?.should be_true }
specify('empty array') { [].blank?.should be_true }
specify('array') { [1].blank?.should be_false }
specify('string') { 'a'.blank?.should be_false }
specify('empty string') { ''.blank?.should be_true }
end
end
| true |
61d46151f5258e8ae2c9a89f8153e7611ad3b152 | Ruby | ivanacorovic/recommender | /app/helpers/application_helper.rb | UTF-8 | 2,107 | 2.703125 | 3 | [] | no_license | module ApplicationHelper
def sign(x)
if x == 0
return 0
else
if x < 0
return -1
else return 1
end
end
end
def entropy(elements)
sum = 0.0
elements.each do |element|
sum += element
end
result = 0.0
elements.each do |x|
zeroFlag = (x == 0 ? 1 : 0)
result += x * Math.log((x + zeroFlag) / sum)
end
return -result
end
def logLikelihoodRatio(k11, k12, k21, k22)
rowEntropy = entropy([k11, k12]) + entropy([k21, k22])
columnEntropy = entropy([k11, k21]) + entropy([k12, k22])
matrixEntropy = entropy([k11, k12, k21, k22])
return 2 * (matrixEntropy - rowEntropy - columnEntropy)
end
def similarity(summedAggregations, normA, normB, numberOfColumns)
logLikelihood = logLikelihoodRatio(summedAggregations.to_f,
(normA.to_f - summedAggregations),
(normB.to_f - summedAggregations),
(numberOfColumns - normA - normB + summedAggregations).to_f)
return 1.0 - 1.0 / (1.0 + logLikelihood)
end
def nearestN(arr, n=10)
return arr.sort_by { |k| k[:similarity] }.reverse.take(n)
end
def duplicate(arr)
arr.map{ |e| e if arr.count(e) > 1 }
end
def recommend(user, treshold = 0.6)
user_products = user.products.ids
result = []
recommended = Product.all
total = Favorite.count
puts "1"
User.all_except(user).each do |other_user|
other_user_products = other_user.products.ids
common = user_products & other_user_products
sim = similarity(common.size, user_products.size, other_user_products.size, total)
if sim > treshold
result << {user_id: other_user.id, similarity: sim}
end
end
result = nearestN(result)
puts "2, result #{result}"
result.each do |r|
products = User.find(r[:user_id]).products.ids
# products.each do |p|
# recommended << p
# end
puts "products #{products}"
recommended = recommended & products
end
recommended = recommended.uniq - user_products
return recommended.map { |r| Product.find(r).name }
end
end
| true |
b5426b1e684d72890284b231e73c031524cc688f | Ruby | jeffreychuc/aA-projects | /AA Questions/questionfollow.rb | UTF-8 | 1,506 | 2.828125 | 3 | [] | no_license | require_relative 'QuestionsDatabase'
require_relative 'User'
require_relative 'Question'
class QuestionFollow
def initialize(options)
@id = options['id']
@user_id = options['user_id']
@question_id = options['question_id']
end
def self.followers_for_question_id(question_id)
options =
QuestionsDatabase.instance.execute(<<-SQL, question_id)
SELECT
users.id, users.fname, users.lname
FROM
question_follows
JOIN
users ON users.id = question_follows.user_id
WHERE
question_follows.question_id = ?
SQL
options.map {|user_option| User.new(user_option)}
end
def self.followed_questions_for_user_id(user_id)
options =
QuestionsDatabase.instance.execute(<<-SQL, user_id)
SELECT
questions.id, questions.title, questions.body, questions.user_id
FROM
question_follows
JOIN
questions ON questions.id = question_follows.question_id
WHERE
question_follows.user_id = ?
SQL
options.map {|q_op| Question.new(q_op)}
end
def self.most_followed_questions(n)
options =
QuestionsDatabase.instance.execute(<<-SQL, n)
SELECT
questions.id, questions.title, questions.body, questions.user_id
FROM
question_follows
JOIN
questions ON question_follows.question_id = questions.id
GROUP BY
question_follows.question_id
ORDER BY
COUNT(question_follows.user_id) DESC
LIMIT ?
SQL
options.map {|q_op| Question.new(q_op)}
end
end
| true |
38706b68370cfb3ef9c0f508042ab1b8bd0a95c4 | Ruby | pladdy/dijkstra | /bin/dijkstra | UTF-8 | 533 | 3.421875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'dijkstra'
graph = Dijkstra::Graph.new()
# argument 0 is the file path, argument 1 is the first node, argument 2 the
# second node
if ARGV[0]
graph.file_to_graph( ARGV[0] )
else
puts "please supply a file name"
exit
end
if ARGV[1] and ARGV[2]
short_path_data = graph.find_shortest_path( ARGV[1], ARGV[2] )
else
puts "please supply two nodes to find the shortest path between"
exit
end
puts "Shortest path is #{ short_path_data['path'] }" +
" with cost #{ short_path_data['cost'] }"
| true |
b49e831b41b8876bb8e34a491ebf1daf8a686fad | Ruby | Arepo/TDD-Student-directory | /spec/directory2_spec.rb | UTF-8 | 2,845 | 3.625 | 4 | [] | no_license | require 'directory2'
describe 'adding a student to the directory' do
it 'the directory is empty when first used' do
expect(students).to be_empty
end
it 'adds students to the directory' do
add_student('Bob')
expect(students).not_to be_empty
end
it 'checks that the student saved is the student entered' do
add_student('Fred')
expect(@students[0][:name]).to eq 'Fred'
end
it 'assumes students are from may cohort if not specified' do
add_student('James')
expect(students[0][:cohort]).to eq :May
end
it 'accepts a cohort different from the default' do
add_student('James', :November)
expect(students[0][:cohort]).to eq :November
end
it 'assumes the year is 2014 if not specified' do
add_student('James', :February)
expect(students[0][:year]).to eq 2014
end
it 'accepts a year different from the default' do
add_student('James', nil, 2013)
expect(students[0][:year]).to eq 2013
end
end
describe 'it lists students' do
it 'in the following way "Bob (May cohort)"' do
add_student('Bob', :May, 2014)
expect(list_students).to eq "Bob (May cohort, 2014)"
end
it 'having also met Roy' do
add_student('Roy', :November, 2013)
expect(list_students).to eq "Roy (November cohort, 2013)"
end
it 'can list more than one student, Bob and Roy' do
add_student('Roy', :November, 2013)
add_student('Bob', :May, 2014)
expect(list_students).to eq "Roy (November cohort, 2013)\nBob (May cohort, 2014)"
end
end
describe 'pluralises appropriately' do
it 'knows if there are 2 students' do
add_student('Fred')
add_student('Bob')
expect(count_students).to eq 2
end
it 'knows if there is 1 student' do
add_student('Bob')
expect(count_students).to eq 1
end
end
describe 'deleting students' do
it 'deletes students by first name' do
add_student("Steve")
add_student("Bob")
expect(delete_student("Steve")).to eq [{name: "Bob", cohort: :May, year: 2014}]
end
it 'actually deletes students by first name' do
add_student("Steve")
add_student("Bob")
expect(delete_student("Bob")).to eq [{name: "Steve", cohort: :May, year: 2014}]
end
it 'knows to delete May Steve' do
add_student("Steve", :May)
add_student("Steve", :November, 2013)
expect(delete_student("Steve", :May)).to eq [{name: "Steve", cohort: :November, year: 2013}]
end
end
describe 'writing to CSV file' do
# it 'check file called students.csv exists' do
# expect(File.exists?("students.csv")).to be_true
# end
it 'leaves behind a file called students.csv' do
save_student_list
expect(File.exists?("students.csv")).to be_true
end
it 'puts current student list into students.csv' do
add_student("Steve", :May)
add_student("John", :November, 2013)
save_student_list
expect(CSV.readlines("students.csv")).to eq [["Steve", "May", "2014"], ["John", "November", "2013"]]
end
end
| true |
bab45cba93187d92c6cb75ace5d4fce535878bfc | Ruby | l3iodeez/aa_poker | /poker/spec/card_spec.rb | UTF-8 | 340 | 2.71875 | 3 | [] | no_license | require 'card'
describe Card do
let(:five_of_hearts) { Card.new(5, :hearts) }
describe "#value" do
it "returns the value of the card" do
expect(five_of_hearts.value).to eq(5)
end
end
describe "#suit" do
it "returns the suit of the card" do
expect(five_of_hearts.suit).to eq(:hearts)
end
end
end
| true |
787c188480d688693bda5c293d35f85b4e6fb658 | Ruby | godspeedyoo/algorithms-practice | /coursera-algorithms-p1/lib/priority_queue/priority_queue.rb | UTF-8 | 285 | 3.453125 | 3 | [] | no_license | require_relative './lib/heap/max_heap.rb'
class PriorityQueue
def initialize(arr = [], max_size)
@mh = ::MaxHeap.new(arr, max_size)
end
def pop
mh.pop
end
def push(el)
mh.insert(el)
end
def <<(el)
push(el)
end
private
def mh
@mh
end
end
| true |
9c874c51d6a8f2b61b5ba8593fbcade1e40493e7 | Ruby | subeshb1/project-back-end | /app/form_objects/create_user_form.rb | UTF-8 | 768 | 2.515625 | 3 | [] | no_license | # frozen_string_literal: true
class CreateUserForm < FormObjects::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i.freeze
attr_reader :params
def initialize(params = {})
@params = params
super()
end
def validate
validate_email
validate_password
validate_no_user
validate_result
end
private
def validate_email
@errors << error('email', 'must be a valid email pattern') unless
params[:email] =~ VALID_EMAIL_REGEX
end
def validate_no_user
@errors << error('email', 'already taken') if
User.where(email: params[:email]).last
end
def validate_password
@errors << error('password', 'don\'t match') unless
params[:password] == params[:confirm_password]
end
end
| true |
3979e2414f5dedd8c02f38860a452363cf50ccf6 | Ruby | yutoJ/ruby_samples | /test/color/RGBTest.rb | UTF-8 | 607 | 2.890625 | 3 | [] | no_license | require 'minitest/autorun'
require './lib/color/RGB'
class RGBTest < Minitest::Test
def test_hex_s
assert_equal '00', to_hex_rgb(0)
assert_equal 'ff', to_hex_rgb(255)
assert_equal '78', to_hex_rgb(120)
end
def test_hex
assert_equal '#000000', to_hex(0,0,0)
assert_equal '#ffffff', to_hex(255,255,255)
assert_equal '#043c78', to_hex(4,60,120)
end
def test_ints
block = [0,0,0]
white = [255,255,255]
sample = [4,60,120]
assert_equal block, to_ints('#000000')
assert_equal white, to_ints('#ffffff')
assert_equal sample, to_ints('#043c78')
end
end
| true |
41ad175de0028f7e3154021b36a3fb6b521a5d63 | Ruby | richbai90/elastic | /data/rubies/swrequest.rb | UTF-8 | 4,330 | 2.65625 | 3 | [] | no_license | def add_default_keys_to_event(event, keys)
keys.each do |name|
name = "@metadata" if name == "metadata"
name = name.split(".")
name[0] =~ /s$/ ? event.set(name[0], []) : event.set(name[0], {})
end
end
def handle_unamed_cols(message)
i = 1
message["query"].scan(/\w+\(.*?as '?([\w\.]+)'?/) do |name|
skip = false
message["recorddata"].each do |row|
skip = true unless row[name[0]].nil?
next if skip == true
col = row["unnamedcol#{i}"]
col_name = name[0]
row[col_name] = row.delete("unnamedcol#{i}") unless col.nil?
end
i += 1 unless skip == true
end
end
def setup_event(event, message)
handle_unamed_cols(message)
keys = message["recorddata"][0].keys
@object_keys = (keys.each_with_object([]) do |key, obj_keys|
obj_keys << key.to_s.split(".")[0] if key.to_s =~ /.+(\.).+/
end).uniq
@other_keys = keys.reject { |key| key =~ /.+(\.).+/ }
add_default_keys_to_event(event, @object_keys)
end
def format_status(obj)
return obj["value"] unless obj["type"] == "integer"
formatted_value = case obj["value"]
when "1"
"pending"
when "2"
"unassigned"
when "3"
"unaccepted"
when "4"
"on hold"
when "5"
"off hold"
when "6"
"resolved"
when "7"
"deferred"
when "8"
"incoming"
when "9"
"escalated to owner"
when "10"
"escalated to group"
when "11"
"escalated to all"
when "15"
"lost call"
when "16"
"closed"
when "17"
"cancelled"
when "18"
"closed chargable"
else
obj["value"]
end
formatted_value
end
def format(obj, key)
return nil if obj["value"].nil? || obj["value"].empty?
case key
when "status"
return format_status(obj)
when /_on$/
# elastic search expects milli epoch time
return obj["type"] == "integer" ? obj["value"].to_i * 1000 : obj["value"]
else
return obj["type"] == "integer" ? obj["value"].to_i : obj["value"]
end
end
def get_ready_for_evt(obj_to_get_ready)
obj_to_get_ready.each_with_object({}) do |(obj_key, obj_value), ready_obj|
ready_value = format(obj_value, obj_key)
obj_keys = obj_key.split('.')
obj_keys.slice!(0)
obj_keys.each_with_index do |ready_key, index|
unless ready_obj[ready_key].nil?
ready_obj = ready_obj[ready_key]
next
end
unless index == obj_keys.size - 1
ready_obj[ready_key] = {}
ready_obj = ready_obj[ready_key]
next
end
ready_obj[ready_key] = ready_value unless ready_value.nil?
end
end
end
def add_objs_to_event(event, obj)
@object_keys.each do |key|
cols_for_obj = obj.select { |col, _val| col.split(".")[0] == key.split(".")[0] }
ready = get_ready_for_evt(cols_for_obj)
key = "@metadata" if key == "metadata"
ready = event.get(key) << ready if key =~ /s$/ && !ready.empty?
event.set(key, ready) unless ready.empty?
end
end
def add_values_to_event(event, obj)
@other_keys.each do |key|
ready_value = format(obj[key], key)
event.set(key, ready_value) unless ready_value.nil?
end
end
def add_items(event, message)
message["recorddata"].each do |row|
add_objs_to_event(event, row)
add_values_to_event(event, row)
end
end
def cleanup(event)
@object_keys.select { |key| key =~ /s$/ }.each do |key|
cleaned = event.get(key).uniq do |item|
item.each_with_object("") do |(k, v), str|
str << "#{k}:#{v}:"
end
end
event.set(key, cleaned)
end
end
def filter(event)
message = event.get("message")
# we expect recordata to be an array
message["recorddata"] = [message["recorddata"]].flatten
setup_event(event, message)
add_items(event, message)
cleanup(event)
event.remove("message")
[event]
end
| true |
675150b14cc60cb9123ef20965b980a38e3a40fb | Ruby | ThePhD/awesome-black-developers | /action/create-readme.rb | UTF-8 | 2,986 | 2.921875 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-public-domain"
] | permissive | #!/usr/bin/env ruby
#/ Usage: ./action/update-photos
#/ Update the local README photo wall to reflect the current developers listed in
# bdougie/awesome-black-developers.
require "yaml"
class Readme
DEFAULT_README = "README.md"
def initialize(filename: DEFAULT_README)
@filename = filename
@developers = read_developer_yaml.merge(read_temp_file)
end
def read_developer_yaml
file = File.open('developers.yaml')
file_data = file.read
file.close
YAML::load(file_data)
end
def read_temp_file
file = File.open('temp.txt')
handle = ""
links = []
file_data = file.readlines.each_with_index.map do |line, index|
if index == 0
handle =line.gsub("#", "").strip
else
if !line.nil? && !line.strip.empty?
links.push(line.gsub("*", "").strip)
end
end
end
{handle => links}
end
def update_developer_yaml
yaml = @developers.to_yaml
File.write('developers.yaml', yaml)
end
def preview
[
"# Awesome Black Developers [](https://awesome.re)",
"> Talks, blog posts, and interviews amplifying the voices of Black developers on GitHub because #BlackLivesMatter",
build_photo_grid(@developers),
build_developer_list(@developers),
"## 💅🏾 Contributing",
"Additional suggestions are welcomed! Check out [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.",
"(NOTE: If you're a developer listed on here who would like to be removed, just open an issue or message me privately.)",
"## 📖 License and attribution
This list is available under the Creative Commons CC0 1.0 License, meaning you are free to use it for any purpose, commercial or non-commercial, without any attribution back to me (public domain). (If you ever want to reference me, find me here! [@bdougieYO](http://twitter.com/bdougieYO) But you are in no way required to do so.)"
].join("\n\n")
end
def save!
update_developer_yaml
File.write(@filename, preview)
end
end
def build_photo_grid(users)
lines = []
users.map{|k, v| k}.each_slice(6) do |slice|
header = slice.map { |e| handle_link(e) }.join(" | ").strip
delimiter = slice.map { |e| "---" }.join(" | ")
row = slice.map { |e| photo_link(e) }.join(" | ").strip
lines += [header, delimiter, row, ""]
end
lines.join("\n")
end
def build_developer_list(users)
row = users.map do |handle, links|
developer_row = []
developer_row.push("### [@#{handle}](https://github.com/#{handle})")
links.each do |link|
developer_row.push(" * #{link}")
end
developer_row.join("\n")
end
row.join("\n\n")
end
def handle_link(login)
"[@#{login}](##{login})"
end
def photo_link(login)
""
end
def update_readme(save: false)
readme = Readme.new
save ? readme.save! : (puts readme.preview)
end
update_readme(save: true)
| true |
9f409d29ba12caed4a50de318e3a50b8101d6ddc | Ruby | jayshess/RM-academy | /wargame/gf_card.rb | UTF-8 | 507 | 3.28125 | 3 | [] | no_license |
#load '../card.rb'
require_relative 'card.rb'
class GfCard < Card
def initialize (name)
@rank, @suit = name.split
end
attr_reader :rank
def ranks
@@ranks
end
def has_rank?(test_rank)
rank == test_rank
end
def rank_to_num
(ranks.index(rank)+2)
end
def equivalent_to other
return true if self==nil && other == nil
return false if self == nil || other == nil
rank == other.rank && suit == other.suit
end
def to_s
"#{rank} - #{suit}"
end
end | true |
dbd637643a48571d7950ada7b7d5b276417ca54c | Ruby | kimoto-naoki/original_app | /spec/models/user_spec.rb | UTF-8 | 2,192 | 2.546875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー登録機能' do
context 'ユーザー登録できるとき' do
it '全ての項目を正しく入力すれば登録できる' do
expect(@user).to be_valid
end
end
context 'ユーザー登録できないとき' do
it 'player_nameが空では登録できない' do
@user.player_name = ""
@user.valid?
expect(@user.errors.full_messages).to include("Player name can't be blank")
end
it 'passwordが空では登録できない' do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it 'password_confirmationが空では登録できない' do
@user.password_confirmation = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation can't be blank")
end
it 'passwordとpassword_confirmationが一致していないと登録できない' do
@user.password_confirmation = "bbb222"
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it 'passwordは全角文字だと登録できない' do
@user.password = "aaa111"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it 'passwordは数字のみでは登録できない' do
@user.password = "111111"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it 'passwordは英文字のみでは登録できない' do
@user.password = "aaaaaa"
@user.valid?
expect(@user.errors.full_messages).to include("Password is invalid")
end
it 'passwordが5文字以下だと登録できない' do
@user.password = "aa111"
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
end
end
end
| true |
221fe7ede61b7c6fdb03066bb0fe501ddb6aaaea | Ruby | DmitryBochkarev/mem_db | /lib/mem_db/out.rb | UTF-8 | 329 | 2.78125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
class MemDB
class Out
include Enumerable
def initialize
@arr = []
end
def add(res)
@arr.push(res)
true
end
def each(&block)
return to_enum unless block_given?
@arr.each do |values|
values.each(&block)
end
end
end
end
| true |
a3323e2e4a7ed2929ef858f6ebdeb7938a817721 | Ruby | michaelstsnow/reverse-each-word-cb-000 | /reverse_each_word.rb | UTF-8 | 357 | 3.390625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(phrase)
broken_phrase=phrase.split(" ");
final_phrase="";
broken_phrase.each{ |word|
word_r = word.reverse();
final_phrase = "#{final_phrase}#{word_r} ";
}
final_phrase[0...-1]
final_phrase="";
broken_phrase.collect{ |word|
final_phrase = "#{final_phrase}#{word.reverse()} ";
}
final_phrase[0...-1]
end
| true |
054f7f4a1ef79624aa23033eca7fbe8427634c15 | Ruby | agpiermarini/apicurious-github | /app/models/push_event.rb | UTF-8 | 695 | 2.796875 | 3 | [] | no_license | class PushEvent
attr_reader :created_at
def initialize(push_event_info)
@repo_info = push_event_info[:repo]
@payload_info = push_event_info[:payload]
@created_at = push_event_info[:created_at]
end
def repo_name
repo_info[:name].split("/")[1]
end
def commits
generate_commits
end
private
attr_reader :repo_info, :payload_info
def commit_info
payload_info[:commits]
end
def truncate_sha(sha)
sha[0..5]
end
def generate_commits
commit_info.map do | commit |
Commit.new({sha_partial: truncate_sha(commit[:sha]),
message: commit[:message]
})
end
end
end
| true |
0e2977d6d17936e3820c43d769087b1bbe951630 | Ruby | domtunstill/gilded-rose-ruby | /lib/gilded_rose.rb | UTF-8 | 959 | 3.234375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require_relative 'item'
# GildedRose class is the default class and handles the list of items
class GildedRose
def initialize(items, **item_classes)
@items = items
@normal_item = item_classes[:normal_item] || NormalItem
@special_items = {
'Sulfuras, Hand of Ragnaros' => item_classes[:legendary_item] || LegendaryItem,
'Aged Brie' => item_classes[:cheese_item] || CheeseItem,
'Backstage pass' => item_classes[:backstage_pass_item] || BackstagePassItem,
'Conjured' => item_classes[:conjured_item] || ConjuredItem
}
sort_items
end
def update_quality
@items.each(&:update_quality)
end
def sort_items
@items.map! { |item| return_class(item).new(item.name, item.sell_in, item.quality) }
end
private
def return_class(item)
@special_items.each_key { |key| return @special_items[key] if item.name.downcase.include?(key.downcase) }
@normal_item
end
end
| true |
5fa86258197fd4f0a138f3a8127c8e30b6d94117 | Ruby | GKhalsa/coding_exercises | /may_13/ruby/bst.rb | UTF-8 | 747 | 3.703125 | 4 | [] | no_license | require 'pry'
class Bst
attr_accessor :left, :right, :data
def initialize(data)
@data = data
@left = nil
@right = nil
end
def insert(num)
new_link = Bst.new(num)
if num > data
insert_right(new_link, num)
elsif num <= data
insert_left(new_link, num)
end
end
def insert_right(new_link, num)
if right.nil?
@right = new_link
else
right.insert(num)
end
end
def insert_left(new_link, num)
if @left.nil?
@left = new_link
else
left.insert(num)
end
end
def sorted_data
ordered_data = []
ordered_data << left.sorted_data if left
ordered_data << data
ordered_data << right.sorted_data if right
ordered_data.flatten
end
end
| true |
a824a2dccb86dea049e37a53bd70ae6b13802b53 | Ruby | embulk/embulk | /embulk-ruby/lib/embulk/data_source.rb | UTF-8 | 5,772 | 2.578125 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"NAIST-2003",
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"CC-PDDC",
"GPL-1.0-or-later",
"EPL-1.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-other-... | permissive | module Embulk
require 'json'
module Impl
# copied from https://github.com/intridea/hashie/blob/da232547c29673a0d7a79c7bf2670f1ea76813ed/lib/hashie/extensions/indifferent_access.rb
module IndifferentAccess
def self.included(base)
#Hashie::Extensions::Dash::IndifferentAccess::ClassMethods.tap do |extension|
# base.extend(extension) if base <= Hashie::Dash && !base.singleton_class.included_modules.include?(extension)
#end
base.class_eval do
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
alias_method :[]=, :indifferent_writer
alias_method :store, :indifferent_writer
%w(default update replace fetch delete key? values_at).each do |m|
alias_method "regular_#{m}", m unless method_defined?("regular_#{m}")
alias_method m, "indifferent_#{m}"
end
%w(include? member? has_key?).each do |key_alias|
alias_method key_alias, :indifferent_key?
end
class << self
def [](*)
super.convert!
end
def try_convert(*)
(hash = super) && self[hash]
end
end
end
end
def self.inject!(hash)
(class << hash; self; end).send :include, IndifferentAccess
hash.convert!
end
# Injects indifferent access into a duplicate of the hash
# provided. See #inject!
def self.inject(hash)
inject!(hash.dup)
end
def convert_key(key)
key.to_s
end
def convert!
keys.each do |k|
regular_writer convert_key(k), indifferent_value(regular_delete(k))
end
self
end
def indifferent_value(value)
if hash_lacking_indifference?(value)
IndifferentAccess.inject!(value)
elsif value.is_a?(::Array)
value.replace(value.map { |e| indifferent_value(e) })
else
value
end
end
def indifferent_default(key = nil)
return self[convert_key(key)] if key?(key)
regular_default(key)
end
def indifferent_update(other_hash)
return regular_update(other_hash) if hash_with_indifference?(other_hash)
other_hash.each_pair do |k, v|
self[k] = v
end
end
def indifferent_writer(key, value)
regular_writer convert_key(key), indifferent_value(value)
end
def indifferent_fetch(key, *args, &block)
regular_fetch convert_key(key), *args, &block
end
def indifferent_delete(key)
regular_delete convert_key(key)
end
def indifferent_key?(key)
regular_key? convert_key(key)
end
def indifferent_values_at(*indices)
indices.map { |i| self[i] }
end
def indifferent_access?
true
end
def indifferent_replace(other_hash)
(keys - other_hash.keys).each { |key| delete(key) }
other_hash.each { |key, value| self[key] = value }
self
end
protected
def hash_lacking_indifference?(other)
other.is_a?(::Hash) &&
!(other.respond_to?(:indifferent_access?) &&
other.indifferent_access?)
end
def hash_with_indifference?(other)
other.is_a?(::Hash) &&
other.respond_to?(:indifferent_access?) &&
other.indifferent_access?
end
end
end
class DataSource < Hash
include Impl::IndifferentAccess
def initialize(hash={}, default=nil, &block)
if default.nil?
super(&block)
else
super(default)
end
hash.each {|key,value| self[key] = value }
end
def param(key, type, options={})
if self.has_key?(key)
v = self[key]
value =
case type
when :integer
begin
Integer(v)
rescue => e
raise ConfigError.new e
end
when :float
begin
Float(v)
rescue => e
raise ConfigError.new e
end
when :string
begin
String(v).dup
rescue => e
raise ConfigError.new e
end
when :bool
begin
!!v # TODO validation
rescue => e
raise ConfigError.new e
end
when :hash
raise ConfigError.new "Invalid value for :hash" unless v.is_a?(Hash)
DataSource.new.merge!(v)
when :array
raise ConfigError.new "Invalid value for :array" unless v.is_a?(Array)
v.dup
else
unless type.respond_to?(:load)
raise ArgumentError, "Unknown type #{type.to_s.dump}"
end
begin
type.load(v)
rescue => e
raise ConfigError.new e
end
end
elsif options.has_key?(:default)
value = options[:default]
else
raise ConfigError.new "Required field #{key.to_s.dump} is not set"
end
return value
end
def self.from_java(java_data_source_impl)
json = java_data_source_impl.toString
new.merge!(JSON.parse(json))
end
def self.from_ruby_hash(hash)
new.merge!(hash)
end
def to_java
json = to_json
Java::Injected::ModelManager.readObjectAsDataSource(json.to_java)
end
def load_config(task_type)
Java::Injected::ModelManager.readObjectWithConfigSerDe(task_type.java_class, to_json.to_java)
end
def load_task(task_type)
Java::Injected::ModelManager.readObject(task_type.java_class, to_json.to_java)
end
end
end
| true |
98b5a056a8b7bf03512fa573f504c1ab57459693 | Ruby | jamesangie/Programming-Language-Projects | /Big projects/Language with Expresions(Ruby and F#)/a1t3p2-testing.rb | UTF-8 | 4,021 | 3.40625 | 3 | [] | no_license | # coding: utf-8
#---------------------------------------------------------------------
# Assignment 1, Task 3, Part 2
# Testing script
#
# Instructions: this testing script is provided to help ensure
# your program meets the expectations of the assignment.
#
# It will be run with the command
# irb a1t3p2-testing.rb
# Notice that this file imports IBExpr.rb;
# your code for this part must be in that file.
#
# Complete the interface below as instructed,
# and then run and ensure your program passes the provided tests.
#---------------------------------------------------------------------
$LOAD_PATH << '.' # look in the current directory for the require
#---------------------------------------------------------------------
# BEGIN Interface
#
# Instructions: replace instances of nil with appropriate instances
# of your IBExpr type (i.e., objects of your class).
# DO NOT modify any other aspects of this method.
#---------------------------------------------------------------------
module Interface
require 'IBExpr.rb'
# A method to wrap construction of expressions.
# Fill in your methods to construct expressions.
def c(op,subexpr1=nil,subexpr2=nil)
case op
when :const; return IExpr.new().const(subexpr1)
when :neg; return IExpr.new().neg(subexpr1)
when :abs; return IExpr.new().abs(subexpr1)
when :plus; return IExpr.new().plus(subexpr1, subexpr2)
when :times; return IExpr.new().times(subexpr1, subexpr2)
when :minus; return IExpr.new().minus(subexpr1, subexpr2)
when :exp; return IExpr.new().exp(subexpr1, subexpr2)
when :ttt; return IBExpr.new().ttt()
when :fff; return IBExpr.new().fff()
when :lnot; return IBExpr.new().lnot(subexpr1)
when :land; return IBExpr.new().land(subexpr1, subexpr2)
when :lor; return IBExpr.new().lor(subexpr1, subexpr2)
else; raise 'Invalid op argument'
end
end
end
#---------------------------------------------------------------------
# END Interface
#---------------------------------------------------------------------
#---------------------------------------------------------------------
# BEGIN Testing
#
# Instructions: you should use these tests to make certain your
# interpretation method(s) is (are) working as expected.
# You MAY also add additional tests if you wish,
# but note that this section will be replaced with
# a more robust test suite during marking, so your modifications
# will not be used.
#---------------------------------------------------------------------
include Interface # bring the construct method c into scope
# Construct some expressions for testing
begin
two = c(:const, 2)
five = c(:const, 5)
neg_five = c(:neg, c(:const, 5))
plus_neg_five_two = c(:plus,neg_five,two)
ttt = c(:ttt)
fff = c(:fff)
ttt_land_fff = c(:land,ttt,fff)
puts "All expressions constructed without exception."
rescue => e
puts "Exception “#{e.message}” during expression construction."
end
# Test interpretation on the constructed expressions
begin
failed = 0
unless two.interpret == 2 then
puts "two was not 2!"; failed += 1 end
unless five.interpret == 5 then
puts "five was not 5!"; failed += 1 end
unless neg_five.interpret == -5 then
puts "neg 5 was not -5!"; failed += 1 end
unless plus_neg_five_two.interpret == -5 + 2 then
puts "plus neg 5 2 was not -3!"; failed += 1 end
unless ttt.interpret == true then
puts "ttt was not true!"; failed += 1 end
unless fff.interpret == false then
puts "fff was not false!"; failed += 1 end
unless ttt_land_fff.interpret == false then
puts "land ttt fff was not false!"; failed += 1 end
if failed > 0 then
puts "#{failed} interpretation tests failed."
else
puts "All interpretation tests passed."
end
rescue => e
puts "Exception “#{e.message}” during interpretation."
end
#---------------------------------------------------------------------
# END Testing
#---------------------------------------------------------------------
| true |
3df5d71f0483c0fab4de03c58b4151d1eb497ce5 | Ruby | SciMed/topographer | /lib/topographer/importer/strategy/import_status.rb | UTF-8 | 684 | 2.53125 | 3 | [
"MIT"
] | permissive | module Topographer
class Importer
module Strategy
class ImportStatus
attr_reader :errors, :input_identifier, :timestamp
attr_accessor :message
def initialize(input_identifier)
@input_identifier = input_identifier
@errors = {mapping: [],
validation: []}
end
def set_timestamp
@timestamp ||= DateTime.now
end
def add_error(error_source, error)
errors[error_source] << error
end
def error_count
errors.values.flatten.length
end
def errors?
errors.values.flatten.any?
end
end
end
end
end
| true |
e6e9bac5b69caa25148fc6492ed3201d28764280 | Ruby | JustinData/GA-WDI-Work | /w03/d03/Ernie/morning/user.rb | UTF-8 | 270 | 2.84375 | 3 | [] | no_license | require "faker"
require_relative 'user_db'
class User
def initialize(name, id, address, email)
@name = name
@id = id
@address = address
@email = email
end
def to_s
"Name: #{@name} Id: #{@id} Street: #{@address} Email #{@email}"
end
end
| true |
bbc79ae8f5855bca690fc46d45c1ea1f6aa8b607 | Ruby | Fatheadedbaby/Ruby-Games | /numberchaingame.rb | UTF-8 | 1,797 | 3.6875 | 4 | [] | no_license | puts 'Welcome to puzzle game Guess the next number!'
rn = 1 + rand(10)
rn2 = 1 + rand(5)
rn3 = 1 + rand(15)
rn4 = 1 + rand(20)
non = 1
hp = 100
rhp = 75
life = 1
puts 'Welcome to level 1'
puts 'HP: ' + hp.to_s
puts 'What is the next number in the chain?'
rc = rn + rn2 - rn3
print rc.to_s + ', '
until non==3
non = non.to_i + 1
rc = rc + rn2 - rn3
print rc.to_s + ', '
end
rc = rc + rn2 - rn3
gn = gets.chomp.to_i
until gn == rc or rhp == 0
hp = hp.to_i - 25
rhp = hp.to_i - 25
puts 'Thats not right, please try again you have lost 25HP'
puts 'Current HP: ' + hp.to_s
gn = gets.chomp.to_i
end
if rhp == 0
puts "CURRENT HP: 0"
life = life - 1
puts 'You have died.'
if life.to_i >= 1
puts 'You have ' + life.to_s + 'lives left.'
puts 'Would you like to use your extra life?'
puts '[1]: Use extra life'
puts '[2]: Quit'
ul = gets.chomp
until ul == '1' or ul == '2'
puts 'NOT A VALID INPUT.'
puts 'Please try again.'
puts '****************************************************************************************'
puts '[1] Use extra life'
puts '[2] Quit'
ul = gets.chomp
end
if ul == '1'
puts 'You are filled with determination.'
elsif ul == '2'
puts 'So you have had enough?'
puts 'Ok quiter, you will never get any further with that attitude.'
end
elsif life.to_i < 1
puts "Game Over"
end
end
if gn == rc
puts "Congradulations, you can now choose between 2 prizes!"
puts '[1] 25HP'
puts '[2] 1 extra life'
pr1 = gets.chomp
if pr1.to_s == '1'
rhp = rhp.to_i + 25
hp = hp.to_i + 25
puts 'Current HP: ' + hp.to_s
elsif pr1.to_s == '2'
life = life.to_i + 1
puts 'Current number of lives: ' + life.to_s
end
end
| true |
fb2a4b268e34ac9b6d28feb2cc1ae98d93552e6e | Ruby | wharah/214 | /projects/06/ruby/script.ruby | UTF-8 | 1,370 | 3.78125 | 4 | [] | no_license | Script started on Tue 12 Mar 2019 10:24:07 PM EDT
smw42@gold29:~/CS214/projects/06$ cat print.rb
# print.rb creates and displays a user-specified array
# Output: the contents of the array
#
# Created by: Sarah Whitten
# Date: March 11, 2019
########################################################
###############################################
# printArray() displays the contents of the array
# Receive: anArray, an array of numbers
# Return: void
################################################
def printArray anArray
anArray.each do |i|
puts i
end
end
###############################################
# readArray() inputs values into the array
# Receive: anArray, an array of numbers
# Return: void
################################################
def readArray anArray
for i in 1..anArray.size
anArray[i] = gets.to_i
end
end
def main
puts "Enter the size of your array:"
size = gets.to_i
anArray = Array.new size
puts "Enter the contents of your array:"
readArray anArray
print "Here are the contents of your array:"
printArray anArray
end
main
smw42@gold29:~/CS214/projects/06$ ruby print.rb
Enter the size of your array:
3
Enter the contents of your array:
1
2
3
Here are the contents of your array:
1
2
3
smw42@gold29:~/CS214/projects/06$ exit
Script done on Tue 12 Mar 2019 10:24:30 PM EDT
| true |
e8fff6cb08029fb8fe2f4c1f4caf7bd32b137fb3 | Ruby | fcarlosdev/the_odin_project | /chess_game/lib/modules/diagonals.rb | UTF-8 | 864 | 3.375 | 3 | [] | no_license | require_relative 'coordenates'
module Diagonals
include Coordenates
def diagonals_between(from,to)
positions = diagonals(from).select {|ps| ps.include?(to[1..2])}.flatten
select_from(positions,from[1..2],to[1..2])
end
def diagonals(from)
from_coordinates = map_to_axis(from)
positions = []
positions << generate_positions(from,get_northwest_coordinates(from_coordinates[0]))
positions << generate_positions(from,get_southeast_coordinates(from_coordinates[0]))
positions << generate_positions(from,get_southwest_coordinates(from_coordinates[1]))
positions << generate_positions(from,get_northeast_coordinates(from_coordinates[0]))
end
def select_from(positions,from,to)
positions.select {|v| range(from,to).include?(v) && v != to}
end
def range(from,to)
(from < to) ? (from..to) : (to..from)
end
end
| true |
a9d48742c6940fad480ca0b8f68b0879ef806d64 | Ruby | FcoJimenez/Intro-Ruby | /Ejercicio2.rb | UTF-8 | 324 | 3.828125 | 4 | [] | no_license | #mostrar numeros impares entre 1 y 255
#ejercicio n2 Coding dojo
# 1.upto(255) do |number|
# if number.odd?
# puts number
# end
# end
1.upto(255) do |number|
puts number if number.odd?
end
#1.upto(255) { |number| puts number if number.odd? }
| true |
b48b934f2f4c6e9cb05005a07b45853629cae4e8 | Ruby | joshpeterson/mos | /tools/newcs.rb | UTF-8 | 1,384 | 3.15625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
templateCs = %{namespace <namespace>
{
public class <class>
{
}
}
}
templateTest = %{using NUnit.Framework;
namespace <namespace>.Tests
{
[TestFixture]
public class <class>Tests
{
[Test]
public void TheTruth()
{
Assert.That(true, Is.True);
}
}
}
}
def replaceNamespace(namespace, template)
template.gsub("<namespace>", namespace)
end
def replaceClass(klass, template)
template.gsub("<class>", klass)
end
if (ARGV.length != 2)
puts "Usage: newcs.rb namespace class\n"
exit
end
namespace = ARGV[0]
klass = ARGV[1]
codeDirectory = namespace;
if (!Dir.exists?(codeDirectory))
puts "Error: The directory '#{codeDirectory}' does not exist.\n"
exit
end
testDirectory = "#{namespace}.Tests"
if (!Dir.exists?(testDirectory))
puts "Error: The directory '#{testDirectory}' does not exist.\n"
exit
end
codeFile = "#{codeDirectory}/#{klass}.cs"
if (File.exists?(codeFile))
puts "Error: The file '#{codeFile}' already exists.\n"
exit
end
testFile = "#{testDirectory}/#{klass}Tests.cs"
if (File.exists?(testFile))
puts "Error: The file '#{testFile}' already exists.\n"
exit
end
File.open(codeFile, 'w') { |file|
file.write(replaceClass(klass, replaceNamespace(namespace, templateCs)))
}
File.open(testFile, 'w') { |file|
file.write(replaceClass(klass, replaceNamespace(namespace, templateTest)))
}
| true |
5d04c3d59680ee7bd0f35afa580ceb52b0e29f03 | Ruby | learn-co-students/dumbo-web-102918 | /05-many-to-many/tweet.rb | UTF-8 | 647 | 3.0625 | 3 | [] | no_license | class Tweet
attr_accessor :user, :content
@@all = []
def initialize(content, user)
@content = content
@user = user
@@all << self
end
def username
# self = tweet1 || tweet2.username
# in an instance method,
# self is always the instance
self.user.username
end
def self.all
# self = Tweet
@@all
end
def create_like(user)
Like.new(user, self)
end
def likes
Like.all.select do |like|
like.tweet == self
end
end
def likers
likes.map do |like|
like.user
end
end
def liker_usernames
likers.map do |user|
user.username
end
end
end
| true |
bb8b244925702daf451c3da23a00745f3d0c3d61 | Ruby | bspates/SE331_Fuzzers | /Fuzzers/StageFuzzer.rb | UTF-8 | 2,035 | 2.546875 | 3 | [] | no_license | require './Fuzzers/Fuzzer.rb'
require './Utility/WebSpecific.rb'
require './Utility/DvwaSetup.rb'
require './Fuzzers/XSSFuzzer.rb'
require './Fuzzers/SQLFuzzer.rb'
require './Fuzzers/InputFuzzer.rb'
class StageFuzzer < Fuzzer
def initialize(d, t, c, g, f)
super(d, t, c, f)
@logons = loadLogons
@vectors = loadVectors
@webSpec = WebSpecific.new(d)
@xssFuzz = XSSFuzzer.new(d, t, c, f)
@inputFuzz = InputFuzzer.new(d, t, c, f)
@sqlFuzz = SQLFuzzer.new(d, t, c, f)
@sqlKey = "SQLInjections"
@xssKey = "XSS"
if(g =="on")
@guess = true
else
@guess = false
end
end
def fuzz(results)
if(results.has_key?("http://127.0.0.1/dvwa/login.php"))
if(@logons.has_key?("http://127.0.0.1/dvwa/login.php"))
newUrl = @webSpec.run(@logons, "http://127.0.0.1/dvwa/login.php")
end
@dvs = DvwaSetup.new(@driver)
@dvs.setup
end
if(@random == true)
key = self.randomizer(results)
self.getUrl(key)
@file.puts "SQL Injections:"
@sqlFuzz.fuzz(@vectors["SQLInjections"], results[key]["inputs"], key)
if(@guess)
@inputFuzz.fuzz( results[key]["inputs"], key)
end
@file.puts "XSS:"
@xssFuzz.fuzz(@vectors["XSS"], results[key]["inputs"], key)
else
results.each do | key, value |
@file.puts "#{key} is vulnerable to:"
if(value["inputs"] != nil && key != "http://127.0.0.1/dvwa/login.php" && key != "http://127.0.0.1/dvwa/index.php")
self.getUrl(key)
@file.puts "SQL Injections:"
@sqlFuzz.fuzz(@vectors[@sqlKey], value["inputs"], key)
#@inputFuzz.fuzz(value["inputs"], key)
if(@guess)
@inputFuzz.fuzz(value["inputs"], key)
end
@file.puts "XSS:"
@xssFuzz.fuzz(@vectors[@xssKey], value["inputs"], key)
@file.puts ""
end
end
end
end
def loadVectors
File.open("./Confs/vectors.txt", "r") do |file|
JSON.load(file)
end
end
def loadLogons
File.open("./Confs/Logons.txt", "r") do |file|
JSON.load(file)
end
end
end | true |
66585fab96af1f2d65eaec032a3d037f8f59a713 | Ruby | Zannisdf/weather-roulette | /app/models/bet.rb | UTF-8 | 430 | 2.71875 | 3 | [] | no_license | class Bet < ApplicationRecord
belongs_to :player
belongs_to :game
after_create :handle_payments
def handle_payments
paying_odds = { green: 15, red: 2, black: 2 }
factor = choice == game.result ? paying_odds[choice.to_sym] : 0
update_player_wallet(factor)
end
def update_player_wallet(factor)
player.update(wallet: player.wallet + amount * (factor - 1))
end
enum choice: %i[green red black]
end
| true |
f4ff0ce5c3bef5e70a6c3f92ee51e22c279ecfa3 | Ruby | Mimerme/RTermGame | /TerminalGame.rb | UTF-8 | 2,858 | 3.015625 | 3 | [] | no_license | #Library is powered entirely without the Curses library
#Allows for cross-platform support
#Graphics object
require './RenderFactory.rb'
require './RTermGame.rb'
require './keypress.rb'
require 'io/console'
class TerminalGame
def initialize(name, width, height)
@game_name = name
@game_width = width
@game_height = height
@gameobjects = {}
#@logic_bits_start = {}
#@logic_bits_update = {}
@graphics_factory = RenderFactory.new(width,height)
@gameobject_count = 0
end
def add_gameobject(gameobject)
@gameobjects[@gameobject_count] = gameobject
@gameobject_count+=1
end
#def add_logic(logic_id, logic_start, logic_update)
#Only add the logic bits if they are defined
# logic_start != nil ? @logic_bits_start[logic_id] = logic_start : :nothing
# logic_update != nil ? @logic_bits_update[logic_id] = logic_update : :nothing
#end
#methods to be overriden by the superclass
#called when the game starts
def loop_start
end
#called at the beginning of each game loop
def loop_update_begin
end
#called at the end of each game loop
def loop_update_end
end
#Start the game loop
def begin_loop
Keyboard.begin_key_record
@gameobjects.each do |id, gameobject|
gameobject.start
end
#@logic_bits_start.each do |id, logic_bit|
# logic_bit.call
#end
loop_start
begin
loop do
sleep (0.1)
loop_update_begin
@gameobjects.each do |id, gameobject|
gameobject.update
end
@graphics_factory.clear_screen
@gameobjects.each do |id, gameobject|
@graphics_factory.buffer_at_position(gameobject.get_x, gameobject.get_y, gameobject.get_sprite)
end
#@logic_bits_update.each do |id, logic_bit|
# logic_bit.call
# end
loop_update_end
@graphics_factory.draw
Keyboard.reset_key_record
end
rescue SystemExit
puts "Terminated Safely"
rescue Exception => e
time = Time.now
RTermGame.println "\'#{@game_name}' ran into an exception during the game loop"
RTermGame.println "Error Report Generated " + time.inspect
RTermGame.println "==[Details]=============================================="
RTermGame.println e.inspect
RTermGame.println "==[Backtrace]=============================================="
RTermGame.println e.backtrace.join("")
quit_game "Exception Quit"
end
end
def get_width
return @game_width
end
def get_height
return @game_height
end
def get_name
return @game_name
end
def quit_game(quit_code)
STDIN.cooked!
puts quit_code
Keyboard.end_thread
exit
end
def get_gameobject_at(x_pos, y_pos)
@gameobjects.each do |id, gameobject|
if(gameobject.get_x == x_pos && gameobject.get_y == y_pos)
return gameobject
else
return :none
end
end
end
end
| true |
662419e0b082b4e3e1b19a85d18036a4469f55b9 | Ruby | lsaville/exercism | /ruby/raindrops/raindrops_v2.rb | UTF-8 | 431 | 2.9375 | 3 | [] | no_license | class Raindrops
def self.translation
number_to_word = Hash.new('')
number_to_word = {
3 => 'Pling',
5 => 'Plang',
7 => 'Plong'
}
end
def self.convert(number)
rain_speak = ''
translation.each do |test_number, rain_word|
rain_speak << rain_word if (number % test_number).zero?
end
rain_speak.empty? ? number.to_s : rain_speak
end
end
module BookKeeping
VERSION = 3
end
| true |
0aa3356e3ec2193d063c29f2bceb01d1513e222c | Ruby | Rooks-on-Rails/rooks_on_rails | /app/models/game.rb | UTF-8 | 1,947 | 2.75 | 3 | [] | no_license | class Game < ApplicationRecord
scope :available, -> { where('black_player_id IS NULL or white_player_id IS NULL') }
belongs_to :white_player, class_name: 'User', dependent: false, optional: true
belongs_to :black_player, class_name: 'User', dependent: false, optional: true
belongs_to :winning_player, class_name: 'User', dependent: false, optional: true
has_many :pieces, dependent: false
def populate_board!
Rook.create(position_x: 0, position_y: 7, game: self, color: 'black')
Knight.create(position_x: 1, position_y: 7, game: self, color: 'black')
Bishop.create(position_x: 2, position_y: 7, game: self, color: 'black')
Queen.create(position_x: 3, position_y: 7, game: self, color: 'black')
King.create(position_x: 4, position_y: 7, game: self, color: 'black')
Bishop.create(position_x: 5, position_y: 7, game: self, color: 'black')
Knight.create(position_x: 6, position_y: 7, game: self, color: 'black')
Rook.create(position_x: 7, position_y: 7, game: self, color: 'black')
Rook.create(position_x: 0, position_y: 0, game: self, color: 'white')
Knight.create(position_x: 1, position_y: 0, game: self, color: 'white')
Bishop.create(position_x: 2, position_y: 0, game: self, color: 'white')
Queen.create(position_x: 3, position_y: 0, game: self, color: 'white')
King.create(position_x: 4, position_y: 0, game: self, color: 'white')
Bishop.create(position_x: 5, position_y: 0, game: self, color: 'white')
Knight.create(position_x: 6, position_y: 0, game: self, color: 'white')
Rook.create(position_x: 7, position_y: 0, game: self, color: 'white')
0.upto(7) do |b| # b to stand in for black for now
Pawn.create(position_x: b, position_y: 6, game: self, color: 'black')
end
0.upto(7) do |w| # w to stand in for white for now
Pawn.create(position_x: w, position_y: 1, game: self, color: 'white')
end
end
def check?
# code
end
end
| true |
dacb8169ddd82f7aca9afcda31d9bad20da2f33b | Ruby | murex/murex-coding-dojo | /Beirut/2016/2016-04-13-LRU-ruby - Continued/lru.rb | UTF-8 | 2,931 | 3.90625 | 4 | [
"MIT"
] | permissive | class LRU
attr_accessor :capacity, :hash, :list
def initialize
@capacity = 5
@hash = {}
@list = DoublyLinkedList.new
end
def get(key)
if !hash.has_key?(key)
return
end
node = list.delete(hash[key])
list.push(node)
return node.data.value
end
def set(key,value)
if hash.has_key?(key)
node = list.delete(hash[key])
node.data.value = value
list.push(node)
else
if @list.size == @capacity
tail = list.delete(list.tail)
hash.delete(tail.data.key)
end
newNode = Node.new(Pair.new(key, value))
hash[key] = newNode
list.push(newNode)
end
end
def display
puts @hash
@list.display
end
end
class Pair
attr_accessor :key, :value
def initialize(key,value)
@key = key
@value = value
end
def to_s
@key.to_s + ", "+ @value.to_s
end
end
class Node
attr_accessor :next_node, :prev_node, :data
def initialize(data=nil, n=nil, p=nil)
@data = data
@next_node = n
@prev_node = p
end
def print
puts @data
end
end
class DoublyLinkedList
attr_accessor :head, :tail, :size
def initialize()
@size = 0
@head = nil
@tail = nil
end
def display
ptr = @head
puts 'Linked list:'
while ptr != nil
puts ptr.data
ptr = ptr.next_node
end
puts 'end;'
end
def displayR
ptr = @tail
puts 'Linked list:'
while ptr != nil
puts ptr.data
ptr = ptr.prev_node
end
puts 'end;'
end
def push(node)
if size == 0
@tail = node
@head = node
else
@head.prev_node = node
node.next_node = @head
end
@head = node
@size = @size + 1
end
def delete(node)
if @size == 0
return
end
if @size == 1
@head = nil
@tail = nil
elsif node != @head && node != @tail
node.prev_node.next_node=node.next_node
node.next_node.prev_node=node.prev_node
elsif node == @head
@head = @head.next_node
@head.prev_node = nil
elsif node == @tail
@tail = @tail.prev_node
@tail.next_node = nil
end
@size = @size - 1
node.next_node = nil
node.prev_node = nil
return node
end
end
# dll = DoublyLinkedList.new()
#
# dll.display
#
# node1 = Node.new(Pair.new(1,10))
# dll.push(node1)
# node2 = Node.new(Pair.new(2,20))
# dll.push(node2)
# node3 = Node.new(Pair.new(3,30))
# dll.push(node3)
# node4 = Node.new(Pair.new(4,40))
# dll.push(node4)
#
# dll.display
# puts "removing 2"
# dll.delete(node2)
# dll.display
#
# puts "removing 1"
# dll.delete(node1)
# dll.display
# puts "removing 4"
# dll.delete(node4)
# dll.display
# puts "removing 3"
# dll.delete(node3)
# dll.display
lru = LRU.new()
lru.set(1,10)
lru.set(2,20)
lru.set(3,30)
lru.set(1,100)
lru.set(4,40)
lru.set(5,50)
lru.set(2,200)
lru.set(6,60)
puts lru.get(5)
puts lru.get(10)
lru.display
| true |
def2c069fdd519bba0b4359775b6f165d243506f | Ruby | chdezmar/test-jt-ruby | /spec/grid_spec.rb | UTF-8 | 522 | 2.796875 | 3 | [] | no_license | require 'grid'
describe Grid do
subject(:grid) { described_class.new }
it 'has a default x of 10' do
expect(grid.x).to eq(10)
end
it 'has a default y of 10' do
expect(grid.y).to eq(10)
end
it 'can be set with a custom x and y' do
grid = described_class.new(100,100)
expect(grid.x).to eq(100)
expect(grid.y).to eq(100)
end
it 'can hold a set of obstacles' do
grid = described_class.new(100,100, obstacles: [[0,3], [1,2]])
expect(grid.obstacles).to eq([[0,3], [1,2]])
end
end | true |
4ba929510546c1a351f5bec4265b6b0885d25cb9 | Ruby | jilion/my.sublimevideo.net | /app/services/highcharts_graph_builder.rb | UTF-8 | 800 | 3.03125 | 3 | [] | no_license | # Simple DSL to build Highcharts graph
class HighchartsGraphBuilder
def initialize
@options = {}
@raw_options = []
yield self
end
def option(hash = {})
@options.update(hash)
end
def raw_option(string)
@raw_options << string
end
def draw(options = { on_dom_ready: true })
result = "new Highcharts.Chart(#{draw_options});"
result = '$(document).ready(function() {' + result + '});' if options[:on_dom_ready]
'<script type="text/javascript">' + result + '</script>'
end
private
def draw_options
result = '{ '
if @options.to_json.inspect.size > 2
result << @options.to_json[1..-2]
result << ', ' if @raw_options.present?
end
result << @raw_options.join(', ') if @raw_options.present?
"#{result} }"
end
end
| true |
886ff3e4de556fc9099e6923bc7b9eb80c24f106 | Ruby | mjunaidi/slinky | /lib/slinky/errors.rb | UTF-8 | 2,308 | 2.875 | 3 | [
"MIT"
] | permissive | require 'continuation'
module Slinky
# Common base class for all Slinky errors
class SlinkyError < StandardError
class NoContinuationError < StandardError; end
attr_accessor :continuation
# Continue where we left off
def continue
raise NoContinuationError unless continuation.respond_to?(:call)
continuation.call
end
def messages
[message]
end
# Raises an error with a continuation that allows us to continue
# with processing as if no error had been thrown
def self.raise(exception = SlinkyError, string = nil, array = caller)
if exception.is_a?(String)
string = exception
exception = SlinkyError
end
callcc do |cc|
obj = string.nil? ? exception : exception.exception(string)
obj.set_backtrace(array)
obj.continuation = cc
super obj
end
end
# batches all SlinkyErrors thrown in the supplied block and
# re-raises them at the end of processing wrapped in a MultiError.
def self.batch_errors
errors = []
result = nil
begin
result = yield
rescue SlinkyError => e
errors << e
if e.continuation.respond_to?(:call)
e.continue
end
end
if !errors.empty?
if errors.size == 1
raise errors.first
else
raise MultiError, errors
end
end
result
end
end
# Raised when a compilation fails for any reason
class BuildFailedError < SlinkyError; end
# Raised when a required file is not found.
class FileNotFoundError < SlinkyError; end
# Raised when there is a cycle in the dependency graph (i.e., file A
# requires file B which requires C which requires A)
class DependencyError < SlinkyError; end
# Raise when there is a request for a product that doesn't exist
class NoSuchProductError < SlinkyError; end
# Raise when there are multiple errors
class MultiError < SlinkyError
attr_reader :errors
def initialize errors
@errors = errors.map{|e|
case e
when MultiError then e.errors
else e
end
}.flatten
end
def message
@errors.map{|e| e.message}.join(", ")
end
def messages
@errors.map{|e| e.message}
end
end
end
| true |
9f347824b1e12172bccf06ae51c8ebd3ce05f98a | Ruby | Federal-Aviation-Administration/faa_auth | /exe/faa_auth | UTF-8 | 1,551 | 2.90625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require_relative "../lib/faa_auth"
require 'highline/import'
result = []
domain = ask("Enter your faa domain: ") { |q| q.echo = true ; q.default = FaaInfo.domain }
login = ask("Enter your #{domain} username: ") { |q| q.echo = true }
passwd = ask("Enter your FAA Access pin : ") { |q| q.echo = "*" }
sec1 = ask("Enter security question1: "){ |q| q.echo = true ;}
ans1 = ask("Enter security answer1: "){ |q| q.echo = true ;}
sec2 = ask("Enter security question2: "){ |q| q.echo = true ;}
ans2 = ask("Enter security answer2: "){ |q| q.echo = true ;}
sec3 = ask("Enter security question3: "){ |q| q.echo = true ;}
ans3 = ask("Enter security answer3: "){ |q| q.echo = true ;}
salt = ask("Enter your salt: ") { |q| q.default = FaaAuth::Converter.default_salt ; q.echo = true }
raise "Empty login or password" if login.to_s.size == 0 || passwd.to_s.size == 0
converter = FaaAuth::Converter.new(salt)
puts "Put the following lines in .env"
puts
puts "FAA_DOMAIN=#{domain}"
puts "FAA_USERNAME_CODE=#{converter.encode(login)}"
puts "FAA_ACCESS_PIN=#{converter.encode(passwd)}"
puts "FAA_SECURITY_QUESTION1=#{converter.encode(sec1)}"
puts "FAA_SECURITY_ANSWER1=#{converter.encode(ans1)}"
puts "FAA_SECURITY_QUESTION2=#{converter.encode(sec2)}"
puts "FAA_SECURITY_ANSWER2=#{converter.encode(ans2)}"
puts "FAA_SECURITY_QUESTION3=#{converter.encode(sec3)}"
puts "FAA_SECURITY_ANSWER3=#{converter.encode(ans3)}"
puts "FAA_CODE_SALT=#{salt}"
#Which city were you born in?
#Where did you first meet your spouse?
#What is your pet's name?
| true |
e1be41f96ab47731395f614e1340b6242f92876f | Ruby | ConjurTech/fingerpress-server | /app/models/payment_record_time_log.rb | UTF-8 | 2,381 | 2.515625 | 3 | [] | no_license | class PaymentRecordTimeLog < ActiveRecord::Base
belongs_to :payment_record_pay_scheme, dependent: :destroy
belongs_to :payment_record
before_save :calculate_pay, if: :payment_scheme_is_hourly_type?
def payment_scheme_is_hourly_type?
self.payment_record_pay_scheme.hourly?
end
def weekend?
self.date_time_in.saturday? || self.date_time_in.sunday?
end
def has_ot?
ot_hours > 0 && !public_holiday? && !weekend?
end
def calculate_pay
self.pay = total_pay
end
# Calculate pay functions
def total_pay
normal_pay + ot_pay + weekend_pay + public_holiday_pay
end
def normal_pay
normal_hours * self.payment_record_pay_scheme.pay
end
def ot_pay
case self.payment_record_pay_scheme.weekend_type
when 'same_as_normal'
ot_hours * self.payment_record_pay_scheme.pay
when 'per_hour'
ot_hours * self.payment_record_pay_scheme.pay_ot
when 'multiplier'
ot_hours * self.payment_record_pay_scheme.pay * self.payment_record_pay_scheme.ot_multiplier
else
0
end
end
def weekend_pay
case self.payment_record_pay_scheme.weekend_type
when 'same_as_normal'
weekend_hours * self.payment_record_pay_scheme.pay
when 'per_hour'
weekend_hours * self.payment_record_pay_scheme.pay_weekend
when 'multiplier'
weekend_hours * self.payment_record_pay_scheme.pay * self.payment_record_pay_scheme.weekend_multiplier
else
0
end
end
def public_holiday_pay
case self.payment_record_pay_scheme.public_holiday_type
when 'same_as_normal'
public_holiday_hours * self.payment_record_pay_scheme.pay
when 'per_hour'
public_holiday_hours * self.payment_record_pay_scheme.pay_public_holiday
when 'multiplier'
public_holiday_hours * self.payment_record_pay_scheme.pay * self.payment_record_pay_scheme.public_holiday_multiplier
else
0
end
end
def worked_hours
TimeDifference.between(self.date_time_in, self.date_time_out).in_hours
end
def normal_hours
normal_hours = worked_hours - ot_hours - weekend_hours - public_holiday_hours
(normal_hours < 0) ? 0 : normal_hours
end
def weekend_hours
(weekend? && !public_holiday? && !workday?) ? worked_hours : 0
end
def public_holiday_hours
public_holiday? ? worked_hours : 0
end
end
| true |
fad5c9d566cd5c7b574a6fc1e8557bef7541085c | Ruby | JoyJing1/W3D3_Associations_ActiveRecord_Partner-Yi-Ke | /URLShortener/app/models/shortened_url.rb | UTF-8 | 1,619 | 2.515625 | 3 | [] | no_license | require 'securerandom'
class ShortenedUrl < ActiveRecord::Base
validates :short_url, presence: true, uniqueness: true
validates :user_id, presence: true
validates :long_url, presence: true, length: {maximum: 1024}
validate :max_5_submissions
belongs_to :submitter,
class_name: :User,
foreign_key: :user_id,
primary_key: :id
has_many :visits,
class_name: :Visit,
foreign_key: :short_url,
primary_key: :short_url
has_many :uniq_visitors,
-> { distinct },
through: :visits,
source: :user
has_many :visitors,
class_name: :Visit,
through: :visits,
source: :user
has_many :clicks,
class_name: :Click,
foreign_key: :short_url,
primary_key: :short_url
def max_5_submissions
user = User.find_by_id(user_id)
if user.num_recent_submissions >= 1 && user.premium == false
errors[:user] << "can't add more than 5 shortened urls per minute"
end
end
def self.random_code
curr_short_url = SecureRandom::urlsafe_base64
if exists?( short_url: curr_short_url )
curr_short_url = ShortenedURL.random_code
end
curr_short_url
end
def self.create_for_user_and_long_url!(user, long_url)
short_url = ShortenedUrl.random_code
ShortenedUrl.create!(long_url: long_url, short_url: short_url, user_id: user.id)
end
def num_clicks
clicks.length
end
def num_uniques
clicks.select(:user_id).distinct.count
end
def num_uniques_via_assc
uniq_visitors.count
end
def num_recent_uniques
clicks.where("created_at > ?", 10.minutes.ago).select(:user_id).distinct.count
end
end
| true |
2a9289343c1e3a57e404c55424fb74b1a3664745 | Ruby | WonderDev21/hb-webapi | /spec/lib/markdown_renderer_spec.rb | UTF-8 | 1,023 | 2.609375 | 3 | [] | no_license | require 'rails_helper'
require 'markdown_renderer'
RSpec.describe MarkdownRenderer, type: :model do
describe '#render' do
let(:renderer) { MarkdownRenderer.new }
{
'# Header' => "<h1>Header</h1>\n",
'**bold text**' => "<p><strong>bold text</strong></p>\n",
'*italicized text*' => "<p><em>italicized text</em></p>\n",
" 1. first item\n 2. second item" => "<ol>\n<li>first item</li>\n<li>second item</li>\n</ol>\n",
" - first item\n - second item" => "<ul>\n<li>first item</li>\n<li>second item</li>\n</ul>\n",
'[inline link](https://www.google.com)' => "<p>[inline link](https://www.google.com)</p>\n",
'' => "<p></p>\n",
'<dl><dt>hello</dt><dd>world</dd></dl>' => "<p>helloworld</p>\n"
}.each do |markdown, expected_output|
it "render Markdown text as HTML: #{markdown}" do
expect(renderer.render(markdown)).to eq(expected_output)
end
end
end
end
| true |
b3bcb7c861185faa039d185b0e7217a184695144 | Ruby | havocesp/dev-twofactorauth | /_deployment/regions.rb | UTF-8 | 1,415 | 2.671875 | 3 | [] | no_license | # frozen_string_literal: true
require 'yaml'
require 'fileutils'
data_dir = '../_data'
sections = YAML.load_file("#{data_dir}/sections.yml")
regions_data = YAML.load_file("#{data_dir}/regions.yml")
regions = regions_data['regions']
# Region loop
regions.each do |region|
puts region
dest_dir = "/tmp/#{region}"
unless File.exist?(dest_dir)
Dir.mkdir(dest_dir) unless File.exist?(dest_dir)
files = Dir.glob('../*').reject { |file| file.end_with?('../.') }
FileUtils.cp_r(files, dest_dir)
end
# Category loop
sections.each do |section|
data = YAML.load_file("#{data_dir}/#{section['id']}.yml")
websites = data['websites']
section_array = []
# Website loop
websites.each do |website|
if website['regions'].nil?
section_array.push(website)
else
section_array.push(website) if website['regions'].include?(region.to_s)
end
end
website_array = {websites: section_array}
website_yaml = website_array.to_yaml.gsub("---\n:", '')
File.open("#{dest_dir}/_data/#{section['id']}.yml", 'w') do |file|
file.write website_yaml
end
end
out_dir = "#{Dir.pwd}/../#{region}"
puts "Building #{region}..."
puts `cd #{dest_dir} && bundle exec jekyll build -d #{out_dir} --config _config-regions.yml` # Add -V for debugging
puts `cd #{out_dir} && rm -R -- */` # Delete Subdirectories
puts "#{region} built!"
end
| true |
6f6ddffdf6d890afafe23d76d176207434d338fa | Ruby | wbzyl/rack-codehighlighter | /lib/rack/codehighlighter.rb | UTF-8 | 5,665 | 2.703125 | 3 | [
"MIT"
] | permissive | require 'rack/utils'
require 'nokogiri'
module Rack
class Codehighlighter
include Rack::Utils
# for logging use
FORMAT = %{%s - [%s] [%s] "%s %s%s %s" (%s) %d %d %0.4f\n}
def initialize(app, highlighter = :censor, opts = {})
@app = app
@highlighter = highlighter
@opts = {
:element => "pre",
:pattern => /\A:::([-\w]+)\s*(\n|
)/i, # 
 == line feed
:reason => "[[-- ugly code removed --]]", #8-)
:markdown => false
}
@opts.merge! opts
end
def call(env)
began_at = Time.now
status, headers, response = @app.call(env)
headers = HeaderHash.new(headers)
if !STATUS_WITH_NO_ENTITY_BODY.include?(status) &&
!headers['transfer-encoding'] &&
headers['content-type'] &&
headers['content-type'].include?("text/html")
content = ""
response.each { |part| content += part }
doc = Nokogiri::HTML(content, nil, 'UTF-8')
nodes = doc.search(@opts[:element])
nodes.each do |node|
s = node.inner_html || "[++where is the code?++]"
if @opts[:markdown]
node.parent.swap(send(@highlighter, s))
else
node.swap(send(@highlighter, s))
end
end
body = doc.to_html
headers['Content-Length'] = body.bytesize.to_s
log(env, status, headers, began_at) if @opts[:logging]
[status, headers, [body]]
else
[status, headers, response]
end
end
private
def log(env, status, headers, began_at)
# 127.0.0.1 - [ultraviolet] [10/Oct/2009 12:12:12] "GET /pastie HTTP/1.1" (text/html) 200 512 1.23
now = Time.now
logger = env['rack.errors']
logger.write FORMAT % [
env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-",
@highlighter,
now.strftime("%d/%b/%Y %H:%M:%S"),
env["REQUEST_METHOD"],
env["PATH_INFO"],
env["QUERY_STRING"].empty? ? "" : "?"+env["QUERY_STRING"],
env["HTTP_VERSION"],
headers["content-type"] || "unknown",
status.to_s[0..3],
headers['content-length'],
now - began_at
]
end
# simplifies testing
def censor(string)
"<pre class='censor'>#{@opts[:reason]}</pre>"
end
def syntax(string)
# allow use html instead of xml
translate = {
'html' => 'xml',
'c' => 'ansic',
'css' => 'css21',
'sql' => 'sqlite'
}
lang = 'unknown'
refs = @opts[:pattern].match(string) # extract language name
if refs
lang = refs[1]
convertor = ::Syntax::Convertors::HTML.for_syntax translate[lang] || lang
convertor.convert(unescape_html(string.sub(@opts[:pattern], "")) || "[=this can'n happen=]")
else
"<pre>#{string}</pre>"
end
end
def coderay(string)
lang = 'unknown'
refs = @opts[:pattern].match(string) # extract language name
if refs
lang = refs[1]
str = unescape_html(string.sub(@opts[:pattern], ""))
"<pre class='CodeRay'>#{::CodeRay.encoder(:html).encode str, lang}</pre>"
else
"<pre class='CodeRay'>#{string}</pre>"
end
end
# experimental Javascript highlighter
def prettify(string)
# prettify uses short names; I want to use full names
translate = {
'ruby' => 'rb',
'bash' => 'bsh',
'javascript' => 'js',
'python' => 'py'
}
lang = 'unknown'
refs = @opts[:pattern].match(string) # extract language name
if refs
lang = refs[1]
str = string.sub(@opts[:pattern], "")
"<pre class='prettyprint lang-#{translate[lang] || lang}'>#{str}</pre>"
else
"<pre>#{string}</pre>"
end
end
def pygments(string)
refs = @opts[:pattern].match(string)
if refs
lang = refs[1]
str = unescape_html(string.sub(@opts[:pattern], ""))
options = @opts[:options]
Pygments.highlight(str, :lexer => lang, :formatter => 'html', :options => options)
else
"<pre>#{string}</pre>"
end
end
def rygments(string)
refs = @opts[:pattern].match(string)
if refs
lang = refs[1]
str = unescape_html(string.sub(@opts[:pattern], ""))
Rygments.highlight_string(str, lang, 'html')
else
"<pre>#{string}</pre>"
end
end
def pygments_api(string)
require 'net/http'
require 'uri'
lang = 'unknown'
refs = @opts[:pattern].match(string) # extract language name
if refs
lang = refs[1]
str = unescape_html(string.sub(@opts[:pattern], ""))
req = Net::HTTP.post_form(URI.parse('http://pygments.appspot.com/'),
{'lang' => lang, 'code' => str})
"#{req.body}"
else
"<pre>#{string}</pre>"
end
end
def ultraviolet(string)
opts = { :theme => 'dawn', :lines => false, :themes => {} }
opts.merge! @opts
lang = 'text'
refs = @opts[:pattern].match(string) # extract language name
if refs
lang = refs[1]
theme = opts[:themes].collect do |k,v|
k if v.include? lang end.compact.first || opts[:theme]
str = unescape_html(string.sub(@opts[:pattern], ""))
"#{::Uv.parse(str, 'xhtml', lang, opts[:lines], theme)}"
else
"<pre class='#{opts[:theme]}'>#{string}</pre>"
end
end
def unescape_html(string)
string.to_s.gsub(/
/i, "\n").gsub("<", '<').gsub(">", '>').gsub("&", '&')
end
end
end
| true |
08900752f7ce8ee85ec704d3a0ad0ff3d7bd2340 | Ruby | 3WFH/ruby-challenges | /each.rb | UTF-8 | 141 | 3 | 3 | [] | no_license | all_tweets = [
"My first tweet",
"Another tweet",
"Yep, another one",
"Four",
"Meh"
]
all_tweets.each do |tweet|
puts tweet
end
| true |
26fe63ce07a74c8cdeea722665c7cc99ff0d8183 | Ruby | ttowncompiled/HackerRank | /Project-Euler+/large_sum.rb | UTF-8 | 729 | 3.6875 | 4 | [] | no_license | #!/bin/ruby
################################################################################
# This is a rather simple problem in most modern languages. Languages
# such as Ruby or Python will autobox integers to BigInt once the number
# becomes too large. However, most system languages such as C/C++, Java, etc.
# will require the explicit use of BigInt. The important point to know is
# that the solution requires the efficient use of an array of numbers.
################################################################################
s = 0
n = gets.strip.to_i
(1..n).each do
s += gets.strip.to_i # Ruby will autobox to BigInt
end
puts s.to_s[0...10] # only print out the first 10 digits (highest-ordered)
| true |
7b8a3ecc78c41119252b1a66131c6184317d7c8f | Ruby | reddyonrails/sitemap-parser | /lib/sitemap-parser.rb | UTF-8 | 3,333 | 2.6875 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'typhoeus'
class SitemapParser
def initialize(url, opts = {})
@url = url
@options = {:followlocation => true, :recurse => false, url_limited_count: 500}.merge(opts)
@from_date = Date.parse(@options[:from_date]) rescue nil
end
def raw_sitemap
@raw_sitemap ||= begin
if @url =~ /\Ahttp/i
request(@url)
elsif File.exist?(@url) && @url =~ /[\\\/]sitemap\.xml\Z/i
open(@url) { |f| f.read }
end
end
end
# Check for redirection and re-request
def request(url)
request = Typhoeus::Request.new(url, followlocation: @options[:followlocation])
request.options['headers']={}
request.on_complete do |response|
if response.success?
return response.body
elsif response.redirect_count > 0 && response.effective_url
return request(response.effective_url)
else
raise "HTTP request to #{url} failed"
end
end
request.run
end
def sitemap
@sitemap ||= Nokogiri::XML(raw_sitemap)
end
def urls
if sitemap.at('urlset')
sitemap.at("urlset").search("url")
elsif sitemap.at('sitemapindex')
found_urls = []
if @options[:recurse]
if @options[:from_date]
sitemap.at('sitemapindex').search('sitemap').each do |sitemap|
child_sitemap_location = sitemap.at('loc').content
if ll= child_sitemap_location.match('yyyy=(\d{4})&mm=(\d{1,2})&dd=(\d{1,2})')
is_latest_published_date = begin
Date.parse("#{$3}-#{$2}-#{$1}") > @from_date
rescue nil
end
if is_latest_published_date
found_urls << self.class.new(child_sitemap_location, :recurse => false, from_date: @from_date.to_s).urls
end
elsif sitemap.at('lastmod').try(:content)
is_latest_published_date = begin
Date.parse(sitemap.at('lastmod').content) > @from_date
rescue nil
end
if is_latest_published_date
found_urls << self.class.new(child_sitemap_location, :recurse => false, from_date: @from_date.to_s).urls
end
else
found_urls << self.class.new(child_sitemap_location, :recurse => false, from_date: @from_date.to_s).urls
end
break if @options[:url_limited_count] < found_urls.count
end
else
sitemap.at('sitemapindex').search('sitemap').each do |sitemap|
child_sitemap_location = sitemap.at('loc').content
found_urls << self.class.new(child_sitemap_location, :recurse => false).urls
break if @options[:url_limited_count] < found_urls.count
end
end
end
return found_urls.flatten
else
[]
end
end
def to_a
list = []
urls.each do |url|
if @options[:from_date]
is_latest_published_date = begin
Date.parse(url.at('lastmod').content) > @from_date
rescue Exception => e
nil
end
if is_latest_published_date
list << url.at("loc").content
end
else
list << url.at("loc").content
end
break if @options[:url_limited_count] < list.count
end
list
rescue NoMethodError
list
end
end
| true |
a56b5c20386ea1a3d9ecafe59bb67c6aa18fd2c1 | Ruby | RebekkaRove/RebekkaRove | /Undervisning Rocketlab/christmas-list/wishlist.rb | UTF-8 | 478 | 3.09375 | 3 | [] | no_license | def display_options(input_options)
input_options.each_with_index do |option, index|
puts "#{index + 1} - #{option}"
end
end
def display_wishlist(wishlist)
wishlist.each_with_index do |item, index|
purchased_box = item[:purchased] ? "[X]" : "[ ]" # Ternary
puts "#{index + 1} - #{purchased_box} #{item[:description]}"
end
end
def display_etsy_results(etsy_results)
etsy_results.each_with_index do |item, index|
puts "#{index + 1} - #{item}"
end
end
| true |
63f69ab9748b962ad59668f20ea65d9c6aeef605 | Ruby | janlelis/harvester | /lib/harvester/generator/link_absolutizer.rb | UTF-8 | 1,056 | 2.6875 | 3 | [] | no_license | # encoding: utf-8
class Harvester; class Generator; end; end
# This module rewrites relative to absolute links
module Harvester::Generator::LinkAbsolutizer
def self.run(body, base, logger = nil)
logger ||= Logger.new(STDOUT)
require 'nokogiri'
require 'uri'
html = Nokogiri::HTML("<html><body>#{body}</body></html>")
[%w[img src], %w[a href]].each{ |elem, attr|
html.css(elem).each{ |e|
begin
src = e[attr]
uri = URI::join(base, src.to_s).to_s
if src.to_s != uri.to_s
logger.debug "* rewriting #{src.inspect} => #{uri.inspect}"
e[attr] = uri.to_s
end
rescue URI::Error
logger.debug "* cannot rewrite relative URL: #{src.inspect}" #unless src.to_s =~ /^[a-z]{2,10}:/
end
}
}
html.css('body').children.to_s
rescue LoadError
logger.warn "* nokogiri not found, will not mangle relative links in <description/>"
body
rescue Exception => e
logger.warn "* there was a nokogiri exception: #{e}"
end
end
| true |
e7e92866c9f6d75c94de578947b1eff465d53484 | Ruby | OmairRaza9/farm | /farm.rb | UTF-8 | 910 | 3.28125 | 3 | [] | no_license | require_relative 'field'
attr_accessor: :fields :total_harvest
class farm
def initialize()
@fields = []
@total_harvest = 0
end
def add_field(field)
@fields << @field
end
def harvest
@field.each do |field|
@total_harvest += field.production
puts "Harvesting #{field.production} food from #{field.size}
#{field.type} field"
end
puts "The farm has #{total_harvest} food so far"
total_harvested
end
def status
@fields.each do |field|
puts "#{field.type} field is #{field.size} hectares"
end
puts "The farm has #{@total_harvest} harvested food so far"
end
def relax
corn_total_size = 0
wheat_total_size = 0
fields.each do |field|
if field.type == "corn"
corn_total_size += field.size
else
field.type == "wheat"
wheat_total_size += field.size
end
end
end
| true |
e05ce277400abb57dc8902e6159044ae22bb7c49 | Ruby | ArpanMaheshwari144/Complete-Ruby-Programming | /tut72.rb | UTF-8 | 514 | 4.0625 | 4 | [] | no_license | # Method Overriding
class ParentArea
# Constructor
def initialize(w, h)
@width = w
@height = h
end
# To calculate the area from parent class
def getArea
return "Area from Parent class is #{@width * @height}"
end
end
class ChildArea < ParentArea
# To calculate the area from child class
def getArea
puts super()
return "Area from Child class is #{@width * @height}"
end
end
childobj = ChildArea.new(10,20)
puts childobj.getArea | true |
7dabcf566845e07f0edeb6a37dad1aa92f98a9b6 | Ruby | GeoffPurdy/fifteen | /lib/fifteen.rb | UTF-8 | 843 | 4.3125 | 4 | [] | no_license | require "player"
class Fifteen
attr_accessor :player, :numbers
def initialize
puts "Hello! What is your name?"
@name = gets.chomp.capitalize
puts "Okay #{@name}, let's get started!"
@player = Player.new
@computer = Player.new
@numbers = [1,2,3,4,5,6,7,8,9]
start
end
def start
@heads_or_tails = ["heads","tails"].sample
puts "Heads or tails?"
@player_answer = gets.chomp.downcase
if @player_answer == @heads_or_tails
puts "You win!"
@player.pick_num
check_hand(@player)
else
puts "YOU LOSE. Computer goes first."
@computer.hand << @numbers.sample
puts "The computer chose a(n) #{@computer.hand}."
end
end
def win(hand)
#if player or computer has at least three cards that total exactly 15
end
end
me = Fifteen.new
| true |
30b959d4f3312c86a8cf12307be8e60bdfb581c4 | Ruby | lbvf50mobile/til | /20190810_Saturday/20190810countElements.rb | UTF-8 | 449 | 2.828125 | 3 | [] | no_license | p "alias x='ruby 20190810_Saturday/20190810countElements.rb'"
# Ruby countElements
require "minitest/autorun"
require_relative "countElements.rb"
require 'ostruct'
describe "countElements" do
it "Pass the tests" do
[
OpenStruct.new({
inputString: "[[0, 20], [33, 99]]",
answer: 4
}),
].each{|x| assert_equal x.answer, Task.new.countElements(x.inputString)}
end
end
| true |
26dd97ae0aad6a87d5bd5638dc649fe5db452669 | Ruby | chaimoosh/sql-library-lab-v-000 | /lib/querying.rb | UTF-8 | 1,265 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def select_books_titles_and_years_in_first_series_order_by_year
"SELECT books.title, books.year
FROM books
JOIN series ON series.id = books.series_id
WHERE series.id = 1
GROUP BY books.year;"
end
def select_name_and_motto_of_char_with_longest_motto
"SELECT characters.name, characters.motto FROM characters
ORDER BY (motto) LIMIT 1; "
end
def select_value_and_count_of_most_prolific_species
"SELECT species, COUNT (species) FROM characters
GROUP BY species
ORDER BY COUNT (species) DESC LIMIT 1;"
end
def select_name_and_series_subgenres_of_authors
"SELECT authors.name, subgenres.name
FROM authors
JOIN series ON series.author_id = authors.id
JOIN subgenres ON subgenres.id = series.subgenre_id
GROUP BY authors.name;"
end
def select_series_title_with_most_human_characters
"SELECT series.title
FROM series
JOIN characters ON characters.series_id
WHERE characters.species = 'human'
GROUP BY series.title LIMIT 1;"
end
def select_character_names_and_number_of_books_they_are_in
"SELECT characters.name, COUNT (character_books.character_id)
FROM characters
JOIN character_books ON character_books.character_id = characters.id
GROUP BY characters.name
ORDER BY COUNT (character_books.character_id) DESC;"
end
| true |
dc58e8c0346b6a28f305e635eb35a0b4bcaf3a0b | Ruby | Ladas/rjr | /lib/rjr/em_adapter.rb | UTF-8 | 4,412 | 2.921875 | 3 | [
"Apache-2.0"
] | permissive | # EventMachine Adapter
#
# Copyright (C) 2012 Mohammed Morsi <mo@morsi.org>
# Licensed under the Apache License, Version 2.0
require 'singleton'
require 'eventmachine'
# EventMachine wrapper / helper interface, ties reactor
# lifecycle to an instance of this class.
#
# TODO move to the RJR namespace
class EMManager
# Run reactor in its own interally managed thread
attr_accessor :reactor_thread
# Number of jobs being run in the reactor
attr_accessor :em_jobs
# EMManager initializer
def initialize
@em_lock = Mutex.new
@em_jobs = 0
@keep_alive = false
ObjectSpace.define_finalizer(self, self.class.finalize(self))
end
# Ruby ObjectSpace finalizer to ensure that EM is terminated
def self.finalize(em_manager)
proc { em_manager.halt ; em_manager.join }
end
# Update local em settings
# @param [Hash] args options to set on em manager
# @option args [Boolean] :keep_alive set to true to indicate event machine
# should be kept alive until 'halt' is called, set to false to indicate
# event machine should be terminated when there are no more pending operations
def update(args = {})
if args[:keep_alive]
@keep_alive = true
elsif args[:keep_alive] == false
@keep_alive = false
end
end
# Start the eventmachine reactor thread if not running
def start
@em_lock.synchronize{
@reactor_thread = Thread.new {
begin
EventMachine.run
rescue Exception => e
puts "Critical exception #{e}\n#{e.backtrace.join("\n")}"
ensure
@reactor_thread = nil
end
} unless @reactor_thread
}
sleep 0.1 until EventMachine.reactor_running? # XXX hack but needed
end
# Schedule a new job to be run in event machine
# @param [Callable] bl callback to be invoked by eventmachine
def schedule(&bl)
@em_lock.synchronize{
@em_jobs += 1
}
# TODO move into block? causes deadlock
EventMachine.schedule bl
end
# Schedule a job to be run once after a specified interval in event machine
# @param [Integer] seconds int interval which to wait before invoking specified block
# @param [Callable] bl callback to be invoked by eventmachine
def add_timer(seconds, &bl)
EventMachine.add_timer(seconds) {
@em_lock.synchronize { @em_jobs += 1 }
bl.call
#@em_lock.synchronize { @em_jobs -= 1 }
}
end
# Schedule a block to be run periodically in event machine
# @param [Integer] seconds int interval which to invoke specified block
# @param [Callable] bl callback to be invoked by eventmachine
def add_periodic_timer(seconds, &bl)
@em_lock.synchronize{
@em_jobs += 1
}
# TODO move into block ?
EventMachine.add_periodic_timer(seconds, &bl)
end
# Return boolean indicating if event machine reactor is running
def running?
@em_lock.synchronize{
EventMachine.reactor_running?
}
end
# Return boolean indicating if event machine has jobs to run
def has_jobs?
@em_lock.synchronize{
@em_jobs > 0
}
end
# Block until reactor thread is terminated
def join
@em_lock.synchronize{
@reactor_thread.join unless @reactor_thread.nil?
}
end
# Gracefully stop event machine if no jobs are running.
# Set @keep_alive to true to ignore calls to stop
def stop
@em_lock.synchronize{
old_em_jobs = @em_jobs
@em_jobs -= 1
if !@keep_alive && @em_jobs == 0
EventMachine.stop_event_loop
#@reactor_thread.join # trusting event machine here to finish up
end
old_em_jobs != 0 && @em_jobs == 0 # only return true if this operation stopped the reactor
}
end
# Terminate the event machine reactor under all conditions
def halt
@em_lock.synchronize{
EventMachine.stop_event_loop
#@reactor_thread.join
}
end
end
# Provides an interface which to access a shared EMManager
#
# EMManager operations may be invoked on this class after
# the 'init' method is called
#
# EMAdapter.init
# EMAdapter.start
class EMAdapter
# Initialize EM subsystem
def self.init(args = {})
if @em_manager.nil?
@em_manager = EMManager.new
end
@em_manager.update args
@em_manager.start
end
# Delegates all methods invoked on calls to EMManager
def self.method_missing(method_id, *args, &bl)
@em_manager.send method_id, *args, &bl
end
end
| true |
5573ceaae23e3ceb3684037b613259ce23a7d21f | Ruby | thetron/cli | /lib/ninefold/services/runner.rb | UTF-8 | 385 | 2.609375 | 3 | [
"MIT"
] | permissive | # Runs stuff on remote hosts via ssh
require "shellwords"
module Ninefold
class Runner
def initialize(host, command)
print "\e[90mStarting the process, press ctrl+d when you're done:\e[0m\n"
begin
system "ssh -oStrictHostKeyChecking=no #{host} -t '#{command}'"
rescue Interrupt => e
print "\n\e[90mLater...\e[0m\n"
end
end
end
end
| true |
19286d9d9107435fd56f4ca9f69d7600d9b42dc6 | Ruby | franky-og/ruby-enumerables-hash-practice-green-grocer-lab-dumbo-web-82619 | /grocer.rb | UTF-8 | 1,773 | 3.0625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def consolidate_cart(cart)
# code here
consolidated_cart = {}
cart.map {|cart_item_hash|
if consolidated_cart.key?(cart_item_hash.keys.first) == true
consolidated_cart[cart_item_hash.keys.first][:count] += 1
else
consolidated_cart[cart_item_hash.keys.first] = cart_item_hash[cart_item_hash.keys.first]
consolidated_cart[cart_item_hash.keys.first][:count] = 1
end
}
return consolidated_cart
end
def apply_coupons(cart, coupons)
# code here
discounted_hash = cart
coupons.map {|coupon|
if cart.key?(coupon[:item]) == true && coupon[:num] <= cart[coupon[:item]][:count]
discounted_hash[coupon[:item] + " W/COUPON"]= {:price => coupon[:cost] / coupon[:num], :clearance => cart[coupon[:item]][:clearance], :count => cart[coupon[:item]][:count] - cart[coupon[:item]][:count] % coupon[:num]} #newcount = count - count%num
discounted_hash[coupon[:item]][:count] = discounted_hash[coupon[:item]][:count] - discounted_hash[coupon[:item] + " W/COUPON"][:count]
end
}
return discounted_hash
end
def apply_clearance(cart)
# code here
clearanced_hash = cart
clearanced_hash.map {|cart_item_key, cart_item_value|
if cart_item_value[:clearance] == true
cart_item_value[:price] = (cart_item_value[:price] * 0.80).round(2)
end
}
return clearanced_hash
end
def checkout(cart, coupons)
# code here
consolidated_cart = consolidate_cart(cart)
applied_coupons = apply_coupons(consolidated_cart, coupons)
applied_clearance= apply_clearance(applied_coupons)
final_value = applied_clearance.values.reduce(0) {|sum, cart_item_value|
sum + (cart_item_value[:price] * cart_item_value[:count])
}
if final_value > 100
final_value = final_value * 0.90
end
final_value
end
| true |
9504bcbed312d1c8c8a3b431b1258eda661e10f5 | Ruby | Willgg/freshair | /lib/tasks/airbnb/cache_all.rake | UTF-8 | 2,032 | 2.671875 | 3 | [] | no_license | namespace :airbnb do
desc "Scrap Airbnb for all destinations supported by Amadeus"
task cache_all: :environment do
destinations = Scraper::european_airports
dates = Scraper::dates
durations = Scraper::DURATIONS
adults_range = Scraper::PEOPLE
puts "#####################################"
puts "START AIRBNB SCRAPING ..."
puts "DESTINATIONS: #{destinations.inspect}"
puts "DATES: #{dates.inspect}"
puts "DURATIONS: #{durations.inspect}"
puts "PEOPLE: #{adults_range.inspect}"
puts "#####################################"
dates = dates.map { |date| date.to_date }
results = {}
count = 0
destinations.each do |destination|
results[destination] = {} if results[destination].nil?
dates.each do |date|
results[destination][date] = {} if results[destination][date].nil?
durations.each do |duration|
results[destination][date][duration] = {} if results[destination][date][duration].nil?
adults_range.each do |adults|
checkin = date
checkout = checkin + duration.days
request = AirbnbScrapping.new(destination, checkin, checkout , adults)
puts ''
puts '*** Request for ' + destination.to_s + ', checkin: ' + checkin.to_s + ', checkout:' + checkout.to_s + ', ' + adults.to_s + ' adults people ***'
price = request.scrap_price
price_person = ((price / adults) * duration).round(2)
results[destination][date][duration][adults] = price_person
puts '* ' + price_person.to_s + ' for ' + adults.to_s + ' adults for ' + duration.to_s + ' nights'
sleep [5, 4, 6, 7, 8, 9].sample
end
end
end
count += 1
puts (destinations.count - count).to_s + ' remaining destinations'
puts ''
$redis.set('airbnb', results.to_json)
end
puts "#####################################"
puts "AIRBNB SCRAPING DONE !"
puts "#####################################"
end
end
| true |
dee550d65ee2e5dd127c4c684b0fec604c8fc84b | Ruby | ElyKar/ElyKrawler | /TernarySearchTree.rb | UTF-8 | 2,352 | 3.53125 | 4 | [] | no_license | class TSTNode
attr_accessor :size
attr_accessor :c
attr_accessor :val
attr_accessor :left
attr_accessor :mid
attr_accessor :right
end
class TernarySearchTree
attr_accessor :root
attr_accessor :size
def initialize
@root = nil
@size = 0
end
def isEmpty?
return @size == 0
end
def size
return @size
end
def put(key, val)
@root = put_recur(@root, key, val, 0);
end
def put_recur(x, key, val, cur)
c = key[cur]
if !x then
x = TSTNode.new
x.c = key[cur]
end
if (c < x.c) then x.left = put_recur(x.left, key, val, cur)
elsif (c > x.c) then x.right = put_recur(x.right, key, val, cur)
elsif (cur < key.size - 1) then x.mid = put_recur(x.mid, key, val, cur+1)
else
if x.val then @size+=1 end
x.val = val
end
return x
end
def get(key)
x = get_recur(@root, key, 0)
if !x then return x end
return x.val
end
def get_recur(x, key, cur)
if !x then return x end
c = key[cur]
if (c < x.c) then return get_recur(x.left, key, cur)
elsif (c > x.c) then return get_recur(x.right, key, cur)
elsif (cur < key.size - 1) then return get_recur(x.mid, key, cur+1)
else return x end
end
def contains?(key)
return !get(key)
end
def remove(key)
stack = []
getPath(@root, key, 0, stack)
cur = stack.pop
if !cur then return cur end
res = cur.val
cur.val = nil
@size -= 1
if cur.mid then return res end
while (stack.size > 0 && cur)
cur.mid = nil
cur = stack.pop
end
return res
end
def getPath(x, key, cur, stack)
stack.push(x)
if !x then return end
c = key[cur]
if (c < x.c) then getPath(x.left, key, cur, stack)
elsif (c > x.c) then getPath(x.right, key, cur, stack)
elsif (cur < key.size - 1) then getPath(x.mid, key, cur+1, stack) end
end
def each
keys = []
vals = []
str = String.new("")
fill(@root, keys, vals, str, ' ', false)
while (keys.size > 0)
yield(keys.pop, vals.pop)
end
end
def fill(x, keys, vals, str, last, mid)
if !x then return end
if mid then str<<last end
if x.val then
keys.push(str+x.c)
vals.push(x.val)
end
fill(x.left, keys, vals, str, x.c, false)
fill(x.right, keys, vals, str, x.c, false)
fill(x.mid, keys, vals, str, x.c, true)
if mid then str.chop! end
end
def toString
self.each{|k, v| print "#{k} --> #{v}\n"}
end
end | true |
898c30a9227c72776f4960b2d0628519bf8fb0cf | Ruby | pschwyter/mtg_json_api | /app/models/listed_card.rb | UTF-8 | 2,008 | 2.96875 | 3 | [] | no_license | class ListedCard < ActiveRecord::Base
belongs_to :card
belongs_to :list
after_save :destroy_if_amount_zero
after_save :reconcile_inventory_and_trade
def add(n)
self.amount += n
self.save!
end
def remove(n)
if self.amount > n
self.amount -= n
self.save
else
self.destroy
end
end
def trade_to(user, qty)
original_owner = self.list.user
# Remove qty from the original_owners inventory list as well
if original_owner.inventory_cards.find_by(card_id: self.card_id)
original_owner.inventory_cards.find_by(card_id: self.card_id).remove(qty)
end
card = self.card
self.remove(qty)
# If receiving user already has the card in their inventory_list
if user.inventory_list.listed_cards.find_by(card_id: card.id)
lc = user.inventory_list.listed_cards.find_by(card_id: card.id)
lc.add(qty)
# If receiving user does NOT have the card in their inventory_list
elsif user.inventory_list.listed_cards.find_by(card_id: card.id) == nil
user.inventory_list.listed_cards.build(card: card, amount: qty)
user.inventory_list.save
else
raise "how did you mess up this bad?"
end
end
private
def destroy_if_amount_zero
self.destroy if self.amount <= 0
end
def reconcile_inventory_and_trade
user = self.list.user
if self.list.name == "tradeable_list"
if user.inventory_cards.find_by(card_id: self.card_id)
inventory_card = user.inventory_cards.find_by(card_id: self.card_id)
if inventory_card.amount < self.amount
inventory_card.amount = self.amount
inventory_card.save
end
else
inventory_card = ListedCard.create(list: user.inventory_list, amount: self.amount, card_id: self.card_id)
end
elsif self.list.name == "inventory_list"
if user.tradeable_cards.find_by(card_id: self.card_id)
tradeable_card = user.tradeable_cards.find_by(card_id: self.card_id)
if tradeable_card.amount > self.amount
tradeable_card.amount = self.amount
tradeable_card.save
end
end
end
end
end
| true |
f715b40f4cc37fc7685f0c6df4e3bac04f8699d4 | Ruby | LewisYoul/ruby-kickstart | /session3/notes/07-hash-iterating.rb | UTF-8 | 710 | 4.4375 | 4 | [
"MIT"
] | permissive | # in 1.8, HASHES ARE NOT ORDERED, if you iterate through them,
# you don't know what order they will be passed
# in 1.9, they will passed to your block in the order they were inserted.
# When you iterate over the hash, you pass it a block, just like
# arrays. But this block takes two arguments, the key and value
student_ids = {'Bill' => 25, 'Danya' => 15, 'Mei' => 12}
student_ids.each do |student, id|
puts "#{student}'s student id is #{id}"
end
# >> Bill's student id is 25
# >> Danya's student id is 15
# >> Mei's student id is 12
housemates = {
:tom => 35,
:lewis => 28,
:adam => 27
}
housemates.each { |name, age| #name = key, age = value
puts "#{name.to_s.capitalize}'s age is #{age}"
}
| true |
1f33e37f77ff16b31736c8e0977da0e08dbff055 | Ruby | jadamduff/ruby-objects-has-many-through-lab-v-000 | /lib/genre.rb | UTF-8 | 195 | 3.28125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Genre
attr_accessor :name, :songs, :artists
def initialize(name)
@name = name
@songs = []
end
def artists
self.songs.map {|song| song.artist if song.genre == self}
end
end
| true |
13e7480e63f2f78efe7af02d29f7f86f19500618 | Ruby | AjayKThakkar/News-aggregator-plus | /spec/features/user_posts_articles_spec.rb | UTF-8 | 1,312 | 2.546875 | 3 | [] | no_license | require "spec_helper"
feature "users can submit articles", %(
As a slacker
I want to be able to submit an incredibly interesting article
So that other slackers may benefit from my distraction
[x]the form accepts article, title, URL, and description.
[x]when I successfully post an article, it should be saved into a CSV file
[x]If I try to submit an empty form, I stay on my form page, and nothing is saved to my CSV file.
) do
scenario "User enters article details and hits submit, details are saved to csv" do
visit '/articles/new'
fill_in 'article_title', with: "Mechanic 'posed as general with helicopter to impress date'"
fill_in 'article_description', with: "A car mechanic has been indicted on charges of posing as a three-star US army general in order to land a helicopter, officials say."
fill_in 'article_url', with: "https://www.bbc.com/news/world-us-canada-44538395"
click_button 'Submit'
expect(page).to have_content("A car mechanic has been indicted on charges of posing as a three-star US army general in order to land a helicopter, officials say.")
end
scenario "User submits empty form, stays on same page, nothing is saved to csv" do
visit '/articles/new'
click_button 'Submit'
expect(page).to have_current_path('/articles/new')
end
end
| true |
c45d229eb05184a40520232e0cd7b8b694986110 | Ruby | skipjac/ruby-stuff | /generateGroups.rb | UTF-8 | 834 | 2.6875 | 3 | [] | no_license | require 'rubygems'
require 'httparty'
require 'pp'
require 'json'
require 'FileUtils'
require 'open-uri'
require 'nokogiri'
class Zenuser
include HTTParty
base_uri 'https://z3nofskip.zendesk.com'
headers 'content-type' => 'application/json'
def initialize(u, p)
@auth = {:username => u, :password => p}
end
def post(f)
json = JSON.generate "group"=>{"name"=>f}
options = { :body => json, :basic_auth => @auth}
#print options
self.class.post('/api/v1/entries.json', options)
end
end
x = Zenuser.new( 'email@gmail.com/token', 'token')
for s in 1...10
newGroup = "Skip Group " + ss
data = x.post(newGroup)
pp data.headers
if data.headers['status']== '201 Created'
print data.headers['location'] + "\n"
else
print data.headers['status'] + "\n"
end
end | true |
71511b895bdc274d7b3dbb0984ccfc57e4b695d8 | Ruby | feigningfigure/WDI_NYC_Apr14_String | /w01/d03/Keyan_Bagheri/Practice Problems/favorite_colors.rb | UTF-8 | 585 | 3.53125 | 4 | [] | no_license | def find_common_elements(array1,array2)
common_elements = []
array1.each do |item|
array2.each do |item2|
if item == item2
unless common_elements.include? item2
common_elements << item2
end
end
end
end
return common_elements
end
def array_plus(array1,array2)
array3 = array1 + array2
array3 = array3.flatten.uniq
return array3
end
def array_minus(array1,array2)
array = array1
array.each do |item|
array2.each do |item2|
if item == item2
array.delete(item)
end
end
end
return array
end
| true |
e786a37df005050d94392f366d70e3c1cdb31e83 | Ruby | codebar/planner | /lib/services/mailing_list.rb | UTF-8 | 1,699 | 2.546875 | 3 | [
"MIT"
] | permissive | class MailingList
SUBSCRIBED = 'subscribed'.freeze
MEMBER_EXISTS = 'Member Exists'.freeze
attr_reader :list_id
def initialize(list_id)
@list_id = list_id
end
def subscribe(email, first_name, last_name)
return if disabled?
begin
client.lists(list_id).members
.create(body: { email_address: email,
status: 'subscribed',
merge_fields: { FNAME: first_name, LNAME: last_name } })
rescue Gibbon::MailChimpError => e
reactivate_subscription(email, first_name, last_name) if e.title.eql?(MEMBER_EXISTS)
end
end
handle_asynchronously :subscribe
def unsubscribe(email)
return if disabled?
client.lists(list_id).members(md5_hashed_email_address(email))
.update(body: { status: 'unsubscribed' })
rescue Gibbon::MailChimpError
false
end
handle_asynchronously :unsubscribe
def reactivate_subscription(email, first_name, last_name)
return if disabled?
client.lists(list_id).members(md5_hashed_email_address(email))
.upsert(body: { email_address: email,
status: 'subscribed',
merge_fields: { FNAME: first_name, LNAME: last_name } })
end
def subscribed?(email)
return if disabled?
info = client.lists(list_id).members(md5_hashed_email_address(email)).retrieve
info.body[:status].eql?(SUBSCRIBED)
rescue Gibbon::MailChimpError
false
end
private
def client
@client ||= Gibbon::Request.new
end
def md5_hashed_email_address(email)
require 'digest'
Digest::MD5.hexdigest(email.downcase)
end
def disabled?
!ENV['MAILCHIMP_KEY']
end
end
| true |
9d861fb3ebda32cf2756f3878165e3f8bd494174 | Ruby | rizo/crystal | /spec/type_inference/c_enum_spec.rb | UTF-8 | 693 | 2.546875 | 3 | [] | no_license | require 'spec_helper'
describe 'Type inference: enum' do
it "types enum value" do
mod, type = assert_type("lib Foo; enum Bar; X, Y, Z = 10, W; end end Foo::Bar::X") { int32 }
end
it "allows using an enum as a type in a fun" do
assert_type(%q(
lib C
enum Foo
A
end
fun my_mega_function(y : Foo) : Foo
end
C.my_mega_function(C::Foo::A)
)) { int32 }
end
it "allows using an enum as a type in a struct" do
assert_type(%q(
lib C
enum Foo
A
end
struct Bar
x : Foo
end
end
f = C::Bar.new
f.x = C::Foo::A
f.x
)) { int32 }
end
end
| true |
e3d2e5dc8be9564ec7227b86c308ab2dec35b14a | Ruby | Troy76/Task-List | /task_list.rb | UTF-8 | 408 | 3.1875 | 3 | [] | no_license | task_list = Hash.new
puts "What do you want to put on your task list?"
task = gets.chomp
while task != "exit"
if task_list.has_key?(task)
puts "You already have that task"
else
task_list[task] = 1
end
puts "Do you want to add anything else on your task list. Type exit to find out what is on your list."
task = gets.chomp
end
task_list.each do |task, number|
puts "-You must #{task}"
end | true |
151fc88ddf7c9147768487f79bbdce791d178723 | Ruby | jievans/Chess | /employee.rb | UTF-8 | 1,158 | 3.9375 | 4 | [] | no_license | class Employee
attr_accessor :manager
attr_reader :name, :title, :salary
def initialize(name, title, salary, multiplier = 0.2)
@name = name
@title = title
@salary = salary
@multiplier = multiplier
end
def bonus
@salary * @multiplier
end
end
class Manager < Employee
attr_reader :employees
def initialize(name, title, salary, multiplier = 0.3)
super(name, title, salary, multiplier)
@employees = []
end
def calculate_under_salary
total_salaries = 0
@employees.each do |employee|
if employee.is_a?(Manager)
total_salaries += employee.calculate_under_salary
end
total_salaries += employee.salary
end
total_salaries
end
def calculate_bonus
(@salary + calculate_under_salary) * @multiplier
end
def bonus
calculate_bonus
end
def add_employee(employee)
employee.manager = self
@employees << employee
end
end
james = Employee.new("James", "Staffer", 50000)
boss = Manager.new("Bosser", "Boss", 60000)
more_boss = Manager.new("MoreBosser", "Super Boss", 70000)
more_boss.add_employee(boss)
boss.add_employee(james)
puts more_boss.bonus | true |
5aa576483459f36c3192ae4c8d7973bc13d33bda | Ruby | sjmog/battleships | /lib/ship.rb | UTF-8 | 177 | 2.875 | 3 | [] | no_license | class Ship
attr_reader :position, :size, :direction
def initialize(position, size, direction)
@position = position
@size = size
@direction = direction
end
end | true |
671998f60ce0a95e134cd6c9b79701f89d04b821 | Ruby | apotonick/gemgem | /app/concepts/rating.rb | UTF-8 | 4,953 | 2.828125 | 3 | [] | no_license | # ### Entity
# initialize
# populate
# save/sync
# update_attributes (save strategy)
# accessors
# why: to let the database layer be awesome but without business logic
# ActiveRecord/ActiveModel stuff is optional, so you can start working on a nested concept without having to implement the outer stuff (rateable)
# * make a validation where the thing is only valid when "owned"?
class Rating < ActiveRecord::Base
# TODO: one example with clean Persistance approach, one with facade for a legacy monolith.
belongs_to :thing
belongs_to :user
module Form
include Reform::Form::Module
property :comment
property :weight
# i want rateable to be an actual object so i can verify it is a valid rateable_id!
property :thing, virtual: true #, populate_if_empty: lambda { |fragment, *| Thing.find(fragment[:id]) } do
#end # TODO: mark as typed. parse_strategy: :find_by_id would actually do what happens in the controller now.
validates :comment, length: { in: 6..160 }
validates :thing, presence: true
end
# think of this as Operation::Update
class Create < Trailblazer::Operation
builds do |params|
SignedIn if params[:current_user]
end
contract do
include Reform::Form::ModelReflections
include Form
model :rating
validates :weight, presence: true
# DISCUSS: this is presentation.
def weight # only for presentation layer (UI).
super or 1 # select Nice!
end
# TODO: if this remains necessary, implement readonly: true in Reform.
def thing=(*)
# property :thing, readonly: true
# it should not be allowed!
end
property :user, populate_if_empty: User do # we could create the User in the Operation#process?
# property :name
property :email
validates :email, presence: true
# validates :email, email: true
#validates_uniqueness_of :email # this assures the new user is new and not an existing one.
# this should definitely NOT sit in the model.
validate :confirmed_or_new_and_unique?
def confirmed_or_new_and_unique?
existing = User.find_by_email(email)
return if existing.nil?
return if existing and existing.password_digest
errors.add(:email, "User needs to be confirmed first.")
end
end
validates :user, presence: true
end
include CRUD
model Rating
def process(params) # or (params, env)
# I don't want that as populate_if_empty bull.
model.thing = Thing.find_by_id(params[:id])
#model = SignedInRating.new(@model, user: current_user)
validate(params[:rating]) do |f|
@unconfirmed = !f.user.model.persisted? # if we create the user here, we don't need this logic?
# should that go to the Twin?
# @needs_confirmation_to_proceed
f.save # save rating and user.
# TODO: test this via OP#ran
Monban::ConfirmLater[id: f.model.user.id] # set confirmation_token.
# send_confirmation_email(f) if @unconfirmed
# notify!
end
end
# i hereby break the statelessness!
def unconfirmed?
@unconfirmed
end
class SignedIn < self
contract do
property :user, virtual: true # don't read user: field anymore, (but save it?????)
property :thing, virtual: true # TODO: should be readonly: true
# FIXME: find out why this is not inherited?
# def confirmed_or_new_and_unique?; end # TODO: make it simple to remove validations.
end
def process(params)
# demonstrates that we're not bound to hashs, only.
model.user = params[:current_user] # this is always present as it comes from the caller?
model.thing = Thing.find_by_id(params[:id])
validate(params[:rating]) do |f|
f.save # save rating and user.
end
end
end
end
class New < Create
def setup!(params)
thing = Thing.find(params[:id])
@model = Rating.new(thing_id: thing.id)
@model.build_user
end
end
class Delete < Trailblazer::Operation
def process(params)
model = Rating.find(params[:id])
model.update_column(:deleted, 1)
model
end
end
class Undo < Trailblazer::Operation
def process(params)
# note that we could also use a Form here.
model = Rating.find(params[:id])
model.update_column(:deleted, 0)
model
end
end
class Twin < Disposable::Twin
def deleted?
model.deleted == 1
end
end
# name for "intermediate data copy can can sync back to twin"... copy, twin, shadow
# property :rateable#, getter: lambda { |*| } # TODO: mark an attribute as prototype (not implemented in persistance, yet)
# TODO: make it simple to override def rateable, etc.
# Entity doesn't know about ids, form doesn't know about associations?
end
| true |
acbb73e419b540cd9e91875762ba860745347c48 | Ruby | extreem-engineer/extreme-engineer3 | /Strategy/bucho.rb | UTF-8 | 313 | 2.953125 | 3 | [] | no_license | require_relative 'Yakushoku'
class Bucho < Yakushoku
def ask
puts "従来のやり方を踏襲しましょう。"
end
def settle_expense(expense)
puts "部長の東京大阪間の新幹線 グリーン席 #{expense} + 手当 #{teate} です。"
end
def teate
5000
end
end
| true |
016c24046df6c9858b230d1f228da4aa3d8a26dc | Ruby | heathercreighton/atl-ft-nov2016 | /Rails/heather_twitter/app/helpers/tweets_helper.rb | UTF-8 | 1,223 | 2.953125 | 3 | [] | no_license | module TweetsHelper
def get_tagged(tweet)
#Create an empty array to store an instance of our TweetTag data
tweet_tag = []
message_arr = tweet.message.split
message_arr.each_with_index do |word, index|
if word[0] == "#"
if Tag.pluck(:phrase).include?(word)
tag = Tag.find_by(phrase: word)
else
tag = Tag.create(phrase: word)
end
#Below we create a TweetTag record for our model, but we still don't have a tweet.id assigned, so it is initially being created as nil.
tweet_tag = TweetTag.create(tweet_id: tweet.id, tag_id: tag.id)
message_arr.delete(word)
message_arr[index] = "<a href='/tag_tweets?id=#{tag.id}'>#{word}</a>"
#message_arr[index] = "<%= link_to #{word}, tag_tweets_path(id: #{tag.id}) %>"
end
end
#tweet.message = message_arr.join(" ")
tweet.update(message: message_arr.join(" "))
#Stores the newly assigned tweet.id into out TweetTag model tying it to the tag.id.
tweet_tag.update(tweet_id: tweet.id)
return tweet
end
end
| true |
818b27b99f36085d5b3a71e04c7ed558aed5837d | Ruby | unixpickle/PushProvider | /RKBKit/BinaryValue.rb | UTF-8 | 883 | 2.609375 | 3 | [] | no_license | #!/usr/bin/ruby
require 'StringValue'
module KeyedBits
class BinaryString < String
def kbHeader()
lenLen = KeyedBits.bytesRequiredForLength(self.bytesize)
Header.new(Header::TypeData, lenLen, false)
end
def kbWrite(stream)
header = kbHeader
stream.putc(header.encode)
# write length + data
len = header.lenLength
encodedLen = IntCoding.new(self.bytesize).encode(len)
stream.write(encodedLen)
stream.write(self)
end
def BinaryString.kbDecodeType()
Header::TypeData
end
def BinaryString.kbDecode(stream, header)
BinaryString.new(KeyedBits.readDataValue(stream, header))
end
def to_s
buff = "<"
bytes = unpack('C' * length).collect {|x| x.to_s(16)}
for i in (0..(bytes.length - 1))
if i % 4 == 0 && i > 0
buff << " "
end
buff << bytes[i].rjust(2, '00')
end
buff << ">"
end
end
end
| true |
8ec3a9cccc9a2d1e223676b34be323a661cc240f | Ruby | jmandala/epub_hero | /app/models/product.rb | UTF-8 | 1,242 | 2.8125 | 3 | [] | no_license | class Product < ActiveRecord::Base
module COMPLEXITIES
SIMPLE = :simple
IMAGE_RICH = :image_rich
COMPLEX = :complex
ALL = [SIMPLE, IMAGE_RICH, COMPLEX]
ALL.freeze
end
COMPLEXITIES.freeze
validates_presence_of :title, :print_isbn, :eisbn, :complexity
validates_length_of :title, :in => 1..256, :allow_blank => true
validates_length_of :subtitle, :maximum => 256, :allow_blank => true
validates_length_of :print_isbn, :in => 13..20, :allow_blank => true
validates_length_of :eisbn, :in => 13..20, :allow_blank => true
# validates_inclusion_of :complexity, :in => COMPLEXITIES::ALL
validates_uniqueness_of :print_isbn, :eisbn
def to_s
"#{title} [eisbn: #{eisbn.gsub(/-/, '')}]"
end
def to_param
@__to_param = nil if title_changed? # clear the cached value if title has changed
@__to_param ||= begin # read cached value or recalculate slug
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}".squeeze('-')[0..19]
end
end
def self.getComplexity(c)
case c
when 'simple'
return COMPLEXITIES::SIMPLE
when 'image_rich'
return COMPLEXITIES::IMAGE_RICH
when 'complex'
return COMPLEXITIES::COMPLEX
end
end
end
| true |
a7d0704027963bf29d2f3dfbed5513069389672f | Ruby | weemanjz/pairguru | /app/services/movie_data_puller.rb | UTF-8 | 529 | 2.671875 | 3 | [] | no_license | class MovieDataPuller
BASE_URI = "https://pairguru-api.herokuapp.com/api/v1/movies".freeze
def call(title)
@title = title
do_request
parsed_response.dig("data", "attributes") || {}
end
private
attr_reader :title, :response
def do_request
@response = Rails.cache.fetch("#{title} API data", expires_in: 24.hours) do
uri = URI.encode("#{BASE_URI}/#{title}")
Net::HTTP.get(URI(uri))
end
end
def parsed_response
JSON.parse(response)
rescue JSON::ParserError
{}
end
end
| true |
3701f6b33956487f83cdaac708d8cd4de6c00ebb | Ruby | mhing/Quixo-Board-Game | /default_scene/players/pieces.rb | UTF-8 | 13,548 | 2.765625 | 3 | [] | no_license | require "game"
require "placement"
require "minimax"
require "ai"
module Pieces
prop_reader :board
prop_reader :victory
def mouse_clicked(e)
place = Placement.new
turn_bar = scene.find("turn_bar")
status_bar = scene.find("status_bar")
###Human vs Human
if production.game_type == "Two Player Game"
if production.pull_position == nil
pulling_of_piece(place,status_bar)
elsif place.legal_push_position(production.pull_position, (self.id).to_i)
pushing_of_piece
else
check_for_undo(status_bar)
end
###Human vs AI
elsif production.game_type == "One Player Game"
if production.pull_position == nil
if production.game.current_turn == "X"
pulling_of_piece(place,status_bar)
end
elsif place.legal_push_position(production.pull_position, (self.id).to_i) && production.game.current_turn == "X"
production.comp_player.set_prev_board(production.game.board)
pushing_of_piece
check_victory
production.comp_player.set_current_board(production.game.board)
if check_victory == false
make_computer_move(place)
end
check_victory
else
check_for_undo(status_bar)
end
end
end
private #########################
def make_computer_move(place)
minmax = Minimax.new
best_move = []
status_bar = scene.find("status_bar")
best_move = minmax.evaluate_possible_moves(production.game.board,"O",production.comp_difficulty)
computer_pull_piece(place,best_move[0])
delay
computer_push_piece(status_bar,place,best_move[1])
highlight_comp_pull
check_victory
end
def delay
5000000.times do
end
end
def computer_pull_piece(place,pull)
pull_pos = pull
game_piece = scene.find(pull)
game_piece.style.background_color = "#5E0900"
game_piece.style.text_color = "tan"
if place.legal_pull_position(pull_pos) && pull_pos != nil
if production.game.board[pull_pos] == "O"
production.pull_position = pull_pos
elsif production.game.board[pull_pos] == nil
production.pull_position = pull_pos
end
end
production.comp_pull = production.pull_position
end
def computer_push_piece(status_bar,place,push)
push_pos = push
if place.legal_push_position(production.pull_position, push_pos)
production.push_position = push_pos
increment_turn
status_bar.text = "Piece Placed"
production.game.shift_board(production.pull_position, production.push_position, "O")
production.game.board[production.push_position] = "O"
production.pull_position = nil
production.game.change_turn
check_victory
board.update
change_turn
highlight_previous_move
end
end
def check_for_undo(status_bar)
if production.pull_position != nil
if production.pull_position == (self.id).to_i
undo_move
else
status_bar.text = "Illegal Push Position"
end
end
highlight_previous_move
end
def pushing_of_piece
production.push_position = (self.id).to_i
increment_turn
shift
check_victory
board.update
change_turn
highlight_previous_move
end
def pulling_of_piece(place,status_bar)
if place.legal_pull_position((self.id).to_i)
if production.game_type == "Two Player Game"
timer_config
end
select_piece
find_legal_moves
else
status_bar.text = "Illegal Pull Position"
end
end
def timer_config
if production.timed_game == "Yes" && production.new_game == "Yes"
production.timer_started = "Yes"
timer_start
production.new_game = "No"
end
end
def timer_start
status_bar = scene.find("status_bar")
no_time = scene.find("no_time")
stats_button = scene.find('stats')
production.player1_sec = 60
production.player1_min = production.game_length_min - 1
production.player2_sec = 60
production.player2_min = production.game_length_min - 1
production.animation = animate(:updates_per_second => 1) do
if production.game.current_turn == "X"
timer1 = scene.find("player1_timer")
if production.player1_sec == 0
production.player1_min = production.player1_min - 1
production.player1_sec = 60
end
production.player1_sec = production.player1_sec - 1
if production.player1_sec >= 10
timer1.text = "#{production.player1_min}:#{production.player1_sec}"
elsif production.player1_sec >= 0
timer1.text = "#{production.player1_min}:0#{production.player1_sec}"
end
if production.player1_sec == 0 && production.player1_min == 0
status_bar.text = "#{production.player2} Wins, #{production.player1} Ran Out Of Time"
production.animation.stop
stats_button.style.width = 90
stats_button.style.height = 25
no_time.style.width = 354
no_time.style.height = 354
end
elsif production.game.current_turn == "O"
timer2 = scene.find("player2_timer")
if production.player2_sec == 0
production.player2_min = production.player2_min - 1
production.player2_sec = 60
end
production.player2_sec = production.player2_sec - 1
if production.player2_sec >= 10
timer2.text = "#{production.player2_min}:#{production.player2_sec}"
elsif production.player2_sec >= 0
timer2.text = "#{production.player2_min}:0#{production.player2_sec}"
end
if production.player2_sec == 0 && production.player2_min == 0
status_bar.text = "#{production.player1} Wins, #{production.player2} Ran Out Of Time"
production.animation.stop
stats_button.style.width = 90
stats_button.style.height = 25
no_time.style.width = 354
no_time.style.height = 354
end
end
end
end
def increment_turn
if production.game.current_turn == "X"
production.player1_turns = production.player1_turns + 1
elsif production.game.current_turn == "O"
production.player2_turns = production.player2_turns + 1
end
end
def highlight_comp_pull
pos = production.comp_pull
game_piece = scene.find(pos)
game_piece.style.background_color = "#004358"
game_piece.style.text_color = "tan"
end
def highlight_previous_move
if production.game.prev_turn != ""
pos = production.push_position
game_piece = scene.find(pos)
game_piece.style.background_color = "#CCFFFF"
end
end
def find_legal_moves
if production.pull_position != nil
count = 0
if production.pull_position == 0
legals = [4,20]
elsif production.pull_position == 1
legals = [0, 4, 21]
elsif production.pull_position == 2
legals = [0, 4, 22]
elsif production.pull_position == 3
legals = [0, 4, 23]
elsif production.pull_position == 4
legals = [0, 24]
elsif production.pull_position == 5
legals = [0, 9, 20]
elsif production.pull_position == 9
legals = [4, 5, 24]
elsif production.pull_position == 10
legals = [0, 14, 20]
elsif production.pull_position == 14
legals = [4, 10, 24]
elsif production.pull_position == 15
legals = [0, 19, 20]
elsif production.pull_position == 19
legals = [4, 15, 24]
elsif production.pull_position == 20
legals = [0, 24]
elsif production.pull_position == 21
legals = [1, 20, 24]
elsif production.pull_position == 22
legals = [2, 20, 24]
elsif production.pull_position == 23
legals = [3, 20, 24]
elsif production.pull_position == 24
legals = [4, 20]
end
legals.each do
count = count + 1
end
count.times do |i|
pos = legals[i]
game_piece = scene.find(pos)
game_piece.style.background_color = "chartreuse"
end
end
end
def undo_move
status_bar = scene.find("status_bar")
self.style.background_color = "tan"
self.style.text_color = "#004358"
board.update
production.pull_position = nil
status_bar.text = "Piece Returned"
end
def select_piece
status_bar = scene.find("status_bar")
if production.game.board[(self.id).to_i] == "X"
if production.game.current_turn == "X"
status_bar.text = "An X Was Pulled"
pull_piece
elsif production.game.current_turn == "O"
status_bar.text = "Invalid Move. That Is Not Your Piece"
end
elsif production.game.board[(self.id).to_i] =="O"
if production.game.current_turn == "O"
status_bar.text = "An O Was Pulled"
pull_piece
elsif production.game.current_turn == "X"
status_bar.text = "Invalid Move. That Is Not Your Piece"
end
else
status_bar.text = "Blank Piece Pulled"
pull_piece
end
end
def pull_piece
production.pull_position = (self.id).to_i
self.style.background_color = "#5E0900"
self.style.text_color = "tan"
end
def shift
status_bar = scene.find("status_bar")
self.text = production.game.current_turn
status_bar.text = "Piece Placed"
production.game.shift_board(production.pull_position, production.push_position, self.text)
production.game.board[production.push_position] = self.text
production.pull_position = nil
production.game.change_turn
end
def check_victory
status_bar = scene.find("status_bar")
if production.game.victory?("O")
if production.timed_game == "Yes"
production.animation.stop
end
if production.player2 == ""
status_bar.text = "Player 2 Wins!"
else
status_bar.text = "#{production.player2} Wins!"
end
strike_victory
board.update
return true
elsif production.game.victory?("X")
if production.timed_game == "Yes"
production.animation.stop
end
if production.player1 == ""
status_bar.text = "Player 1 Wins!"
else
status_bar.text = "#{production.player1} Wins!"
end
strike_victory
board.update
return true
end
return false
end
def strike_victory
stats_button = scene.find('stats')
stats_button.style.width = 90
stats_button.style.height = 25
strike = scene.find("strike_through")
strike.style.transparency = 20
strike.style.width = 354
strike.style.height = 354
if production.game.win_row == 0
strike.style.top_padding = 30
strike.style.left_padding = 2
strike.style.right_padding = 2
strike.rotation = 0
elsif production.game.win_row == 1
strike.style.top_padding = 100
strike.style.left_padding = 2
strike.style.right_padding = 2
strike.rotation = 0
elsif production.game.win_row == 2
strike.style.top_padding = 170
strike.style.left_padding = 2
strike.style.right_padding = 2
strike.rotation = 0
elsif production.game.win_row == 3
strike.style.top_padding = 240
strike.style.left_padding = 2
strike.style.right_padding = 2
strike.rotation = 0
elsif production.game.win_row == 4
strike.style.top_padding = 310
strike.style.left_padding = 2
strike.style.right_padding = 2
strike.rotation = 0
elsif production.game.win_col == 0
strike.style.top_padding = 2
strike.style.left_padding = 30
strike.style.bottom_padding = 2
strike.rotation = 90
elsif production.game.win_col == 1
strike.style.top_padding = 2
strike.style.left_padding = 100
strike.style.bottom_padding = 2
strike.rotation = 90
elsif production.game.win_col == 2
strike.style.top_padding = 2
strike.style.left_padding = 170
strike.style.bottom_padding = 2
strike.rotation = 90
elsif production.game.win_col == 3
strike.style.top_padding = 2
strike.style.left_padding = 240
strike.style.bottom_padding = 2
strike.rotation = 90
elsif production.game.win_col == 4
strike.style.top_padding = 2
strike.style.left_padding = 310
strike.style.bottom_padding = 2
strike.rotation = 90
elsif production.game.diag_win == "down_right"
strike.style.padding = 4
strike.rotation = 45
elsif production.game.diag_win == "up_right"
strike.style.left_padding = 4
strike.style.top_padding = 4
strike.rotation = 135
end
end
def change_turn
timer1 = scene.find("player1_timer")
timer2 = scene.find("player2_timer")
turn_bar = scene.find("turn_bar")
p1 = scene.find("p1")
p2 = scene.find("p2")
if production.game.current_turn == "X"
p1.style.background_color = "#CCFFFF"
p2.style.background_color = "#D99963"
if production.player1 == ""
turn_bar.text = "It's #{production.game.current_turn}'s Turn"
else
turn_bar.text = "It's #{production.player1}'s Turn"
end
else
p1.style.background_color = "#D99963"
p2.style.background_color = "#CCFFFF"
if production.player2 == ""
turn_bar.text = "It's #{production.game.current_turn}'s Turn"
else
turn_bar.text = "It's #{production.player2}'s Turn"
end
end
end
end | true |
31885d468188194adf109e049f4017f8b6ec757a | Ruby | rsupak/tc-challenges | /RubySnake/game.rb | UTF-8 | 2,248 | 3.21875 | 3 | [] | no_license | require 'ruby2d'
require_relative './lib/snake'
# window constants
set title: 'Ruby Snake'
set background: 'lime'
set fps_cap: 10
set width: 640
set height: 640
GRID_SIZE = 20
GRID_WIDTH = Window.width / GRID_SIZE
GRID_HEIGHT = Window.height / GRID_SIZE
# main class
class Game
attr_accessor :apple
attr_reader :finished, :score
def initialize
@score = 0
@apple = nil
@apple_x = rand(GRID_WIDTH)
@apple_y = rand(GRID_HEIGHT)
@finished = false
select_apple
end
# randomly chooses apple to draw and assigns points depending on apple size
def select_apple
apples = { big_apple: ['img/BigApple.png', 2],
small_apple: ['img/SmallApple.png', 1] }
@apple = apples[apples.keys.sample]
end
# draws apple and score board onto the window
def draw
unless finished
Image.new(@apple[0],
x: @apple_x * GRID_SIZE,
y: @apple_y * GRID_SIZE)
end
Text.new(text_message, color: 'navy', x: 10, y: 10, size: 25)
end
# checks to see if snake run into the apple
def snake_hit_apple?(x, y)
@apple_x == x && @apple_y == y
end
# if snake has hit apple, add to score and draw new apple
def record_hit
@score += @apple[1]
select_apple
@apple_x = rand(GRID_WIDTH)
@apple_y = rand(GRID_HEIGHT)
end
# checks for game over
def finish
@finished = true
end
private
# sets scoreboard messages
def text_message
if finished
"Game Over! Final Score: #{@score}! Press R to restart"
else
"Score: #{@score}"
end
end
end
# game loop
if $PROGRAM_NAME == __FILE__
snake = Snake.new
game = Game.new
update do
clear
snake.move unless game.finished
snake.draw
game.draw
if game.snake_hit_apple?(snake.x, snake.y)
prev_score = game.score
game.record_hit
until prev_score == game.score
snake.grow
prev_score += 1
end
end
game.finish if snake.collision?
end
on :key_down do |event|
if %w[up down left right].include?(event.key) &&
snake.can_change_direction_to?(event.key)
snake.direction = event.key
elsif event.key == 'r'
snake = Snake.new
game = Game.new
end
end
show
end
| true |
b0ef7cae1a9877140ecc7eeefdf1e8794724d5ad | Ruby | priscillashort/cs271 | /06/assembler/assembler.rb | UTF-8 | 968 | 3.015625 | 3 | [] | no_license | require_relative 'parser'
require_relative 'variable_manager'
require 'fileutils'
class Assembler
attr_reader :asm_file_name, :hack_file_name, :variable_manager
def initialize(asm_file_name)
@asm_file_name = asm_file_name
@hack_file_name = create_hack_file_name
@variable_manager = VariableManager.new
end
def translate_program
create_hack_file
parser = Parser.new(@hack_file_name)
File.open(asm_file_name).each do |line|
parser.add_label_variables(line, variable_manager)
end
File.open(asm_file_name).each do |line|
parser.parse(line, variable_manager)
end
end
def create_hack_file_name
if asm_file_name[/\.asm$/] != ".asm"
raise "This is not an .asm file"
end
return asm_file_name.gsub(/\.asm$/, ".hack")
end
def create_hack_file
if File.exists?(@hack_file_name)
FileUtils.rm(@hack_file_name)
end
FileUtils.touch(@hack_file_name)
end
end
assembler = Assembler.new(ARGV[0])
assembler.translate_program
| true |
efd571230c2dff53f7947b300e7ec8f0d4a887c0 | Ruby | djmetzle/project_euler | /113_ruby/solve.rb | UTF-8 | 1,451 | 3.796875 | 4 | [] | no_license | #!/usr/bin/ruby
puts "Euler 113"
def get_single_digit_array
single_digits = Array.new(10, 1)
single_digits[0] = 0
return single_digits
end
def print_out digit_array
digit_array.each_with_index do |x, i|
puts " #{i}: #{x}"
end
end
def iterate_inc digit_array
next_array = Array.new(10,0)
(1..9).each { |i|
(1..9).each { |j|
if i >= j
next_array[i] += digit_array[j]
end
}
}
return next_array
end
def iterate_dec digit_array
next_array = Array.new(10,0)
(0..9).each { |i|
(0..9).each { |j|
if i <= j
next_array[i] += digit_array[j]
end
}
}
return next_array
end
def inc_table n
by_digits = []
by_digits[1] = get_single_digit_array
(2..n).each { |d|
by_digits[d] = iterate_inc by_digits[d-1]
}
return by_digits
end
def dec_table n
by_digits = []
by_digits[1] = get_single_digit_array
(2..n).each { |d|
by_digits[d] = iterate_dec by_digits[d-1]
}
return by_digits
end
def n_increasing n
table = inc_table n
return table.reject(&:nil?).map { |row| row.reduce(:+) }.reduce(:+)
end
def n_decreasing n
table = dec_table n
return table.reject(&:nil?).map { |row| row.reduce(:+) }.reduce(:+)
end
def n_duplicates n
return 9*n
end
def n_total n
return puts n_increasing(n) + n_decreasing(n) - n_duplicates(n)
end
puts n_total 6
puts n_total 10
puts n_total 100
| true |
4e1667a907bdf4485a923fe895eb9fd1e40f7dc5 | Ruby | OMGDuke/takeaway-challenge | /lib/order.rb | UTF-8 | 970 | 3.484375 | 3 | [] | no_license | require_relative "message"
class Order
def initialize(menu, message_class=Message)
@my_order = []
@menu = menu
@message_class = message_class
end
def my_order
@my_order.dup
end
def add(item, number = 1)
message = "This item is not on the menu"
fail message unless on_menu?(item)
number.times {dish_finder(item)}
end
def order_cost
@total = 0
my_order.each do |item|
@total += item.price
end
@total
end
def confirm(pay)
pay_err = "You have not paid enough, "\
"The total is £#{format('%.2f', order_cost)}"
fail pay_err if not_enough?(pay)
@message_class.new(del_time).send
end
private
def not_enough?(pay)
pay != order_cost
end
def del_time
(Time.now + 3600).strftime("%H:%M")
end
def on_menu?(item)
@menu.dishes.any? {|dish| dish.name == item}
end
def dish_finder(item)
@my_order << @menu.dishes.detect {|dish| dish.name == item }
end
end
| true |
c88ff9a02e119d210502c927e07d14a88dfede85 | Ruby | alexanderplotnikov/learn_ruby | /05_book_titles/book.rb | UTF-8 | 497 | 3.671875 | 4 | [] | no_license | class Book
# write your code here
attr_accessor :title
def title
@res = []
@littleWords = ['the', 'over', 'a', 'to', 'from', 'and', 'an', 'in', 'of']
@words = @title.split(" ")
@words.each do |word|
if(not @littleWords.include?(word))
@res.push(word.capitalize())
else
@res.push(word)
end
end
@res[0] = @res[0].capitalize()
@res.join(" ")
end
end
| true |
d83863179973798445d6b4df987fa5b3e1a4af1e | Ruby | pierreboulanger/fullstack-challenges | /02-OOP/05-Food-Delivery-Day-One/Lars-01-Food-Delivery/app/models/employee.rb | UTF-8 | 431 | 3.078125 | 3 | [] | no_license | class Employee
attr_accessor :orders, :id
attr_reader :password, :status, :name
def initialize(attributes = {})
@id = attributes[:id]
@name = attributes[:name]
@password = attributes[:password]
@status = attributes[:status]
@orders = []
end
def password(password)
password_checker(password)
end
private
def password_checker(password)
@password == password ? true : false
end
end
| true |
b4e906ce8c40939c361e2c67dcfa5bb81247105d | Ruby | Dequisa/dailyprogrammer | /projecteuler-ruby/p1_multiples_of_3_and_4.rb | UTF-8 | 548 | 4.15625 | 4 | [] | no_license |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
def sumOfAllMultiples(multiples = [3,5], limit = 1000)
sum = 0
(0...limit).each do |element|
sum += isMultiple(element, multiples) ? element : 0
end
return sum
end
def isMultiple(element, multiples)
multiples.each do |multiple|
if element % multiple == 0
return true
end
end
return false
end
puts sumOfAllMultiples
| true |
63b05473ca25618c7f19bc34cec9b3e30ecd8f30 | Ruby | berto168/sinatra-mvc-lab-web-0916 | /models/piglatinizer.rb | UTF-8 | 530 | 3.796875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class PigLatinizer
VOWELS = "aeiou"
def piglatinize(word)
if VOWELS.include?(word[0].downcase)
word = word + "way"
else
split_word = word.split("")
first_vowel = split_word.find {|letter| VOWELS.include?(letter)}
first_vowel_index = split_word.index(first_vowel)
first_vowel_index.times {split_word << split_word.shift}
split_word.join("") + "ay"
end
end
def to_pig_latin(phrase)
words = phrase.split(" ")
words.map {|word| piglatinize(word)}.join(" ")
end
end
| true |
cc8dedf4ea84df65ca05d90509346b8365534c54 | Ruby | moebooru/moebooru | /lib/dtext.rb | UTF-8 | 4,504 | 2.78125 | 3 | [
"ISC"
] | permissive | # encoding: utf-8
module DText
def parse(str)
return "" unless str
state = ["newline"]
result = ""
# Normalize newlines.
str.strip!
str.gsub!(/(\r\n?)/, "\n")
str.gsub!(/\n{3,}/, "\n\n")
str = CGI.escapeHTML str
# Nuke spaces between newlines.
str.gsub!(/ *\n */, "\n")
# Keep newline, use carriage return for split.
str.gsub!("\n", "\n\r")
data = str.split("\r")
# Parse header and list first, line by line.
data.each do |d|
result << parseline(d, state)
end
# Parse inline tags as a whole.
result = parseinline(result)
# Nokogiri ensures valid html output.
Nokogiri::HTML::DocumentFragment.parse(result).to_html
end
def parseinline(str)
# Short links subtitution:
str.gsub!(/\[\[(.+?)\]\]/) do # [[title]] or [[title|label]] ;link to wiki
data = Regexp.last_match[1].split("|", 2)
title = data[0]
label = data[1].nil? ? title : data[1]
"<a href=\"/wiki/show?title=#{CGI.escape(CGI.unescapeHTML(title.tr(" ", "_")))}\">#{label}</a>"
end
str.gsub!(/\{\{(.+?)\}\}/) do # {{post tags here}} ;search post with tags
"<a href=\"/post?tags=#{CGI.escape(CGI.unescapeHTML(Regexp.last_match[1]))}\">#{Regexp.last_match[1]}</a>"
end
# Miscellaneous single line tags subtitution.
str.gsub! /\[b\](.+?)\[\/b\]/, '<strong>\1</strong>'
str.gsub! /\[i\](.+?)\[\/i\]/, '<em>\1</em>'
str.gsub! /(post #(\d+))/i, '<a href="/post/show/\2">\1</a>'
str.gsub! /(forum #(\d+))/i, '<a href="/forum/show/\2">\1</a>'
str.gsub! /(comment #(\d+))/i, '<a href="/comment/show/\2">\1</a>'
str.gsub! /(pool #(\d+))/i, '<a href="/pool/show/\2">\1</a>'
# Single line spoiler tags.
str.gsub! /\[spoilers?\](.+?)\[\/spoilers?\]/, '<span class="spoiler js-comment--spoiler"><span class="spoilerwarning">spoiler</span></span><span class="spoilertext" style="display: none">\1</span>'
str.gsub! /\[spoilers?=(.+?)\](.+?)\[\/spoilers?\]/, '<span class="spoiler js-comment--spoiler"><span class="spoilerwarning">\1</span></span><span class="spoilertext" style="display: none">\2</span>'
# Multi line spoiler tags.
str.gsub! /\[spoilers?\]/, '<span class="spoiler js-comment--spoiler"><span class="spoilerwarning">spoiler</span></span><div class="spoilertext" style="display: none">'
str.gsub! /\[spoilers?=(.+?)\]/, '<span class="spoiler js-comment--spoiler"><span class="spoilerwarning">\1</span></span><div class="spoilertext" style="display: none">'
str.gsub! /\[\/spoilers?\]/, "</div>"
# Quote.
str.gsub! /\[quote\]/, "<blockquote><div>"
str.gsub! /\[\/quote\]/, "</div></blockquote>"
str = parseurl(str)
# Extraneous newlines before closing div are unnecessary.
str.gsub! /\n+(<\/div>)/, '\1'
# So are after headers, lists, and blockquotes.
str.gsub! /(<\/(ul|h\d+|blockquote)>)\n+/, '\1'
# And after opening blockquote.
str.gsub! /(<blockquote><div>)\n+/, '\1'
str.gsub! /\n/, "<br>"
str
end
def parseline(str, state)
if state.last =~ /\d/ || str =~ /^\*+\s+/
parselist str, state
elsif str =~ /^(h[1-6])\.\s*(.+)\n*/
"<#{Regexp.last_match[1]}>#{Regexp.last_match[2]}</#{Regexp.last_match[1]}>"
else
str
end
end
def parselist(str, state)
html = ""
if state.last =~ /\d/
n = ((str =~ /^\*+\s+/ && str.split[0]) || "").count("*")
if n < state.last.to_i
html << "</ul>" * (state.last.to_i - n)
state[-1] = n.to_s
elsif n > state.last.to_i
html << "<ul>"
state[-1] = (state.last.to_i + 1).to_s
end
unless str =~ /^\*+\s+/
state.pop
return html + parseline(str, state)
end
else
state.push "1"
html << "<ul>"
end
html << str.gsub(/\*+\s+(.+)\n*/, '<li>\1')
end
def parseurl(str)
# url
str.gsub! %r{(^|[\s\(>])(h?ttps?://(?:(?!>>)[^\s<"])+[^\s<".])}, '\1<a href="\2">\2</a>'
# <<url|label>>
str.gsub! %r{<<(h?ttps?://(?:(?!>>).)+)\|((?:(?!>>).)+)>>}, '<a href="\1">\2</a>'
# <<url>>
str.gsub! %r{<<(h?ttps?:\/\/(?:(?!>>).)+)>>}, '<a href="\1">\1</a>'
# "label":url
str.gsub! %r{(^|[\s>])"((?:(?!").)+)":(h?ttps?://[^\s<"]+[^\s<".])}, '\1<a href="\3">\2</a>'
# Fix ttp(s) scheme
str.gsub! /<a href="ttp/, '<a href="http'
str
end
module_function :parse, :parseline, :parseinline, :parselist, :parseurl
end
| true |
bdf42b30e74f1bd5ad666dfbaf200ed4cbe99bda | Ruby | jcarver989/kagglein-api | /test/score.rb | UTF-8 | 2,703 | 3.0625 | 3 | [] | no_license | require './test/test_helper'
describe Score do
before do
Score.delete_all
Team.delete_all
end
it "can calculate a score" do
score = Score.calculate_and_record_score("123", [1,0], [1,1])
assert_equal Score.all.size, 1
assert_equal score.api_key, "123"
assert_equal score.score, 0.5
end
it "can calculate scores from multiple api_keys" do
score1 = Score.calculate_and_record_score("456", [1,0], [1,1])
assert_equal Score.all.size, 1
assert_equal score1.api_key, "456"
assert_equal score1.score, 0.5
score2 = Score.calculate_and_record_score("123", [1,1], [1,1])
assert_equal Score.all.size, 2
assert_equal score2.api_key, "123"
assert_equal score2.score, 1
end
it "gives 3 attempts when no attempts today have been made" do
assert_equal Score.score_attempts_left_today("123"), 3
end
it "gives 2 attempts when 1 attempt today has been made" do
Score.calculate_and_record_score("123", [1,0], [1,1])
assert_equal Score.score_attempts_left_today("123"), 2
end
it "does not count score against limit if score was 0" do
Score.calculate_and_record_score("123", [1,1], [0,0])
assert_equal Score.score_attempts_left_today("123"), 3
end
it "never says less than 0 attempts " do
Score.calculate_and_record_score("123", [1,0], [1,1])
Score.calculate_and_record_score("123", [1,0], [1,1])
Score.calculate_and_record_score("123", [1,0], [1,1])
Score.calculate_and_record_score("123", [1,0], [1,1])
assert_equal Score.score_attempts_left_today("123"), 0
end
it "allows new score attempts after 1 day has passed" do
Timecop.travel(1.day.ago) do
Score.calculate_and_record_score("123", [1,0], [1,1])
Score.calculate_and_record_score("123", [1,0], [1,1])
Score.calculate_and_record_score("123", [1,0], [1,1])
assert_equal Score.score_attempts_left_today("123"), 0
end
assert_equal Score.score_attempts_left_today("123"), 3
end
it "can output a leaderboard" do
Team.create(name: "team1", api_key: "team1")
Team.create(name: "team2", api_key: "team2")
Team.create(name: "team3", api_key: "team3")
answers = [1,0,0]
#team 1 gets 2/3
Score.calculate_and_record_score("team1", answers, [0,0,0])
# team 3 gets 1/3 on first guess, 3/3 on second guess
Score.calculate_and_record_score("team2", answers, [1,1,0])
Score.calculate_and_record_score("team2", answers, [1,0,0])
#team 3 gets 1/3
Score.calculate_and_record_score("team3", answers, [1,1,1])
expected = [
["team2", 100],
["team1", 66.67],
["team3", 33.33]
]
assert_equal expected, Score.leaders
end
end
| true |
edd19b82a7bcedf8db3bffd541e4db576af2d76e | Ruby | kendrickbogan/mediblock-backend | /app/models/peer_reference.rb | UTF-8 | 510 | 2.546875 | 3 | [] | no_license | # frozen_string_literal: true
class PeerReference < ApplicationRecord
belongs_to :person
validates :person, presence: true
# The position field is being used on the front end to determine which peer
# reference to fetch, e.g., Peer Reference #1 or Peer Reference #3.
validates :position, presence: true, uniqueness: { scope: :person_id }
def address
[
address_line_1,
address_line_2,
city,
state,
zip,
country
].reject(&:blank?).join(", ")
end
end
| true |
b8bea14f9feef7accdf610400007e51a34698cb0 | Ruby | kev-kev/ruby-oo-self-cash-register-lab-nyc04-seng-ft-021720 | /lib/cash_register.rb | UTF-8 | 997 | 3.25 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class CashRegister
attr_accessor :total, :discount, :discounted_total, :cart, :last_transaction
def initialize(discount = 0)
@total = 0
@discount = discount
@cart = []
@last_transaction = 0
end
def total
return @total
end
def add_item(title, price, quant = 1)
# binding.pry
@total += price * quant
quant.times {@cart << title}
# need to allow last_transaction to update as we add items to the cart...
@last_transaction = (price * quant)
end
def apply_discount
if @discount == 0
return "There is no discount to apply."
else
@total -= ((@discount/100.0) * @total).to_i
# binding.pry
return "After the discount, the total comes to $#{@total}."
end
end
def items
# binding.pry
@cart
end
#whats the difference between using self. and an instance variable?
def void_last_transaction
# binding.pry
@total = 0.0 if @cart == []
@total -= @last_transaction
end
end | true |
2fa06a4bdfe9c4b4cc5a412f2c86d823bae116b3 | Ruby | amyamyx/chess | /stepable.rb | UTF-8 | 259 | 2.59375 | 3 | [] | no_license | module Stepable
def possible_end_pos(start_pos,move_set)
res = []
move_set.each do |move|
x,y = start_pos
x += move[0]
y += move[1]
res << [x,y] if x.between?(0,7) && y.between?(0,7)
end
res
end
end
| true |
407cf79353fa7a9514cdfd9670929a3c6988aaad | Ruby | shadchnev/Airpot-test | /lib/plane.rb | UTF-8 | 362 | 2.890625 | 3 | [] | no_license | class Plane
def fly
@flying = true
end
def initialize
@flying = true
end
def flying?
!!@flying
end
def land
@flying = false
end
# this method will always return true
# because you never change the value of @landing,
# so it's nil. Negating nil will return true.
def landing?
!@landing
end
def take_off
@flying = true
end
end
| true |
501a4328e86efeb46ccb50e1dc5edd9be8c41354 | Ruby | shadman-a/ttt-4-display-board-rb-ruby-intro-000 | /lib/display_board.rb | UTF-8 | 269 | 3.53125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | board = ["X", "O", "X", "O", "X", "X", "O", "X", "O"]
def display_board(spot)
puts " #{spot[0]} | #{spot[1]} | #{spot[2]} "
puts "-----------"
puts " #{spot[3]} | #{spot[4]} | #{spot[5]} "
puts "-----------"
puts " #{spot[6]} | #{spot[7]} | #{spot[8]} "
end
| true |
024771bb53932951a54dade0df0168a55b37cdc2 | Ruby | bruno248/pairprogram | /exo_12.rb | UTF-8 | 276 | 3.40625 | 3 | [] | no_license | puts "année"
annee=gets.chomp.to_i
annee.step(2021, +1) do |i|
puts i
if 2021-i == i-annee
puts "il y a #{2021-i} ans, tu avais la moitié de l'age que tu as aujourd'hui"
else
print "il y a #{2021-i} ans "
puts "tu avais #{i-annee} ans"
end
end | true |
fa170006494d4df10249337df957812b70200dd9 | Ruby | alphagov/e-petitions | /app/models/concerns/topics.rb | UTF-8 | 1,490 | 2.609375 | 3 | [
"LicenseRef-scancode-proprietary-license",
"MIT"
] | permissive | require 'active_support/concern'
module Topics
extend ActiveSupport::Concern
CODE_PATTERN = /\A[a-z][-a-z0-9]*\z/
included do
validate :topics_exist
end
class_methods do
def all_topics(*topics)
where(topics_column.contains(normalize_topics(topics)))
end
alias_method :for_topic, :all_topics
def topics(*codes)
codes = normalize_topic_codes(codes)
ids = Topic.where(code: codes).ids
if codes.empty?
all
elsif ids.empty?
none
else
where(topics_column.contains(ids))
end
end
alias_method :topic, :topics
def any_topics(*topics)
where(topics_column.overlaps(normalize_topics(topics)))
end
def with_topic
where(topics_column.not_eq([]))
end
def without_topic
where(topics_column.eq([]))
end
def topics_column
arel_table[:topics]
end
def normalize_topics(topics)
Array(topics).flatten.map(&:to_i).reject(&:zero?)
end
def normalize_topic_codes(codes)
Array(codes).flatten.inject([]) do |codes, code|
code = code.to_s.downcase.strip
codes << code if code.match?(CODE_PATTERN)
codes
end
end
end
def normalize_topics(topics)
self.class.normalize_topics(topics)
end
def topics=(topics)
super(normalize_topics(topics))
end
def topics_exist
unless topics.all? { |topic| Topic.exists?(topic) }
errors.add :topics, :invalid
end
end
end
| true |
04cfb953719d11ec112b80aee1cef2758c527326 | Ruby | jcoleman/mercatorial | /lib/mercatorial/distance_matrix_response.rb | UTF-8 | 874 | 2.75 | 3 | [
"MIT"
] | permissive | class Mercatorial::DistanceMatrixResponse < Mercatorial::GoogleMapsResponse
class ResponseElement
attr_reader :status
attr_reader :success
attr_reader :element
def initialize(parsed_element_json)
@status = parsed_element_json['status']
@success = (@status == 'OK')
@element = parsed_element_json
end
def distance
self.element['distance']['value']
end
def duration
self.element['duration']['value']
end
end
attr_reader :rows
def initialize(parsed_json={})
super(parsed_json)
@rows = parsed_json['rows']
end
def elements
if defined? @elements
@elements
else
elements = []
self.rows.each do |row|
row['elements'].each do |element|
elements << ResponseElement.new(element)
end
end
@elements = elements
end
end
end
| true |
8f676703a74f9a457e37e772fcc854ee2fcd98ad | Ruby | brunocordeiro180/Astar-algorithm-in-Ruby | /rua.rb | UTF-8 | 370 | 3.078125 | 3 | [] | no_license | class Rua
#Classe usada para armazenar informacao sobre a rua
# O nome e a velocidade nao estao sendo usados neste projeto
attr_accessor :name, :endX, :speed, :startX, :startY, :endY
def initialize(name, numbers)
@name = name
@startX = numbers[0]
@startY = numbers[1]
@endX = numbers[2]
@endY = numbers[3]
@speed = numbers[4]
end
end | true |
a9e8b76d53d16d2c5a515a51d95639cecfe7edf3 | Ruby | c1iff/album_organizer | /spec/album_spec.rb | UTF-8 | 1,087 | 2.96875 | 3 | [] | no_license | require('rspec')
require('album')
describe(Album) do
before() do
Album.clear()
@new_album = Album.new({:name =>'Revolver'})
end
describe('#name') do
it('creates a new album object and returns the album name') do
expect(@new_album.name).to(eq('Revolver'))
end
end
describe('.all') do
it('will be empty at first') do
expect(Album.all()).to(eq([]))
end
end
describe('#save') do
it('save an album') do
@new_album.save()
expect(Album.all()).to(eq([@new_album]))
end
end
describe('.clear') do
it('clears out all of the albums') do
Album.new({:name => 'Let It Be'})
Album.clear()
expect(Album.all()).to(eq([]))
end
end
describe('#id') do
it('returns unique id of an album') do
expect(@new_album.id()).to(eq(1))
end
end
describe('.find') do
it('returns album based on id number') do
@new_album.save()
second_album = Album.new({:name => 'Sgt. Peppers'})
second_album.save()
expect(Album.find(@new_album.id)).to(eq(@new_album))
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.