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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
46b8a41869e043437d9a6e4dcba044ed46c537cf | Ruby | MartijnBakker/bureau | /spec/bureau_drawer_management.rb | UTF-8 | 2,085 | 2.546875 | 3 | [
"MIT"
] | permissive | describe "A Bureau Managing It's Drawers" do
before do
class UIViewController < UIResponder
include Bureau::Controller
end
@x = UIViewController.new
@y = UIViewController.new
@structure = [
{
drawers:
[
{target: nil, action: :something},
{controller: @x},
]
},
{
drawers:
[
{target: nil, action: :something_else},
{controller: @y, open: true},
]
},
]
end
it "can find the open drawer" do
bureau = Bureau::Bureau.new(structure:@structure)
bureau.open_drawer.should == @structure.last[:drawers].last
end
it "opens the first drawer with a controller if one isn't already open" do
@structure.last[:drawers].last[:open] = false
bureau = Bureau::Bureau.new(structure:@structure)
bureau.open_drawer.should == @structure.first[:drawers].last
end
it "adds the open drawer's view controller and view" do
bureau = Bureau::Bureau.new(structure:@structure)
drawer = @structure.last[:drawers].last
bureau.childViewControllers.should.include drawer[:controller]
bureau.view.subviews.should.include drawer[:controller].view
end
it "does not error if there is no possible drawer to open" do
@structure.first[:drawers].last.delete(:controller)
@structure.last[:drawers].last.delete(:controller)
@structure.last[:drawers].last.delete(:open)
lambda do
Bureau::Bureau.new(structure:@structure)
end.should.not.raise StandardError
end
it "initializes the open drawers view frame based on the menu state (open or closed)" do
screen = UIScreen.mainScreen.bounds
open_bureau = Bureau::Bureau.new(structure:@structure, state: :open)
open_state_frame = CGRectMake(open_bureau.slide_width, 0, screen.size.width, screen.size.height)
open_bureau.open_drawer[:controller].view.frame.should == open_state_frame
closed_bureau = Bureau::Bureau.new(structure:@structure, state: :closed)
closed_bureau.open_drawer[:controller].view.frame.should == screen
end
end
| true |
ab9836fd472b8ece9a3aa9f17dbcb4035a48422a | Ruby | ECOtterstrom/Ruby_Basics | /8_return/ex_84.rb | UTF-8 | 318 | 4.65625 | 5 | [] | no_license | # 8_return exercise 4
def meal
puts 'Dinner'
return 'Breakfast'
end
puts meal
# The above code will print the following:
# Dinner (returns as nil)
# Breakfast (returns as breakfast)
# The items will be on separate lines due to the two puts, the return
# will exit the method. | true |
b852de4123d6816c47260a3ab285781a9696f4b9 | Ruby | samiulsyed/terminalapp | /models/tradie_model.rb | UTF-8 | 676 | 3.09375 | 3 | [] | no_license | require_relative "./tradie_record"
class Tradie < TradieRecord
class RecordNotFound < StandardError; end
attr_accessor :businessname, :contact_num, :email, :trade
def initialize (business_name, contact_number, trade, email )
@businessname = business_name
@contact_num = contact_number
@trade = trade
@email = email
@valid=false
end
def self.[](index)
puts "Class method: #{index}"
end
def trade=(trade)
@trade = trade
@valid = !(@trade.nil? || @trade.empty?)
end
# def save
# super
# end
def [](index)
puts "This is great!"
end
end | true |
d1236bec0447288f6bd903c713dcfcd65d8af716 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/roman-numerals/d423312ad1f04e9ea8baf7a386035ab8.rb | UTF-8 | 883 | 3.671875 | 4 | [] | no_license | class Numeric
ROMAN_NUMERALS = {
10 => [ 'I', 'V', 'X' ],
100 => [ 'X', 'L', 'C' ],
1000 => [ 'C', 'D', 'M' ],
10000 => [ 'M' ]
}
def to_roman
roman_numeral = ''
base = 1
while self >= base do
digit = (self / base) % 10
base *= 10
numerals = ROMAN_NUMERALS[base]
roman_numeral.insert(0, case digit
when 1..3 then numerals[0] * digit
when 4 then numerals[0] + numerals[1]
when 5 then numerals[1]
when 6..8 then numerals[1] + numerals[0] * (digit - 5)
when 9 then numerals[0] + numerals[2]
when 10 then numerals[2]
else ''
end)
end
roman_numeral
end
end
| true |
b4b1818bf42d137f10c15cb959621ec87451fae3 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/palindrome-products/9e99974937b6485cab601b914ff47b5f.rb | UTF-8 | 905 | 3.609375 | 4 | [] | no_license | require 'ostruct'
class Palindromes
def initialize(options={})
min_factor = options.fetch(:min_factor, 1)
max_factor = options.fetch(:max_factor)
@factors = [*min_factor..max_factor]
@palindromes = []
end
def generate
@factors.product(@factors).each do |factor_a, factor_b|
product = factor_a * factor_b
@palindromes << product if product.to_s == product.to_s.reverse
end
end
def largest
palindrome = @palindromes.sort.last
OpenStruct.new(value: palindrome, factors: factor(palindrome))
end
def smallest
palindrome = @palindromes.sort.first
OpenStruct.new(value: palindrome, factors: factor(palindrome))
end
private
def factor(value)
@factors.map do |factor|
quotient, remainder = value.divmod(factor)
[factor, quotient] if remainder == 0 && @factors.include?(quotient)
end.compact.map(&:sort).uniq
end
end
| true |
eeee28cfefc63ffc6dd09b248bed16f6a80d1f9d | Ruby | muffatruffa/launch_school_ruby_challenges | /medium_2/palindrome_products.rb | UTF-8 | 5,981 | 3.34375 | 3 | [] | no_license | module FactorsInRangePalindrome
Palindrome = Struct.new(:value, :factors)
def set_range(min, max)
@min = min
@max = max
end
def factors(n)
return [] if n < @min
result = []
current = @min
while current * current <= n
if n/current <= @max
result << [current, n/current] if (n % current).zero?
end
current +=1
end
result
end
def select_valid_smallest_largest
palindrome_hash = build_palindromes(@min, @max).map do |plainidrome|
[plainidrome, factors(plainidrome)]
end.to_h.reject { |_, f| f.empty?}
palindromes = palindrome_hash.keys.sort
[
Palindrome.new(palindromes.first, palindrome_hash[palindromes.first]),
Palindrome.new(palindromes.last, palindrome_hash[palindromes.last])
]
end
end
module PalindromesLoopSelector
Plaindrome = Struct.new(:value, :factors) do
def update(new_value, factor_pair)
if new_value == value
factors << factor_pair if new_pair?(factor_pair)
else
self.value = new_value
self.factors = [factor_pair]
end
end
def new_pair?(pair)
!factors.include?(pair) &&
!factors.include?(pair.reverse)
end
end
def smallest_largest
sm = Plaindrome.new(@max * @max, [])
lg = Plaindrome.new(@min * @min, [])
first_factor = @min
while first_factor <= @max
second_factor = first_factor
first_factor.upto(@max) do |first|
while second_factor <= @max
current = first * second_factor
if palindrome?(current)
if current <= sm.value
sm.update(current, [first, second_factor])
end
if current >= lg.value
lg.update(current, [first, second_factor])
end
end
second_factor += 1
end
end
first_factor += 1
end
[
sm,
lg
]
end
module_function
def palindrome?(n)
n.to_s == n.to_s.reverse
end
end
module PalindromesMapSelector
def self.included klass
klass.class_eval do
include FactorsInRangePalindrome
end
end
def smallest_largest
select_valid_smallest_largest
end
module_function
def build_palindromes(min, max)
(min * min..max * max).to_a.select { |n| n.to_s == n.to_s.reverse}
end
end
module PalindromesBuilder
def self.included klass
klass.class_eval do
include FactorsInRangePalindrome
end
end
def smallest_largest
select_valid_smallest_largest
end
module_function
def build_palindromes(min, max)
palindromes = []
from = (min * min).to_s.size
to = (max * max).to_s.size
(from..to).each do |size|
palindromes.concat build_n_digits_strings(size)
end
palindromes.reject do |palindorme|
/\A0.*/ =~ palindorme || palindorme.to_i > max * max
end.map(&:to_i)
end
def build_n_digits_strings(size)
return ('0'..'9').to_a if size == 1
if size.even?
build_even(size)
else
build_odd(size)
end
end
def build_even(size)
palindromes = []
('0'..'9').to_a.repeated_permutation(size / 2).each do |digit_combination|
str_combination = digit_combination.join('')
palindromes << str_combination + str_combination.reverse
end
palindromes
end
def build_odd(size)
palindromes = []
('0'..'9').to_a.repeated_permutation(size / 2).each do |digit_combination|
str_combination = digit_combination.join('')
('0'..'9').to_a.each do |digit|
palindromes << str_combination + digit + str_combination.reverse
end
end
palindromes
end
end
class PalindromeGenerator
attr_reader :max, :min
def self.get(max, min, palindromes_engineer = 'PalindromesBuilder')
new(max, min, palindromes_engineer)
end
def initialize(max, min, palindromes_engineer = 'PalindromesBuilder')
@max = max
@min = min
include_engineer_module(palindromes_engineer)
end
private
def include_engineer_module(module_name)
if Module.const_defined?(module_name)
self.singleton_class.send(:include, Module.const_get(module_name))
end
end
end
class Palindromes
attr_reader :largest, :smallest
def initialize(max_factor:nil, min_factor:nil)
@max = max_factor
@min = min_factor || 1
@palindromes_generator = if block_given?
yield(@max, @min)
else
PalindromeGenerator.new(@max, @min)
end
end
def generate
@smallest, @largest = @palindromes_generator.smallest_largest
end
end
if $PROGRAM_NAME == __FILE__
require 'benchmark'
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesLoopSelector')
end
p (Benchmark.realtime do # 0.164155626000138
palindromes.generate
end)
palindromes = Palindromes.new(max_factor: 9999, min_factor: 1000) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesLoopSelector')
end
p (Benchmark.realtime do # 16.31405066300067
palindromes.generate
end)
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesMapSelector')
end
p (Benchmark.realtime do # 0.3845328660099767
palindromes.generate
end)
palindromes = Palindromes.new(max_factor: 9999, min_factor: 1000) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesMapSelector')
end
p (Benchmark.realtime do # 42.2232261300087
palindromes.generate
end)
palindromes = Palindromes.new(max_factor: 999, min_factor: 100) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesBuilder')
end
p (Benchmark.realtime do # 0.05663906500558369
palindromes.generate
end)
palindromes = Palindromes.new(max_factor: 9999, min_factor: 1000) do |max, min|
PalindromeGenerator.get(max, min, 'PalindromesBuilder')
end
p (Benchmark.realtime do # 3.7876757479971275
palindromes.generate
end)
end | true |
af16c6888c07e9db13ae96a0a1c9363a509ca9d1 | Ruby | sp-nil/pb_qs | /phonebook/lib/contact.rb | UTF-8 | 1,104 | 3.546875 | 4 | [] | no_license | require 'lib/conio'
class Contact
extend ConIO
include ConIO
attr_accessor :phonebook
def initialize(pb)
@phonebook = pb
end
def self.add_new(phonebook)
name = prompt('Enter new name: ')
number = prompt('Enter new number: ')
phonebook.add_entry(name, number)
end
def update
# Reads entire phonebook into memory. Ugh.
index = find_by_name(true)
number = prompt('Enter new number: ')
@phonebook.update(index, number)
end
def find_by_name(get_index=false)
find :name, prompt('Enter name to find: ').downcase()
if get_index
return prompt('Enter index number to change: ')
end
end
# Not a requirement, but we can leverage this method to ask for which record
# to update, just like we did with find_by_name
def find_by_number
find :number, prompt('Enter number to find: ').downcase()
end
private
def print_entry(line)
puts line.values_at(:index, :number, :name).join( "\t" )
end
def find(key, item)
@phonebook.read do |line|
print_entry line if /#{item}/ === line[key].downcase
end
end
end
| true |
07442e16fb634b349efd822b9fbfb8ffce9af065 | Ruby | masimasima/ruby-lecture | /hello.rb | UTF-8 | 43 | 2.515625 | 3 | [] | no_license | puts "Hello Ruby!"
puts "Hello Ruby講義" | true |
91988e4ed6e7254665d7256fc0b2d8e34bb37a67 | Ruby | J-Y/RubyQuiz | /ruby_quiz/quiz126_sols/solutions/Donald Ball/fizzbuzz3.rb | UTF-8 | 67 | 3.3125 | 3 | [
"MIT"
] | permissive | puts (1..100).map{|n|n%15>0?n%5>0?n%3>0?n:'fizz':'buzz':'fizzbuzz'} | true |
95708868590e8a40f029f144acc53ed259baae03 | Ruby | dhimasadiyasapro/ruby-learning | /exe01.rb | UTF-8 | 132 | 3.5 | 4 | [] | no_license | puts "Hello World"
puts 3+2
puts 3*2
puts 3**2 # kuadrat
puts Math.sqrt(9) # akar kuadrat
a = 3 ** 2
b = 4 ** 2
puts Math.sqrt(a+b)
| true |
13b603d7324aa3852fcb5a67dd29ba03268e5b4f | Ruby | taylorthurlow/advent-of-code-2018 | /day8/part2-golf.rb | UTF-8 | 404 | 3.1875 | 3 | [] | no_license | #!/usr/bin/env ruby
def process(list)
num_children = list.shift
num_metadata = list.shift
[(0..num_children - 1).to_a.map { process(list) }, list.shift(num_metadata)]
end
def value(node)
node[0].any? ? node[1].map { |m| m != 0 && (m - 1) >= 0 && (m - 1) < node[0].size ? value(node[0][m - 1]) : 0 }.sum : node[1].sum
end
puts value(process(File.read('data.txt').chomp.split(' ').map(&:to_i)))
| true |
6914c651adc19b4b8bebd9ba184af776333cfd22 | Ruby | rasmusra/FiRe | /lib/workers/worker_factory.rb | UTF-8 | 1,019 | 2.71875 | 3 | [] | no_license | require_relative '../helpers/resource_locator'
require_relative '../extensions/string'
require 'yaml'
include FiRe
# Factory-class for workers. The createJobs-method reads
# worker-list from config-file and returns list of worker-instances
# Naming conventions for workers in class and configfile are:
#
# classname: FooBar
# libname: 'lib/fire/workers/foo_bar.rb'
# configname: foo_bar
#
# When the configname is found, the other two will
# be read out of it.
class WorkerFactory
# creates a worker for given worker-name.
def WorkerFactory.create(workerConfig)
fn = workerConfig["worker"].downcase
cls = fn.camelize!
FiRe::log.info "--------------------------------- creating #{cls}"
FiRe::log.info "config: #{workerConfig.to_yaml}"
# require the library for the job
require_relative fn
# create the class for the job
klass = Object.const_get(cls)
# return an instance of the worker
klass.new(workerConfig["parameters"])
end
end | true |
aee84c63d4806dae387f51e99d7aea2d985ad3bf | Ruby | KalebGz/Flatiron | /code/module-1/active-record-associations-tvland-lab-yale-web-yss-052520/app/models/actor.rb | UTF-8 | 306 | 2.5625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Actor < ActiveRecord::Base
has_many :characters
has_many :shows, through: :characters
def full_name
first_name + " " + last_name
end
def list_roles
roles = []
roles.push(Character.all.where(:actor == self).map{|char| char.name + " - " + char.show.name})
roles[0]
end
end | true |
82a1a726c24109cbeaccba79ac41e4584db9ba8d | Ruby | Pignataro67/parrot-ruby-v-000 | /parrot.rb | UTF-8 | 138 | 2.921875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot (chirp ="Squawk!")
puts chirp
return chirp
end
| true |
2589759d98e1949d953d2cfa47f2d698a5444124 | Ruby | Trevor-Robinson/Enigma | /lib/encrypt.rb | UTF-8 | 311 | 2.78125 | 3 | [] | no_license | require './lib/enigma'
enigma = Enigma.new
file = File.open("./lib/#{ARGV[0]}")
enigma.encrypt(file.readline)
new_file = File.open("./lib/#{ARGV[1]}", "w")
new_file.write(enigma.output_hash[:encryption])
puts "Created '#{ARGV[1]}' with the key #{enigma.output_hash[:key]} and date #{enigma.output_hash[:date]}"
| true |
35a27c8712da63b38bc0451ab879be8c251f699b | Ruby | avvo/validates_not_shouting | /lib/validates_not_shouting/not_shouting_validator.rb | UTF-8 | 516 | 2.859375 | 3 | [
"MIT"
] | permissive | # this is not namespaced so that we can do
# validates :body, not_shouting: true
class NotShoutingValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return true if value.blank?
if shouting?(value)
record.errors[attribute] << options.fetch(:message, "cannot be mostly caps. It's not polite to shout.")
end
end
def shouting?(value)
threshold = options.fetch(:threshold, 0.5)
(value.gsub(/[^A-Z]/, '').length.to_f / value.length) > threshold
end
end | true |
55e8d3d4dfd3ef08734bf0ecbdd6fe230389097a | Ruby | bsdpunk/rib | /rib | UTF-8 | 280 | 2.53125 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'Resolv'
require "ipaddress"
res = Resolv::DNS.new(:nameserver => [ARGV[1]],
:search => [''],
:ndots => 1)
if IPAddress.valid? ARGV[0]
puts res.getname(ARGV[0])
else
puts res.getaddress(ARGV[0])
end
| true |
6b931938890dcb470930044c2a974f3f3c84bb35 | Ruby | jonatas/fast | /lib/fast/experiment.rb | UTF-8 | 14,545 | 2.9375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'fast'
# Allow to replace code managing multiple replacements and combining replacements.
# Useful for large codebase refactor and multiple replacements in the same file.
module Fast
class << self
# Fast.experiment is a shortcut to define new experiments and allow them to
# work together in experiment combinations.
#
# The following experiment look into `spec` folder and try to remove
# `before` and `after` blocks on testing code. Sometimes they're not
# effective and we can avoid the hard work of do it manually.
#
# If the spec does not fail, it keeps the change.
#
# @example Remove useless before and after block
# Fast.experiment("RSpec/RemoveUselessBeforeAfterHook") do
# lookup 'spec'
# search "(block (send nil {before after}))"
# edit { |node| remove(node.loc.expression) }
# policy { |new_file| system("rspec --fail-fast #{new_file}") }
# end
def experiment(name, &block)
@experiments ||= {}
@experiments[name] = Experiment.new(name, &block)
end
attr_reader :experiments
end
# Fast experiment allow the user to combine single replacements and make multiple
# changes at the same time. Defining a policy is possible to check if the
# experiment was successfull and keep changing the file using a specific
# search.
#
# The experiment have a combination algorithm that recursively check what
# combinations work with what combinations. It can delay years and because of
# that it tries a first replacement targeting all the cases in a single file.
#
# You can define experiments and build experimental files to improve some code in
# an automated way. Let's create a hook to check if a `before` or `after` block
# is useless in a specific spec:
#
# @example Remove useless before or after block RSpec hooks
# # Let's say you want to experimentally remove some before or after block
# # in specs to check if some of them are weak or useless:
# # RSpec.describe "something" do
# # before { @a = 1 }
# # before { @b = 1 }
# # it { expect(@b).to be_eq(1) }
# # end
# #
# # The variable `@a` is not useful for the test, if I remove the block it
# # should continue passing.
# #
# # RSpec.describe "something" do
# # before { @b = 1 }
# # it { expect(@b).to be_eq(1) }
# # end
# #
# # But removing the next `before` block will fail:
# # RSpec.describe "something" do
# # before { @a = 1 }
# # it { expect(@b).to be_eq(1) }
# # end
# # And the experiments will have a policy to check if `rspec` run without
# # fail and only execute successfull replacements.
# Fast.experiment("RSpec/RemoveUselessBeforeAfterHook") do
# lookup 'spec' # all files in the spec folder
# search "(block (send nil {before after}))"
# edit {|node| remove(node.loc.expression) }
# policy {|new_file| system("rspec --fail-fast #{new_file}") }
# end
#
# @example Replace FactoryBot create with build_stubbed method
# # Let's say you want to try to automate some replacement of
# # `FactoryBot.create` to use `FactoryBot.build_stubbed`.
# # For specs let's consider the example we want to refactor:
# # let(:person) { create(:person, :with_email) }
# # And the intent is replace to use `build_stubbed` instead of `create`:
# # let(:person) { build_stubbed(:person, :with_email) }
# Fast.experiment('RSpec/ReplaceCreateWithBuildStubbed') do
# lookup 'spec'
# search '(block (send nil let (sym _)) (args) $(send nil create))'
# edit { |_, (create)| replace(create.loc.selector, 'build_stubbed') }
# policy { |new_file| system("rspec --format progress --fail-fast #{new_file}") }
# end
# @see https://asciinema.org/a/177283
class Experiment
attr_writer :files
attr_reader :name, :replacement, :expression, :files_or_folders, :ok_if
def initialize(name, &block)
@name = name
puts "\nStarting experiment: #{name}"
instance_exec(&block)
end
# It combines current experiment with {ExperimentFile#run}
# @param [String] file to be analyzed by the experiment
def run_with(file)
ExperimentFile.new(file, self).run
end
# @param [String] expression with the node pattern to target nodes
def search(expression)
@expression = expression
end
# @param block yields the node that matches and return the block in the
# instance context of a [Fast::Rewriter]
def edit(&block)
@replacement = block
end
# @param [String] files_or_folders that will be combined to find the {#files}
def lookup(files_or_folders)
@files_or_folders = files_or_folders
end
# It calls the block after the replacement and use the result
# to drive the {Fast::ExperimentFile#ok_experiments} and {Fast::ExperimentFile#fail_experiments}.
# @param block yields a temporary file with the content replaced in the current round.
def policy(&block)
@ok_if = block
end
# @return [Array<String>] with files from {#lookup} expression.
def files
@files ||= Fast.ruby_files_from(@files_or_folders)
end
# Iterates over all {#files} to {#run_with} them.
# @return [void]
def run
files.map(&method(:run_with))
end
end
# Suggest possible combinations of occurrences to replace.
#
# Check for {#generate_combinations} to understand the strategy of each round.
class ExperimentCombinations
attr_reader :combinations
def initialize(round:, occurrences_count:, ok_experiments:, fail_experiments:)
@round = round
@ok_experiments = ok_experiments
@fail_experiments = fail_experiments
@occurrences_count = occurrences_count
end
# Generate different combinations depending on the current round.
# * Round 1: Use {#individual_replacements}
# * Round 2: Tries {#all_ok_replacements_combined}
# * Round 3+: Follow {#ok_replacements_pair_combinations}
def generate_combinations
case @round
when 1
individual_replacements
when 2
all_ok_replacements_combined
else
ok_replacements_pair_combinations
end
end
# Replace a single occurrence at each iteration and identify which
# individual replacements work.
def individual_replacements
(1..@occurrences_count).to_a
end
# After identifying all individual replacements that work, try combining all
# of them.
def all_ok_replacements_combined
[@ok_experiments.uniq.sort]
end
# Divide and conquer combining all successful individual replacements.
def ok_replacements_pair_combinations
@ok_experiments
.combination(2)
.map { |e| e.flatten.uniq.sort }
.uniq - @fail_experiments - @ok_experiments
end
end
# Combines an {Fast::Experiment} with a specific file.
# It coordinates and regulate multiple replacements in the same file.
# Everytime it {#run} a file, it uses {#partial_replace} and generate a
# new file with the new content.
# It executes the {Fast::Experiment#policy} block yielding the new file. Depending on the
# policy result, it adds the occurrence to {#fail_experiments} or {#ok_experiments}.
# When all possible occurrences are replaced in isolated experiments, it
# #{build_combinations} with the winner experiments going to a next round of experiments
# with multiple partial replacements until find all possible combinations.
# @note it can easily spend days handling multiple one to one combinations,
# because of that, after the first round of replacements the algorithm goes
# replacing all winner solutions in the same shot. If it fails, it goes
# combining one to one.
# @see Fast::Experiment
# @example Temporary spec to analyze
# tempfile = Tempfile.new('some_spec.rb')
# tempfile.write <<~RUBY
# let(:user) { create(:user) }
# let(:address) { create(:address) }
# let(:phone_number) { create(:phone_number) }
# let(:country) { create(:country) }
# let(:language) { create(:language) }
# RUBY
# tempfile.close
# @example Temporary experiment to replace create with build stubbed
# experiment = Fast.experiment('RSpec/ReplaceCreateWithBuildStubbed') do
# lookup 'some_spec.rb'
# search '(send nil create)'
# edit { |node| replace(node.loc.selector, 'build_stubbed') }
# policy { |new_file| system("rspec --fail-fast #{new_file}") }
# end
# @example ExperimentFile exploring combinations and failures
# experiment_file = Fast::ExperimentFile.new(tempfile.path, experiment)
# experiment_file.build_combinations # => [1, 2, 3, 4, 5]
# experiment_file.ok_with(1)
# experiment_file.failed_with(2)
# experiment_file.ok_with(3)
# experiment_file.ok_with(4)
# experiment_file.ok_with(5)
# # Try a combination of all OK individual replacements.
# experiment_file.build_combinations # => [[1, 3, 4, 5]]
# experiment_file.failed_with([1, 3, 4, 5])
# # If the above failed, divide and conquer.
# experiment_file.build_combinations # => [[1, 3], [1, 4], [1, 5], [3, 4], [3, 5], [4, 5]]
# experiment_file.ok_with([1, 3])
# experiment_file.failed_with([1, 4])
# experiment_file.build_combinations # => [[4, 5], [1, 3, 4], [1, 3, 5]]
# experiment_file.failed_with([1, 3, 4])
# experiment_file.build_combinations # => [[4, 5], [1, 3, 5]]
# experiment_file.failed_with([4, 5])
# experiment_file.build_combinations # => [[1, 3, 5]]
# experiment_file.ok_with([1, 3, 5])
# experiment_file.build_combinations # => []
class ExperimentFile
attr_reader :ok_experiments, :fail_experiments, :experiment
def initialize(file, experiment)
@file = file
@ast = Fast.ast_from_file(file) if file
@experiment = experiment
@ok_experiments = []
@fail_experiments = []
@round = 0
end
# @return [String] from {Fast::Experiment#expression}.
def search
experiment.expression
end
# @return [String] with a derived name with the combination number.
def experimental_filename(combination)
parts = @file.split('/')
dir = parts[0..-2]
filename = "experiment_#{[*combination].join('_')}_#{parts[-1]}"
File.join(*dir, filename)
end
# Keep track of ok experiments depending on the current combination.
# It keep the combinations unique removing single replacements after the
# first round.
# @return void
def ok_with(combination)
@ok_experiments << combination
return unless combination.is_a?(Array)
combination.each do |element|
@ok_experiments.delete(element)
end
end
# Track failed experiments to avoid run them again.
# @return [void]
def failed_with(combination)
@fail_experiments << combination
end
# @return [Array<Astrolabe::Node>]
def search_cases
Fast.search(experiment.expression, @ast) || []
end
# rubocop:disable Metrics/MethodLength
#
# Execute partial replacements generating new file with the
# content replaced.
# @return [void]
def partial_replace(*indices)
replacement = experiment.replacement
new_content = Fast.replace_file experiment.expression, @file do |node, *captures|
if indices.nil? || indices.empty? || indices.include?(match_index)
if replacement.parameters.length == 1
instance_exec node, &replacement
else
instance_exec node, *captures, &replacement
end
end
end
return unless new_content
write_experiment_file(indices, new_content)
new_content
end
# rubocop:enable Metrics/MethodLength
# Write new file name depending on the combination
# @param [Array<Integer>] combination
# @param [String] new_content to be persisted
def write_experiment_file(combination, new_content)
filename = experimental_filename(combination)
File.open(filename, 'w+') { |f| f.puts new_content }
filename
end
def done!
count_executed_combinations = @fail_experiments.size + @ok_experiments.size
puts "Done with #{@file} after #{count_executed_combinations} combinations"
return unless perfect_combination = @ok_experiments.last # rubocop:disable Lint/AssignmentInCondition
puts 'The following changes were applied to the file:'
`diff #{experimental_filename(perfect_combination)} #{@file}`
puts "mv #{experimental_filename(perfect_combination)} #{@file}"
`mv #{experimental_filename(perfect_combination)} #{@file}`
end
# Increase the `@round` by 1 to {ExperimentCombinations#generate_combinations}.
def build_combinations
@round += 1
ExperimentCombinations.new(
round: @round,
occurrences_count: search_cases.size,
ok_experiments: @ok_experiments,
fail_experiments: @fail_experiments
).generate_combinations
end
def run
while (combinations = build_combinations).any?
if combinations.size > 1000
puts "Ignoring #{@file} because it has #{combinations.size} possible combinations"
break
end
puts "#{@file} - Round #{@round} - Possible combinations: #{combinations.inspect}"
while combination = combinations.shift # rubocop:disable Lint/AssignmentInCondition
run_partial_replacement_with(combination)
end
end
done!
end
# Writes a new file with partial replacements based on the current combination.
# Raise error if no changes was made with the given combination indices.
# @param [Array<Integer>] combination to be replaced.
def run_partial_replacement_with(combination)
content = partial_replace(*combination)
experimental_file = experimental_filename(combination)
File.open(experimental_file, 'w+') { |f| f.puts content }
raise 'No changes were made to the file.' if FileUtils.compare_file(@file, experimental_file)
result = experiment.ok_if.call(experimental_file)
if result
ok_with(combination)
puts "✅ #{experimental_file} - Combination: #{combination}"
else
failed_with(combination)
puts "🔴 #{experimental_file} - Combination: #{combination}"
end
end
end
end
| true |
1d8b3eb580d914e8477a88fba873f45e8a72ab63 | Ruby | GraemeHBrown/wk4_day4_hogwarts_lab | /console.rb | UTF-8 | 432 | 2.578125 | 3 | [] | no_license | require_relative('./models/student.rb')
require('pry-byebug')
# @id = options['id'].to_i if options['id']
# @first_name = options['first_name']
# @second_name = options['second_name']
# @house = options['house']
# @age = options['age'].to_i
harry = Student.new({'first_name' => 'Harry', 'second_name' => 'Potter',
'house' => 'Gryffindor', 'age' => '12'})
harry.save()
all_students = Student.find_all()
binding.pry
nil
| true |
e302da5aa5a0592fcf6d1ba5632f8779738f7f04 | Ruby | djdeath/uni_projects | /projet_optimisation/annealing.rb | UTF-8 | 5,034 | 3.015625 | 3 | [] | no_license | require 'graph'
require 'timecounter'
require 'display'
module Annealing
def draw_annealing(display)
# Compte le temps écoulé
time = TimeCounter.new
time.start
# Température
t0 = display.prefs['annealing_t0']
t = t0
mut = display.prefs['annealing_tdec']
mu = mut
# Remplissage du tableau des arêtes avec une
# méthode quelque peu... hmmm... simplette ;)
nexts = Array.new(self.nb_sommet)
prevs = Array.new(self.nb_sommet)
n = 1
p = self.nb_sommet - 1
nexts.each_index do |i|
nexts[i] = n % self.nb_sommet
prevs[i] = p % self.nb_sommet
n = n.next
p = p.next
end
time.stop # arrêt du temps pour dessiner
# On dessine le tout
weight = 0
nexts.each_with_index do |p1, p2|
weight += self.map[p1][p2]
display.draw_edge_ids(p1, p2)
end
display.set_text("Poids courant : #{weight}")
time.start
n = 0 # nombre de transformation
nb = self.nb_sommet * (self.nb_sommet - 1)
while n < nb
# On tire au hasard 2 arêtes
a1 = Kernel::rand(self.nb_sommet)
a2 = Kernel::rand(self.nb_sommet)
while (a2 == a1) or (nexts[a1] == a2) or (prevs[a1] == a2)
a2 = Kernel::rand(self.nb_sommet)
end
a3 = nexts[a1]
a4 = nexts[a2]
# On calcule le coût de ces arêtes
oc1 = self.map[a1][a3]
oc2 = self.map[a2][a4]
# On calcule le coût des nouvelles arêtes
nc1 = self.map[a1][a2]
nc2 = self.map[a3][a4]
# Le nouveau cycle est il moins coûteux ?
if (nc1 + nc2) < (oc1 + oc2)
opt2(nexts, prevs, a1, a2)
# On fait décroitre t
t = mut * t
#mut *= mu
n = 0
else
q = 10000000
p = Kernel::rand(q) / q
if p < Math::exp(-Math::sqrt(self.nb_sommet) * (nc1 + nc2) - (oc1 + oc2) / t)
opt2(nexts, prevs, a1, a2)
n = 0
t = mut * t
else
n = n.next
end
end
time.stop # arrêt du temps pour redessiner
if n == 0 # Affichage si modification
display.clean_edges
weight = 0
nexts.each_with_index do |p1, p2|
weight += self.map[p1][p2]
display.draw_edge_ids(p1, p2)
end
display.set_text("Poids courant : #{weight}")
display.redraw
end
time.start
end
time.stop
display.set_text("Poids final : #{weight}")
display.stats.set_stat('Récuit simulé', time.to_s, weight)
end
#######
private
#######
# 2 échange
def opt2(nexts, prevs, a1, a2)
a3 = nexts[a1]
a4 = nexts[a2]
# On procède à l'échange des arêtes
nexts[a1] = a2
nexts[a3] = a4
prevs[a4] = a3
# Mise à jour des circuits nexts et prevs
p = a1
c = a2
while (c != a3)
nexts[c] = prevs[c]
prevs[c] = p
p = c
c = nexts[p]
end
prevs[a3] = p
end
end
| true |
8b374fd267dd721ef3f56da1e024c78fb7d3acc8 | Ruby | ayellapragada/root | /lib/root/actions/dominance.rb | UTF-8 | 958 | 2.859375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module Root
module Actions
# Handles all Dominance related logic
class Dominance
attr_reader :faction
def initialize(faction)
@faction = faction
end
def check
raise Errors::WinConditionReached.new(faction, :dominance) if dominance?
end
private
def dominance?
suit = faction.victory_points
if %i[fox mouse rabbit].include?(suit)
suit_dominance?(suit)
elsif suit == :bird
bird_dominance?
end
end
def bird_dominance?
faction.board.corners.any? do |cl|
opposite_cl = faction.board.clearing_across(cl)
faction.rule?(cl) && faction.rule?(opposite_cl)
end
end
def suit_dominance?(suit)
ruled_cl = faction.board.clearings_of_suit(suit).count do |cl|
faction.rule?(cl)
end
ruled_cl >= 3
end
end
end
end
| true |
ae16b92c20b7c39eadefb932517aeca5ad66f79a | Ruby | jihwan512/bbgr | /chatbot.rb | UTF-8 | 4,259 | 2.703125 | 3 | [] | no_license | require 'sinatra'
get '/keyboard' do
msg =
{
type: "buttons",
buttons: ["소개", "멋쟁이 사자처럼", "깃허브","멋사 AT KOREATECH"]
}
#render json: @msg, status: :ok
msg.to_json
end
post '/message' do
response = params[:content]
if response == "소개"
msg = {
message: {
text: "안녕하세요. 저는 개발자 꿈나무입니다. 네이버와 티스토리에서 블로그를 운영하고 있습니다. 서로이웃 환영합니다~",
photo: {
url: "https://s3.ap-northeast-2.amazonaws.com/tongilstorage/kakaochat/MAKERS.jpg",
width: 640,
height: 480
},
message_button: {
label: "NAVER BLOG",
url: "https://blog.naver.com/xhdtn8070/221231786261"
}
},
keyboard: {
type: "buttons",
buttons: ["소개", "멋쟁이 사자처럼", "깃허브","멋사 AT KOREATECH"]
}
}
msg.to_json
elsif response == "멋쟁이 사자처럼"
msg = {
message: {
text: "멋쟁이 사자처럼은 어떤 동아리 인가요? 멋쟁이사자처럼은 비전공자도 코딩을 통해 자신이 만들고 싶은 서비스를 만들 수 있게 하는 것을 모토로 2013년 서울대학교에서 시작한 단체입니다. 현재 전국 각지의 대학교에서 멋쟁이사자차럼 활동이 진행되고 있고, 많은 학생들이 자신만의 서비스를 직접 만들고 있습니다.자체 개발된 온라인 강의 플랫폼 '클래스라이언' 을 통해 강의를 듣고 과제를 수행합니다.
다양한 오프라인 활동과 병행하여 뜻을 같이하는 동료를 찾고
자신이 만들고자 하는 서비스를 직접 프로그래밍 하도록 돕습니다.",
photo: {
url: "https://s3.ap-northeast-2.amazonaws.com/tongilstorage/kakaochat/3.PNG",
width: 640,
height: 480
},
message_button: {
label: "LIKE LION",
url: "https://likelion.net/"
}
},
keyboard: {
type: "buttons",
buttons: ["소개", "멋쟁이 사자처럼", "깃허브","멋사 AT KOREATECH"]
}
}
msg.to_json
elsif response == "깃허브"
msg = {
message: {
text: "하나씩 공부의 흔적을 남기는 곳입니다. 필요한 코드가 있으시면 다 가져가세요~",
photo: {
url: "https://s3.ap-northeast-2.amazonaws.com/tongilstorage/kakaochat/5.PNG",
width: 640,
height: 480
},
message_button: {
label: "GitHub",
url: "https://github.com/xhdtn8070"
}
},
keyboard: {
type: "buttons",
buttons: ["소개", "멋쟁이 사자처럼", "깃허브","멋사 AT KOREATECH"]
}
}
msg.to_json
elsif response == "멋사 AT KOREATECH"
msg = {
message: {
text: "안녕하세요. 저는 멋쟁이 사자처럼 AT KOREATECH 소속입니다. 복거톤이나 다른 연합활동에 뜻이 있는 분들은 블로그에 댓글주세요~~~~~ ",
photo: {
url: "https://s3.ap-northeast-2.amazonaws.com/tongilstorage/kakaochat/2.PNG",
width: 640,
height: 480
},
message_button: {
label: "멋사 AT KOREATECH",
url: "http://koreatech.likelion.org/"
}
},
keyboard: {
type: "buttons",
buttons: ["소개", "멋쟁이 사자처럼", "깃허브","멋사 AT KOREATECH"]
}
}
msg.to_json
end
end | true |
5c2c2e2fd303f0f7010308e539f131ed66037bd0 | Ruby | JuanFPelaez/CursoRoR5 | /Apuntes Ruby Dicampus/Ejercicios resueltos/Ejercicio 7.rb | UTF-8 | 601 | 4.03125 | 4 | [] | no_license | =begin
Hacer un método que recibe una sentencia y devuelve
true si es un palindromo (ignoramos espacios y
mayusculas/minusculas). El método reverse de
cadenas puede ser util.
=end
def palindromo?(sentence)
# eliminamos todos los espacios introducidos en 'sentence'
downcase_stripped_sentence = sentence.downcase.gsub(" ", "")
# comparamos el contenido introducido en 'sentence' con el el mismo contenido invertido,
# porque los palíndromos son aquellos que da igual leer de izquierda a derecha o viceversa
downcase_stripped_sentence == downcase_stripped_sentence.reverse
end | true |
38e7e30be10d7d8c2e6d0a88c759b58f2977da72 | Ruby | MufuckaHero/rack-lesson | /application.rb | UTF-8 | 372 | 2.5625 | 3 | [] | no_license | require "slim"
module Lesson1
class EndpointContacts
def call(env)
[200, {'Content-Type' => 'text/plain'}, [env.inspect]]
end
end
class EndpointWelcome
def call(env)
_request = Rack::Request.new(env)
_body = Slim::Template.new('index.slim', {}).render(_request)
[200, {'Content-Type' => 'text/html'}, [_body]]
end
end
end | true |
b12597e1d572845761ccdb64d7035aa6bd264ef3 | Ruby | chen7897499/Codewars | /zip_it.rb | UTF-8 | 501 | 3.578125 | 4 | [] | no_license | #这题不能使用原来的zip方法, 被去掉了
class Array
def zip(arr, &block)
# Good Luck!
result = []
bigarray = []
lala = self
if lala.length > arr.length
lala = lala[0,arr.length]
elsif arr.length > lala.length
arr = arr[0,lala.length]
end
bigarray << lala
bigarray << arr
base = bigarray.transpose
base.each do |a,b|
if a.nil? || b.nil?
break;
end
result << yield(a,b)
end
result
end
end
| true |
afba793c6f47e9e1e41a5b151db9eb474051130f | Ruby | bethsebian/sorting_suite | /insertion_sort_archive3.rb | UTF-8 | 1,550 | 3.671875 | 4 | [] | no_license | class InsertionSort
attr_reader :unsorted, :sorted, :array_length
def initialize(unsorted,sorted=[])
@unsorted = unsorted
@sorted = sorted
@array_length = unsorted.length
end
def move_to_sorted_array_and_remove_from_old_array(new_position)
sorted.insert(new_position,unsorted[0])
unsorted.shift
end
def sort
if array_length == 0
[]
else
move_to_sorted_array_and_remove_from_old_array(0)
if array_length >= 2
if (sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
else
move_to_sorted_array_and_remove_from_old_array(1)
end
end
if array_length >=3
if (sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
elsif (sorted[1] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(1)
else
move_to_sorted_array_and_remove_from_old_array(2)
end
end
if array_length >= 4
if
(sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
elsif
(sorted[1] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(1)
elsif
(sorted[2] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(2)
else
(sorted[3] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(3)
end
end
@sorted
end
end
end
| true |
57964c1f13a7324af9e80f6aae8dbfcfcd914a4a | Ruby | jnunemaker/cassanity | /lib/cassanity/operator.rb | UTF-8 | 674 | 3.125 | 3 | [
"MIT"
] | permissive | module Cassanity
def self.Operator(*args)
Operator.new(*args)
end
class Operator
# Internal
attr_reader :symbol
# Internal
attr_reader :value
# Public: Returns an operator instance
def initialize(symbol, value)
@symbol = symbol
@value = value
end
def eql?(other)
self.class.eql?(other.class) &&
value == other.value &&
symbol == other.symbol
end
alias_method :==, :eql?
# Public
def inspect
attributes = [
"symbol=#{symbol.inspect}",
"value=#{value.inspect}",
]
"#<#{self.class.name}:#{object_id} #{attributes.join(', ')}>"
end
end
end
| true |
772d0c634b302fbb886544d172413b884b821441 | Ruby | planningalerts-scrapers/parramatta | /scraper.rb | UTF-8 | 1,710 | 2.703125 | 3 | [] | no_license | require 'scraperwiki'
require 'mechanize'
class Hash
def has_blank?
self.values.any?{|v| v.nil? || v.length == 0}
end
end
base_url = "http://eplanning.parracity.nsw.gov.au/Pages/XC.Track/SearchApplication.aspx"
# meaning of t parameter
# %23427 - Development Applications
# %23437 - Constuction Certificates
# %23434,%23435 - Complying Development Certificates
# %23475 - Building Certificates
# %23440 - Tree Applications
url = base_url + "?d=last14days&t=%23437,%23437,%23434,%23435,%23475,%23440"
agent = Mechanize.new
page = agent.get(url)
results = page.search('div.result')
results.each do |result|
info_url = base_url + "?" + result.search('a.search')[0]['href'].strip.split("?")[1]
detail_page = agent.get(info_url);
council_reference = detail_page.search('h2').text.split("\n")[0].strip
description = detail_page.search("div#b_ctl00_ctMain_info_app").text.split("Status:")[0].strip.split.join(" ")
date_received = detail_page.search("div#b_ctl00_ctMain_info_app").text.split("Lodged: ")[1].split[0]
date_received = Date.parse(date_received.to_s)
address = detail_page.search("div#b_ctl00_ctMain_info_prop").text.split("\n")[0].squeeze(' ') rescue nil
record = {
'council_reference' => council_reference,
'description' => description,
'date_received' => date_received.to_s,
'address' => address,
'date_scraped' => Date.today.to_s,
'info_url' => info_url
}
unless record.has_blank?
puts "Saving record " + record['council_reference'] + ", " + record['address']
# puts record
ScraperWiki.save_sqlite(['council_reference'], record)
else
puts "Something not right here: #{record}"
end
end
| true |
f063d63320a4f7a7f7a9f91137fe461604d11600 | Ruby | JaehunYoon/Study | /Programming Language/Ruby/Example/04 method/rand/srand.rb | UTF-8 | 122 | 2.671875 | 3 | [] | no_license | srand 1234
puts rand(100)
puts rand(100)
puts rand(100)
puts " "
srand 1234
puts rand(100)
puts rand(100)
puts rand(100) | true |
e40f79f59120c44f98f769c781ab73495b39e3f2 | Ruby | Dew0Tgx/asciidoctor.js | /packages/core/lib/asciidoctor/js/opal_ext/string.rb | UTF-8 | 499 | 3.015625 | 3 | [
"MIT"
] | permissive | class String
# Safely truncate the string to the specified number of bytes.
def limit_bytesize size
return self.to_s unless size < bytes.length
result = byteslice 0, size
result.to_s
end unless method_defined? :limit_bytesize
alias :limit :limit_bytesize unless method_defined? :limit
alias :_original_unpack :unpack
def unpack format
if format == 'C3'
self[0, 3].bytes.select.with_index {|_, i| i.even? }
else
_original_unpack format
end
end
end
| true |
1c0f034f7d7c1b284aafeb8b200bce1f4591b245 | Ruby | justin-lilly/piglatin | /spec/pig_latin_spec.rb | UTF-8 | 330 | 2.65625 | 3 | [
"MIT"
] | permissive | require './lib/pig_latin.rb'
describe PigLatin do
before do
@string = "This is a test for the program"
end
it "first letter of word is a vowel" do
expect(PigLatin.translate("String")[0]).to eq ("i")
end
it "returns ay at the end of word" do
expect(PigLatin.translate("String")[0]).to eq ("i")
end
end
| true |
ae3f73f7b49fdafd4d4cd71519d67af3a67d93dc | Ruby | elliotthilaire/drip-photography | /lights-out-and-shoot/drip_and_shoot_sequence.rb | UTF-8 | 411 | 3.453125 | 3 | [
"MIT"
] | permissive | require "rubyserial"
class DripAndShootSequence
def initialize(serial_string:)
@serial_port = Serial.new serial_string, 9600
end
def run
@serial_port.write("shoot\n")
while true
data = @serial_port.read(1)
print data
# A quick and dirty hack to brack the loop.
# This is the last character returned in the sequence.
break if data.include?"*"
end
end
end
| true |
10cc93da0a6ab47c1958c0731d929b3f42cd2430 | Ruby | lucidsoftware/cumulus | /lib/s3/models/WebsiteConfig.rb | UTF-8 | 2,798 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | module Cumulus
module S3
class WebsiteConfig
attr_reader :error
attr_reader :index
attr_reader :redirect
# Public: Constructor
#
# json - a hash representing the JSON configuration, expects to be handed
# the 'website' node of S3 configuration.
def initialize(json = nil)
if json
@redirect = json["redirect"]
@index = json["index"]
@error = json["error"]
end
end
# Public: Populate this WebsiteConfig with the values in an AWS WebsiteConfiguration
# object.
#
# aws - the aws object to populate from
def populate!(aws)
@index = aws.safe_index
@error = aws.safe_error
@redirect = aws.safe_redirection
end
# Public: Produce a hash that is compatible with AWS website configuration.
#
# Returns the website configuration in AWS format
def to_aws
if @index
{
error_document: {
key: @error
},
index_document: {
suffix: @index
},
}
else
{
redirect_all_requests_to: {
host_name: if @redirect and @redirect.include?("://")
@redirect.split("://")[1]
else
@redirect
end,
protocol: if @redirect and @redirect.include?("://") then @redirect.split("://")[0] end
}
}
end
end
# Public: Converts this WebsiteConfig to a hash that matches Cumulus
# configuration.
#
# Returns the hash
def to_h
{
error: @error,
index: @index,
redirect: @redirect,
}.reject { |k, v| v.nil? }
end
# Public: Check WebsiteConfig equality with other objects
#
# other - the other object to check
#
# Returns whether this WebsiteConfig is equal to `other`
def ==(other)
if !other.is_a? WebsiteConfig or
@redirect != other.redirect or
@index != other.index or
@error != other.error
false
else
true
end
end
# Public: Check if this WebsiteConfig is not equal to the other object
#
# other - the other object to check
#
# Returns whether this WebsiteConfig is not equal to `other`
def !=(other)
!(self == other)
end
def to_s
if @redirect
"Redirect all traffic to #{@redirect}"
elsif @index
if @error
"Index document: #{@index}, Error document: #{@error}"
else
"Index document: #{@index}"
end
end
end
end
end
end
| true |
69e20c9c30eda5874cbaa3cb453ceabda61f8b36 | Ruby | aydyn-gur/intro-to-ruby | /more_stuff/exercise_2.rb | UTF-8 | 224 | 3.421875 | 3 | [] | no_license | def execute(&block)
block
end
execute { puts "Hello from inside the execute method!" }
# This program will not print anything to the screen because there
# is no call method on the block. It will return a Proc object. | true |
e83850fa2018df217b1fc8f4ba6f357160badf2b | Ruby | gropax/golyglot | /app/helpers/cmn/lexical_entries_helper.rb | UTF-8 | 274 | 2.546875 | 3 | [] | no_license | module Cmn::LexicalEntriesHelper
def cmn_lemma(lexical_entry)
[
lexical_entry.simplified,
brackets(lexical_entry.traditional),
lexical_entry.pinyin
].compact.join(" ")
end
def brackets(text)
text.blank? ? nil : "【#{text}】"
end
end
| true |
cb86d7500cec4c1b53a895f91dc8ed687545a364 | Ruby | nuthatch-s/RB101 | /3-practice_problems/array_add_many_elements.rb | UTF-8 | 183 | 2.796875 | 3 | [] | no_license | flintstones = %w(Fred Barney Wilma Betty Pebbles BamBam)
flintstones.append("Dino", "Hoppy")
# or flintstones.push("Dino", "Hoppy")
# or flintstones.concat(%w(Dino Hoppy))
p flintstones
| true |
01a95ac1bd23aa59e812a72f5708cee04b6e2e1c | Ruby | jeanmerlet/ruby_games | /dungeon/src/gui/viewport.rb | UTF-8 | 1,432 | 2.796875 | 3 | [] | no_license | class Viewport
attr_reader :width, :height, :x_off, :y_off
def initialize(map, entities, player)
@map, @entities, @player = map, entities, player
@width = (Config::SCREEN_WIDTH - Config::SIDE_PANEL_WIDTH)/2
@height = Config::SCREEN_HEIGHT - Config::VERT_PANEL_HEIGHT
@x_off, @y_off = @width/2, @height/2
end
def refresh
clear
render
end
def render
px, py = @player.x, @player.y
fov_id = @player.fov_id
@width.times do |i|
@height.times do |j|
x, y = px - @x_off + i, py - @y_off + j
if !@map.out_of_bounds?(x, y)
tile = @map.tiles[x][y]
if @map.fov_tiles[x][y] == fov_id
if tile.blocked
BLT.print(2*i, j, "[color=light_wall][font=bold]#")
else
BLT.print(2*i, j, "[color=light_floor][font=char]·")
end
if !tile.entities.empty?
color, char = tile.entities.last.color, tile.entities.last.char
BLT.print(2*i, j, "[font=char][color=#{color}]#{char}")
end
else
if tile.explored
if tile.blocked
BLT.print(2*i, j, "[color=unlit][font=bold]#")
else
BLT.print(2*i, j, "[color=unlit][font=char]·")
end
end
end
end
end
end
end
def clear
BLT.clear_area(0, 0, 2*@width, @height)
end
end
| true |
64e44b4c0254b22f6fc8b039dd6380979ee7269d | Ruby | SocialCentivPublic/cheftacular | /lib/cheftacular/stateless_actions/clean_cookbooks.rb | UTF-8 | 4,020 | 2.71875 | 3 | [
"MIT"
] | permissive |
class Cheftacular
class StatelessActionDocumentation
def clean_cookbooks
@config['documentation']['stateless_action'][__method__] ||= {}
@config['documentation']['stateless_action'][__method__]['long_description'] = [
"`cft clean_cookbooks [force] [remove_cookbooks]` allows you to update the internal chef-repo's cookbooks easily. " +
"By default this script will force you to decide what to do with each cookbook individually (shows version numbers and whether to overwrite it to cookbooks or not).",
[
" 1. `force` argument will cause the downloaded cookbooks to *always* overwrite the chef-repo's cookbooks as long as the downloaded cookbook has a higher version number.",
" 2. If you would like to remove all the cookbooks on the chef server, run `knife cookbook bulk delete '.*' -p -c ~/.chef/knife.rb`"
]
]
@config['documentation']['stateless_action'][__method__]['short_description'] = 'Allows you to update all cookbooks via berkshelf'
end
end
class StatelessAction
def clean_cookbooks local_options={'interactive' => true}
raise "This action can only be performed if the mode is set to devops" unless @config['helper'].running_in_mode?('devops')
ARGV.each do |arg|
case arg
when "force" then local_options['interactive'] = false
end
end
@config['cheftacular']['wrapper_cookbooks'].split(',').each do |wrapper_cookbook|
wrapper_cookbook_loc = "#{ @config['locs']['cookbooks'] }/#{ wrapper_cookbook }"
FileUtils.rm(File.expand_path("#{ wrapper_cookbook_loc }/Berksfile.lock")) if File.exists?(File.expand_path("#{ wrapper_cookbook_loc }/Berksfile.lock"))
FileUtils.rm_rf(File.expand_path("#{ @config['locs']['berks'] }/cookbooks")) if File.exists?(File.expand_path("#{ @config['locs']['berks'] }/cookbooks"))
Dir.chdir wrapper_cookbook_loc
puts "Installing new cookbooks..."
out = `berks install`
puts "#{out}\nFinished... Beginning directory scanning and conflict resolution..."
berkshelf_cookbooks = @config['filesystem'].parse_berkshelf_cookbook_versions
chef_repo_cookbooks = @config['filesystem'].parse_chef_repo_cookbook_versions
berkshelf_cookbooks.each_pair do |berkshelf_cookbook, cookbook_hash|
if chef_repo_cookbooks.has_key?(berkshelf_cookbook) || chef_repo_cookbooks.has_key?(cookbook_hash['location']) #don't overwrite cookbooks without user input
if local_options['interactive']
puts "COOKBOOK::~~~~#{ berkshelf_cookbook }~~~~::VERSION::~~~~~~~~#{ cookbook_hash['version'] } VS #{ chef_repo_cookbooks[berkshelf_cookbook] }"
puts "\nEnter O | o | overwrite to overwrite ~~~~#{ berkshelf_cookbook }~~~~ in the chef-repo (THIS SHOULD NOT BE DONE LIGHTLY)"
puts "Enter N | n | no to skip to the next conflict"
puts "If you pass force to this script, it will always overwrite."
#puts "If you pass a STRING of comma delimited cookbooks, it will skip these cookbooks automatically and overwrite others"
#puts "Example: ruby ./executables/clean-cookbooks 'application_ruby,wordpress'"
puts "Input:"
input = STDIN.gets.chomp
next if (input =~ /N|n|no/) == 0
end
next if @config['helper'].is_higher_version?(chef_repo_cookbooks[berkshelf_cookbook], cookbook_hash['version'])
end
cmnd = "#{ @config['locs']['berks'] }/#{ cookbook_hash['location'] } #{ @config['locs']['cookbooks'] }/#{ berkshelf_cookbook }"
puts "Moving #{ cmnd } (#{ cookbook_hash['version'] }:#{ chef_repo_cookbooks[berkshelf_cookbook] })" if @options['verbose']
`rm -Rf #{ @config['locs']['cookbooks'] }/#{ berkshelf_cookbook }`
`cp -Rf #{ cmnd }`
end
end
end
end
end
| true |
0f9d5b7d234c3dd8310753d4b32bcf5c8a6a9dce | Ruby | abalewis/cyrillic | /lib/cyrillic.rb | UTF-8 | 1,795 | 3.25 | 3 | [
"MIT"
] | permissive | require "cyrillic/version"
module Cyrillic
# Note. The letters І, Ѣ, Ѳ and Ѵ were eliminated in the orthographic reform of 1918.
# For other obsolete letters appearing in Russian texts, consult the Church Slavic table.
CHARACTER_TABLE = {
"А" => "A",
"Б" => "B",
"В" => "V",
"Г" => "G",
"Д" => "D",
"Е" => "E",
"Ё" => "Ë",
"Ж" => "ZH",
"З" => "Z",
"И" => "I",
"І" => "Ī",
"Й" => "Ĭ",
"К" => "K",
"Л" => "L",
"М" => "M",
"Н" => "N",
"О" => "O",
"П" => "P",
"Р" => "R",
"С" => "S",
"Т" => "T",
"У" => "U",
"Ф" => "F",
"Х" => "KH",
"Ц" => "TS",
"Ч" => "CH",
"Ш" => "SH",
"Щ" => "SHCH",
"Ъ" => "ʺ", #(HARD SIGN)
"Ы" => "Y",
"Ь" => "ʹ", #(SOFT SIGN)
"Ѣ" => "IE",
"Э" => "Ė",
"Ю" => "IU",
"Я" => "IA",
"Ѳ" => "Ḟ",
"Ѵ" => "Ẏ",
"а" => "a",
"б" => "b",
"в" => "v",
"г" => "g",
"д" => "d",
"е" => "e",
"ё" => "ë",
"ж" => "zh",
"з" => "z",
"и" => "i",
"і" => "ī",
"й" => "ĭ",
"к" => "k",
"л" => "l",
"м" => "m",
"н" => "n",
"о" => "o",
"п" => "p",
"р" => "r",
"с" => "s",
"т" => "t",
"у" => "u",
"ф" => "f",
"х" => "kh",
"ц" => "ts",
"ч" => "ch",
"ш" => "sh",
"щ" => "shch",
"ъ" => "ʺ", #(hard sign)
"ы" => "y",
"ь" => "ʹ", #(soft sign)
"ѣ" => "ie",
"э" => "ė",
"ю" => "iu",
"я" => "ia",
"ѳ" => "ḟ",
"ѵ" => "ẏ",
}
class << self
def transliterate(string = "")
string.to_s.gsub(Regexp.union(CHARACTER_TABLE.keys), CHARACTER_TABLE)
end
alias_method :t, :transliterate
end
end
| true |
ca5054fd22376ac68335d92f3314f450ac12e4a7 | Ruby | SeaRbSg/rosalind | /sotoseattle/problems/rear.rb | UTF-8 | 1,178 | 3.46875 | 3 | [
"MIT"
] | permissive | class Rosalind
def self.rear inputo
inputo.split(/\n+/).map {|s| s.split(' ').map(&:to_i)}
.each_slice(2).map { |x, y| [switcheroo(x, y), switcheroo(y, x)].min }
.join(" ")
end
def self.switcheroo wip, goal, n = 0
return n if wip == goal
[basic_swap(wip, goal, n),
basic_swap(wip.reverse, goal.reverse, n),
slingshoot(wip, goal, n)].compact.min
end
def self.basic_swap wip, goal, n
to, from = switchers(wip, goal)
switcheroo(flipper(wip, to, from), goal, n+1)
end
def self.slingshoot wip, goal, n
to, from = switchers(wip, goal)
if pivot = index_first_right(wip[to..from], goal[to..from])
pivot = pivot + to + 1
return switcheroo(flipper(wip, pivot, from), goal, n+1) if pivot < from
end
end
def self.switchers wip, goal
a = index_first_wrong(wip, goal)
b = wip.find_index(goal[a])
[a, b]
end
def self.flipper arr, i, j
flip = arr[i..j].reverse
arr[0...i] + flip + arr[j+1..-1]
end
def self.index_first_wrong a, b
(0..b.size).find { |i| a[i] != b[i] }
end
def self.index_first_right a, b
(0..b.size).find { |i| a[i] == b[i] }
end
end
| true |
3d014cfbe86dcb621d3d1bd82e039f7be79f06f6 | Ruby | binarytemple/enron_slurper | /app/helpers/email.rb | UTF-8 | 1,474 | 2.609375 | 3 | [
"MIT"
] | permissive | # Make it easy to convert RFC822 to JSON
module Mail
class Message
# DELIMITER = "\x1f"
DELIMITER = ','
attr_accessor :person, :mailbox
# keyed by
# customer-id | mailbox | message-id
def message_id
id = header.fields.detect do |x|
x.name == 'Message-ID'
end.to_s
id = id[1..id.length-1].match /^\d+\.\d+/
id.to_s
end
def date
date = header.fields.detect do |x|
x.name == 'Date'
end.to_s
Time.parse(date).to_i
end
def to_json(opts = {})
hash = {}
hash['customer_id'] = @person unless @person.nil?
hash['mailbox'] = @mailbox unless @mailbox.nil?
hash['timestamp'] = date
hash['message_id'] = message_id
# headers
hash['headers'] = {}
allowed = ['Date', 'From', 'To', 'Subject']
header.fields.each do |field|
hash['headers'][field.name] = field.value if allowed.include?(field.name)
end
special_variables = [:@header]
# limit to just body, use detect or something to short circut
hash['body_raw'] = instance_variable_get('@body_raw')
# (instance_variables.map(&:to_sym) - special_variables).each do |var|
# hash[var.to_s] = instance_variable_get(var) # send all the things
# end
begin
hash.to_json(opts)
rescue Exception => e
puts "Warning: #{e.inspect}"
'' # for now; toss bad characters
end
end
end
end | true |
88b783ca263d09f49cc518a41e37eb12f68aa682 | Ruby | ericawinne/active-record-toy-tale-practice | /app/models/toy.rb | UTF-8 | 396 | 2.6875 | 3 | [] | no_license | class Toy < ActiveRecord::Base
has_many :purchases
has_many :kids, through: :purchases
def self.most_expensive
self.find_by(price: Toy.maximum(:price)) #like doing Toy.all.maximum
end
def self.most_popular
most_popular = self.all.map{ |t| t.purchases.count}.max
self.all.find{ |t| t.purchases.count == most_popular }
end
def kids_name
kids.pluck(:name)
end
end | true |
b0dab2fd2455c4b80f14751aa0ae9209b3e498c1 | Ruby | yudai142/fleamarket_sample_61a | /app/models/category.rb | UTF-8 | 239 | 2.65625 | 3 | [] | no_license | class Category < ApplicationRecord
has_many :items
has_ancestry
def self.c_category(parent)
ch = []
parent.each do |parent|
parent.children.each do |child|
ch << child
end
end
return ch
end
end | true |
4d350bb504d52bd1d15b0b13c794cd2ba7a39dba | Ruby | JordanYu4/algorithms_practice | /ruby/spec/array_diff_spec.rb | UTF-8 | 1,072 | 2.859375 | 3 | [] | no_license | require 'rspec'
require 'array_diff'
describe 'array_diff' do
before { @arr1 = [1] }
before { @arr2 = [2] }
it 'returns a new array' do
array_diff([1, 2, 4, 5], [1, 4]).should_not be([2, 5])
array_diff(@arr1, @arr2).should_not be(@arr1)
array_diff(@arr1, @arr2).should_not be(@arr2)
end
it 'returns an array of arr1 elements not found in arr2' do
array_diff([1, 2, 4, 5], [1, 4]).should == [2, 5]
array_diff([1, 3, 5], [3, 4, 2, 5]).should_not include(3, 5)
end
end
describe 'array_diff_faster' do
before { @arr1 = [1] }
before { @arr2 = [2] }
it 'returns a new array' do
array_diff_faster([1, 2, 4, 5], [1, 4]).should_not be([2, 5])
array_diff_faster(@arr1, @arr2).should_not be(@arr1)
array_diff_faster(@arr1, @arr2).should_not be(@arr2)
end
it 'returns an array of arr1 elements not found in arr2' do
array_diff_faster([1, 2, 4, 5], [1, 4]).should == [2, 5]
array_diff_faster([1, 3, 5], [3, 4, 2, 5]).should_not include(3, 5)
end
end | true |
c354c8cd20080cf35b07bd36548d9e870cc24754 | Ruby | tlunter/Prerender | /lib/prerender/searcher.rb | UTF-8 | 1,063 | 2.71875 | 3 | [] | no_license | require 'excon'
require 'nokogiri'
def search_document(conn, contents, previous_links)
document = Nokogiri::HTML(contents)
document.xpath('//a/@href').each do |a|
puts "Found: #{a}"
next_uri = URI.parse(a)
if next_uri.host == nil && next_uri.scheme == nil
unless previous_links.include? next_uri
puts "Getting #{next_uri}"
puts "Already seen: #{previous_links.map(&:to_s)}"
get_document(conn, next_uri, previous_links)
end
end
end
end
def get_document(conn, uri, previous_links)
previous_links << uri
if uri.query.to_s.empty?
query = "_escaped_fragment_="
else
query << "&_escaped_fragment_="
end
resp = conn.request(path: uri.path, query: query)
search_document(conn, resp.body, previous_links)
end
def start_search(link)
base_uri = URI.parse(link)
conn = Excon::Connection.new({
:host => base_uri.host,
:port => base_uri.port,
:scheme => base_uri.scheme,
:method => "get"
})
uri = URI.parse("/")
get_document(conn, uri, [])
end
| true |
7672f5980006f18cb6155810d7f5dc4fb2cbcdb5 | Ruby | alexamy/thinknetica-blackjack | /models/card/deck.rb | UTF-8 | 364 | 3.15625 | 3 | [] | no_license | # Cards holder
class Deck
attr_reader_writer :cards
delegate :pop, :push, :map, :length, to: :cards
alias get pop
alias add push
def initialize(cards = [])
@cards = cards.shuffle
end
def points
sum = cards.sum(&:points)
aces = cards.select { |card| card.value == :ace }
sum += 10 if aces.any? && sum + 10 <= 21
sum
end
end
| true |
f842520e048fe9a197f5f1dd3139a0d2868f3226 | Ruby | mashan/Benchmarks | /NoSQL/benchmark.rb | UTF-8 | 8,207 | 2.703125 | 3 | [] | no_license | require 'pp'
require 'benchmark'
require 'optparse'
require './lib/kvs_benchmarker'
DB_NAME = 'test'
TABLE_NAME = 'hs_test'
HS_RO_PORT = '9998'
HS_RW_PORT = '9999'
MEMCACHE_PORT = '11211'
STDOUT.sync = true
options = {}
OptionParser.new do |o|
o.banner = "Usage ruby #{File.basename($0)} [OPTIOINS]"
o.separator ''
begin
required = [ :size, :host ]
o.on('--size size', 'size of records.(must)', Integer){|size|
raise ArgumentError, '--size must be specified!(>1)' if size < 0
options[:size] = size
}
o.on('--threads num', 'num of records.', Integer){|num|
options[:threads] = num
}
o.on('--host host', 'KVS host.(must)'){|host|
raise ArgumentError, '--host must be specified!' if host.empty?
options[:host] = host
}
o.parse!(ARGV)
required.each do |r|
raise ArgumentError, 'lack options.' unless options.key?(r)
end
options[:threads] = 1 if options[:threads].nil? || options[:threads] <= 0
rescue OptionParser::InvalidArgument, OptionParser::InvalidOption, ArgumentError => e
print <<-EOS
#{e.message}
#{o}
EOS
exit
end
end
sample = KvsBenchmarker::Sample.new({:size => options[:size]})
puts <<-EOS
####################
# INSERT BENCHMARK #
####################
EOS
puts "'set(insert)' benchmark..."
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
mysql.drop_data
hs = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RW_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
redis = KvsBenchmarker::RedisBench.new({
:host => options[:host],
:port => MEMCACHE_PORT,
:sample => sample
})
Benchmark.bm(30) do |rep|
rep.report("mysql2(single)") do
mysql.set
end
rep.report("HandlerSocket(single)") do
id = rand(10000)
hs.set
end
redis.drop_data
rep.report("redis(single)") do
redis.set
end
end
mysql.close
hs.close
redis.close
puts <<-EOS
####################
# SELECT BENCHMARK #
####################
EOS
puts "get benchmark..."
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
redis = KvsBenchmarker::RedisBench.new({
:host => options[:host],
:sample => sample
})
puts "Preparing data..."
puts "\t MySQL..."
mysql.setup
puts "\t Redis..."
redis.setup
hs = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RO_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
Benchmark.bm(30) do |rep|
rep.report("mysql2") do
options[:size].times do
mysql.get
end
end
rep.report("HandlerSocket(single)") do
options[:size].times do
hs.get
end
end
rep.report("redis(single)") do
options[:size].times do
redis.get
end
end
end
mysql.close
hs.close
redis.close
puts <<-EOS
#############################
# PARALLEL SELECT BENCHMARK #
#############################
EOS
puts "get benchmark..."
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
redis = KvsBenchmarker::RedisBench.new({
:host => options[:host],
:sample => sample
})
puts "Preparing data..."
puts "\t MySQL..."
mysql.setup
puts "\t Redis..."
redis.setup
mysql.close
redis.close
Benchmark.bm(40) do |rep|
rep.report("mysql2(#{options[:threads]}process)") do
options[:threads].times do |n|
Process.fork() {
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
(options[:size]/options[:threads]).times do
mysql.get
end
}
end
Process.waitall
end
rep.report("HandlerSocket(#{options[:threads]}process)") do
options[:threads].times do |n|
Process.fork() {
hs = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RO_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
(options[:size]/options[:threads]).times do
hs.get
end
hs.close
}
end
Process.waitall
end
rep.report("redis(#{options[:threads]}process)") do
options[:threads].times do |n|
Process.fork() {
redis = KvsBenchmarker::RedisBench.new({
:host => options[:host],
:port => MEMCACHE_PORT,
:sample => sample
})
(options[:size]/options[:threads]).times do
redis.get
end
redis.close
}
end
Process.waitall
end
end
puts <<-EOS
##########################################
# FOR REPLICATION TEST (By MySQL INSERT) #
##########################################
EOS
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
mysql.drop_data
Benchmark.bm(30) do |rep|
rep.report("mysql2 insert)") do
mysql.set
end
end
mysql.close
puts <<-EOS
##################################################
# FOR REPLICATION TEST (By HandlerSocket INSERT) #
##################################################
EOS
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
mysql.drop_data
mysql.close
Benchmark.bm(30) do |rep|
rep.report("HS insert") do
hs_1 = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RW_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
hs_1.set
hs_1.close
end
end
puts <<-EOS
#########################################################
# COMPLEX BENCHMARK(MySQL Insert + HandlerSocket SELECT #
#########################################################
EOS
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
mysql.drop_data
hs = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RO_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
Benchmark.bm(30) do |rep|
rep.report("mysql2 + HS") do
puts
Process.fork() {
begin
mysql.set
rescue
puts "mysql2 error occurred"
end
}
Process.fork() {
options[:size].times do |n|
begin
hs.get_first_record_slowly
rescue
puts "handlersocket error occurred : #{n}"
end
end
}
Process.waitall
end
end
mysql.close
hs.close
puts <<-EOS
#####################
# COMPLEX BENCHMARK #
#####################
EOS
mysql = KvsBenchmarker::MySQLBench.new({
:host => options[:host],
:port => 3306,
:database => DB_NAME,
:username => 'root',
:table => TABLE_NAME,
:sample => sample
})
mysql.drop_data
mysql.close
Benchmark.bm(30) do |rep|
rep.report("HS + HS") do
hs_1 = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RW_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
Process.fork() { hs_1.set }
hs_2 = KvsBenchmarker::HandlerSocketBench.new({
:host => options[:host],
:port => HS_RO_PORT,
:database => DB_NAME,
:table => TABLE_NAME,
:sample => sample
})
Process.fork() { options[:size].times { hs_2.get } }
Process.waitall
hs_1.close
hs_2.close
end
end
| true |
c0a4ce0faedf1642b67acbb323c3090339122d2e | Ruby | arlemi/OpenRecord-CI | /array.rb | UTF-8 | 560 | 2.6875 | 3 | [] | no_license | class Array
#
# Selectionne les elements dont le champ id satisfait le critere
# specifie par le bloc.
#
def selectionner_avec( id )
DBC.check_type( id, Symbol,
"** L'argument a selectionner_avec doit etre un symbole" )
nil
end
def method_missing( id, *args )
if id.to_s =~/=$/
newId = id.to_s.chop
definir_reader_et_writer(newId.to_sym)
instance_eval "@#{newId} = args[0]"
else
raise NoMethodError
end
end
end
| true |
b3426cf76570c5cce344c68aa15046a59f01e059 | Ruby | motapuma/al-tweets | /app/helpers/tweets_helper.rb | UTF-8 | 555 | 2.75 | 3 | [] | no_license | module TweetsHelper
def correct_txt_and_class_fav(current_user,tweet)
faved = current_user.faved?(tweet)
txt = faved ? "UnFav" : "Fav"
button_class = faved ? "btn btn-danger btn-lg" : "btn btn-warning btn-lg"
return txt, button_class , faved
end
def correct_txt_and_class_retweet(current_user,tweet)
retweeted = current_user.retweeted?(tweet)
txt = retweeted ? "UnRetweet" : "Retweet"
button_class = retweeted ? "btn btn-danger btn-lg" : "btn btn-info btn-lg"
return txt, button_class , retweeted
end
end | true |
102b9a431440228229d4f31b29330ee048c873e8 | Ruby | asjedh/slacker_news_sql | /server.rb | UTF-8 | 1,384 | 3.03125 | 3 | [] | no_license | require 'sinatra'
require 'csv'
require 'pry'
require 'pg'
require 'net/http'
require 'addressable/uri'
### METHODS
def db_conn
begin
connection = PG.connect(dbname: 'slacker_news')
yield(connection)
ensure
connection.close
end
end
def save_article_to_db(article_info_array)
db_conn do |conn|
conn.exec_params("INSERT INTO articles (title, url, description, created_at)
VALUES ($1,$2,$3, NOW())", article_info_array)
end
end
def import_articles_from_db
db_conn do |conn|
conn.exec("SELECT * FROM articles")
end.to_a
end
SCHEMES = %w(http https)
def valid_url?(url)
parsed = Addressable::URI.parse(url) or return false
SCHEMES.include?(parsed.scheme)
rescue Addressable::URI::InvalidURIError
false
end
### PATHS
get '/articles' do
@articles = import_articles_from_db
erb :home
end
get '/articles/new' do
erb :'submit/submit', layout: :'submit/layout'
end
post '/articles/new' do
url = params[:url]
if !valid_url?(url)
@error_message = "Please enter a valid URL!"
redirect back
elsif #description is less than 20 char
#error message and go back
redirect back
else #we're good to go... put the article in the database!
new_article = [params[:title], params[:url], params[:description]]
save_article_to_db(new_article)
redirect '/articles'
end
end
get '/' do
redirect '/articles'
end
| true |
85d84e1abf1bf861e69a88fc24d0175bd41c848d | Ruby | hging/trex | /vendor/screen/lib/screen/colourize.rb | UTF-8 | 723 | 3.359375 | 3 | [] | no_license | class Colourize
FG_NORMAL = -1
BG_NORMAL = -1
COLORS = [
0,1,2,3,4,5,6,7,9
]
def self.generate str, fcol=FG_NORMAL, bcol=BG_NORMAL, bold: false
bcol = 9 if bcol == -1
bcol = bcol + 40 if bcol <= 9
fcol = 9 if fcol == -1
fcol = fcol + 30 if fcol <= 9
bcol = 1 if bold
"\e[#{fcol};#{bcol}m"+str+"\e[0m"
end
def self.case str, truth, aset, bset = [-1,-1], &b
if truth
return generate str,*aset
end
generate str, *bset
end
end
class String
def colourize? truth, aset, bset=[-1,-1]
Colourize.case self, truth, aset, bset
end
def colourize fg,bg=-1, bold: false
Colourize.generate self,fg,bg, bold: bold
end
end
| true |
e92bfda6376647bf1bed0a0441f89dbc3c01d314 | Ruby | laurawhalin/book_search | /app/models/search.rb | UTF-8 | 662 | 2.671875 | 3 | [] | no_license | class Search < ApplicationRecord
validates :author, presence: true, unless: :title
validates :title, presence: true, unless: :author
validates :title, uniqueness: { scope: :author, message: "Title/author pairing already exists" }
before_validation :format_title
before_validation :format_author
before_save :set_refresh_date
private
def set_refresh_date
self.refreshed_at = Time.now.utc
end
def format_title
self.title = formatter(self.title)
end
def format_author
self.author = formatter(self.author)
end
def formatter(value)
value.downcase.gsub(/\W+/, " ").split(" ").sort.join(" ") if value
end
end
| true |
da40e0fd311c8d88e467360229e4d85f083ac452 | Ruby | shelkarvijay/ruby_basics | /class.rb | UTF-8 | 564 | 4.09375 | 4 | [] | no_license | class Class
def initialize(m,n)
@width ,@height = m, n
end
def width #this methos is known as accessor method
@width
end
def height #this methos is known as accessor method
@height
end
def setter1=(value)
@width = value
end
def self.setter2=(value) #class method definition
@height = value
end
end
c = Class.new(10,20)
a = c.width()
b = c.height()
puts "height : #{b} And width : #{a}"
c.setter1 = 30
Class.setter2 = 40 #this method call is known as class method
a = c.width()
b = c.height()
puts "height : #{b} And width : #{a}" | true |
ec29af8290372fb6bbf2dbf8d5ce09150d490319 | Ruby | DouglasAllen/code-Metaprogramming_Ruby | /raw-code/PART_II_Metaprogramming_in_Rails/gems/activesupport-4.0.2/lib/active_support/core_ext/string/zones.rb | UTF-8 | 748 | 2.875 | 3 | [
"MIT"
] | permissive | #---
# Excerpted from "Metaprogramming Ruby",
# published by The Pragmatic Bookshelf.
# Copyrights apply to this code. It may not be used to create training material,
# courses, books, articles, and the like. Contact us if you are in doubt.
# We make no guarantees that this code is fit for any purpose.
# Visit http://www.pragmaticprogrammer.com/titles/ppmetr2 for more book information.
#---
require 'active_support/core_ext/time/zones'
class String
# Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
# is set, otherwise converts String to a Time via String#to_time
def in_time_zone(zone = ::Time.zone)
if zone
::Time.find_zone!(zone).parse(self)
else
to_time
end
end
end
| true |
4fe8be6d66ebf8224227a21918b353e3ed775e03 | Ruby | Carlospp/mariaauxiliadora | /app/models/treatment.rb | UTF-8 | 496 | 2.65625 | 3 | [] | no_license | class Treatment < ActiveRecord::Base
validates :nombre , presence: { message: " es requerido"} , confirmation: true
validates :costo , presence: { message: " es requerido"} , confirmation: true
validates :costo, numericality: { only_integer: true ,message: "no es un numero"}
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |student|
csv << student.attributes.values_at(*column_names)
end
end
end
end
| true |
89facdd65e2fd6c39e7714b55bc82c6c5c6a5729 | Ruby | nico-hn/PseudoHikiParser | /test/test_htmlplugin.rb | UTF-8 | 1,772 | 2.765625 | 3 | [
"BSD-2-Clause"
] | permissive | #/usr/bin/env ruby
require 'minitest/autorun'
require 'lib/pseudohiki/htmlplugin'
class TC_HtmlPlugin < MiniTest::Unit::TestCase
include PseudoHiki
def test_visit_pluginnode
formatter = HtmlFormat.get_plain
tree = InlineParser.new("{{co2}} represents the carbon dioxide.").parse.tree
assert_equal("CO<sub>2</sub> represents the carbon dioxide.",tree.accept(formatter).to_s)
end
def test_escape_inline_tags
formatter = HtmlFormat.get_plain
tree = InlineParser.new("a line with an inline tag such as {{''}}").parse.tree
assert_equal("a line with an inline tag such as ''",tree.accept(formatter).to_s)
end
def test_html_plugin
formatter = HtmlFormat.get_plain
tree = InlineParser.new("you can directly embed a snippet of html code like '{{html(<i>italic</i>)}}'.").parse.tree
assert_equal("you can directly embed a snippet of html code like '<i>italic</i>'.",tree.accept(formatter).to_s)
end
def test_html
expected_html = '<ul>
<li>list
<li>list
</ul>'
input = "html(
<ul>
<li>list
<li>list
</ul>)"
assert_equal(expected_html, HtmlPlugin.new("div", input).apply)
end
def test_inline
input = "inline(
*list
*list
)"
assert_raises(ArgumentError) do
HtmlPlugin.new("div", input).apply
end
end
def test_co2
assert_equal("CO<sub>2</sub>", HtmlPlugin.new("div", "co2").apply)
assert_equal("carbon dioxide", HtmlPlugin.new("div", "co2 :en").apply)
end
def test_cubic
assert_equal("3km<sup>3</sup>", HtmlPlugin.new("div", "cb(3km)").apply)
end
def test_per
assert_equal("m<sup>-1</sup>", HtmlPlugin.new("div", "per m").apply)
end
def test_co2_isotope
assert_equal("<sup>18</sup>CO<sub>2</sub>", HtmlPlugin.new("div", "iso 18co2").apply)
end
end
| true |
9c8e211a6c39cd5dbe3e503122da53488bab8dd7 | Ruby | phistando/Redmart-Sinatra | /app.rb | UTF-8 | 5,256 | 2.765625 | 3 | [] | no_license | class RedmarkSinatraApp < Sinatra::Base
get '/' do
erb ''
end
# RESTFUL RESOURCES, CREATE READ UPDATE DELETE
################################ Users ###################################
get '/users' do
@users = User.all
erb :'users/index'
end
get '/users/:id' do
if params[:id] == 'new'
erb :'users/new'
else
@user = User.find(params[:id])
erb :'users/show'
end
end
get '/users/:id/edit' do
@user = User.find(params[:id])
erb :'users/edit'
end
post '/users' do
puts params[:user]
# this is how we do it in pizza shop
# Pizza.new(parameters to pass in)
# Pizza.save
@new_user = User.new(params[:user])
if @new_user.save
# go to all users list
redirect("/users")
else
# throw an error
erb :"users/new"
end
end
put '/users/:id' do
@updated_user = User.find(params[:id])
if @updated_user.update_attributes( params[:user] )
redirect("/users")
end
end
delete '/users/:id' do
@deleted_user = User.find(params[:id])
if @deleted_user.destroy
# go to all users list
redirect("/users")
else
# throw an error
erb :"users/#{ @deleted_user.id }"
end
end
############################# Products #####################################
get '/products' do
@products = Product.all
erb :'products/index'
end
get '/products/:id' do
if params[:id] == 'new'
erb :'products/new'
else
@product = Product.find(params[:id])
erb :'products/show'
end
end
get '/products/:id/edit' do
@product = Product.find(params[:id])
erb :'products/edit'
end
post '/products' do
puts params[:product]
# this is how we do it in pizza shop
# Pizza.new(parameters to pass in)
# Pizza.save
@new_product = Product.new(params[:product])
if @new_product.save
redirect("/products")
else
erb :"products/new"
end
end
put '/products/:id' do
@updated_product = Product.find(params[:id])
if @updated_product.update_attributes( params[:product] )
redirect("/products")
end
end
delete '/products/:id' do
@deleted_product = Product.find(params[:id])
if @deleted_product.destroy
redirect("/products")
else
erb :"products/#{ @deleted_product.id }"
end
end
############################ Brands ######################################
get '/brands' do
@brands = Brand.all
erb :'brands/index'
end
get '/brands/:id' do
if params[:id] == 'new'
erb :'brands/new'
else
@brand = Brand.find(params[:id])
erb :'brands/show'
end
end
get '/brands/:id/edit' do
@brand = Brand.find(params[:id])
erb :'brands/edit'
end
post '/brands' do
puts params[:brand]
@new_brand = Brand.new(params[:brand])
if @new_brand.save
redirect("/brands")
else
erb :"brands/new"
end
end
put '/brands/:id' do
@updated_brand = Brand.find(params[:id])
if @updated_brand.update_attributes( params[:brand] )
redirect("/brands")
end
end
delete '/brands/:id' do
@deleted_brand = Brand.find(params[:id])
if @deleted_brand.destroy
redirect("/brands")
else
erb :"brands/#{ @deleted_brand.id }"
end
end
############################ Categories ######################################
get '/categories' do
@categories = Category.all
erb :'categories/index'
end
get '/categories/:id' do
if params[:id] == 'new'
erb :'categories/new'
else
@category = Category.find(params[:id])
erb :'categories/show'
end
end
get '/categories/:id/edit' do
@category = Category.find(params[:id])
erb :'categories/edit'
end
post '/categories' do
puts params[:category]
@new_category = Category.new(params[:category])
if @new_category.save
redirect("/categories")
else
erb :"categories/new"
end
end
put '/categories/:id' do
@updated_category = Category.find(params[:id])
if @updated_category.update_attributes( params[:category] )
redirect("/categories")
end
end
delete '/categories/:id' do
@deleted_category = Category.find(params[:id])
if @deleted_category.destroy
redirect("/categories")
else
erb :"categories/#{ @deleted_category.id }"
end
end
############################ Purchases ######################################
get '/purchases' do
@purchases = Purchase.all
erb :'purchases/index'
end
get '/purchases/:id' do
if params[:id] == 'new'
erb :'purchases/new'
else
@purchase = Purchase.find(params[:id])
erb :'purchases/show'
end
end
get '/purchases/:id/edit' do
@purchase = Purchase.find(params[:id])
erb :'purchases/edit'
end
post '/purchases' do
puts params[:purchase]
@new_purchase = Purchase.new(params[:purchase])
if @new_purchase.save
redirect("/purchases")
else
erb :"purchases/new"
end
end
put '/purchases/:id' do
@updated_purchase = Purchase.find(params[:id])
if @updated_purchase.update_attributes( params[:purchase] )
redirect("/purchases")
end
end
delete '/purchases/:id' do
@deleted_purchase = Purchase.find(params[:id])
if @deleted_purchase.destroy
redirect("/purchases")
else
erb :"purchases/#{ @deleted_purchase.id }"
end
end
end
| true |
388c2445f20b1b87dc4de91634768b9da95fffaa | Ruby | DevGGuedes/Ruby-POO | /Times.rb | UTF-8 | 77 | 3.125 | 3 | [] | no_license |
5.times {
puts "Rodando"
}
puts ""
10.times { |i|
puts "Rodando #{i}"
} | true |
f2c77174de6bc40700fd6f3706bc7d4d2f099b38 | Ruby | DimaSamodurov/browser_crawler | /spec/lib/hooks_operator_spec.rb | UTF-8 | 3,304 | 2.609375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe BrowserCrawler::HooksOperator do
before :each do
lambda do
return nil unless Object.constants.include?(:ClassSubject)
Object.send(:remove_const, :ClassSubject)
end.call
end
describe '.with_hooks_for' do
it 'executes hooks with type :all for a passed block' do
ClassSubject = Class.new do
include BrowserCrawler::HooksOperator
def before(type: :all, &hook)
BrowserCrawler::HooksContainer.instance.add_hook(method: :before,
type: type,
hook: hook)
end
def after(type: :all, &hook)
BrowserCrawler::HooksContainer.instance.add_hook(method: :after,
type: type,
hook: hook)
end
end
message = []
subject = ClassSubject.new
subject.before(type: :all) do
message << 'before all'
end
subject.after(type: :all) do
message << 'after all'
end
subject.after(type: :each) do
message << 'after each'
end
subject.with_hooks_for(type: :all) do
message << 'body'
end
expect(message).to eq(['before all', 'body', 'after all'])
end
it 'executes hooks with type :each for a passed block' do
ClassSubject = Class.new do
include BrowserCrawler::HooksOperator
def before(type: :all, &hook)
BrowserCrawler::HooksContainer.instance.add_hook(method: :before,
type: type,
hook: hook)
end
def after(type: :all, &hook)
BrowserCrawler::HooksContainer.instance.add_hook(method: :after,
type: type,
hook: hook)
end
end
message = []
subject = ClassSubject.new
subject.before(type: :each) do
message << 'before each'
end
subject.after(type: :each) do
message << 'after each'
end
subject.after(type: :all) do
message << 'after all'
end
subject.with_hooks_for(type: :each) do
message << 'body'
end
expect(message).to eq(['before each', 'body', 'after each'])
end
end
describe '.exchange_on_hooks' do
it 'executes hooks with type :scan_rules or :unvisited_links' do
ClassSubject = Class.new do
include BrowserCrawler::HooksOperator
def unvisited_links(&hook)
BrowserCrawler::HooksContainer.instance
.add_hook(method: :run_only_one,
type: :unvisited_links,
hook: hook)
end
end
links_array = [1, 2, 3, 4]
subject = ClassSubject.new
subject.unvisited_links do
links_array.select! { |i| i.even? }
end
subject.exchange_on_hooks(type: :unvisited_links) do
links_array.select! { |i| i.odd? }
end
expect(links_array).to eq([2, 4])
end
end
end
| true |
8467c1e21dad67dfc02faf0ff0a2028b4c6658dc | Ruby | yurifrl/curly | /spec/scanner_spec.rb | UTF-8 | 2,546 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | require 'spec_helper'
describe Curly::Scanner, ".scan" do
it "returns the tokens in the source" do
scan("foo {{bar}} baz").should == [
[:text, "foo "],
[:component, "bar"],
[:text, " baz"]
]
end
it "scans components with identifiers" do
scan("{{foo.bar}}").should == [
[:component, "foo.bar"]
]
end
it "allows components with whitespace" do
scan("{{ foo bar}}").should == [
[:component, " foo bar"]
]
end
it "scans comments in the source" do
scan("foo {{!bar}} baz").should == [
[:text, "foo "],
[:comment, "bar"],
[:text, " baz"]
]
end
it "allows newlines in comments" do
scan("{{!\nfoo\n}}").should == [
[:comment, "\nfoo\n"]
]
end
it "scans to the end of the source" do
scan("foo\n").should == [
[:text, "foo\n"]
]
end
it "allows escaping Curly quotes" do
scan('foo {{{ bar').should == [
[:text, "foo "],
[:text, "{{"],
[:text, " bar"]
]
scan('foo }} bar').should == [
[:text, "foo }} bar"]
]
scan('foo {{{ lala! }} bar').should == [
[:text, "foo "],
[:text, "{{"],
[:text, " lala! }} bar"]
]
end
it "scans conditional block tags" do
scan('foo {{#bar?}} hello {{/bar?}}').should == [
[:text, "foo "],
[:conditional_block_start, "bar?"],
[:text, " hello "],
[:conditional_block_end, "bar?"]
]
end
it "scans inverse block tags" do
scan('foo {{^bar?}} hello {{/bar?}}').should == [
[:text, "foo "],
[:inverse_conditional_block_start, "bar?"],
[:text, " hello "],
[:conditional_block_end, "bar?"]
]
end
it "scans collection block tags" do
scan('foo {{*bar}} hello {{/bar}}').should == [
[:text, "foo "],
[:collection_block_start, "bar"],
[:text, " hello "],
[:collection_block_end, "bar"]
]
end
it "treats quotes as text" do
scan('"').should == [
[:text, '"']
]
end
it "treats Ruby interpolation as text" do
scan('#{foo}').should == [
[:text, '#{foo}']
]
end
it "raises Curly::SyntaxError on unclosed components" do
["{{", "{{yolo"].each do |template|
expect { scan(template) }.to raise_error(Curly::SyntaxError)
end
end
it "raises Curly::SyntaxError on unclosed comments" do
["{{!", "{{! foo bar"].each do |template|
expect { scan(template) }.to raise_error(Curly::SyntaxError)
end
end
def scan(source)
Curly::Scanner.scan(source)
end
end
| true |
c19b8eb694014ba241c8b65125f614cc8ba12c01 | Ruby | Linktheoriginal/Euler | /triangle_numbers.rb | UTF-8 | 957 | 3.78125 | 4 | [] | no_license | #I originally was running x up to k/2 (started k at 1 for dividing itself), but I stole
#the sqrt idea from here:http://www.mathblog.dk/triangle-number-with-more-than-500-divisors/
#The second solution is basically usingthe prime divisor code from problem 3 plus combinatorics
#of the prime factors to figure it out. Faster, but a lot more coding.
#While I generally understand the process of the coprime solution at the above url, that code is
#so unreadable that I wouldn't use it. Once you understand it, it's great, but I would
#only go that far if it was a major gain in the program I'm writing. Generally, avoid until required,
#but if that's required, write paragraphs of comments explaining it.
i = 0
y = 0
while y < 500
k = 0
for j in 1..i
k = j + k
end
#print " k = " + k.to_s
y = 0
for x in 1..Math.sqrt(k)
if (k.to_f / x) % 1.to_f == 0
y += 2
end
end
#print " y = " + y.to_s
i += 1
end
print k | true |
16f068eab7b537fa461eac614559596f2dca117e | Ruby | alpaca-tc/tweet_cleaner | /twitter.rb | UTF-8 | 713 | 2.546875 | 3 | [] | no_license | require 'twitter'
require 'yaml'
require 'parallel'
current_dir = File.expand_path(File.dirname(__FILE__))
CONFIG = YAML.load_file("#{current_dir}/config.yml").freeze
client = Twitter::REST::Client.new do |config|
config.consumer_key = CONFIG['CONSUMER_KEY']
config.consumer_secret = CONFIG['CONSUMER_SECRET']
config.access_token = CONFIG['ACCESS_TOKEN']
config.access_token_secret = CONFIG['ACCESS_TOKEN_SECRET']
end
user = client.user
tweets = []
begin
loop do
tweets = client.user_timeline
Parallel.map(tweets, in_processes: 8) do |tweet|
puts "Destroy: #{tweet.id} : #{tweet.text}"
client.destroy_tweet(tweet)
end
end
rescue => e
puts e.message
end
| true |
03b28dac9b796807559dcf5e3975c8d8a07255c6 | Ruby | lorijustlori/C25-REPL-Game | /replgame.rb | UTF-8 | 15,879 | 3.546875 | 4 | [] | no_license | puts "Good morning, Wynfamily! Looks like we have a full house today and everyone is ready to learn!"
puts "Oh, wait. Why is everyone leaving?"
puts "Choose the corresponding number to follow an escapee group of Wyncoders...."
puts "Choose 1 to follow Andrew, Andreina, Gabe and Angel, Choose 2 to follow Stephen, Alexis, Natalia and Greg, Choose 3 to follow Tushani, Clermondo, Dan and Marc and Choose 4 to follow Shane, Joel and Lori."
# input = gets.chomp(input)._to.i
input = gets.chomp
case input
when "1"
puts "Wow, look at them go! Andrew is forcing Andreina, Gabe and Angel to dance. This could go all kinds of wrong. Should the group let him tag along or dump him over on 2nd Ave? Choose 1 to let him tag along or 2 to dump him!"
# puts "Enter numeric value: "
# result = gets
# if result =~ /^-?[0-4]+$/
# puts "Valid input"
# else
# puts "Invalid input."
# end
andrew = gets.chomp
case andrew
when "1"
puts "Good choice, Andrew! Stick with the group. The alternative could have been dance-astrous! So off they go toward Wynwood Walls. Andreina wants to check out some art for her new apartment. Should the guys agree to suffer through the shopping experience or should Andreina follow the guys to a different adventure? Choose 1 for Andreina to stick for the group or choose 2 for Andreina to go shopping alone."
andreina = gets.chomp
case andreina
when "1"
puts "So glad Andreina stuck with the guys....her shopping experience would have ended with not so art-tacular results... So off they go, walking through Wynwood when Gabe spots on of those electric scooters! He's so excited! The rest of the group tells him it's not such a good idea to try one. Should he scoot or should he stay with his friends? Choose 1 for Gabe staying close to the group or choose 2 for Gabe scooting off into the sunset."
gabe = gets.chomp
case gabe
when "1"
puts "Good thing Gabe stuck close. The great Scotter Escape had tread-jedy written all over it! But now Angel is in a hurry. He sees someone he knows across the street and wants to say hello. Do you think he should check in with his friend later or should he head over to say hi? Choose 1 if you think Angel should stick with the WynSquad or choose 2 if you think he should take five minutes with his friend."
angel = gets.chomp
case angel
when "1"
puts "Yowza! Angel made a wise decision and crossed the street at the light with his C25 buddies. This group of Wyncoders is happy to have escaped a boat load of trouble. They decide to head to the beach to celebrate! Wonder what happened to everyone else?"
when "2"
puts "Angel! No! Don't cross in the middle of the.... Well, look who ran him over...Mario. Well, Mario won't be charging for this Uber trip to the ER.... Let's head back to the beginning since it's a temporary end for Angel today...."
end
when "2"
puts "Gabe, Gabe, Gabe. Why did he have to hop on a scooter...in traffic. He got distracted by a puppy riding the scooter next to him and ended up with tread marks on his face. Luckily, Mario was Ubering in the neighborhood and dropped him off at the hospital to get fixed up! Too bad for Gabe!"
end
when "2"
puts "Well, Andreina is off on her own. The guys wanted nothing to do with art or shopping. Personally, I think she made the right choice, until she actually picked out her new picture and it fell on her head. She had to call Uber to take her to the ER. Good thing Mario was in the area and could drive her quickly to get her concussion checked out! Check back later to see what everyone else is up to!"
else
puts "Did you check out that new mural at the Walls? Could you grab a pic for me and meet me where you last saw Mario pick up an injured person?"
end
when "2"
puts "Poor Andrew! He got dumped and while showing off some of his dance moves while crossing the street, the kids at the nearby school challenged him to a dance-off. Let's just say that Andrew didn't quite keep up. He left the competition in an Uber - driven by Mario - WHAT!? - and headed to the ER with a twisted ankle and bruised ego. Come back later to check out your other favorite Wyncoder adventures..."
else
puts "Could you look up some dance classes in the area? I suspect that Andrew is going to attempt to teach the entire cohort to dance. Let's just get him straightened out now before more potential disaster strikes."
end
when "2"
puts "Oh my...I'm not sure who is running faster to check out the newest Wynwood brewery! Natalia has her hands full! Do you think she she head back to Wynbase to finish up some homework or should she agree to check out the latest batch o' brew? Choose 1 for grab some brew or choose 2 for head back to Wynbase."
natalia = gets.chomp
case natalia
when "1"
puts "Whew! Natalia missed a truly slippery situation by sticking with the Brew Crew! Alexis has decided that he wants to stop first for a street hot dog but no one wants to wait. Do you think Alexis should wait and get food at the brewery or should he stop for a street dog? Choose 1 for the brewery food or choose 2 for the street food."
alexis = gets.chomp
case alexis
when "1"
puts "Alexis escaped a hot situation by sticking with the Brew Crew. If only Stephen wouldn't be walking so fast! He claims that the beer is calling his name. Do you think he should slow down, take a deep breath and walk with the crew or should he just listen to the call of the beer and run ahead? Choose 1 for the Crew or choose 2 for follow the sound of the beer."
stephen = gets.chomp
case stephen
when "1"
puts "Good job Stephen. Friends that drink together, stay together. Thinking of the alternative gets me all choked up. But Greg is being awfully quiet. Is he just a quiet member of the Brew Crew or is he about to fall asleep? Choose 1 for him being quiet or choose 2 for Greg being about to doze off..."
greg = gets.chomp
case greg
when "1"
puts "Greg apparently doesn't have much to say. He said that he woke up with codes running through his head and he needs some time to think about how to get his idea implemented. The rest of the Brew Crew is anxious to celebrate an awesome day of inspiration. They head over to the beach to soak up some rays! Have you heard from the rest of C25? Wonder how they are doing?"
when "2"
puts "Zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
else
puts "You may want to stick around to see how this day ends."
end
when "2"
puts "Stephen has that look on his face like Violet in Charlie and the Chocolate Factory. She couldn't stop chewing gum, he couldn't stop running after the beer. Well...he made it to the brewery, but guzzled down his first beer so quickly, that he started choking on it. Since no one was with him, the grumpy guy behind the bar called Uber to pick him up. Sorry Stephen. No more brews for you today!"
else
puts "Maybe you could figure out how Mario is tracking all of these injuries. Curious and curiouser."
end
when "2"
puts "Alexis could not resist the hot dog stand. Too bad for him. A banana pepper caused an allergic reaction that swelled up his throat. He called an ambulance, but Mario was just around the block and got to him faster. Sorry Alexis. No more banana peppers for you!"
else
puts "Do you get the feeling that there is more to this story? Maybe you could see what other trouble is brewing."
end
when "2"
puts "Hey Natalia! No one else is at Wynbase! Oh no! She was so excited to get back and work on her next project, that she slipped on a fake banana peel ... sidewalk art... it looks so real.... and she landed on her elbow. Super Uber Mario answered her call for help and rushed her to Urgent Care! Start over to see what happened to the rest of the brew crew!"
else
puts "Stop laughing. This is some legitimately stressful stuff going on!"
end
when "3"
puts "Uh oh! Tushani is trying to convince the guys to try out pastries at Zak the Baker and Clermondo wants to know if he can take his skateboard. Should he stay with the group or go head to scout out the place? Choose 1 for Clermondo to stay with the team or 2 for Clermondo to skateboard off into the sunset."
clermondo = gets.chomp
case clermondo
when "1"
puts "Clermondo decided to skateboard slowly by his WynFamily and thankfully so as he avoided a situation he could Harley have enjoyed. Tushani however, is so excited to share her love of chocolate babka, that she is taking a short-cut through one of the parking lots. Should she take the long way around with the group or should she heed the call of the babka and take a shortcut? Choose 1 for a slow babka walk or 2 for a babka jog."
tushani = gets.chomp
case tushani
when "1"
puts "Tushani heard the guys calling for her - they needed her to explain what a babka is... really - what IS it? She rolled her babka-loving eyes and told them to follow her lead. Meanwhile, Dan received a text from a friend about reaching the next major level of a game. He's debating heading back to Wynbase to try it out. Do you think he should at least try the babka first or go get his game on? Choose 1 for babka or choose 2 for game."
dan = gets.chomp
case dan
when "1"
puts "Dan considered that the game could wait and that if the babka was as good as Tushani proclaimed, it may actually increase his energy level and give him a boost for the rest of the day! Dan turned around and saw Marc standing in the middle of the street. Marc is thinking that he doesn't want a babka. Sill Marc. Choose 1 if you think Marc should try the life-changing babka or choose 2 if you think Marc should follow his stomach."
marc = gets.chomp
case marc
when "1"
puts "Marc figured that he could hold out for sushi. C25 was pretty insistent that the sushi would taste better after the babka. No one can verify this because while in a babka-induced state, they somehow found themselves at the beach? Too bad the rest of the group didn't have that idea....or did they?"
when "2"
puts "The way to a man's heart (or hospital) is a man's stomach. Yep. You guessed it. Marc opted for sushi. But he couldn't wait to head down to Crazy Poke - he stopped off at a street vendor on the corner of 3rd Ave and 25th...and instantly regretted his decision. The sushi vendor was seen hiding his cart behind a dumpster and running into a shady alley while Marc was doubled over in the street. Fortunately, a kind driver stopped to pick him up. The driver also confiscated his phone and added an Uber request to it before they drove off to the ER."
else
puts "Hey, thanks for helping out! Can you check on the other folks now?"
end
when "2"
puts "Dan couldn't resist. The text was tempting him too much. He headed back to Wynbase, but on his way, a crazy Uber driver threw a half-eaten apple out of the window and hit him in the head. Dan suffered an immediate concussion and starting acting like his favorite game character. The Uber driver came back and loaded him up in the car with 3 other injured people. They recognized Dan, but Dan only saw other game characters looking back at him...his health level was quickly declining!"
else
puts "Wow. Is this your version of helping out? Go do something else."
end
when "2"
puts "Tushani couldn't even hear the sound of the guys calling after her to slow down. She ran into Zak the Baker and they had her babka waiting. She was so happy to see the babka that she passed out from joy. Her head landed on a fresh challah loaf, but her left pinky finger got burned by hot coffee spilled by another patron that tripped over her. A random Uber driver (Mario - how does he know when these things happen?) picked her up before anyone could call 911. Tushani will be fine, but she's still mad that she left her babka on the floor."
else
puts "Ahem....Go. Away."
end
when "2"
puts "Man, can Clermondo go fast on that board, faster than a..... oh... well, not faster than the Harley that just took the wheels off his board. Clermondo's shoes went flying too. Not sure how that happened, but one of them hit Uber Mario's car, so Uber Mario picked him up (without stopping the car) and rushed him to the hospital to be treated for Harley Burn to his leg. He'll be okay. Tomorrow..."
else
puts "Are you seriously just sitting there eating a snack? Could you help a gang out please? This crew needs some assistance!"
end
when "4"
puts "Poor Shane and Joel. Lori is making them stop and look at some street art. Shane and Joel are worried about the neighborhood. Shane doesn't want to head down that creepy alley. Should he stay on the street or go with the group? Choose 1 for stay with the group or choose 2 for stand on the sidewalk looking lonely."
shane = gets.chomp
case shane
when "1"
puts "Shane decided to take care of his peeps and good thing he wasn't clowing around on the street! They found a secret society of street artists planning their next street takeover. Joel wanted to join them? Should he? Choose 1 for Joel staying with his friends or choose to for Joel leaving the coding life for a life filled with spray paint cans."
joel = gets.chomp
case joel
when "1"
puts "Although Joel thought he could help out his painting buddies, he figured that he could laugh it up with them later. He opted to move on through the mysterious alley. But where is Lori leading them? Choose 1 if she follows her instinct about being followed or choose 2 if she chooses to order a Lyft to escape."
lori = gets.chomp
case lori
when "1"
puts "Dude. Have you ever had that feeling that doom is just around the corner? That someone is following you? That a mysterious Uber car is hovering close by? Of course! Mario has been looking for us for hours! He wants to make sure that we meet up with the rest of C25 at the beach! We have to do our retro there! Maybe by the end of the week, Lori will be able to add pictures to this nonsensical story..."
when "2"
puts "Silly Goose! Of course she chooses a Lyft! Have you noticed how many Uber drivers have been on the road with injured people today? However, the Lyft driver doesnt' take them back to Wynbase. No. They end up at the beach....and with the rest of C25! What a crazy day. Maybe they will stick close to class tomorrow...."
else
puts "Why are you just sitting there? Go check on everyone or get yourself to the beach!"
end
when "2"
puts "Joel decided that he could use his newly acquired coding skills to help his new-found friends to plan their street art takover. What he didn't realize is that he needed to bring a gas mask to use the spray paint. He was last seen being swept away in a mystery Uber car while laughing uncontrollably from the spray paint. He may be the only one that finds it funny."
else
puts "Are you still there? Hop to it, buddy! We have friends to find!"
end
when "2"
puts "Oh Shane. Haven't you watched enough scary movies to know NOT to leave the group? Joel and Lori were actually safer than you. A clown from a nearby childrens' party was headed home after the festivities and scared you half to death. No worries. An Uber driver picked you up and took you to the ER where they diagnosed you with SCS - Severe Clown Syndrome. It's totally curable with a balloon animal making class."
else
puts "Excuse me.... what are you doing? Either get yourself to the beach or go round up everyone in the ER!"
end
end | true |
9eeae35ce6ba87f471e28100df56c475bf16925f | Ruby | erikbenton/AppAcademyFullStackOnline | /SQL/Object Relational Model/AA Questions/reply.rb | UTF-8 | 1,768 | 3.140625 | 3 | [] | no_license | require_relative 'questions_database.rb'
require_relative 'model_base'
require_relative 'user.rb'
require_relative 'question.rb'
class Reply < ModelBase
attr_accessor :id, :question_id, :parent_id, :author_id, :body
def self.find_by_question_id(question_id)
replies = QuestionsDBConnection.execute(<<-SQL, question_id)
SELECT
*
FROM
replies
WHERE
replies.question_id = ?;
SQL
raise "No replies with question_id: #{question_id}" if replies.nil? || replies.empty?
replies.map { |reply| Reply.new(reply.first) }
end
def self.find_by_author_id(author_id)
replies = QuestionsDBConnection.execute(<<-SQL, author_id)
SELECT
*
FROM
replies
WHERE
replies.author_id = ?;
SQL
raise "No replies with author_id: #{author_id}" if replies.nil? || replies.empty?
replies.map { |reply| Reply.new(reply) }
end
def initialize(options)
@id = options['id']
@question_id = options['question_id']
@parent_id = options['parent_id']
@author_id = options['author_id']
@body = options['body']
end
def author
User.find_by_id(@author_id)
end
def question
Question.find_by_id(@question_id)
end
def parent_reply
return nil if @parent_id.nil?
Reply.find_by_id(@parent_id)
end
def child_replies
children = QuestionsDBConnection.execute(<<-SQL, @id)
SELECT
*
FROM
replies
WHERE
replies.parent_id = ?;
SQL
children.map { |child| Reply.new(child) }
end
end
if __FILE__ == $PROGRAM_NAME
p Reply.all
erik_reply = Reply.find_by_id(1)
utas_reply = Reply.find_by_id(3)
puts
p erik_reply.child_replies.first.body
p utas_reply.parent_reply.body
end | true |
9c191c02e777b2b7a594ba4aa80f56f10fe38735 | Ruby | aleksarakic/scraperio | /lib/helper.rb | UTF-8 | 646 | 3.546875 | 4 | [] | no_license | require_relative 'translate/translation.rb'
module Helper
def temp_hash
{
-50..0 => ['Freezing', 'Time for winter clothes', 'Fire would be nice'],
1..15 => ['Meek', "Let's go south", "I will stay home"],
16..25 => ['Feels nice', 'Where are we?', 'Possible rain'],
26.. => ['Boils inside', 'Fan noise', 'Hot']
}
end
# @param temperature [String]; language direction [String](eg. en-de)
# returns [String]
def define_note(weather, languages)
note = temp_hash.select {|temp| temp === weather.to_i }.values.flatten.sample
translation = Translation.new(note, languages).translate
translation ? translation : note
end
end | true |
b8feb80b45e4054c8a8f0c31a8b5a7a18b4c333c | Ruby | qqdipps/hotel | /lib/room.rb | UTF-8 | 1,133 | 2.953125 | 3 | [] | no_license | require_relative "reservation"
module Hotel
class Room
attr_reader :id, :cost_per_night, :unavailable_list
def initialize(id:, cost_per_night:, unavailable_list: nil)
@id = id
@cost_per_night = cost_per_night
@unavailable_list ||= []
end
def available_for_date_range?(date_range:)
return date_range.all? do |date|
available?(date: date)
end
end
def available?(date:)
unavailable_list.each do |unavailable|
return false if unavailable.date_unavailable?(date: date)
end
return true
end
def reservation?(date:)
unavailable_list.each do |unavailable|
return true if unavailable.date_unavailable?(date: date) && unavailable.id[0] == "R"
end
return false
end
def has_unavailable_object?(unavailable_object:)
return true if unavailable_list.find { |unavail_obj| unavail_obj == unavailable_object }
return false
end
def remove_unavailable_object(unavailable_object:)
unavailable_list.reject! { |unavail_obj| unavail_obj == unavailable_object }
end
end
end
| true |
2798d96d3ca3fe167a28a44c6704c3b47d3d4a67 | Ruby | jetpackpony/travelbot | /lib/chat.rb | UTF-8 | 4,354 | 2.671875 | 3 | [] | no_license | require "json"
require "dotenv"
Dotenv.load
require "./lib/skyscanner_api/skyscanner_api"
module TravelBot
class Chat
WAIT_MESSAGE = { type: :none, label: "Hold on I'll fetch you flight info" }
FATAL_MESSAGE = { type: :none, label: "Oops, there was a problem with searching for your flight. A well trained group of ponies was notified of this and they are rushing to the rescue!" }
NUMBER_OF_OPTIONS_TO_DISPLAY = 5
def initialize(scenario, logger, &send_action)
@send_action = send_action
@scenario = scenario
@logger = logger
end
def start
respond JSON.generate @scenario.current
end
def push_message(msg)
@scenario.set_value = parse_value(@scenario, msg)
if @scenario.complete?
respond JSON.generate(WAIT_MESSAGE)
begin
flights = get_flights(*@scenario.request)
decorated = decorate_results(flights)
respond JSON.generate({
type: :results,
label: @scenario.results_label,
flights: decorated
})
rescue Exception => e
@logger.fatal e.message
respond JSON.generate FATAL_MESSAGE
end
else
respond JSON.generate(@scenario.current)
end
end
private
def respond(msg)
@send_action.call msg
end
def parse_value(scenario, msg)
case scenario.current[:type]
when :text
search_location(msg)
when :select
parse_option(scenario, msg)
when :date
parse_date(msg)
end
end
def search_location(msg)
request = SkyScannerAPI::LocationAutocompleteRequest.new
request.market = "US"
request.currency = "USD"
request.locale = "en-EN"
request.apiKey = ENV["SKYSCANNERAPI_KEY"]
request.query = msg
promise = request.send_request
value =
begin
promise.sync
rescue
raise "Couldn't query the country: #{promise.reason.body}"
end
JSON.parse(value.body)["Places"].map do |p|
{ id: p["PlaceId"], name: "#{p["PlaceName"]}, #{p["CountryName"]}" }
end
end
def parse_option(scenario, msg)
scenario.current[:options].find { |item| item[:id] == msg }
end
def parse_date(msg)
begin
Date.parse(msg)
rescue
"Couldn't parse the date"
end
end
def get_flights(from, to, date)
@logger.info "Searching for flights: #{from} to #{to} on #{date}"
request = SkyScannerAPI::FlightsLivePricingRequest.new
request.country = "US"
request.currency = "USD"
request.locale = "en-EN"
request.apiKey = ENV["SKYSCANNERAPI_KEY"]
request.origin = from[:id]
request.destination = to[:id]
request.departureDate = date.strftime("%Y-%m-%d")
request.adultsNumber = 1
request.locationSchema = "Sky"
@logger.info "Sending request: #{request.inspect}"
promise = request.send_request
value =
begin
promise.sync
rescue
raise "Couldn't query flights: #{[from, to, date].join(", ")}. #{promise.reason.body}"
end
JSON.parse(value.body)
end
def decorate_results(flights)
query = flights["Query"]
from = flights["Places"].find do |p|
p["Id"] == query["OriginPlace"].to_i
end
to = flights["Places"].find do |p|
p["Id"] == query["DestinationPlace"].to_i
end
date = query["OutboundDate"]
itineraries = flights["Itineraries"]
.slice(0, NUMBER_OF_OPTIONS_TO_DISPLAY)
.map do |iti|
res = {
price: iti["PricingOptions"][0]["Price"],
deeplink: iti["PricingOptions"][0]["DeeplinkUrl"],
}
leg = flights["Legs"].find { |leg| leg["Id"] == iti["OutboundLegId"] }
res[:departure] = leg["Departure"]
res[:arrival] = leg["Arrival"]
res[:duration] = leg["Duration"]
res[:stops] = leg["Stops"].map do |stop|
flights["Places"].find { |p| p["Id"] == stop }
end
res[:carriers] = leg["OperatingCarriers"].map do |carrier|
flights["Carriers"].find { |c| c["Id"] == carrier }
end
res
end
{ from: from, to: to, date: date, itineraries: itineraries }
end
end
end
| true |
dff2783723efc72d2edfe9b3da137ece636cf231 | Ruby | jrwest990/blog-app-jaydub | /calculator6.20.rb | UTF-8 | 477 | 3.953125 | 4 | [] | no_license | # @author john
# input should be 2 values and an expression
# output should be a number
def calculate(x, y, expression)
if (x == null || y = null)
puts "invalid input"
elsif (expression == '+')
return x + y
elsif (expression == "*")
return x * y
elsif (expression == "-")
return x - y
elsif (expression == "/")
return x / y
else
puts "invalid input given"
end
end
puts calculate(2, 2, '*')
| true |
7b6eb49fae41d0001b6822e2a6f5bec064d635fb | Ruby | lcowell/railsjam_ruby_examples | /part2_variables/01_assignments.rb | UTF-8 | 123 | 2.734375 | 3 | [] | no_license | #don't need to statically declare the type
#
# a = "hello"
# puts a.class
#
# a = 123
# puts a.class
#
# b = a
# puts b
| true |
36990db6af0035caa4977725a5c519a1e0f7b0fe | Ruby | Valcroca/DevPointCourse | /Exercises_form_Classes/pagination_example/lib/tasks/scrape.rake | UTF-8 | 792 | 2.75 | 3 | [] | no_license | require 'mechanize'
namespace :scrape do
desc "Scape dem rappers off dat webpage foshizzle"
task rappers: :environment do
agent = Mechanize.new
page = agent.get('http://www.buzzle.com/articles/rappers-list.html')
page.search('#article-body .leftnote').each do |rapper|
name = rapper.text.strip
rapper = Rapper.new(name: name)
rapper.og = true if og_rappers.include?(name)
rapper.auto_tune = true if cant_sing_without_help.include?(name)
rapper.save
end
puts "Rappers Scraped DOGGGGG, There are #{Rapper.count} Rappers in the hood now!"
end
def og_rappers
['Tupac', 'Biggie', 'The Notorious B.I.G', 'Eminem', 'M.C Hammer', 'Snoop Dogg', 'Dr. Dre', 'Warren G', 'Nelly']
end
def cant_sing_without_help
['Lil Wayne', 'Kanye West']
end
end
| true |
dbd91ce0e737572e6a5dfb954df24ac0092435a5 | Ruby | aromatt/pushfour | /lib/board.rb | UTF-8 | 20,266 | 3.078125 | 3 | [] | no_license | module PushFour
BLUE_CHAR = 'b'
RED_CHAR = 'r'
ROCK_CHAR = '#'
EMPTY_CHAR = '+'
class Board
attr_accessor :rows, :columns, :win_len, :cache
attr_reader :board_string # arbitrarily setting this would break cache
@@timing = Hash.new { |h,k| h[k] = 0 }
@@calls = Hash.new { |h,k| h[k] = 0 }
# Measures how many times we used cache vs not
@@caching = Hash.new { |h,k| h[k] = { cached: 0, non: 0 } }
@@perms_cache = {}
@@neighbors_cache = {}
def self.caching
@@caching
end
def self.timing
@@timing
end
def self.calls
@@calls
end
# TODO test!
def dup(string = nil)
Board.new(
@rows,
@columns,
@win_len,
string || @board_string.dup,
cache: @cache.dup
)
end
def initialize(rows = 8, columns = 8, win_len = 4, init_string = nil, opts = {})
@win_len = win_len
@rows = rows
@columns = columns
if init_string
init_string.gsub!(/[^rb#\+]|/, '')
if init_string.length != @rows * @columns
fail "init board string must contain #{@rows} * #{@columns} chars"
else
@board_string = init_string
end
else
@board_string ||= '+' * (rows * columns)
end
@cache = opts[:cache] || Hash.new { |h,k| h[k] = {} }
end
def flush_cache
#puts "flushing cache"
@cache[:path] = {}
#@cache[:find_move] = {}
#@cache[:try_move] = {}
end
def board_picture
string = @board_string.dup
(1..@rows).reverse_each do |row|
string.insert(row * @columns, "\n")
end
string
end
# player: 0 or 1
# side: :left, :right, :bottom, :top
# channel: integer
#
# return false if invalid move
#
def apply_move!(player, side, channel)
new_pos = try_move(side, channel)
if new_pos
flush_cache
@board_string[new_pos] = player
invalidate_move_cache(new_pos)
return new_pos
else
return false
end
end
# returns new board with move applied
def apply_move(player, side, channel)
new_pos = try_move(side, channel)
if new_pos
string = @board_string.dup
string[new_pos] = player
b = Board.new(
@rows,
@columns,
@win_len,
string
)
b.flush_cache
b.invalidate_move_cache(new_pos)
#b = self.dup(string)
return b
else
#puts "returning false from apply_move"
return false
end
end
def board_string_write(pos, player)
@board_string[pos] = player
invalidate_move_cache(pos)
end
# use this whenever
def invalidate_move_cache(pos)
col = column_of pos
row = row_of pos
[:right, :left].each do |side|
@cache[:try_move][[side, row]] = nil
end
[:top, :bottom].each do |side|
@cache[:try_move][[side, col]] = nil
end
row_offset = @columns * row
@columns.times do |i|
@cache[:find_move][i + row_offset] = nil
end
@rows.times do |i|
@cache[:find_move][col + i * @columns] = nil
end
end
# returns the resulting position of the move, or false if the move is impossible
def try_move(side, channel)
start_time = Time.now
@@calls[:try_move] += 1
dir_map = {
left: [channel * @columns, 1],
right: [(channel + 1) * @columns - 1, -1],
bottom: [channel + @columns * (rows - 1), -@columns],
top: [channel, @columns]
}
cached = @cache[:try_move][[side, channel]]
if cached
@@timing[:try_move] += Time.now - start_time
return cached
end
#puts "trying move (#{side}, #{channel})"
start, dir = dir_map[side]
if pos_occupied? start
@@timing[:try_move] += Time.now - start_time
@cache[:try_move][[side, channel]] = false
return false
end
cur_pos = start
next_pos = start + dir
loop do
break unless pos_on_board?(next_pos) && !pos_occupied?(next_pos)
dx, dy = xy_delta(cur_pos, next_pos)
break if dx.abs > 1 || dy.abs > 1
cur_pos = next_pos
next_pos += dir
end
@@timing[:try_move] += Time.now - start_time
@cache[:try_move][[side, channel]] = cur_pos
end
def winner
['r', 'b'].each do |player|
return player if won? player
end
nil
end
def won?(player)
poses_for(player).each do |pos|
return true if unocc_win_masks(pos, player).any? do |mask|
mask & get_bitmask(player) == mask
end
end
false
end
def done?
return true if winner
return true if random_move.nil?
false
end
def unocc_win_masks(pos, player)
raw = raw_win_masks(pos)
occ_symbols = ['#', 'r', 'b'] - [player]
occ_mask = occ_symbols.reduce(0) do |a, sym|
a | get_bitmask(sym)
end
raw.reject! { |w| w & occ_mask > 0 }
raw
end
# valid wins for a particular pos and player
def valid_wins(pos, player)
unocc = unocc_win_masks(pos, player).map { |w| mask_to_pos(w) }
unocc.reject do |win|
paths = win.reject { |pos| @board_string[pos] == player }.map { |pos| find_path(pos) }
paths.any?(&:nil?)
end
end
def valid_win_pathsets(pos, player)
debug = false
@@calls[:valid_win_pathsets] += 1
start_time = Time.now
unocc_wins = unocc_win_masks(pos, player).map { |w| mask_to_pos(w) }
pathsets = []
puts "valid_win_pathsets for #{[pos, player]}: unocc_wins: #{unocc_wins.inspect}" if debug
unocc_wins.each do |win|
pathset = nil
# don't need to find paths to positions that we already have
no_self = win.reject { |pos| @board_string[pos] == player }
puts " win: #{no_self}" if debug
# find a path to each position in the win
pathset = []
b_temp = self.dup # TODO optimize
poses_in_paths = []
valid = true
no_self.each do |pos|
path = b_temp.find_path(pos)
if path.nil?
valid = false
break
end
path.reject! { |pos| poses_in_paths.include? pos }
poses_in_paths += path
pathset << path
b_temp.board_string_write(pos, player)
end
next unless valid
# don't add wins with unreachable positions
next if pathset.nil? || pathset.any?(&:nil?)
# don't add superwins (new pathset is a superset of an existing one)
next if pathsets.any? do |existing|
pathset.flatten.sort[0..existing.count - 1] == existing.flatten.sort
end
puts " adding pathset #{pathset.inspect}" if debug
pathsets << pathset
end
@@timing[:valid_win_pathsets] += Time.now - start_time
pathsets
end
# provide a bit-string position
# returns array of masks representing wins containing <pos>
#
def raw_win_masks(pos)
wins = []
[
1, # horizontal
@columns, # vertical
@columns + 1, # /
@columns - 1 # \
].each do |period|
mask = 0
@win_len.times { |i| mask |= (1 << (i * period)) }
@win_len.times do |i|
new_mask = (mask << (pos - (@win_len - 1 - i) * period))
wins << new_mask
end
end
wins.reject do |w|
poses = mask_to_pos(w)
poses.count < @win_len || !contiguous?(poses)
end
end
# returns bit-string positions
def mask_to_pos(mask)
poses = []
check_mask = 1
(@rows * @columns).times do |i|
if mask & check_mask > 0
poses << i
end
check_mask <<= 1
end
poses
end
def pos_to_mask(pos)
pos.inject(0) { |a, p| a | (1 << p) }
end
def xy_to_pos(x, y)
pos = x + y * @columns
end
# returns [] of symbols from {:left, :right, :top, :bottom}
def touching_edges(pos)
edges = []
row = row_of(pos)
col = column_of(pos)
edges << :top if row == 0
edges << :bottom if row == @rows - 1
edges << :left if col == 0
edges << :right if col == @columns - 1
edges
end
# return a shortest path from some neighbor or edge to pos
# return nil if occupied or unreachable
#
# TODO 1) copy cache when creating copies of boards, because copies are used a lot
# 2) instead of flushing cache when board string changes, invalidate intelligently
#
def find_path(pos)
debug = false
puts "finding path to #{pos}" if debug
@@calls[:find_path] += 1
start_time = Time.now
start = 0
if pos_occupied? pos
return nil
end
if @cache[:path][pos]
@@caching[:find_path][:cached] += 1
@@timing[:find_path] += Time.now - start_time
return @cache[:path][pos].dup
end
@@caching[:find_path][:non] += 1
# next to any edges? then check those first
edges = touching_edges(pos)
edges.each do |edge|
puts "edge #{edge}" if debug
side = opposite_side(edge)
channel = get_channel(pos, side)
return_val = [pos] if try_move(side, channel) == pos
return return_val if return_val
end
puts " no edges worked" if debug
# Not next to an edge; find a path from the closest neighbor.
# Consider both occupied neighbors and unoccupied neighbors on edges
dist = 1
loop do
neighbors = neighbors_at_dist(pos, dist)
paths_to_try = []
free_neighbors = (neighbors - mask_to_pos(occupied_mask))
occ_neighbors = neighbors - free_neighbors
# Try building off of occupied positions
puts " in find path, occ_neighbors at dist #{dist} are #{occ_neighbors}" if debug
occ_neighbors.each do |n|
paths_to_try += raw_shortest_paths(n, pos).map { |p| p.shift; p }
end
# Try building off free neighbors on edges
puts " in find path, free_neighbors at dist #{dist} are #{free_neighbors}" if debug
free_neighbors.each do |n|
if touching_edges(n)
paths_to_try += raw_shortest_paths(n, pos)
end
end
# Try all the paths we could find at this dist
#b_temp = Board.new(@rows, @columns, @win_len, @board_string.dup)
paths_to_try.each do |path|
#b_temp.board_string = self.board_string.dup
if valid_path? path
@cache[:path][pos] = path.dup
@@timing[:find_path] += Time.now - start_time
return path.dup
end
end
# Could not find a path at this distance, try farther out
dist += 1
break if dist == [@rows, @columns].max
end # loop do (incr dist)
@@timing[:find_path] += Time.now - start_time
nil
end
def valid_path?(path, b_temp = nil)
debug = false
@@calls[:valid_path?] += 1
start_time = Time.now
b_temp ||= self.dup
valid = true
puts "valid path? #{path.inspect}" if debug
path.each do |step|
move = b_temp.find_move(step)
puts " move: #{move}" if debug
valid &&= move && b_temp.apply_move!('#', *move)
unless valid
puts " step #{step} invalid; breaking" if debug
break
end
end # each step
@@timing[:valid_path?] += Time.now - start_time
return valid
end
# Returns an array of paths (which are each an array of positions)
# Does not consider if paths consist entirely of valid moves, but
# does consider obstructions
def raw_shortest_paths(start, finish)
@@calls[:raw_shortest_paths] += 1
start_time = Time.now
x, y = xy_delta(start, finish)
x_d = (x >= 0 ? 1 : - 1)
y_d = (y >= 0 ? 1 : - 1)
paths = []
perms = []
if @@perms_cache[[x.abs, y.abs]]
perms = @@perms_cache[[x.abs, y.abs]]
else
perms = ([:x] * x.abs + [:y] * y.abs).permutation.to_a.uniq
@@perms_cache[[x.abs, y.abs]] = perms
end
perms.each do |perm|
puts "perm: #{perm}" if @debug
path = [start]
valid = true
perm.each do |dir|
next_pos = nil
if dir == :x
next_pos = apply_delta(path.last, x_d, 0)
else
next_pos = apply_delta(path.last, 0, y_d)
end
if pos_occupied? next_pos
puts "path is obstructed!" if @debug
valid = false
break
else
path << next_pos
end
end
puts "adding path: #{path.inspect}" if @debug
paths << path if valid
end
@@timing[:raw_shortest_paths] += Time.now - start_time
paths
end
# returns a list of positions (will be empty if none)
#
def neighbors_at_dist(pos, dist)
puts "neighbors of pos #{pos}, dist #{dist}" if @debug
start_time = Time.now
@@calls[:neighbors_at_dist] += 1
cached = @@neighbors_cache[[pos, dist]]
if cached
@@caching[:neighbors_at_dist][:cached] += 1
@@timing[:neighbors_at_dist] += Time.now - start_time
return cached
end
# TODO calculate these more efficiently?
neighbors = []
dist.times do |a|
b = dist - a
neighbors << apply_delta(pos, a, b)
neighbors << apply_delta(pos, -b, a)
neighbors << apply_delta(pos, -a, -b)
neighbors << apply_delta(pos, b, -a)
end
@@caching[:neighbors_at_dist][:non] += 1
@@timing[:neighbors_at_dist] += Time.now - start_time
res = neighbors.compact
@@neighbors_cache[[pos, dist]] = res
end
def picture_for_mask(mask)
string = ''
(@columns * @rows).times do |i|
occ = (mask & (1 << i)) > 0
string << (((mask & (1 << i)) > 0) ? '1' : '0')
string << "\n" if column_of(i) == @columns - 1
end
string
end
def row_of(pos)
pos / @columns
end
def column_of(pos)
pos % @columns
end
# positions is an array of bit-string positions
def contiguous?(positions)
c = true
(positions.count - 1).times do |i|
x, y = xy_delta(positions[i], positions[i + 1])
return false if x.abs > 1 || y.abs > 1
end
return true
end
def opposite_side(side)
{left: :right, right: :left, top: :bottom, bottom: :top}[side]
end
# a and b are contiguous positions.
# e.g., a = 0, b = 1, #=> :right
def direction_to(a, b)
fail "#{[a, b]} not contiguous!" unless contiguous?([a, b])
fail "#{a} == #{b}!" if a == b
if column_of(a) == column_of(b)
return a < b ? :bottom : :top
else
return a < b ? :right : :left
end
fail
end
def get_channel(pos, side)
channel = ([:left,:right].include? side) ? row_of(pos) : column_of(pos)
end
# Returns hash { move => pos, ... } where move is array [side, channel]
def all_moves
moves = {}
(0...@columns).each do |chan|
[:top, :bottom].each do |side|
tried = try_move(side, chan)
moves[[side, chan]] = tried if tried
end
end
(0...@rows).each do |chan|
[:left, :right].each do |side|
tried = try_move(side, chan)
moves[[side, chan]] = tried if tried
end
end
moves
end
# returns a move that will get a piece into pos.
# a move is a side (e.g. :left) and channel to get a piece into <pos>
#
def find_move(pos)
debug = false
puts " finding move to #{pos}" if debug
@@calls[:find_move] += 1
start_time = Time.now
if @cache[:find_move][pos]
@@timing[:find_move] += Time.now - start_time
@@caching[:find_move][:cached] += 1
return @cache[:find_move][pos].dup
end
@@caching[:find_move][:non] += 1
edges = touching_edges(pos)
# If a position is next to an edge, try that first
if edges.any?
edges.each do |e|
side = opposite_side(e)
channel = get_channel(pos, side)
if pos == try_move(side, channel)
move = [side, channel]
@cache[:find_move][pos] = move.dup
@@timing[:find_move] += Time.now - start_time
return move
end
end
end
neighbors = neighbors_at_dist(pos, 1)
if neighbors.any?
neighbors.each do |n|
# get direction from neighbor to pos, e.g. :left
side = direction_to(n, pos)
puts " in find_move, neighbor, pos: #{n}, #{pos}" if debug
# TODO remove
unless get_channel(pos, side) == get_channel(n, side)
fail "neighbor and pos not in same channel"
end
channel = get_channel(pos, side)
puts " in find_move, channel: #{channel}, side: #{side}" if debug
if pos == try_move(side, channel)
@@timing[:find_move] += Time.now - start_time
move = [side, channel]
@cache[:find_move][pos] = move.dup
return move
end
end
end
@@timing[:find_move] += Time.now - start_time
nil
end
# input: two bit-string positions
# output: x and y deltas
#
def xy_delta(first, second)
x = column_of(second) - column_of(first)
y = row_of(second) - row_of(first)
[x, y]
end
# Applies x and y to start and returns the resulting position
# return nil if off board
#
def apply_delta(pos, x, y)
puts "applying delta (#{x}, #{y}) to pos #{pos} which is at #{column_of pos}, #{row_of pos}" if @debug
return nil unless xy_on_board?(column_of(pos) + x, row_of(pos) + y)
result = pos + x + y * @columns
result
end
def pos_on_board?(pos)
if (pos >= 0) && (pos < @columns * @rows)
puts "#{pos} is on the board" if @debug
return true
else
puts "#{pos} is not on the board" if @debug
return false
end
end
def xy_on_board?(x, y)
puts "xy_on_board? #{x}, #{y}" if @debug
((0...@columns).cover? x) && ((0...@rows).cover? y)
end
def pos_occupied?(pos)
#puts "Determining if #{pos} is occupied. value of pos in board_string is #{@board_string[pos]}"
fail "pos #{pos} not on board" unless pos_on_board? pos
@board_string[pos] != '+'
end
def random_move
empty_pos.shuffle.each do |pos|
move = find_move pos
return move if move
end
nil
end
def num_empty
@board_string.count('+')
end
def empty_mask
get_bitmask(EMPTY_CHAR)
end
def occupied_mask
blue_mask | red_mask | rock_mask
end
def blue_mask
get_bitmask(BLUE_CHAR)
end
def red_mask
get_bitmask(RED_CHAR)
end
def rock_mask
get_bitmask(ROCK_CHAR)
end
def blue_pos
mask_to_pos(get_bitmask(BLUE_CHAR))
end
def red_pos
mask_to_pos(get_bitmask(RED_CHAR))
end
def rock_pos
mask_to_pos(get_bitmask(ROCK_CHAR))
end
def empty_pos
mask_to_pos(get_bitmask(EMPTY_CHAR))
end
def poses_for(player)
mask_to_pos(get_bitmask(player))
end
def move_mask(side, channel)
mask = 0
if [:left, :right].include? side
@columns.times do |i|
mask |= 1 << channel * @columns + i
end
else
@rows.times do |i|
mask |= 1 << channel + (@columns * i)
end
end
mask
end
def get_bitmask(char)
@board_string.chars.to_a.reverse.inject(0) do |a,c|
(a << 1) + (c == char ? 1: 0)
end
end
def add_rock!(pos)
@board_string[pos] = ROCK_CHAR
end
def add_random_rocks!(num_rocks = nil)
num_rocks ||= Math.sqrt(rows * columns).to_i / 2
num_rocks.times do
add_rock! Random.rand(@board_string.length)
end
end
end
end
| true |
3d8bad6094a8b20d5ff719fd51d80183c5c6326e | Ruby | jjyg/rbircd | /crypto.rb | UTF-8 | 3,732 | 3.453125 | 3 | [] | no_license | # pure ruby implementation of Diffie-Hellman and RC4
module Bignum_ops
# b**e % m
def mod_exp(b, e, m)
raise if e < 0
ret = 1
while e > 0
ret = (ret * b) % m if (e&1) == 1
e >>= 1
b = (b * b) % m
end
ret
end
SMALL_PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] unless defined? SMALL_PRIMES
# miller rabin probabilistic primality test
# t = 3 adequate for n > 1000, smaller are found in SMALL_PRIMES
def miller_rabin(n, t=3)
return false if n < 2
return true if SMALL_PRIMES.include?(n)
SMALL_PRIMES.each { |p|
return false if n % p == 0
}
s = 0
r = n-1
while r & 1 == 0
s += 1
r >>= 1
end
t.times { |i|
# 1st round uses 2, subsequent use rand(2..n-2)
a = (i == 0 ? 2 : crypt_rand(2, n-2))
y = mod_exp(a, r, n)
if y != 1 and y != n-1
(s-1).times {
break if y == n-1
y = mod_exp(y, 2, n)
return false if y == 1
}
return false if y != n-1
end
}
return true
end
# create a random number min <= n <= max from /dev/urandom
def crypt_rand(min, max)
return min if max <= min
nr = 0
File.open('/dev/urandom', 'r') { |fd|
while nr < max-min
nr = (nr << 8) | fd.read(1).unpack('C')[0]
end
}
min + (nr % (max-min+1))
end
end
class DH
include Bignum_ops
attr_accessor :p, :g, :x, :e
# p = prime, g = generator
def initialize(p, g)
@p = p
@g = g
generate
end
# create a random secret & public nr
def generate
@x = crypt_rand(1, @p-2)
@e = mod_exp(@g, @x, @p)
end
# compute the shared secret given the public key
def secret(f)
mod_exp(f, @x, @p)
end
# check that p is a strong prime, and that g's order > 2
def self.validate(p, g)
raise 'DH: p not prime' if not miller_rabin(p)
raise 'DH: p not strong prime' if not miller_rabin((p-1)/2)
raise 'DH: g bad generator' if mod_exp(g, 2, p) == 1
end
def self.test
DH.validate(107, 2)
alice = DH.new(107, 2)
bob = DH.new(107, 2)
raise if alice.secret(bob.e) != bob.secret(alice.e)
end
end
# from https://github.com/juggler/ruby-rc4/blob/master/lib/rc4.rb
class RC4
def initialize(key)
@q1, @q2 = 0, 0
@key = key.unpack('C*')
@key += @key while @key.length < 256
@key = @key[0, 256]
@s = (0..255).to_a
j = 0
256.times { |i|
j = (j + @s[i] + @key[i]) & 0xff
@s[i], @s[j] = @s[j], @s[i]
}
end
def encrypt(text)
return nil if not text
text.unpack('C*').map { |c| c ^ round }.pack('C*')
end
alias decrypt encrypt
def round
@q1 = (@q1 + 1) & 0xff
@q2 = (@q2 + @s[@q1]) & 0xff
@s[@q1], @s[@q2] = @s[@q2], @s[@q1]
@s[(@s[@q1] + @s[@q2]) & 0xff]
end
end
class NullCipher
def encrypt(l)
l
end
def decrypt(l)
l
end
end
class IoWrap
attr_accessor :fd
def to_io
@fd.to_io
end
def sync
@fd.sync
end
def sync=(s)
@fd.sync = s
end
end
class CryptoIo < IoWrap
attr_accessor :rd, :wr
# usage: cryptsocket = CryptoIo.new(socket, RC4.new("foobar"), RC4.new("foobar"))
# can be chained, and passed to IO.select
def initialize(fd, cryptrd, cryptwr)
@fd = fd
@rd = cryptrd || NullCipher.new
@wr = cryptwr || NullCipher.new
end
def read(len)
@rd.decrypt(@fd.read(len))
end
def write(str)
@fd.write(@wr.encrypt(str))
end
end
require 'zlib'
class ZipIo < IoWrap
attr_accessor :ziprd, :zipwr
def initialize(fd, ziprd, zipwr)
@fd = fd
@ziprd = ziprd
@zipwr = zipwr
@r = Zlib::Inflate.new
@w = Zlib::Deflate.new
@bufrd = ''
end
def read(len)
if @ziprd
ret = ''
if not @bufrd.empty?
ret << @bufrd[0, len]
@bufrd[0, len] = ''
len -= ret.length
end
if len > 0
# FAIL
@bufrd += @r.inflate(@fd.read(len))
end
else
@fd.read(len)
end
end
def pending
@bufrd.length
end
def write(str)
end
end
| true |
6ac8e05a0ff64cdba3baa7f4662eb887f9fa09c7 | Ruby | vinhnglx/artistspy | /app/services/searchable_service.rb | UTF-8 | 919 | 2.609375 | 3 | [] | no_license | class SearchableService
include HTTParty
base_uri ENV['api_uri'] || 'api.spotify.com'
DEFAULT_ENDPOINT = ENV['artist_endpoint']
DEFAULT_LIMIT = ENV['api_limit']
# Public: Create constructor
#
# Parameters
#
# searches - A hash contains query and limit
#
# Example
#
# SearchableService.new(limit: 40, query: 'tailor swift')
#
# Returns nothing
def initialize(searches = {})
raise ArgumentError, "Missing query" unless searches[:query]
query = searches[:query]
limit = searches[:limit] || DEFAULT_LIMIT
@options = { query: { limit: limit, query: query } }
@endpoint = searches[:endpoint] || DEFAULT_ENDPOINT
end
# Public: Connect to Spotify Server
#
# Example
#
# searchable = SearchableService.new
# searchable.connect
#
# Returns an object with response from Spotify
def connect
self.class.get(@endpoint, @options)
end
end
| true |
6a65f34206b8a67433da7e7696fb3756aae46601 | Ruby | EvilScott/bard_bot | /lib/bard_bot/dictionary.rb | UTF-8 | 846 | 3.1875 | 3 | [
"MIT"
] | permissive | module BardBot
class Dictionary
def initialize(config)
@prefix = config.prefix.to_i
@max_length = config.max_length
@file_path = File.join(config.character_dir, "#{config.character}.txt")
@dictionary = Hash.new { |h, k| h[k] = [] }
load_corpus!
end
def load_corpus!
corpus = File.read(@file_path).split
until corpus.length < (@prefix + 1)
key = corpus.first(@prefix).join
@dictionary[key] << corpus[@prefix]
corpus.shift
end
end
def generate_sentence
tuple = @dictionary.keys.sample
sentence = tuple
@max_length.times do
sentence += ' ' + @dictionary[tuple].sample
break if %w( ? ! . ).include?(sentence[-1])
tuple = sentence.split.last(2).join
end
sentence.downcase.capitalize
end
end
end
| true |
775a86cf6b2903587f7b58033ea08f7e706da4a6 | Ruby | Denizdius/Ruby_calisma | /ruby/rb_somethings/ornek_3.rb | UTF-8 | 232 | 3.515625 | 4 | [] | no_license |
puts"Merhaba,kameranı çok beğendim adınız nedir ? "
isim=gets
puts "Ben biraz takıntulyım soyadınız nedir ?"
soyad=gets
puts ("OOOO hemşerim naber ya " + isim.chomp +" " soyad.chomp + "bende" + soyad.chomp + "undanım")
| true |
25f379b4085a5567114f651fecfb68d13032e519 | Ruby | trendwithin/effective-couscous | /app/workflows/create_new_symbols.rb | UTF-8 | 716 | 2.6875 | 3 | [] | no_license | class CreateNewSymbols
attr_reader :params, :errors
def initialize params
@params = params
@errors = []
end
def valid_data_format?
true if params.match(/^[[:alpha:][:blank:]]+$/)
end
def params_to_array
params.split(/\W+/)
end
def split_on_return
params.split(/\r?\n/)
end
def run
values = self.split_on_return
values.each do |process|
ticker, company_name = process.split(/\W+/)
begin
StockSymbol.create(ticker: ticker, company_name: company_name)
rescue ActiveRecord::RecordNotUnique => not_unique
@errors << ticker
rescue PG::UniqueViolation => pgu
@errors << ticker
end
end
@errors
end
end
| true |
eae8e75fdac5f94b2c01258a7562e8531d89571e | Ruby | igorsimdyanov/gb | /part3/lesson6/sort.rb | UTF-8 | 198 | 3.0625 | 3 | [] | no_license | p [6, 2, 8, 3, 9, 11, 1].sort
arr = %w[second third fst]
p arr.sort { |a, b| a.size <=> b.size }
p arr.sort_by(&:size)
# лунь
# нуль
# 'лунь'.split('').sort == 'нуль'.split('').sort | true |
03620de8dbb070b18a94670a1fa879ed570e282e | Ruby | eluke66/checkers | /ruby/Driver.rb | UTF-8 | 1,027 | 3.515625 | 4 | [] | no_license | require "benchmark"
require "Game"
require "ConsolePlayer"
class RandomOptionPlayer
def initialize(name)
@name = name
end
def select_move(moves, board)
return moves.sample
end
def to_s
return @name
end
end
def profile(numRuns)
totalTime = 0
player1 = RandomOptionPlayer.new("player 1")
player2 = RandomOptionPlayer.new("player 2")
winsPerPlayer = {player1 => 0, player2 => 0}
(1..numRuns).each do |run|
game = Game.new(player1, player2)
totalTime += Benchmark.realtime { winsPerPlayer[game.play()] += 1 }
end
msPerGame = (totalTime*1000) / numRuns
puts "Total time is %0.2f sec to play %d games, or %0.2f ms/game" % [totalTime, numRuns, msPerGame]
puts "Wins per player: "
winsPerPlayer.each do |p,v|
puts p.to_s + ": " + v.to_s
end
end
def playInteractive
Game.new(ConsolePlayer.new("Player 1"), ConsolePlayer.new("Player 2"), eventHandler: ConsoleEventHandler.new).play
end
if ARGV.length > 0 then
profile(ARGV[0].to_i)
else
playInteractive # TODO
end
| true |
0f4d84850b55f9967146e041585f4e7da3a2ad04 | Ruby | Bitmap0079/CycleSpotter | /app/models/post.rb | UTF-8 | 594 | 2.71875 | 3 | [] | no_license | class Post < ApplicationRecord
validates :name, presence: true
validates :name, length: { maximum: 50 }
# validates :validate_name_not_include_comma
belongs_to :user
scope :recent, -> { order(created_at: :desc)}
private
#コンマを含めないようにするバリデーション
def validate_name_not_include_comma
errors.add(:name, 'にコンマを含めることはできません') if name&.include?(',')
# &.を使っているのはnameがnilのときに例外が発生しないように(nilのときに検証が通るように)
end
end
| true |
3b54faaf0efc7f1c00d2347bdf06b3d5dedd76da | Ruby | brewchetta/alphabetize-in-esperanto-nyc-web-100818 | /lib/alphabetize.rb | UTF-8 | 338 | 3.296875 | 3 | [] | no_license |
ESPERANTO = ["a","b","c","ĉ","d","e","f","g","ĝ","h","ĥ","i","j","ĵ","k","l","m","n","o","p","r","s","ŝ","t",
"u","ŭ","v","z"]
def alphabetize(phrases)
phrases.sort_by!{ |a| ESPERANTO.index(a.split("").first) }
puts phrases
phrases
end
# I got it to work just fine for me so I went ahead and submitted without
# a spec :) | true |
c9fa5817a1249aa691a18ac80864e2f5bf277732 | Ruby | lowellmower/tic_tac_toe | /lib/models/human_player.rb | UTF-8 | 404 | 2.984375 | 3 | [] | no_license | require_relative 'player'
class HumanPlayer < Player
attr_accessor :name, :piece
def initialize(args = {})
args = defaults.merge(args)
end
def make_move(move, board)
if valid_move?(move) && move_available?(move, board)
place_piece(move, board) and return true
end
board.reject_piece
end
private
def defaults
{name: "Human Player", piece: "X"}
end
end | true |
72272ba5a09dfab56e307dd9ac766c0101687637 | Ruby | geoquant/oroshi | /scripts/bin/mobi2epub | UTF-8 | 914 | 3 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'shellwords'
# Converts a .mobi file to a .epub one
class Mobi2Epub
def initialize(*args)
@mobi = File.expand_path(args[0])
@ext = File.extname(@mobi)
@basename = File.basename(@mobi, @ext)
@epub = File.expand_path("#{@basename}.epub")
@cover = File.expand_path("#{@basename}.jpg")
end
def valid?
@ext == '.mobi'
end
def cover?
File.exist?(@cover)
end
def run
unless valid?
puts 'Input is not a .mobi file'
exit
end
options = [
@mobi.shellescape,
@epub.shellescape
]
# Adding cover if one is found
if cover?
options << "--cover #{@cover.shellescape}"
options << '--preserve-cover-aspect-ratio'
end
# Converting to mobi
`ebook-convert #{options.join(' ')}`
# Updating metadata
`ebook-metadata-update #{@mobi.shellescape}`
end
end
Mobi2Epub.new(*ARGV).run
| true |
8fde7488858d5376115e075f8212d338557c6bcd | Ruby | smalruby/smalruby-installer-for-windows | /Ruby216_32/lib/ruby/gems/2.1.0/gems/smalruby-0.1.11-x86-mingw32/samples/hardware_neo_pixel2.rb | UTF-8 | 881 | 2.71875 | 3 | [
"MIT"
] | permissive | # -*- coding: utf-8 -*-
DESCRIPTION = <<EOS
マイコン内蔵RGB LEDを制御します
EOS
# マイコン内蔵RGB LEDデジタルの5番ピンに、
# スイッチをデジタルの3・4番ピンに接続してください。
require 'smalruby'
init_hardware
stage1 = Stage.new(color: 'white')
stage1.on(:start) do
color_codes = Color::NAME_TO_CODE.keys
index = 0
loop do
fill(color: 'white')
color = color_codes[index]
draw_font(string: "#{DESCRIPTION}#{index}:#{color}", color: 'black')
neo_pixel("D5").set(color: color)
until button("D3").pressed? || button("D4").pressed?
await
end
if button("D3").pressed?
index -= 1
if index < 0
index = 0
end
end
if button("D4").pressed?
index += 1
if index >= color_codes.length
index = color_codes.length - 1
end
end
end
end
| true |
0fdd1831ea92803ece275423dd06358fcf4b34d5 | Ruby | PianoFF/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-london-web-102819 | /nyc_pigeon_organizer.rb | UTF-8 | 358 | 2.90625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def nyc_pigeon_organizer(data)
nyc_pigeon = Hash.new
names = data[:gender].values
names.map{|i| i.map {|name|
nyc_pigeon[name]= {:color => [], :gender => [], :lives => []
}
}
}
nyc_pigeon
data.select{|key, value|
value.select{|key_2, value_2|
value_2.map{|name|
nyc_pigeon[name][key]<<key_2.to_s
}
}
}
nyc_pigeon
end
| true |
cf9366346260729471b6d6588418de6f69e4eeb3 | Ruby | t9md/vim-transform | /misc/ruby_handler/lib/transformer/go.rb | UTF-8 | 1,304 | 2.8125 | 3 | [] | no_license | module Transformer
module Go
class Import
def self.run(input)
r = []
repos = {
gh: "github.com",
cg: "code.google.com",
gl: "golang.org",
}
input.each_line do |l|
l.strip.split.map do |e|
repos.each do |k, v|
k = k.to_s
if e =~ /^#{k}\//
e = e.sub k, v
break
end
end
r << e
end
end
return r.map { |e| %!\t"#{e}"! }.join("\n").chomp
end
end
class ConstStringfy
class << self
def parse(s)
type = ""
enums = []
s.split("\n").each do |e|
next if e =~ /\(|\)/
n = e.split
type << n[1] if n.size > 1
enums << n.first
end
[type, enums]
end
def run(s)
type, enums = *parse(s)
v = type[0].downcase
out = ""
enums.each do |e|
out << "\tcase #{e}:\n"
out << "\t\treturn \"#{e}\"\n"
end
return <<-EOS
#{s}
func (#{v} #{type}) String() string {
\tswitch #{v} {
#{out.chomp}
\tdefault:
\t\treturn "Unknown"
\t}
}
EOS
end
end
end
end
end
| true |
0fa50b8e9de495016c7a917c3ef5f24e45494696 | Ruby | Dwire/keys-of-hash-prework | /lib/keys_of_hash.rb | UTF-8 | 151 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Hash
def keys_of(*arguments)
key_arr = []
self.each {|key, value| key_arr << key if arguments.include?(value)}
key_arr
end
end
| true |
f6ac5cbb08fb1eb6b3b78f19ce5e2781ec76b7f9 | Ruby | thomasfedb/warp | /lib/warp/controller_matchers/assign_matcher.rb | UTF-8 | 4,745 | 2.671875 | 3 | [
"MIT"
] | permissive | require "warp/matcher"
module Warp
module ControllerMatchers
class AssignMatcherBuilder
attr_reader :assign_key, :controller
def initialize(assign_key, controller)
@assign_key = assign_key
@controller = controller
end
def with(value)
AssignWithMatcher.new(@controller, @assign_key, value)
end
def with_a(klass)
AssignWithAMatcher.new(@controller, @assign_key, klass)
end
def with_a_new(klass)
AssignWithANewMatcher.new(@controller, @assign_key, klass)
end
def method_missing(method, *args)
matcher.send(method, *args)
end
private
def matcher
@matcher ||= AssignMatcher.new(@controller, @assign_key)
end
end
def assign(assign_key)
AssignMatcherBuilder.new(controller, assign_key)
end
class AssignMatcher < Warp::Matcher
attr_reader :assign_key, :controller
def initialize(assign_key, controller)
@assign_key = assign_key
@controller = controller
end
def matches?(actual)
@controller = actual if actual.is_a?(ActionController::Metal)
check_assign
end
def description
"assign @#{assign_key}"
end
def failure_message
"expected @#{assign_key} to be assigned"
end
def failure_message_when_negated
"expected @#{assign_key} to not be assigned"
end
private
def check_assign
values_match?(false, assign_value.nil?)
end
def assign_value
controller.view_assigns[assign_key.to_s]
end
def has_ancestor?(expected_class, actual)
actual.class.ancestors.any? {|ancestor| values_match?(expected_class, ancestor) }
end
end
class AssignWithMatcher < AssignMatcher
attr_reader :assign_with
def initialize(controller, assign_key, assign_with)
super(controller, assign_key)
@assign_with = assign_with
end
def description
"assign @#{assign_key} with #{description_of(assign_with)}"
end
def failure_message
if assign_value.nil?
"expected @#{assign_key} to be assigned with #{description_of(assign_with)} but was not assigned"
else
"expected @#{assign_key} to be assigned with #{description_of(assign_with)} but was assigned with #{assign_value.inspect}"
end
end
def failure_message_when_negated
"expected @#{assign_key} to not be assigned with #{description_of(assign_with)}"
end
private
def check_assign
values_match?(assign_with, assign_value)
end
end
class AssignWithAMatcher < AssignMatcher
attr_reader :assign_with_a
def initialize(controller, assign_key, assign_with_a)
super(controller, assign_key)
@assign_with_a = assign_with_a
end
def description
"assign @#{assign_key} with an instance of #{assign_with_a.name}"
end
def failure_message
if assign_value.nil?
"expected @#{assign_key} to be assigned with an instance of #{assign_with_a.name} but was not assigned"
else
"expected @#{assign_key} to be assigned with an instance of #{assign_with_a.name} but was assigned with an instance of #{assign_value.class.name}"
end
end
def failure_message_when_negated
"expected @#{assign_key} to not be assigned with an instance of #{assign_with_a.name}"
end
private
def check_assign
has_ancestor?(assign_with_a, assign_value)
end
end
class AssignWithANewMatcher < AssignMatcher
attr_reader :assign_with_a_new
def initialize(controller, assign_key, assign_with_a_new)
super(controller, assign_key)
@assign_with_a_new = assign_with_a_new
end
def description
"assign @#{assign_key} with a new instance of #{assign_with_a_new.name}"
end
def failure_message
if assign_value.nil?
"expected @#{assign_key} to be assigned with a new instance of #{assign_with_a_new.name} but was not assigned"
else
"expected @#{assign_key} to be assigned with a new instance of #{assign_with_a_new.name} but was assigned with a #{assign_value.try(:persisted?) ? "persisted" : "new"} instance of #{assign_value.class.name}"
end
end
def failure_message_when_negated
"expected @#{assign_key} to not be assigned with a new instance of #{assign_with_a_new.name}"
end
private
def check_assign
has_ancestor?(assign_with_a_new, assign_value) && values_match?(false, assign_value.try(:persisted?))
end
end
end
end
| true |
b9f403b307df4a642a6aaa75a5a9ea980b317b08 | Ruby | bottles9/sharetribe-clone | /spec/services/payment_math_spec.rb | UTF-8 | 751 | 2.703125 | 3 | [
"CC-BY-2.5",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | describe PaymentMath do
describe "#service_fee" do
it "calculates service fee from price and commission percentage" do
PaymentMath.service_fee(10000, 12).should == 1200
end
it "ceils the service fee" do
PaymentMath.service_fee(500, 12).should == 100
PaymentMath.service_fee(2900, 10).should == 300
end
end
describe "#ceil_cents" do
it "ceils to whole num" do
PaymentMath.ceil_cents(100).should == 100
PaymentMath.ceil_cents(110).should == 200
end
end
describe ":SellerCommission" do
it "calculates sellers gets" do
PaymentMath::SellerCommission.seller_gets(10000, 12).should == 8800
PaymentMath::SellerCommission.seller_gets(2900, 10).should == 2600
end
end
end | true |
d6a1e298633818eef5bda8fbd95912e266ff9123 | Ruby | TenBesta/exported_scripts | /Classes Setup.rb | UTF-8 | 4,707 | 2.53125 | 3 | [] | no_license | # encoding: utf8
# [127] 62258286: Classes Setup
#==============================================================================
# ** Game_Temp
#------------------------------------------------------------------------------
# This class handles temporary data that is not included with save data.
# The instance of this class is referenced by $game_temp.
#==============================================================================
class Game_Temp
# --------------------------------------------------------------------------
# New public accessors
# --------------------------------------------------------------------------
attr_accessor :actors_fiber # Store actor Fibers thread
attr_accessor :enemies_fiber # Store enemy Fibers thread
attr_accessor :battler_targets # Store current targets
attr_accessor :anim_top # Store anim top flag
attr_accessor :global_freeze # Global freeze flag (not tested)
attr_accessor :anim_follow # Store anim follow flag
attr_accessor :slowmotion_frame # Total frame for slowmotion
attr_accessor :slowmotion_rate # Framerate for slowmotion
attr_accessor :one_animation_id # One Animation ID Display
attr_accessor :one_animation_flip # One Animation flip flag
attr_accessor :one_animation_flag # One Animation assign flag
attr_accessor :tsbs_event # TSBS common event play
# --------------------------------------------------------------------------
# Alias method : Initialize
# --------------------------------------------------------------------------
alias tsbs_init initialize
def initialize
tsbs_init
clear_tsbs
end
# --------------------------------------------------------------------------
# New method : clear TSBS infos
# --------------------------------------------------------------------------
def clear_tsbs
@actors_fiber = {}
@enemies_fiber = {}
@battler_targets = []
@anim_top = 0
@global_freeze = false
@anim_follow = false
@slowmotion_frame = 0
@slowmotion_rate = 2
@one_animation_id = 0
@one_animation_flip = false
@one_animation_flag = false
@tsbs_event = 0
end
end
#==============================================================================
# ** Game_Action
#------------------------------------------------------------------------------
# This class handles battle actions. This class is used within the
# Game_Battler class.
#==============================================================================
class Game_Action
# --------------------------------------------------------------------------
# Alias method : targets for opponents
# --------------------------------------------------------------------------
alias tsbs_trg_for_opp targets_for_opponents
def targets_for_opponents
return abs_target if item.abs_target?
return tsbs_trg_for_opp
end
# --------------------------------------------------------------------------
# New method : Absolute target
# --------------------------------------------------------------------------
def abs_target
opponents_unit.abs_target(item.number_of_targets)
end
end
#==============================================================================
# ** Game_ActionResult
#------------------------------------------------------------------------------
# This class handles the results of battle actions. It is used internally for
# the Game_Battler class.
#==============================================================================
class Game_ActionResult
attr_accessor :reflected # Reflected flag. Purposely used for :if command
# --------------------------------------------------------------------------
# Alias method : Clear
# --------------------------------------------------------------------------
alias tsbs_clear clear
def clear
tsbs_clear
@reflected = false
end
end
#==============================================================================
# ** Game_Unit
#------------------------------------------------------------------------------
# This class handles units. It's used as a superclass of the Game_Party and
# and Game_Troop classes.
#==============================================================================
class Game_Unit
# --------------------------------------------------------------------------
# New method : Make absolute target candidate
# --------------------------------------------------------------------------
def abs_target(number)
candidate = alive_members.shuffle
ary = []
[number,candidate.size].min.times do
ary.push(candidate.shift) if !candidate[0].nil?
end
return ary
end
end
| true |
f27afe3529f73b2acd05203e2cc3b4168242e227 | Ruby | shaun-yb/leetcode | /114_flatten_binart_tree_to_linked_list.rb | UTF-8 | 843 | 3.796875 | 4 | [] | no_license | # https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Void} Do not return anything, modify root in-place instead.
def flatten(root)
return [] if root.nil?
stack = []
build_stack(root, stack)
stack.each_cons(2) do |node1, node2|
node1.left = nil
node1.right = node2
end
last_node = stack.last
last_node.left = nil
last_node.right = nil
stack.first
end
def build_stack(root, stack)
if root.nil?
return
else
stack << root
build_stack(root.left, stack)
build_stack(root.right, stack)
end
end
| true |
fafbc56c896088b7950572016e215bb190006a2f | Ruby | aliwoodman/ruby-test | /calc9.rb | UTF-8 | 315 | 3.640625 | 4 | [] | no_license | puts "Generate leap years list"
puts "Start year?"
start_year = gets.to_i
puts "End year?"
end_year = gets.to_i
while start_year <= end_year
if start_year % 400 == 0
puts start_year
elsif start_year % 100 != 0 and start_year % 4 == 0
puts start_year
else
end
start_year = start_year + 1
end
puts "End"
| true |
d7efd0a304366f3773cfd7829604a3086fe09e13 | Ruby | fiosman/App-Academy | /ruby_curriculum/19_simon/lib/simon.rb | UTF-8 | 1,139 | 3.5625 | 4 | [] | no_license | class Simon
COLORS = %w(red blue green yellow)
attr_accessor :sequence_length, :game_over, :seq
def initialize
@sequence_length = 1
@game_over = false
@seq = []
end
def play
until game_over
self.take_turn
system('clear')
end
self.game_over_message
self.reset_game
end
def take_turn
self.show_sequence
sleep(1)
system('clear')
self.require_sequence
unless @game_over
self.round_success_message
@sequence_length += 1
end
end
def show_sequence
p 'Watch the sequence closely!'
p self.add_random_color
end
def require_sequence
p "Type in each color then press Enter"
@seq.each do |color|
user_guess = gets.chomp
@game_over = true if user_guess != color
end
end
def add_random_color
@seq << COLORS.sample
end
def round_success_message
p "Nice work!"
end
def game_over_message
p "Oops, you lose! Try again."
end
def reset_game
@sequence_length = 1
@game_over = false
@seq = []
end
end
if __FILE__ == $PROGRAM_NAME
game = Simon.new
game.play
end
| true |
e83709fae560abdf0c5254c888376ab00f622fa6 | Ruby | eturino/etudev_rails_app | /spec/support/mini/shared/eql.rb | UTF-8 | 763 | 2.71875 | 3 | [] | no_license |
shared_examples_for "(eql? == hash) no" do
it "eql? false" do
expect(subject.eql?(other)).to be_false
end
it "== false" do
expect(subject == other).to be_false
end
it "hash not the same" do
expect(subject.hash).not_to eq other.hash
end
it "if uniq is called in an array with the 2, both remain" do
expect([subject, other].uniq.size).to eq 2
end
end
shared_examples_for "(eql? == hash) yes" do
it "eql? false" do
expect(subject.eql?(other)).to be_true
end
it "== false" do
expect(subject == other).to be_true
end
it "hash not the same" do
expect(subject.hash).to eq other.hash
end
it "if uniq is called in an array with the 2, only one remains" do
expect([subject, other].uniq.size).to eq 1
end
end | true |
91ae0d56b6048f82f1f354ea2b454c07f78359dd | Ruby | CrystalPea/student-directory | /source_code_reader.rb | UTF-8 | 104 | 2.828125 | 3 | [] | no_license | def read_code(filename = $0)
code_string = (File.read filename).to_s
puts code_string
end
read_code | true |
f98429f0e243dc94d1006f43bc3ba7ade6075ec8 | Ruby | addislw/appA-Intro | /advanced_problems.rb | UTF-8 | 13,784 | 4.40625 | 4 | [] | no_license | # Write a method map_by_name that takes in an array of hashes and returns a new array containing the names of each hash
def map_by_name(hash_array)
hash_array.map { |hash| hash["name"] }
end
pets = [
{"type"=>"dog", "name"=>"Rolo"},
{"type"=>"cat", "name"=>"Sunny"},
{"type"=>"rat", "name"=>"Saki"},
{"type"=>"dog", "name"=>"Finn"},
{"type"=>"cat", "name"=>"Buffy"}
]
print map_by_name(pets) #=> ["Rolo", "Sunny", "Saki", "Finn", "Buffy"]
puts
countries = [
{"name"=>"Japan", "continent"=>"Asia"},
{"name"=>"Hungary", "continent"=>"Europe"},
{"name"=>"Kenya", "continent"=>"Africa"},
]
print map_by_name(countries) #=> ["Japan", "Hungary", "Kenya"]
puts
# Write a method map_by_key that takes in an array of hashes and a key string. The method should returns a new array containing the values from each hash for the given key
def map_by_key(hash_array, key)
hash_array.map { |hash| hash[key] }
end
locations = [
{"city"=>"New York City", "state"=>"New York", "coast"=>"East"},
{"city"=>"San Francisco", "state"=>"California", "coast"=>"West"},
{"city"=>"Portland", "state"=>"Oregon", "coast"=>"West"},
]
print map_by_key(locations, "state") #=> ["New York", "California", "Oregon"]
puts
print map_by_key(locations, "city") #=> ["New York City", "San Francisco", "Portland"]
puts
# Write a method yell_sentence that takes in a sentence string and returns a new sentence where every word is yelled. See the examples. Use map to solve this
def yell_sentence(string)
string.split.map { |word| "#{word.upcase}!" }
.join(' ')
end
puts yell_sentence("I have a bad feeling about this") #=> "I! HAVE! A! BAD! FEELING! ABOUT! THIS!"
# Write a method whisper_words that takes in an array of words and returns a new array containing a whispered version of each word. See the examples. Solve this using map
def whisper_words(word_array)
word_array.map { |word| "#{word.downcase}..." }
end
print whisper_words(["KEEP", "The", "NOISE", "down"]) # => ["keep...", "the...", "noise...", "down..."]
puts
# Write a method o_words that takes in a sentence string and returns an array of the words that contain an "o". Use select in your solution
def o_words(string)
string.split.select { |word| word.include?('o') }
end
print o_words("How did you do that?") #=> ["How", "you", "do"]
puts
# Write a method last_index that takes in a string and a character. The method should return the last index where the character can be found in the string
def last_index(string, char)
i = string.length - 1
while i >= 0
cur_char = string[i]
return i if char == cur_char
i -= 1
end
end
puts last_index("abca", "a") #=> 3
puts last_index("mississipi", "i") #=> 9
puts last_index("octagon", "o") #=> 5
puts last_index("programming", "m")#=> 7
# Write a method most_vowels that takes in a sentence string and returns the word of the sentence that contains the most vowels
def most_vowels(string)
words_array = string.split
vowels = 'aeiou'
hash = {}
words_array.each do |word|
hash[word] = count_vowels(word)
end
# hash.values.sort
sorted = hash.sort_by { |k,v| v}
sorted[-1][0]
end
def count_vowels(word)
word = word.split('')
vowels = 'aeiou'
word.count { |char| vowels.include?(char) }
end
print most_vowels("what a wonderful life") #=> "wonderful"
puts
# Write a method prime? that takes in a number and returns a boolean, indicating whether the number is prime. A prime number is only divisible by 1 and itself
def prime?(num)
return false if num <= 1
(2...num).none? { |factor| num % factor == 0 }
end
puts prime?(2) #=> true
puts prime?(5) #=> true
puts prime?(11) #=> true
puts prime?(4) #=> false
puts prime?(9) #=> false
puts prime?(-5) #=> false
# Write a method pick_primes that takes in an array of numbers and returns a new array containing only the prime numbers
def pick_primes(num_array)
num_array.select { |num| prime?(num) }
end
def prime?(num)
return false if num <= 1
(2...num).none? { |factor| num % factor == 0 }
end
print pick_primes([2, 3, 4, 5, 6]) #=> [2, 3, 5]
puts
print pick_primes([101, 20, 103, 2017]) #=> [101, 103, 2017]
puts
# Write a method prime_factors that takes in a number and returns an array containing all of the prime factors of the given number
def prime_factors(num)
factor_array = []
(2...num).each do |factor|
if num % factor == 0 && prime?(factor)
factor_array << factor
end
end
factor_array
end
print prime_factors(24) #=> [2, 3]
puts
print prime_factors(60) #=> [2, 3, 5]
puts
# Write a method greatest_factor_array that takes in an array of numbers and returns a new array where every even number is replaced with it's greatest factor. A greatest factor is the largest number that divides another with no remainder
def greatest_factor_array(array)
new_array = []
array.each do |num|
if num % 2 != 0
new_array << num
else
possible_factors = num - 1
possible_factors.downto(1) do |i|
if num % i == 0
new_array << i
break
end
end
end
end
new_array
end
=begin
def greatest_factor(num)
debugger
num = num - 1
num.downto(2) do |i|
return i if num % i == 0
end
end
=end
print greatest_factor_array([16, 7, 9, 14]) # => [8, 7, 9, 7]
puts
print greatest_factor_array([30, 3, 24, 21, 10]) # => [15, 3, 12, 21, 5]
puts
# Write a method perfect_square? that takes in a number and returns a boolean indicating whether it is a perfect square. A perfect square is a number that results from multiplying a number by itself. For example, 9 is a perfect square because 3 * 3 = 9, 25 is a perfect square because 5 * 5 = 25
def perfect_square?(num)
(1..num).each do |factor|
return true if factor * factor == num
end
false
end
puts perfect_square?(5) #=> false
puts perfect_square?(12) #=> false
puts perfect_square?(30) #=> false
puts perfect_square?(9) #=> true
puts perfect_square?(25) #=> true
# Write a method triple_sequence that takes in two numbers, start and length. The method should return an array representing a sequence that begins with start and is length elements long. In the sequence, every element should be 3 times the previous element. Assume that the length is at least 1
def triple_sequence(start, length)
array = [start]
i = 1
while i < length
previous_element = array[i - 1]
array.push(previous_element * 3)
i += 1
end
array
end
print triple_sequence(2, 4) # => [2, 6, 18, 54]
puts
print triple_sequence(4, 5) # => [4, 12, 36, 108, 324]
puts
# A number's summation is the sum of all positive numbers less than or equal to the number. For example: the summation of 3 is 6 because 1 + 2 + 3 = 6, the summation of 6 is 21 because 1 + 2 + 3 + 4 + 5 + 6 = 21. Write a method summation_sequence that takes in two numbers: start and length
# The method should return an array containing length total elements. The first number of the sequence should be the start number. At any point, to generate the next element of the sequence we take the summation of the previous element. You can assume that length is not zero
def summation_sequence(start, length)
array = [start]
(length - 1).times do |i|
current_element = array[-1]
next_element = summation(current_element)
array << next_element
end
array
end
def summation(num)
sum = 0
(1..num).each { |i| sum += i }
sum
end
print summation_sequence(3, 4) # => [3, 6, 21, 231]
puts
print summation_sequence(5, 3) # => [5, 15, 120]
puts
# The fibonacci sequence is a sequence of numbers whose first and second elements are 1. To generate further elements of the sequence we take the sum of the previous two elements
# For example the first 6 fibonacci numbers are 1, 1, 2, 3, 5, 8. Write a method fibonacci that takes in a number length and returns the fibonacci sequence up to the given length
def fibonacci(n)
return [] if n == 0
return [1] if n == 1
array = [1, 1]
while array.length < n
array << array[-1] + array[-2]
end
array
end
print fibonacci(0) # => []
puts
print fibonacci(1) # => [1]
puts
print fibonacci(6) # => [1, 1, 2, 3, 5, 8]
puts
print fibonacci(8) # => [1, 1, 2, 3, 5, 8, 13, 21]
puts
# Write a method caesar_cipher that takes in a string and a number. The method should return a new string where every character of the original is shifted num characters in the alphabet
def caesar_cipher(string, num)
alphabet = ('a'..'z').to_a
chars = string.split('')
chars.map do |char|
cur_idx = alphabet.index(char)
new_idx = (cur_idx + num) % 26
alphabet[new_idx]
end
.join
end
puts caesar_cipher("apple", 1) #=> "bqqmf"
puts caesar_cipher("bootcamp", 2) #=> "dqqvecor"
puts caesar_cipher("zebra", 4) #=> "difve"
# Write a method vowel_cipher that takes in a string and returns a new string where every vowel becomes the next vowel in the alphabet
def vowel_cipher(string)
vowels = ['a', 'e', 'i', 'o', 'u']
chars = string.split('')
chars.map do |char|
if vowels.include?(char)
cur_idx = vowels.index(char)
new_idx = (cur_idx + 1) % 5
vowels[new_idx]
else
char
end
end
.join
end
puts vowel_cipher("bootcamp") #=> buutcemp
puts vowel_cipher("paper cup") #=> pepir cap
# Write a method that takes in a string and returns the number of times that the same letter repeats twice in a row
def double_letter_count(string)
string_array = string.split('')
count = 0
i = 1
while i < string.length
count += 1 if string[i] == string[i - 1]
i += 1
end
count
end
puts double_letter_count("the jeep rolled down the hill") #=> 3
puts double_letter_count("bootcamp") #=> 1
# Write a method adjacent_sum that takes in an array of numbers and returns a new array containing the sums of adjacent numbers in the original array
def adjacent_sum(num_array)
sum_array = []
i = 1
while i < num_array.length
sum_element = num_array[i] + num_array[i - 1]
sum_array << sum_element
i += 1
end
sum_array
end
print adjacent_sum([3, 7, 2, 11]) #=> [10, 9, 13], because [ 3+7, 7+2, 2+11 ]
puts
print adjacent_sum([2, 5, 1, 9, 2, 4]) #=> [7, 6, 10, 11, 6], because [2+5, 5+1, 1+9, 9+2, 2+4]
puts
# Write a method pyramid_sum that takes in an array of numbers representing the base of a pyramid. The function should return a 2D array representing a complete pyramid with the given base. To construct a level of the pyramid, we take the sum of adjacent elements of the level below
def pyramid_sum(base)
pyramid = [base]
i = 0
while i < base.length - 1
current_level = pyramid[0]
next_level = adjacent_sum(current_level)
pyramid.unshift(next_level)
i += 1
end
pyramid
end
print pyramid_sum([1, 4, 6]) #=> [[15], [5, 10], [1, 4, 6]]
puts
print pyramid_sum([3, 7, 2, 11]) #=> [[41], [19, 22], [10, 9, 13], [3, 7, 2, 11]]
puts
# Write a method all_else_equal that takes in an array of numbers. The method should return the element of the array that is equal to half of the sum of all elements of the array. If there is no such element, the method should return nil
def all_else_equal(array)
sum = array.sum
target_half = sum / 2
if array.include?(target_half)
return target_half
else
return nil
end
end
p all_else_equal([2, 4, 3, 10, 1]) #=> 10, because the sum of all elements is 20
p all_else_equal([6, 3, 5, -9, 1]) #=> 3, because the sum of all elements is 6
p all_else_equal([1, 2, 3, 4]) #=> nil, because the sum of all elements is 10 and there is no 5 in the array
# Write a method anagrams? that takes in two words and returns a boolean indicating whether or not the words are anagrams. Anagrams are words that contain the same characters but not necessarily in the same order
def anagrams?(word_1, word_2)
permutations = word_1.split('').permutation.to_a
check_word = word_2.split('')
permutations.include?(check_word)
end
p anagrams?("cat", "act") #=> true
puts anagrams?("restful", "fluster") #=> true
puts anagrams?("cat", "dog") #=> false
puts anagrams?("boot", "bootcamp") #=> false
# Write a method consonant_cancel that takes in a sentence and returns a new sentence where every word begins with it's first vowel
def consonant_cancel(string)
vowels = 'aeiou'
string = string.split
new_string = []
string.each do |word|
word = word.split('')
i = 0
while i < word.length
if !vowels.include?(word[0])
word.shift
end
i += 1
end
new_string << word.join
end
new_string.join(' ')
end
# debugger
puts consonant_cancel("down the rabbit hole") #=> "own e abbit ole"
puts consonant_cancel("writing code is challenging") #=> "iting ode is allenging"
# Write a method same_char_collapse that takes in a string and returns a collapsed version of the string. To collapse the string, we repeatedly delete 2 adjacent characters that are the same until there are no such adjacent characters.
# If there are multiple pairs that can be collapsed, delete the leftmost pair. For example, we take the following steps to collapse "zzzxaaxy": zzzxaaxy -> zxaaxy -> zxxy -> zy
def same_char_collapse(string)
repeated = true
# new_str = ''
while repeated
chars = string.split('')
repeated = false
chars.each.with_index do |char, idx|
if chars[idx] == chars[idx + 1]
chars[idx] = ''
chars[idx + 1] = ''
# string.shift(2)
repeated = true
end
end
string = chars.join
end
string
end
# debugger
puts same_char_collapse("zzzxaaxy") #=> "zy"
because zzzxaaxy -> zxaaxy -> zxxy -> zy
puts same_char_collapse("uqrssrqvtt") #=> "uv"
because uqrssrqvtt -> uqrrqvtt -> uqqvtt -> uvtt -> uv | true |
e4408dc1099bf2893ea3fff926c149fb2f599a19 | Ruby | muaad/WhatsWeb | /app/models/ticket.rb | UTF-8 | 1,643 | 2.65625 | 3 | [] | no_license | class Ticket < ActiveRecord::Base
belongs_to :customer
belongs_to :account
scope :not_closed, -> { where("status = ? or status = ? or status = ? or status = ?", "1", "2", "3", "4") }
STATUS_NEW = '1'
STATUS_OPEN = '2'
STATUS_PENDING = '3'
STATUS_SOLVED = '4'
STATUS_CLOSED = '5'
STATUS_WAITING_ON_CUSTOMER = '6'
STATUS_WAITING_ON_THIRD_PARTY = '7'
def self.unsolved_tickets account, phone_number
Ticket.not_closed.where("account_id = ? and phone_number = ?", account.id, phone_number)
end
def self.status_map
status_new = {STATUS_NEW => ["new", "nuevo", "novo", "nieuw", "neu"]}
status_open = {STATUS_OPEN => ["open", "abierto", "aberto", "offen"]}
status_pending = {STATUS_PENDING => ["pending", "pendiente", "in afwachting", "pendente", "wartend"]}
status_waiting_on_customer = {STATUS_WAITING_ON_CUSTOMER => ["waiting on customer", "angehalten"]}
status_waiting_on_third_party = {STATUS_WAITING_ON_THIRD_PARTY => ["waiting on third party"]}
status_solved = {STATUS_SOLVED => ["resolved", "resuelto", "resolvido", "opgelost", "gelöst"]}
status_closed = {STATUS_CLOSED => ["closed", "cerrado", "geschlossen", "fechado"]}
status_dictionary = {status_new: status_new, status_open: status_open, status_pending: status_pending, status_solved: status_solved, status_closed: status_closed, status_waiting_on_customer: status_waiting_on_customer, status_waiting_on_third_party: status_waiting_on_third_party}
end
def self.get_status status
status = status.downcase
statuses = self.status_map
statuses.values.each do |s|
status = s.keys.first if s.values.first.include?(status)
end
status
end
end
| true |
9caa12fcc1019e3001f9bff31e052bee85b71352 | Ruby | chian88/course_120 | /rps8.rb | UTF-8 | 6,585 | 3.65625 | 4 | [] | no_license | require 'pry'
class Score
attr_accessor :value
def initialize(value)
@value = value
end
def full?
@value >= 5
end
def reset
self.value = 0
end
end
class Rock
attr_accessor :value
def initialize
@value = "rock"
end
def win_over(other_type)
(other_type.instance_of? Scissors) || (other_type.instance_of? Lizard)
end
def lose_to(other_type)
(other_type.instance_of? Paper) || (other_type.instance_of? Spock)
end
def to_s
@value
end
end
class Paper
attr_accessor :value
def initialize
@value = "paper"
end
def win_over(other_type)
(other_type.instance_of? Rock) || (other_type.instance_of? Spock)
end
def lose_to(other_type)
(other_type.instance_of? Scissors) || (other_type.instance_of? Lizard)
end
def to_s
@value
end
end
class Scissors
attr_accessor :value
def initialize
@value = "scissors"
end
def win_over(other_type)
(other_type.instance_of? Paper) || (other_type.instance_of? Lizard)
end
def lose_to(other_type)
(other_type.instance_of? Rock) || (other_type.instance_of? Spock)
end
def to_s
@value
end
end
class Lizard
attr_accessor :value
def initialize
@value = "lizard"
end
def win_over(other_type)
(other_type.instance_of? Paper) || (other_type.instance_of? Spock)
end
def lose_to(other_type)
(other_type.instance_of? Rock) || (other_type.instance_of? Scissors)
end
def to_s
@value
end
end
class Spock
attr_accessor :value
def initialize
@value = "spock"
end
def win_over(other_type)
(other_type.instance_of? Rock) || (other_type.instance_of? Scissors)
false
end
def lose_to(other_type)
(other_type.instance_of? Paper) || (other_type.instance_of? Lizard)
end
def to_s
@value
end
end
class Player
attr_accessor :move, :name, :score
def initialize
set_name
@score = Score.new(0)
end
def string_to_obj(string)
case string
when "rock" then Rock.new
when "paper" then Paper.new
when "scissors" then Scissors.new
when "lizard" then Lizard.new
when "spock" then Spock.new
end
end
end
class Human < Player
def choose
choice = ''
loop do
puts "Please choose #{RPSGame::VALUES.join(', ')}:"
choice = gets.chomp
break if RPSGame::VALUES.include?(choice)
puts "Invalid choice."
end
self.move = string_to_obj(choice)
end
def set_name
n = ''
loop do
puts "What's your name?"
n = gets.chomp
break unless n.empty?
puts "Name can't be empty."
end
self.name = n
end
end
class Computer < Player
attr_accessor :history, :weight
def initialize(history)
@history = history
super()
end
def initial_weight
case name
when "R2D2" then @weight = { "rock" => 10, "paper" => 3,
"scissors" => 3, "lizard" => 3, "spock" => 3 }
when "Hal" then @weight = { "rock" => 3, "paper" => 10,
"scissors" => 3, "lizard" => 3, "spock" => 3 }
when "Chappie" then @weight = { "rock" => 3, "paper" => 3, "scissors" => 10,
"lizard" => 3, "spock" => 3 }
when "Sonny" then @weight = { "rock" => 3, "paper" => 3, "scissors" => 3,
"lizard" => 0, "spock" => 3 }
when "Number 5" then @weight = { "rock" => 3, "paper" => 3, "scissors" => 3,
"lizard" => 3, "spock" => 0 }
end
end
def reassign_weight
initial_weight
history.lost.each do |type, percent|
unless weight[type].zero?
weight[type] -= 2 if percent >= 60
end
end
end
def build_population
population = []
weight.each do |key, weight|
weight.times { population << key }
end
population
end
def choose
reassign_weight
move = build_population.sample
self.move = string_to_obj(move)
end
def set_name
self.name = ["R2D2", "Hal", "Chappie", "Sonny", "Number 5"].sample
end
end
class History
attr_accessor :list, :lost
def initialize
@list = { win: [], lose: [], tie: [] }
@lost = { "rock" => 0, "paper" => 0, "scissors" => 0, "lizard" => 0,
"spock" => 0 }
end
def analyze
total_games = list[:win].count + list[:lose].count + list[:tie].count
lost.each do |k, _|
lost_games = list[:win].select { |ary| ary[1].value == k }.count
lost[k] = (lost_games * 100 / total_games) unless total_games.zero?
end
lost
end
end
class RPSGame
VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock'].freeze
attr_accessor :human, :computer, :history
def initialize
@human = Human.new
@history = History.new
@computer = Computer.new(@history)
end
def display_welcome_message
puts "Welcome to rock, paper and scissors."
end
def display_goodbye_message
puts "Thanks for playing rock, paper and scissors."
end
def display_moves
puts "#{human.name} chose #{human.move}. #{computer.name} chose \
#{computer.move}."
end
def display_score
puts "#{human.name} score is #{human.score.value}. #{computer.name} \
score is #{computer.score.value}"
end
def determine_round_winner
if human.move.win_over(computer.move)
human.score.value += 1
history.list[:win] << [human.move, computer.move]
elsif human.move.lose_to(computer.move)
computer.score.value += 1
history.list[:lose] << [human.move, computer.move]
else
puts "It's a tie"
history.list[:tie] << [human.move, computer.move]
end
end
def display_winner
if human.score.full?
puts "#{human.name} won the game."
elsif computer.score.full?
puts "#{computer.name} won the game."
end
end
def play_again?
answer = ''
loop do
puts "Would you like to play again ? (y or n)"
answer = gets.chomp
break if ['y', 'n'].include? answer
puts "sorry, must be y or n."
end
return false if answer.casecmp('n').zero?
return true if answer.casecmp('y').zero?
end
def game_reset
display_winner
human.score.reset
computer.score.reset
end
def play
display_welcome_message
loop do
loop do
human.choose
computer.choose
display_moves
determine_round_winner
display_score
history.analyze
break if human.score.full? || computer.score.full?
end
game_reset
break unless play_again?
end
display_goodbye_message
end
end
RPSGame.new.play
| true |
ade93be05133099dda1435fdc201177d4fc0f775 | Ruby | ntl/raygun-client | /materials/event_store_client_http_session.rb | UTF-8 | 2,432 | 2.546875 | 3 | [
"MIT"
] | permissive | module EventStore
module Client
module HTTP
class Session
setting :host
setting :port
dependency :logger, Telemetry::Logger
def self.build
logger.trace "Building HTTP session"
new.tap do |instance|
Telemetry::Logger.configure instance
Settings.instance.set(instance)
logger.debug "Built HTTP session"
end
end
def self.configure(receiver)
session = build
receiver.session = session
session
end
def request(request, request_body: "", response_body: "")
request.headers.merge! request_headers
request["Content-Length"] = request_body.size
logger.trace "Writing request to #{connection.inspect}"
logger.data "Request headers:\n\n#{request}"
connection.write request
write_request_body request_body
response = start_response
content_length = response["Content-Length"].to_i
read_response_body response_body, content_length
connection.close if response["Connection"] == "close"
response
end
def write_request_body(request_body)
return if request_body.empty?
logger.data "Writing data to #{connection}:\n\n#{request_body}"
connection.write request_body
end
def start_response
builder = ::HTTP::Protocol::Response::Builder.build
until builder.finished_headers?
next_line = connection.gets
logger.data "Read #{next_line.chomp}"
builder << next_line
end
builder.message
end
def read_response_body(response_body, content_length)
amount_read = 0
while amount_read < content_length
packet = connection.read content_length
response_body << packet
amount_read += packet.size
end
end
def request_headers
@request_headers ||=
begin
headers = ::HTTP::Protocol::Request::Headers.build
headers["Host"] = host
headers
end
end
def connection
@connection ||= Connection::Client.build host, port
end
def self.logger
@logger ||= Telemetry::Logger.get self
end
end
end
end
end
| true |
1c15403132593a4cb3ca0768cd4e186f73dd528e | Ruby | carloshdelreal/coding_challenges | /leet/4_median_of_two_sorted.rb | UTF-8 | 1,324 | 3.59375 | 4 | [] | no_license | # frozen_string_literal: true
# @param {Integer[]} nums1
# @param {Integer[]} nums2
# @return {Float}
def find_median_sorted_arrays(nums1, nums2)
total_length = nums1.length + nums2.length
median_index = total_length / 2
previous = nil
if total_length.odd?
loop do
if !nums1[0].nil? && (nums2[0].nil? || nums1[0] < nums2[0])
return nums1.shift.to_f if median_index == 0
nums1.shift
else
return nums2.shift.to_f if median_index == 0
nums2.shift
end
median_index -= 1
end
else
loop do
# puts "previous: #{previous}, nums1: #{nums1}, nums2: #{nums2}"
if !nums1[0].nil? && (nums2[0].nil? || nums1[0] < nums2[0])
return nums1[0].to_f if nums2[0].nil? && previous.nil? && median_index == 0
return (previous + nums1[0]) / 2.0 if median_index == 0
previous = nums1.shift
else
return nums2[0].to_f if nums1[0].nil? && previous.nil? && median_index == 0
return (previous + nums2[0]) / 2.0 if median_index == 0
previous = nums2.shift
end
median_index -= 1
end
end
end
p find_median_sorted_arrays([1, 2], [3, 4])
p find_median_sorted_arrays([2], [])
p find_median_sorted_arrays([], [2])
p find_median_sorted_arrays([2, 3], [])
p find_median_sorted_arrays([], [2, 3])
| true |
3dae6ef3f8e7a8c271e62ab3f2d4f70808d535e8 | Ruby | trumans/ruby | /date_difference.rb | UTF-8 | 3,762 | 3.59375 | 4 | [] | no_license | # Date Difference
require 'test/unit/assertions'
extend Test::Unit::Assertions
def date_difference(start_year, start_month, start_day, end_year, end_month, end_day)
def days_in(year, month)
case month
when 1,3,5,7,8,10,12
31
when 2
# leap year if evenly divisible by 4 and not century, or by 400
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0) ? 29 : 28
when 4,6,9,11
30
end
end
if start_year < 1583 || end_year < 1583
puts 'warning: function may be incorrect earlier than 1583'
end
unless (end_year > start_year) ||
(end_year == start_year && end_month > start_month) ||
(end_year == start_year && end_month == start_month && end_day >= start_day)
#puts 'end date cannot be earlier than start date'
return nil
end
# dates within a year
if start_year == end_year
if start_month == end_month
return end_day - start_day
else
whole_months = (start_month+1..end_month-1).inject(0) do | total, month |
total + days_in(start_year, month)
end
return days_in(start_year, start_month) - start_day +
whole_months +
end_day
end
end
# across multiple years
whole_years = (start_year+1..end_year-1).inject(0) do | total, year |
total + (days_in(year, 2) == 28 ? 365 : 366)
end
return date_difference(start_year, start_month, start_day,
start_year, 12, 31) +
whole_years +
date_difference(end_year, 1, 1,
end_year, end_month, end_day) + 1
end
def display_diff(start_year, start_month, start_day, end_year, end_month, end_day)
diff = date_difference(start_year, start_month, start_day, end_year, end_month, end_day)
puts "days between #{start_year}-#{start_month}-#{start_day} and #{end_year}-#{end_month}-#{end_day} is #{diff}" if diff
end
assert_equal 13, date_difference(2016, 3, 2, 2016, 3, 15), ' ' # same the month
assert_equal 29, date_difference(2010, 9, 1, 2010, 9, 30), ' ' # whole month
assert_equal 1, date_difference(2016, 7, 15, 2016, 7, 16), ' ' # adjacent days
assert_equal 0, date_difference(2016, 2, 25, 2016, 2, 25), ' ' # same day
assert_equal 11, date_difference(2010, 3, 25, 2010, 4, 5), ' ' # adjacent months
assert_equal 36, date_difference(2010, 3, 25, 2010, 4, 30), ' ' # partial + whole month
assert_equal 31, date_difference(2010, 7, 1, 2010, 8, 1), ' ' # whole month + 1 day
assert_equal 42, date_difference(2010, 7, 25, 2010, 9, 5), ' ' # partial + whole + partial months
assert_equal 25, date_difference(2010, 2, 15, 2010, 3, 12), ' ' # adjacent months w/ regular Feb
assert_equal 26, date_difference(2016, 2, 15, 2016, 3, 12), ' ' # adjacent months w/ leap Feb
assert_equal 365, date_difference(2016, 1, 1, 2016, 12, 31), ' ' # whole year, leap year
assert_equal 364, date_difference(2001, 1, 1, 2001, 12, 31), ' ' # whole year, not leap year
assert_equal 365, date_difference(2000, 1, 1, 2000, 12, 31), ' ' # whole century year, leap year
assert_equal 364, date_difference(1900, 1, 1, 1900, 12, 31), ' ' # whole century year, not leap year
assert_equal 365, date_difference(2004, 3, 1, 2005, 3, 1), ' ' # past Feb in leap year
assert_equal 366, date_difference(1999, 3, 1, 2000, 3, 1), ' ' # wrap into leap year
assert_equal 12, date_difference(2001, 12, 25, 2002, 1, 6), ' ' # => 6 + 6
assert_equal 377, date_difference(2001, 12, 25, 2003, 1, 6), ' ' # => 6 + 365 + 6
assert_equal 378, date_difference(2003, 12, 25, 2005, 1, 6), ' ' # => 6 + 366 + 6
assert_equal 1132, date_difference(1996, 1, 25, 1999, 3, 2), ' ' # multi-year with a Feb 29
assert_equal 1498, date_difference(1996, 1, 25, 2000, 3, 2), ' ' # two Feb 29
puts "Assertions passed"
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.