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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ad8021d370e5bd9a69e048c502d169a4f92b636a
|
Ruby
|
mattbeedle/davinci
|
/vendor/plugins/flex_image/test/mock_file.rb
|
UTF-8
| 172
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
class MockFile
attr_reader :path
def initialize(path)
@path = path
end
def size
1
end
def read
File.open(@path) { |f| f.read }
end
end
| true
|
f31eefe70a0aa1a28b4e582095ec650b27609b85
|
Ruby
|
cmingxu/hotel
|
/vendor/plugins/captcha/lib/captcha_image_generator.rb
|
UTF-8
| 2,658
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
begin
require 'RMagick'
rescue Exception => e
puts "Warning: RMagick not installed, you cannot generate captcha images on this machine"
end
require 'captcha_util'
module CaptchaImageGenerator
@@eligible_chars = %w(A B C D E F G H J K L M N P Q R S T U V X Y Z)
#insub @@eligible_chars = (2..9).to_a + %w(a b c d e f g h i j k l m n o p q r s t u v w x y z)
@@default_parameters = {
:image_width => 90, #insub 修改验证码图片生成参数
:image_height => 26,
:captcha_length => 4,
:file_format => 'gif'
}
def self.generate_captcha_image(params = {})
params.reverse_merge!(@@default_parameters)
file_format = ['png', 'gif'].include?(params[:file_format]) ? ".#{params[:file_format]}" : '.png'
#background_type = "granite:" #花岗岩
#background_type = "netscape:" #彩条
#background_type = "xc:#EDF7E7" #指定背景色,例:xc:red
#background_type = "null:" #纯黑
granite = Magick::Image.read('granite:').first
backgroud = Magick::HatchFill.new("#f7feec")#Magick::HatchFill.new('green','blue') # Magick::TextureFill.new(granite)
text_img = Magick::Image.new(params[:image_width].to_i, params[:image_height].to_i, backgroud)
black_img = Magick::Image.new(params[:image_width].to_i, params[:image_height].to_i) do
self.background_color = 'black'
end
# Generate a X character random string
random_string = (1..params[:captcha_length].to_i).collect { @@eligible_chars[rand(@@eligible_chars.size)] }.join(' ')
# Gerenate the filename based on the string where we have removed the spaces
filename = CaptchaUtil::encrypt_string(random_string.gsub(' ', '').downcase) + file_format
# Render the text in the image
text_img.annotate(Magick::Draw.new, 0,0,10,0, random_string) { # 字符偏移位置
self.gravity = Magick::WestGravity
self.font_family = 'Times New Roman'
#self.font_weight = Magick::BoldWeight
self.fill = '#C10002'
self.stroke = '#CD2E00'
self.stroke_width = 1
self.pointsize = 26
self.kerning = -3
}
# Apply a little blur and fuzzing
text_img = text_img.gaussian_blur(0.6, 0.6)
text_img = text_img.wave(1, 30)
# Now we need to get the white out
text_mask = text_img.negate
text_mask.matte = false
# Add cut-out our captcha from the black image with varying tranparency
black_img.composite!(text_mask, Magick::CenterGravity, Magick::CopyOpacityCompositeOp)
# Write the file to disk
puts 'Writing image file ' + filename
text_img.write(filename) # { self.depth = 8 }
# Collect rmagick
GC.start
end
end
| true
|
7ea56431f26ab8d51c9272ea08d7ae13e88eaeb4
|
Ruby
|
rmake/cor-engine
|
/packages/experimentals/experimental_projects/set_on_enter_callback/resources/start.rb
|
UTF-8
| 848
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
class MyObject
def self.create
# nd3.pngの一番左上の画像からspriteを作成する
f0 = SpriteFrame.create "nd3_anim.png", Rect.create(0, 0, 64, 64)
sprite = Sprite.create_with_sprite_frame f0
# sceneに追加されて最初に呼ばれる(add_childのあとくらい?) <- なくていい
#sprite.set_on_enter_callback do
sprite.run_action RotateBy.create(100, 360.0 * 100)
#end
sprite
end
end
# visible_sizeは画面の大きさ
visible_size = Director.get_instance.get_visible_size
# spriteを作って受け取る
sprite = MyObject.create
# 画面の中心に配置
sprite.set_position visible_size.width / 2, visible_size.height / 2
# layerのノードに追加することで表示される
Project.get_current_layer.add_child sprite
| true
|
7ffff83aa5cc4622b753dc739586aff448b58c95
|
Ruby
|
kevinlo123/code-wars-challenge
|
/problems-24.rb
|
UTF-8
| 431
| 3.90625
| 4
|
[] |
no_license
|
=begin
Return the number (count) of vowels in the given string.
We will consider a, e, i, o, and u as vowels for this Kata.
The input string will only consist of lower case letters and/or spaces.
=end
def getCount(inputStr)
count = 0
arr = inputStr.split("");
arr.each do |item|
if item == 'a' || item == 'e' ||
item == 'i' || item == 'o' ||
item == 'u'
count += 1
end
end
return count
end
| true
|
ce8ab8751e7792b9190680a22cf0a9698b2d18ce
|
Ruby
|
Timdavidcole/Oystercard-1
|
/lib/oystercard.rb
|
UTF-8
| 1,747
| 3.4375
| 3
|
[] |
no_license
|
require 'pry'
require_relative 'journey.rb'
class Oystercard
DEFAULT_MAX_BALANCE = 90
MIN_FAIR = 1
attr_reader :balance, :max_balance, :money, :journeys, :current_journey
def initialize(balance = 0, max_balance = DEFAULT_MAX_BALANCE)
@balance = balance
@max_balance = max_balance
@journeys = []
# @money = money
end
def top_up(money)
raise 'Max top up allowed is £90. Please select different amount' if max(money) #money + balance > DEFAULT_MAX_BALANCE
@balance += money
end
#You can only use Journey.new as an argument for RSPEC
def touch_in(station, journey = Journey.new)
raise 'Balance is insuffcient' if insufficient?
@current_journey = journey
@current_journey.add_entry_journey(station)
end
def touch_out(station, journey = Journey.new)
if @current_journey == nil
@current_journey = journey
deduct_and_end(station)
elsif @current_journey.journey.key?(:begin)
deduct_and_end(station)
else
updated_journey
@current_journey = journey
deduct_and_end(station)
end
end
# when we access other object with their private methods we cant access them in test! Only original class
private
def updated_journey
@journeys << @current_journey
@current_journey = nil
end
def add_journey(entry_station, exit_station)
@journeys << Journey.new(entry_station,exit_station)
end
def deduct(money)
@balance -= money
end
def deduct_and_end(station)
@current_journey.add_exit_station(station)
deduct(@current_journey.fare(MIN_FAIR))
updated_journey
end
def insufficient?
@balance < MIN_FAIR
end
def max(money)
money + @balance > DEFAULT_MAX_BALANCE
end
end
# binding.pry
| true
|
e846b49dc018000bbf4ea5e0f67c19b27aa5f0ea
|
Ruby
|
chinnu21131/day3
|
/classes2.rb
|
UTF-8
| 354
| 3.59375
| 4
|
[] |
no_license
|
class Book
attr_reader :title, :author, :price
attr_writer :title, :author, :price
def is_price_high?
if @price>1000
return true
else
return false
end
end
end
b1=Book.new
b1.title='The coven'
b1.author="Prashanth"
puts "Enter the book price : "
b1.price=gets.chomp.to_i
puts b1.title
puts b1.author
puts b1.price
puts b1.is_price_high?
| true
|
927f01ff43ba3b719442c86202b47a7079becc74
|
Ruby
|
Jojograndjojo/learn_to_program
|
/ch09-writing-your-own-methods/roman_numerals.rb
|
UTF-8
| 670
| 3.4375
| 3
|
[] |
no_license
|
def roman_numeral n
thousand = n / 1000
hundreds = n % 1000 / 100
tens = n % 100 / 10
units = n % 10
thousand_to_s = 'M' * thousand
if hundreds == 9
hundreds_to_s = 'CM'
elsif hundreds == 4
rhundreds_to_s = 'CD'
else
hundreds_to_s = 'D' * (n % 1000 / 500) + 'C' * (n % 500 / 100)
end
if tens == 9
tens_to_s = 'XC'
elsif tens == 4
tens_to_s = 'XL'
else
tens_to_s = 'L' * (n % 100 / 50) + 'X' * (n % 50 / 10)
end
if units == 9
units_to_s = 'IX'
elsif units == 4
units_to_s = 'IV'
else
units_to_s = 'V' * (n % 10 / 5) + 'I' * (n % 5 / 1)
end
thousand_to_s + hundreds_to_s + tens_to_s +units_to_s
end
| true
|
849340f858177c25d0a0499c9e2d630bf48a2491
|
Ruby
|
kaljt/live_sessions
|
/etl_test.rb
|
UTF-8
| 634
| 2.796875
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require_relative 'etl'
class ScrabbleScoreTest < MiniTest::Unit::TestCase
def setup; end
def test_empty
old = {}
assert_equal({}, ScrabbleScore.convert(old))
end
def test_one
old = {1=> ['A','E','I','O','U']}
assert_equal({'a' => 1, 'e' => 1,
'i' => 1, 'o' => 1,
'u' => 1}, ScrabbleScore.convert(old))
end
def test_two
old = {1 => ['A','E'], 2=> ['D','G']}
expected = { 'a' => 1,
'e' => 1,
'd' => 2,
'g' => 2 }
assert_equal(expected, ScrabbleScore.convert(old))
end
end
| true
|
89bd45586f3a50f6e144721ca79182fcfccf38fe
|
Ruby
|
matanco/MathLib
|
/lib/math_lib.rb
|
UTF-8
| 1,655
| 3.671875
| 4
|
[
"MIT"
] |
permissive
|
require "math_lib/version"
class String
def is_number?
true if Float(self) rescue false
end
##= move all expressions to same side in equation and equal it to 0
def orginize_equation
gsub!(' ','')
##TODO:: orginaize
end
end
module MathLib
class MathValidator
##= Validate the all input are numbers and convert them to integer
def self.validate_input(input)
input.to_s.is_number? ? input.to_i : raise('MathLib:: handle only numbers.')
end
def self.validate_linear_equation(input)
input.index('=').present? ? true : raise('MathLib:: invalid linear equation')
end
end
class MathBasic
def initialize
end
##= Calculate quadratic equation
def quadratic_equation(a,b,c)
a = MathLib::MathValidator.validate_input(a)
b = MathLib::MathValidator.validate_input(b)
c = MathLib::MathValidator.validate_input(c)
delta = (b * b) - (4 * a * c)
if (delta < 0)
puts 'Delta is complex number'
return 0
elsif (delta == 0)
puts 'quadratic equation has has only 1 answer'
root1 = -b / (2* a);
puts "Roots of quadratic equation is: #{root1}"
return 0
elsif (delta > 0)
puts 'quadratic equation has real numbers'
root1 = ( -b + Math.sqrt(delta)) / (2 * a)
root2 = ( -b - Math.sqrt(delta)) / (2 * a)
puts "Roots of quadratic equation are: #{root1} || #{root2}"
return 0
end
end
##= Calculate linear equation
##= Syntax:: 3x + 7 = 4x * 6^2
##= Syntax:: 2x = 2
def linear_equation(equation)
#TODO:: calculate
end
end
end
| true
|
12033b9049a866bc3683445c853aca7ec4d122b2
|
Ruby
|
mdsol/mauth-client-ruby
|
/exe/mauth-client
|
UTF-8
| 8,433
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path('../lib', File.dirname(__FILE__))
require 'faraday'
require 'logger'
require 'mauth/client'
require 'mauth/faraday'
require 'yaml'
require 'term/ansicolor'
# OPTION PARSER
require 'optparse'
# $options default values
$options = {
authenticate_response: true,
verbose: true,
color: nil,
no_ssl_verify: false
}
additional_headers = []
opt_parser = OptionParser.new do |opts|
opts.banner = 'Usage: mauth-client [options] <verb> <url> [body]'
opts.on('-v', '--[no-]verbose', 'Run verbosely - output is like curl -v (this is the default)') do |v|
$options[:verbose] = v
end
opts.on('-q', 'Run quietly - only outputs the response body (same as --no-verbose)') do |v|
$options[:verbose] = !v
end
opts.on('--[no-]authenticate', 'Authenticate the response received') do |v|
$options[:authenticate_response] = v
end
opts.on('--[no-]color', 'Color the output (defaults to color if the output device is a TTY)') do |v|
$options[:color] = v
end
opts.on('-t', '--content-type CONTENT-TYPE', 'Sets the Content-Type header of the request') do |v|
$options[:content_type] = v
end
opts.on('-H', '--header LINE',
"accepts a json string of additional headers to included. IE 'cache-expirey: 10, other: value") do |v|
additional_headers << v
end
opts.on('--no-ssl-verify', 'Disables SSL verification - use cautiously!') do
$options[:no_ssl_verify] = true
end
$options[:additional_headers] = additional_headers
end
opt_parser.parse!
abort(opt_parser.help) unless (2..3).cover?(ARGV.size)
# INSTANTIATE MAUTH CLIENT
mauth_config = MAuth::ConfigEnv.load
logger = Logger.new($stderr)
mauth_client = MAuth::Client.new(mauth_config.merge('logger' => logger))
# OUTPUTTERS FOR FARADAY THAT SHOULD MOVE TO A LIB SOMEWHERE
# outputs the response body to the given output device (defaulting to STDOUT)
class FaradayOutputter < Faraday::Middleware
def initialize(app, outdev = $stdout)
@app = app
@outdev = outdev
end
def call(request_env)
@app.call(request_env).on_complete do |response_env|
@outdev.puts(response_env[:body] || '')
end
end
end
# this is to approximate `curl -v`s output. but it's all faked, whereas curl gives you
# the real text written and read for request and response. whatever, close enough.
class FaradayCurlVOutputter < FaradayOutputter
# defines a method with the given name, applying coloring defined by any additional arguments.
# if $options[:color] is set, respects that; otherwise, applies color if the output device is a tty.
def self.color(name, *color_args)
define_method(name) do |arg|
if color?
color_args.inject(arg) do |result, color_arg|
Term::ANSIColor.send(color_arg, result)
end
else
arg
end
end
end
color :info, :intense_yellow
color :info_body, :yellow
color :protocol
color :request, :intense_cyan
color :request_verb, :bold
color :request_header
color :request_blankline, :intense_cyan, :bold
color :response, :intense_green
color :response_status, :bold, :green
color :response_header
color :response_blankline, :intense_green, :bold
def call(request_env) # rubocop:disable Metrics/AbcSize
@outdev.puts "#{info('*')} #{info_body("connect to #{request_env[:url].host} on port #{request_env[:url].port}")}"
@outdev.puts "#{info('*')} #{info_body("getting our SSL on")}" if request_env[:url].scheme == 'https'
@outdev.puts "#{request('>')} #{request_verb(request_env[:method].to_s.upcase)} #{request_env[:url].path}" \
"#{protocol('HTTP/1.1' || 'or something - TODO')}"
request_env[:request_headers].each do |k, v|
@outdev.puts "#{request('>')} #{request_header(k)}#{request(':')} #{v}"
end
@outdev.puts "#{request_blankline('>')} "
request_body = color_body_by_content_type(request_env[:body], request_env[:request_headers]['Content-Type'])
(request_body || '').split("\n", -1).each do |line|
@outdev.puts "#{request('>')} #{line}"
end
@app.call(request_env).on_complete do |response_env|
@outdev.puts "#{response('<')} #{protocol('HTTP/1.1' || 'or something - TODO')} " \
"#{response_status(response_env[:status].to_s)}"
request_env[:response_headers].each do |k, v|
@outdev.puts "#{response('<')} #{response_header(k)}#{response(':')} #{v}"
end
@outdev.puts "#{response_blankline('<')} "
response_body = color_body_by_content_type(response_env[:body], response_env[:response_headers]['Content-Type'])
(response_body || '').split("\n", -1).each do |line|
@outdev.puts "#{response('<')} #{line}"
end
end
end
# whether to use color
def color?
$options[:color].nil? ? @outdev.tty? : $options[:color]
end
# a mapping for each registered CodeRay scanner to the Media Types which represent
# that language. extremely incomplete!
CODE_RAY_FOR_MEDIA_TYPES = {
c: [],
cpp: [],
clojure: [],
css: ['text/css', 'application/css-stylesheet'],
delphi: [],
diff: [],
erb: [],
groovy: [],
haml: [],
html: ['text/html'],
java: [],
java_script: ['application/javascript', 'text/javascript', 'application/x-javascript'],
json: ['application/json', %r{\Aapplication/.*\+json\z}],
php: [],
python: ['text/x-python'],
ruby: [],
sql: [],
xml: ['text/xml', 'application/xml', %r{\Aapplication/.*\+xml\z}],
yaml: []
}.freeze
# takes a body and a content type; returns the body, with coloring (ansi colors for terminals)
# possibly added, if it's a recognized content type and #color? is true
def color_body_by_content_type(body, content_type)
return body unless body && color?
# kinda hacky way to get the media_type. faraday should supply this ...
require 'rack'
media_type = ::Rack::Request.new({ 'CONTENT_TYPE' => content_type }).media_type
coderay_scanner = CODE_RAY_FOR_MEDIA_TYPES.select { |_k, v| v.any?(media_type) }.keys.first
return body unless coderay_scanner
require 'coderay'
if coderay_scanner == :json
body = begin
JSON.pretty_generate(JSON.parse(body))
rescue JSON::ParserError
body
end
end
CodeRay.scan(body, coderay_scanner).encode(:terminal)
end
end
# CONFIGURE THE FARADAY CONNECTION
faraday_options = {}
if $options[:no_ssl_verify]
faraday_options[:ssl] = { verify: false }
end
connection = Faraday.new(faraday_options) do |builder|
builder.use MAuth::Faraday::MAuthClientUserAgent, 'MAuth-Client CLI'
builder.use MAuth::Faraday::RequestSigner, mauth_client: mauth_client
if $options[:authenticate_response]
builder.use MAuth::Faraday::ResponseAuthenticator, mauth_client: mauth_client
end
builder.use $options[:verbose] ? FaradayCurlVOutputter : FaradayOutputter
builder.adapter Faraday.default_adapter
end
httpmethod, url, body = *ARGV
unless Faraday::Connection::METHODS.map { |m| m.to_s.downcase }.include?(httpmethod.downcase)
abort "Unrecognized HTTP method given: #{httpmethod}\n\n" + opt_parser.help
end
headers = {}
if $options[:content_type]
headers['Content-Type'] = $options[:content_type]
elsif body
headers['Content-Type'] = 'application/json'
# I'd rather not have a default content-type, but if none is set then the HTTP adapter sets this to
# application/x-www-form-urlencoded anyway. application/json is a better default for our purposes.
end
$options[:additional_headers]&.each do |cur|
raise 'Headers must be in the format of [key]:[value]' unless cur.include?(':')
key, _throw_away, value = cur.partition(':')
headers[key] = value
end
# OH LOOK IT'S FINALLY ACTUALLY CONNECTING TO SOMETHING
begin
connection.run_request(httpmethod.downcase.to_sym, url, body, headers)
rescue MAuth::InauthenticError, MAuth::UnableToAuthenticateError, MAuth::MAuthNotPresent, MAuth::MissingV2Error => e
if $options[:color].nil? ? $stderr.tty? : $options[:color]
class_color = Term::ANSIColor.method(e.is_a?(MAuth::UnableToAuthenticateError) ? :intense_yellow : :intense_red)
message_color = Term::ANSIColor.method(e.is_a?(MAuth::UnableToAuthenticateError) ? :yellow : :red)
else
class_color = proc { |s| s }
message_color = proc { |s| s }
end
warn(class_color.call(e.class.to_s))
warn(message_color.call(e.message))
end
| true
|
2e8a315d2023e33005c2cc8fb0fce8a94de91039
|
Ruby
|
nickborromeo/edx-saas
|
/OOP/spec/jelly_bean_spec.rb
|
UTF-8
| 586
| 2.515625
| 3
|
[] |
no_license
|
require "spec_helper"
describe "JellyBean" do
describe "#delicious?" do
it "black-licorice should not be delicious" do
jelly_bean = JellyBean.new("jelly bean", "250", "black-licorice")
jelly_bean.delicious?.should == false
end
it "all other flavors should be delicious" do
jelly_bean = JellyBean.new("jelly bean", "250", "green")
jelly_bean.delicious?.should == true
end
it "all non-JellyBean desserts should be delicious" do
dessert = Dessert.new("non jelly bean", "250")
dessert.delicious?.should == true
end
end
end
| true
|
ebae5b10ab7886fcba59b4fcc86d071c721ebf2c
|
Ruby
|
chienleow/ruby-collaborating-objects-lab-online-web-sp-000
|
/lib/song.rb
|
UTF-8
| 529
| 3.1875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Song
attr_accessor :name, :artist
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def self.new_by_filename(file_name)
# binding.pry
split_file_name = file_name.split(" - ")
song = self.new(split_file_name[1])
artist = Artist.find_or_create_by_name(split_file_name[0])
artist.add_song(song)
song
end
def artist_name=(artist_name)
self.artist = Artist.find_or_create_by_name(artist_name)
end
end
| true
|
062c6e57d9671a4ed53d5e3e3cb05a33b8104a68
|
Ruby
|
malbrecht0792/learn_ruby
|
/03_simon_says/simon_says.rb
|
UTF-8
| 628
| 4.125
| 4
|
[] |
no_license
|
#write your code here
def echo(word)
return word
end
def shout(word)
return word.upcase
end
def repeat(word, num = 2)
num.times do |x|
return word + (" " + word) * (num - 1)
end
end
def start_of_word(word, num)
return word[0..num-1]
end
def first_word(word)
word.split[0]
end
def titleize(word)
non_cap_array = ["a","an","the","and", "over"]
temp_string = word.gsub(/\w+/) {|match| non_cap_array.include?(match) ? match : match.capitalize}
if non_cap_array.include?(temp_string.split[0]) then
return temp_string.split[0].capitalize + " " + temp_string.split[1..-1].join(' ')
else
return temp_string
end
end
| true
|
e701c02bf33992f6f067386f9203a53288bfe38f
|
Ruby
|
ryangreenberg/welder
|
/spec/board_spec.rb
|
UTF-8
| 7,896
| 3.4375
| 3
|
[] |
no_license
|
require 'spec_helper'
describe Welder::Board do
it "has a coordinate system zero-indexed from the top-left" do
letters = <<-EOS
abcd
efgh
ijkl
mnop
EOS
tiles = get_tiles_for_string(letters)
board = get_board_for_tiles(tiles)
tiles.each_with_index do |row, y|
row.each_with_index do |tile, x|
board.get_tile(x, y).should == tiles[y][x]
end
end
board.to_s.should == letters.gsub(/^\s*|\s*$/, '')
end
describe "#populate" do
it "calls the provided block once for each space on the board" do
board = Welder::Board.new(4)
times_called = 0
board.populate {|x, y| times_called += 1}
times_called.should == 16
end
it "places the returned tile on the board at the yielded coordinates" do
tiles = [
Welder::Tile.new('a'),
Welder::Tile.new('b'),
Welder::Tile.new('c'),
Welder::Tile.new('d')
]
placed_tiles = []
board = Welder::Board.new(2)
board.populate do |x, y|
tile = tiles.shift
placed_tiles << [x, y, tile]
tile
end
placed_tiles.size.should == 4
placed_tiles.each do |x, y, tile|
board.get_tile(x, y).should == tile
end
end
it "does not change the tile if the provided block yields a falsy value" do
board = get_board_for_string <<-EOS
abc
def
ghi
EOS
original_tiles = board.tiles
board.populate do |x, y|
false
end
board.tiles.should == original_tiles
end
end
describe "#swap" do
before do
board_size = 3
@board = Welder::Board.new(board_size)
letters = "abcdefghi".split("")
@board.populate do |x, y|
Welder::Tile.new(letters.shift)
end
@center_tile = @board.get_tile(1, 1)
end
it "moves the tile up when direction is :north" do
@board.swap(1, 1, :north)
@board.get_tile(1, 0).should == @center_tile
end
it "moves the tile up-right when direction is :northeast" do
@board.swap(1, 1, :northeast)
@board.get_tile(2, 0).should == @center_tile
end
it "moves the tile right when direction is :east" do
@board.swap(1, 1, :east)
@board.get_tile(2, 1).should == @center_tile
end
it "moves the tile down-right when direction is :southeast" do
@board.swap(1, 1, :southeast)
@board.get_tile(2, 2).should == @center_tile
end
it "moves the tile down when direction is :south" do
@board.swap(1, 1, :south)
@board.get_tile(1, 2).should == @center_tile
end
it "moves the tile down-left when direction is :southwest" do
@board.swap(1, 1, :southwest)
@board.get_tile(0, 2).should == @center_tile
end
it "moves the tile left when direction is :west" do
@board.swap(1, 1, :west)
@board.get_tile(0, 1).should == @center_tile
end
it "moves the tile up-left when direction is :northwest" do
@board.swap(1, 1, :northwest)
@board.get_tile(0, 0).should == @center_tile
end
it "returns false when the swap would go off the board" do
# Coordinates keyed to invalid moves from those coordinates on a 3x3 grid
# Invalid options are listed in clockwise order
invalid_moves_from_coords = {
[0, 0] => [:sw, :w, :nw, :n, :ne],
[1, 0] => [:nw, :n, :ne],
[2, 0] => [:nw, :n, :ne, :e, :se],
[0, 1] => [:sw, :w, :nw],
[1, 1] => [],
[2, 1] => [:ne, :e, :se],
[0, 2] => [:se, :s, :sw, :w, :nw],
[1, 2] => [:se, :s, :sw],
[2, 2] => [:ne, :e, :se, :s, :sw]
}
invalid_moves_from_coords.each do |(x, y), invalid_moves|
invalid_moves.each do |invalid_move|
@board.swap(x, y, invalid_move).should be_false
end
end
end
end
describe "#all_possible_moves" do
it "lists all possible moves in the form of (num, num, direction)" do
board = get_board_for_string("ab\ncd")
all_possible_moves = board.all_possible_moves
tiles = [[0,0], [0, 1], [1, 0], [1, 1]]
Welder::Board::MOVE_DIRECTIONS.each do |direction|
tiles.each do |tile|
expected_move = tile.dup.concat(Array(direction))
all_possible_moves.should include(expected_move)
end
end
end
end
describe "#get_word" do
before do
@board = get_board_for_string <<-EOS
abc
def
ghi
EOS
end
it "returns the word of the specified length and orientation at the given position" do
@board.get_word(0, 0, :horizontal, 3).to_s.should == "abc"
@board.get_word(0, 2, :horizontal, 3).to_s.should == "ghi"
@board.get_word(0, 0, :vertical, 3).to_s.should == "adg"
@board.get_word(2, 0, :vertical, 3).to_s.should == "cfi"
end
it "sets the position of the word on the board" do
word = @board.get_word(0, 2, :horizontal, 3)
word.x.should == 0
word.y.should == 2
end
it "sets the orientation of the word on the board" do
word = @board.get_word(0, 2, :horizontal, 3)
word.orientation.should == :horizontal
end
it "returns false if the specified row or colum doesn't exist" do
@board.get_word(0, 3, :horizontal, 3).should == false
@board.get_word(3, 0, :vertical, 3).should == false
@board.get_word(3, 3, :horizontal, 3).should == false
@board.get_word(3, 3, :vertical, 3).should == false
end
it "returns false if the specified length run off the board" do
@board.get_word(0, 0, :horizontal, 4).should == false
@board.get_word(0, 0, :vertical, 4).should == false
end
it "raises ArgumentError if an invalid orientation is provided" do
lambda { @board.get_word(0, 0, :diagonal, 3) }.should raise_error(ArgumentError)
end
end
describe "#remove_word" do
it "removes the provided word from the board" do
board = get_board_for_string <<-EOS
abc
def
ghi
EOS
word = board.get_word(0, 0, :horizontal, 3)
board.remove_word(word)
board_without_word = <<-EOS.gsub(/^\s*|\s*$/, '')
...
def
ghi
EOS
board.to_s.should == board_without_word
end
end
describe "#possible_words" do
it "returns all the words on the board with the given minimum length" do
board = get_board_for_string <<-EOS
abc
def
ghi
EOS
possible_words = board.possible_words(2)
possible_word_strings = possible_words.map{|w| w.to_s}
%w|ab bc de ef gh hi ad dg be eh cf fi|.each do |expected_word|
possible_word_strings.should include(expected_word)
end
end
it "returns words with their position on the board" do
board = get_board_for_string <<-EOS
abc
def
ghi
EOS
possible_words = board.possible_words(2)
word_ab = possible_words.detect {|w| w.to_s == 'ab'}
word_ab.x.should == 0
word_ab.y.should == 0
word_cf = possible_words.detect {|w| w.to_s == 'cf'}
word_cf.x.should == 2
word_cf.y.should == 0
word_dg = possible_words.detect {|w| w.to_s == 'dg'}
word_dg.x.should == 0
word_dg.y.should == 1
word_hi = possible_words.detect {|w| w.to_s == 'hi'}
word_hi.x.should == 1
word_hi.y.should == 2
end
end
describe "#drop_tiles" do
it "moves all tiles on board so that no tile has a blank space below/south of it" do
letters = <<-EOS
abcd
ef..
g.h.
....
EOS
tiles = get_tiles_for_string(letters)
board = get_board_for_tiles(tiles)
board.drop_tiles
dropped_letters = <<-EOS.gsub(/^\s*|\s*$/, '')
....
a...
ebc.
gfhd
EOS
board.to_s.should == dropped_letters
end
end
end
| true
|
805790fa8300812157057340d8f1c36879d7d5b1
|
Ruby
|
purpleD17/pairwise-api
|
/vendor/cache/rails-e53a9789b873/actionmailer/lib/action_mailer/vendor/tmail-1.2.7/tmail/vendor/rchardet-1.3/lib/rchardet/hebrewprober.rb
|
UTF-8
| 12,871
| 2.96875
| 3
|
[
"LGPL-2.1-only",
"MIT",
"LGPL-2.0-or-later",
"BSD-3-Clause"
] |
permissive
|
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Shy Shalom
# Portions created by the Initial Developer are Copyright (C) 2005
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Jeff Hodges - port to Ruby
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
# This prober doesn't actually recognize a language or a charset.
# It is a helper prober for the use of the Hebrew model probers
### General ideas of the Hebrew charset recognition ###
#
# Four main charsets exist in Hebrew:
# "ISO-8859-8" - Visual Hebrew
# "windows-1255" - Logical Hebrew
# "ISO-8859-8-I" - Logical Hebrew
# "x-mac-hebrew" - ?? Logical Hebrew ??
#
# Both "ISO" charsets use a completely identical set of code points, whereas
# "windows-1255" and "x-mac-hebrew" are two different proper supersets of
# these code points. windows-1255 defines additional characters in the range
# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific
# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.
# x-mac-hebrew defines similar additional code points but with a different
# mapping.
#
# As far as an average Hebrew text with no diacritics is concerned, all four
# charsets are identical with respect to code points. Meaning that for the
# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters
# (including final letters).
#
# The dominant difference between these charsets is their directionality.
# "Visual" directionality means that the text is ordered as if the renderer is
# not aware of a BIDI rendering algorithm. The renderer sees the text and
# draws it from left to right. The text itself when ordered naturally is read
# backwards. A buffer of Visual Hebrew generally looks like so:
# "[last word of first line spelled backwards] [whole line ordered backwards
# and spelled backwards] [first word of first line spelled backwards]
# [end of line] [last word of second line] ... etc' "
# adding punctuation marks, numbers and English text to visual text is
# naturally also "visual" and from left to right.
#
# "Logical" directionality means the text is ordered "naturally" according to
# the order it is read. It is the responsibility of the renderer to display
# the text from right to left. A BIDI algorithm is used to place general
# punctuation marks, numbers and English text in the text.
#
# Texts in x-mac-hebrew are almost impossible to find on the Internet. From
# what little evidence I could find, it seems that its general directionality
# is Logical.
#
# To sum up all of the above, the Hebrew probing mechanism knows about two
# charsets:
# Visual Hebrew - "ISO-8859-8" - backwards text - Words and sentences are
# backwards while line order is natural. For charset recognition purposes
# the line order is unimportant (In fact, for this implementation, even
# word order is unimportant).
# Logical Hebrew - "windows-1255" - normal, naturally ordered text.
#
# "ISO-8859-8-I" is a subset of windows-1255 and doesn't need to be
# specifically identified.
# "x-mac-hebrew" is also identified as windows-1255. A text in x-mac-hebrew
# that contain special punctuation marks or diacritics is displayed with
# some unconverted characters showing as question marks. This problem might
# be corrected using another model prober for x-mac-hebrew. Due to the fact
# that x-mac-hebrew texts are so rare, writing another model prober isn't
# worth the effort and performance hit.
#
#### The Prober ####
#
# The prober is divided between two SBCharSetProbers and a HebrewProber,
# all of which are managed, created, fed data, inquired and deleted by the
# SBCSGroupProber. The two SBCharSetProbers identify that the text is in
# fact some kind of Hebrew, Logical or Visual. The final decision about which
# one is it is made by the HebrewProber by combining final-letter scores
# with the scores of the two SBCharSetProbers to produce a final answer.
#
# The SBCSGroupProber is responsible for stripping the original text of HTML
# tags, English characters, numbers, low-ASCII punctuation characters, spaces
# and new lines. It reduces any sequence of such characters to a single space.
# The buffer fed to each prober in the SBCS group prober is pure text in
# high-ASCII.
# The two SBCharSetProbers (model probers) share the same language model:
# Win1255Model.
# The first SBCharSetProber uses the model normally as any other
# SBCharSetProber does, to recognize windows-1255, upon which this model was
# built. The second SBCharSetProber is told to make the pair-of-letter
# lookup in the language model backwards. This in practice exactly simulates
# a visual Hebrew model using the windows-1255 logical Hebrew model.
#
# The HebrewProber is not using any language model. All it does is look for
# final-letter evidence suggesting the text is either logical Hebrew or visual
# Hebrew. Disjointed from the model probers, the results of the HebrewProber
# alone are meaningless. HebrewProber always returns 0.00 as confidence
# since it never identifies a charset by itself. Instead, the pointer to the
# HebrewProber is passed to the model probers as a helper "Name Prober".
# When the Group prober receives a positive identification from any prober,
# it asks for the name of the charset identified. If the prober queried is a
# Hebrew model prober, the model prober forwards the call to the
# HebrewProber to make the final decision. In the HebrewProber, the
# decision is made according to the final-letters scores maintained and Both
# model probers scores. The answer is returned in the form of the name of the
# charset identified, either "windows-1255" or "ISO-8859-8".
# windows-1255 / ISO-8859-8 code points of interest
module CharDet
FINAL_KAF = "\xea"
NORMAL_KAF = "\xeb"
FINAL_MEM = "\xed"
NORMAL_MEM = "\xee"
FINAL_NUN = "\xef"
NORMAL_NUN = "\xf0"
FINAL_PE = "\xf3"
NORMAL_PE = "\xf4"
FINAL_TSADI = "\xf5"
NORMAL_TSADI = "\xf6"
# Minimum Visual vs Logical final letter score difference.
# If the difference is below this, don't rely solely on the final letter score distance.
MIN_FINAL_CHAR_DISTANCE = 5
# Minimum Visual vs Logical model score difference.
# If the difference is below this, don't rely at all on the model score distance.
MIN_MODEL_DISTANCE = 0.01
VISUAL_HEBREW_NAME = "ISO-8859-8"
LOGICAL_HEBREW_NAME = "windows-1255"
class HebrewProber < CharSetProber
def initialize
super()
@_mLogicalProber = nil
@_mVisualProber = nil
reset()
end
def reset
@_mFinalCharLogicalScore = 0
@_mFinalCharVisualScore = 0
# The two last characters seen in the previous buffer,
# mPrev and mBeforePrev are initialized to space in order to simulate a word
# delimiter at the beginning of the data
@_mPrev = ' '
@_mBeforePrev = ' '
# These probers are owned by the group prober.
end
def set_model_probers(logicalProber, visualProber)
@_mLogicalProber = logicalProber
@_mVisualProber = visualProber
end
def is_final(c)
return [FINAL_KAF, FINAL_MEM, FINAL_NUN, FINAL_PE, FINAL_TSADI].include?(c)
end
def is_non_final(c)
# The normal Tsadi is not a good Non-Final letter due to words like
# 'lechotet' (to chat) containing an apostrophe after the tsadi. This
# apostrophe is converted to a space in FilterWithoutEnglishLetters causing
# the Non-Final tsadi to appear at an end of a word even though this is not
# the case in the original text.
# The letters Pe and Kaf rarely display a related behavior of not being a
# good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak' for
# example legally end with a Non-Final Pe or Kaf. However, the benefit of
# these letters as Non-Final letters outweighs the damage since these words
# are quite rare.
return [NORMAL_KAF, NORMAL_MEM, NORMAL_NUN, NORMAL_PE].include?(c)
end
def feed(aBuf)
# Final letter analysis for logical-visual decision.
# Look for evidence that the received buffer is either logical Hebrew or
# visual Hebrew.
# The following cases are checked:
# 1) A word longer than 1 letter, ending with a final letter. This is an
# indication that the text is laid out "naturally" since the final letter
# really appears at the end. +1 for logical score.
# 2) A word longer than 1 letter, ending with a Non-Final letter. In normal
# Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi, should not end with
# the Non-Final form of that letter. Exceptions to this rule are mentioned
# above in isNonFinal(). This is an indication that the text is laid out
# backwards. +1 for visual score
# 3) A word longer than 1 letter, starting with a final letter. Final letters
# should not appear at the beginning of a word. This is an indication that
# the text is laid out backwards. +1 for visual score.
#
# The visual score and logical score are accumulated throughout the text and
# are finally checked against each other in GetCharSetName().
# No checking for final letters in the middle of words is done since that case
# is not an indication for either Logical or Visual text.
#
# We automatically filter out all 7-bit characters (replace them with spaces)
# so the word boundary detection works properly. [MAP]
if get_state() == ENotMe
# Both model probers say it's not them. No reason to continue.
return ENotMe
end
aBuf = filter_high_bit_only(aBuf)
for cur in aBuf.split(' ')
if cur == ' '
# We stand on a space - a word just ended
if @_mBeforePrev != ' '
# next-to-last char was not a space so self._mPrev is not a 1 letter word
if is_final(@_mPrev)
# case (1) [-2:not space][-1:final letter][cur:space]
@_mFinalCharLogicalScore += 1
elsif is_non_final(@_mPrev)
# case (2) [-2:not space][-1:Non-Final letter][cur:space]
@_mFinalCharVisualScore += 1
end
end
else
# Not standing on a space
if (@_mBeforePrev == ' ') and (is_final(@_mPrev)) and (cur != ' ')
# case (3) [-2:space][-1:final letter][cur:not space]
@_mFinalCharVisualScore += 1
end
end
@_mBeforePrev = @_mPrev
@_mPrev = cur
end
# Forever detecting, till the end or until both model probers return eNotMe (handled above)
return EDetecting
end
def get_charset_name
# Make the decision: is it Logical or Visual?
# If the final letter score distance is dominant enough, rely on it.
finalsub = @_mFinalCharLogicalScore - @_mFinalCharVisualScore
if finalsub >= MIN_FINAL_CHAR_DISTANCE
return LOGICAL_HEBREW_NAME
end
if finalsub <= -MIN_FINAL_CHAR_DISTANCE
return VISUAL_HEBREW_NAME
end
# It's not dominant enough, try to rely on the model scores instead.
modelsub = @_mLogicalProber.get_confidence() - @_mVisualProber.get_confidence()
if modelsub > MIN_MODEL_DISTANCE
return LOGICAL_HEBREW_NAME
end
if modelsub < -MIN_MODEL_DISTANCE
return VISUAL_HEBREW_NAME
end
# Still no good, back to final letter distance, maybe it'll save the day.
if finalsub < 0.0
return VISUAL_HEBREW_NAME
end
# (finalsub > 0 - Logical) or (don't know what to do) default to Logical.
return LOGICAL_HEBREW_NAME
end
def get_state
# Remain active as long as any of the model probers are active.
if (@_mLogicalProber.get_state() == ENotMe) and (@_mVisualProber.get_state() == ENotMe)
return ENotMe
end
return EDetecting
end
end
end
| true
|
23317f6d4ee9151dfd161bfbb7f7e1a79f1a1c52
|
Ruby
|
cyber-dojo/start-points-base
|
/app/src/from_script/check_image_name.rb
|
UTF-8
| 1,145
| 2.8125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
require_relative 'show_error'
require_relative 'well_formed_image_name'
module CheckImageName
include ShowError
include WellFormedImageName
def check_image_name(url, filename, json, error_code)
ok = json['image_name']
ok &&= image_name_is_string(url, filename, json, error_code)
ok && image_name_is_well_formed(url, filename, json, error_code)
end
# - - - - - - - - - - - - - - - - - - - -
def image_name_is_string(url, filename, json, error_code)
result = true
image_name = json['image_name']
unless image_name.is_a?(String)
title = 'image_name is not a String'
key = quoted('image_name')
msg = "#{key}: #{image_name}"
result = error(title, url, filename, msg, error_code)
end
result
end
# - - - - - - - - - - - - - - - - - - - -
def image_name_is_well_formed(url, filename, json, error_code)
image_name = json['image_name']
unless well_formed_image_name?(image_name)
title = 'image_name is malformed'
key = quoted('image_name')
msg = "#{key}: #{quoted(image_name)}"
error(title, url, filename, msg, error_code)
end
end
end
| true
|
dc19d5a4ad095068417ae7d98b313843efdbbf29
|
Ruby
|
rranelli/advisor
|
/spec/advisor/factory_spec.rb
|
UTF-8
| 1,381
| 2.5625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
describe Advisor::Factory do
subject(:factory) { described_class.new(advice_klass) }
let(:advice_klass) do
Struct.new(:obj, :method, :call_args, :args) do
define_method(:call) { 'overridden!' }
define_singleton_method(:applier_method) { 'apply_advice_to' }
end
end
let(:advice_instance) do
advice_klass.new(advised_instance, :apply_advice_to, [], arg1: 1, arg2: 2)
end
let(:advised_klass) do
advisor = build
Struct.new(:advised_method) do
extend advisor
apply_advice_to :advised_method, arg1: 1, arg2: 2
end
end
let(:advised_instance) { advised_klass.new(33) }
before do
allow(advised_klass).to receive(:new)
.and_return(advised_instance)
allow(advice_klass).to receive(:new)
.and_return(advice_instance)
end
describe '#build' do
subject(:build) { factory.build }
it { is_expected.to be_kind_of(Module) }
describe 'when applying the advice to methods' do
subject(:invoke_advised_method) { advised_instance.advised_method }
it do
expect(advice_klass).to receive(:new)
.with(advised_instance, :advised_method, [], arg1: 1, arg2: 2)
invoke_advised_method
end
it do
expect(advice_instance).to receive(:call)
invoke_advised_method
end
it { is_expected.to eq('overridden!') }
end
end
end
| true
|
2ca18a9086cb57c023b8a81acd07ce826d6d65f4
|
Ruby
|
jtuchscherer/super-simple-load-generator
|
/load_generator.rb
|
UTF-8
| 1,197
| 2.8125
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
$stdout.sync = true
$stderr.sync = true
require 'open-uri'
require 'openssl'
base_url = ENV["base_url"]
time_start = ENV["lower_bound"]
time_end = ENV["upper_bound"]
paths = ENV["url_paths"].split(",") unless ENV["url_paths"].nil? || ENV["url_paths"].empty?
username = ENV["username"]
password = ENV["password"]
def load_generator (base_url, time_start, time_end, paths, username, password)
outstanding_requests = 0
while true do
endpoint = if paths.nil? then base_url else base_url + paths.sample() end
options = {:ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE}
unless username.nil? || password.nil?
options[:http_basic_authentication] = [username, password]
end
Thread.new do
outstanding_requests = outstanding_requests + 1
open(endpoint, options) do |response|
puts "#{response.base_uri} returned #{response.status}"
end
outstanding_requests = outstanding_requests - 1
puts "#{outstanding_requests} outstanding requests"
end
sleep rand(time_start..time_end)
end
end
load_generator(base_url, time_start.to_f, time_end.to_f, paths, username, password)
| true
|
4101b82b160d0e0e6cfb85fbbe9ab6da2d748838
|
Ruby
|
gdhaworth/lua-table_reader
|
/spec/lib/lua/table_reader/lua_parser_spec.rb
|
UTF-8
| 3,127
| 2.890625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
require 'spec_helper'
describe Lua::TableReader::LuaParser do
subject(:parser) { Lua::TableReader::LuaParser.new }
context 'when parsing tables' do
let(:rule) { parser.table }
it 'consumes empty tables' do
rule.parse('{ }')
end
context 'with only key-value pairs' do
it 'consumes simple tables' do
sample = <<-EOS
{
["foo"] = "bar baz",
["a"] = "b",
}
EOS
rule.parse(sample.strip)
sample = <<-EOS
{
["foo"] = "bar baz",
["a"] = "b"
}
EOS
rule.parse(sample.strip)
end
it 'consumes nested tables' do
sample = <<-EOS
{
["foo"] = {
["bar"] = "baz",
},
}
EOS
rule.parse(sample.strip)
end
it 'consumes a mix of key and value definitions' do
sample = File.read(File.join(File.dirname(__FILE__), 'key-value_table.lua'))
rule.parse(sample.strip)
end
end
# Other types of table data is handled in lua_transformer_spec.rb
end
context 'when parsing strings' do
let(:rule) { parser.string }
context 'with double-quotes' do
it 'consumes simple samples' do
expect(rule.parse('"foo bar"')).to include(quoted_string: "foo bar")
expect(rule.parse('"foo \'bar\' baz"')).to include(quoted_string: "foo 'bar' baz")
end
it 'consumes samples with escape sequences' do
expect(rule.parse('"The cow says \\"Moo\\""')).to include(quoted_string: 'The cow says \\"Moo\\"')
end
end
context 'with single-quotes' do
it 'consumes simple samples' do
expect(rule.parse("'Hello world!'")).to include(quoted_string: "Hello world!")
end
it 'consumes samples with escape sequences' do
expect(rule.parse("'I\\\'ve got an escape sequence!'")).to include(quoted_string: "I\\\'ve got an escape sequence!")
expect(rule.parse("'foo bar \\\'asdf\\\' baz?'")).to include(quoted_string: "foo bar \\\'asdf\\\' baz?")
end
end
context 'with multi-line delimeters' do
it 'consumes simple samples' do
expect(rule.parse('[[A single-line multi-line!]]')).to include(multiline_string: 'A single-line multi-line!')
sample = <<-EOS
[[This is a multi-line string that
actually takes up multiple lines!]]
EOS
expect(rule.parse(sample.strip)).to include(
multiline_string: "This is a multi-line string that\nactually takes up multiple lines!")
end
it 'consumes samples with padded \'=\'' do
expect(rule.parse('[=[The cake is a lie.]=]')).to include(multiline_string: 'The cake is a lie.')
expect(rule.parse('[===[sample text]===]')).to include(multiline_string: 'sample text')
expect(rule.parse('[==[ a ]=] b ]==]')).to include(multiline_string: ' a ]=] b ')
sample = <<-EOS
[=[Line 1
[[Line 2]]
Line 3]=]
EOS
expect(rule.parse(sample.strip)).to include(multiline_string: "Line 1\n[[Line 2]]\nLine 3")
end
end
end
end
| true
|
89d7f16bdf48a36b4cdf434c08645c2012ccfa7c
|
Ruby
|
lucanioi/exercism-ruby
|
/resistor-color/resistor_color.rb
|
UTF-8
| 188
| 2.515625
| 3
|
[] |
no_license
|
module ResistorColor
COLORS = %w[black brown red orange yellow
green blue violet grey white]
module_function
def color_code(color)
COLORS.index(color)
end
end
| true
|
fdcaf1c8c7492fd543062a02ff0b3bcfb9dc4704
|
Ruby
|
cwkarwisch/RB101
|
/small_problems/easy_9/exer_05.rb
|
UTF-8
| 1,096
| 4.09375
| 4
|
[] |
no_license
|
=begin
Input: string
Output: boolean
Explicit Reqs:
Returns true if all alpha characters are uppercase
False otherwise
Ignore non slphs characters
Implicit Reqs
Empty string should return true
Validate for non-string input?
- return nil
Look througyh every character in the string
- If the character is alphabetic
- IF uppercase
- go to next character
- IF NOT uppercase
return false
- IF the character is non-alphavetic, go to the next character
DEfault: returning true
=end
LC_ALPHABETIC_CHARACTERS = ('a'..'z').to_a
def all_alpha_chars_uppercase?(string)
return nil unless string.class == String
string.each_char do |char|
if LC_ALPHABETIC_CHARACTERS.include?(char)
return false
end
end
true
end
puts all_alpha_chars_uppercase?('t') == false
puts all_alpha_chars_uppercase?('T') == true
puts all_alpha_chars_uppercase?('Four Score') == false
puts all_alpha_chars_uppercase?('FOUR SCORE') == true
puts all_alpha_chars_uppercase?('4SCORE!') == true
puts all_alpha_chars_uppercase?('') == true
puts all_alpha_chars_uppercase?(45) == nil
| true
|
02c6e602de47d65ab859af089a5227d6063c464b
|
Ruby
|
scottzero/sweater_weather_api
|
/app/models/background_poro.rb
|
UTF-8
| 159
| 2.546875
| 3
|
[] |
no_license
|
class BackgroundPoro
attr_reader :id, :url
def initialize(img)
@id = img[:photos][:photo][0][:id]
@url = img[:photos][:photo][0][:url_o]
end
end
| true
|
4532340f54ee6f25098af2002ad3d6ffce3383b7
|
Ruby
|
conf/dotfiles
|
/bin/balance
|
UTF-8
| 1,051
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'httparty'
require 'nokogiri'
def osx_password(domain)
res = %x(find-internet-password #{domain}).strip.split(':')
end
def get_html
login, pass = osx_password('cabinet.st.uz')
form = { 'LoginForm' => { username: login, password: pass } }
res = HTTParty.post('https://cabinet.st.uz', body: form)
res.body
end
def parse_and_print(html)
parsed = Nokogiri::HTML(html)
account, traffic = parsed.css('.x50')[-2..-1].map { |node| node.text.split("\n").map(&:strip) }
# account info
puts account.grep(/текущ|\$/i).each_slice(2).map { |pair| pair.join(' ') }
# traffic info
lines = traffic.grep(/(Тариф|лимит|MB|Вход|Исход|Включено|ДА|НЕТ)/)
full, splitted = lines.partition { |line| line =~ /тариф|лимит/i }
tariff, limit = full.map { |line| line.gsub(/[\s\u00a0]*00:00:00 - 23:59:59/, '')}
puts '===================================='
puts tariff, limit
puts splitted.each_slice(2).map { |pair| pair.join(' ') }
end
parse_and_print(get_html)
| true
|
83f84231cc897623b659aedd43387702020e5992
|
Ruby
|
lsylvain1726/Launch_School2017
|
/methods/exercise4.rb
|
UTF-8
| 226
| 3.875
| 4
|
[] |
no_license
|
#methods exercise4.rb
def scream(words)
words = words + "!!!!"
return
puts words
end
scream("Yippeee")
#It will print nothing because the return in the
#middle of the method stops the method from
#executing any further
| true
|
b2229e051cff0f3a52acd9192d609ae5b039f358
|
Ruby
|
RailsEventStore/rails_event_store
|
/ruby_event_store/lib/ruby_event_store/correlated_commands.rb
|
UTF-8
| 918
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module RubyEventStore
class CorrelatedCommands
def initialize(event_store, command_bus)
@event_store = event_store
@command_bus = command_bus
end
class MiniEvent < Struct.new(:correlation_id, :message_id)
end
def call(command)
correlation_id = event_store.metadata[:correlation_id]
causation_id = event_store.metadata[:causation_id]
if correlation_id && causation_id
command.correlate_with(MiniEvent.new(correlation_id, causation_id)) if command.respond_to?(:correlate_with)
event_store.with_metadata(causation_id: command.message_id) { command_bus.call(command) }
else
event_store.with_metadata(correlation_id: command.message_id, causation_id: command.message_id) do
command_bus.call(command)
end
end
end
private
attr_reader :event_store, :command_bus
end
end
| true
|
8a666073920904c347cbd9dbb3d1b48ec9906600
|
Ruby
|
livash/AppAcademy_work
|
/Poker/lib/hand.rb
|
UTF-8
| 796
| 3.09375
| 3
|
[] |
no_license
|
require_relative 'deck'
require_relative 'card_suits_faces'
class Hand
include CardSuitsFaces
attr_accessor :cards
def initialize(*cards)
@cards = cards
puts "cards = #{cards.class}"
end
#private
def suits_hash
return_hash = {}
cards.each do |card|
if return_hash[card.suit].nil?
return_hash[card.suit] = 1
else
return_hash[card.suit] += 1
end
end
return_hash
end
def is_high_card?
cards.each do |card|
end
end
def is_straight_flush?
end
def is_four_kind?
end
def is_full_house?
end
def is_flush?
end
def is_straight?
end
def is_three_kind?
end
def is_two_pair?
end
def is_one_pair?
end
end
| true
|
f5de01be9636f46643eb102f5431c65f602e21d7
|
Ruby
|
rkh/travis-lite
|
/lib/travis/lite/views/repositories.rb
|
UTF-8
| 1,212
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
require 'travis/lite/views/layout'
module Travis
module Lite
module Views
class Repositories < Layout
def repositories
@repositories.map do |repository|
{
slug: repository.slug,
last_build_number: repository.last_build_number,
last_build_status: format_build_status(build_status(repository)),
row_class: class_for_build_status(build_status(repository)),
}
end
end
private
def build_status(repository)
if repository.last_build_finished?
repository.last_build_passed? ? :passed : :failed
else
:running
end
end
def format_build_status(status)
case status
when :passed
'<span class="text-success">Passed</span>'
when :failed
'<span class="text-error">Failed</span>'
when :running
'Running'
end
end
def class_for_build_status(status)
case status
when :passed
:success
when :failed
:error
end
end
end
end
end
end
| true
|
14d84b738c2c30d5cdecc8338a2a9fd3eeb164fc
|
Ruby
|
crest-cassia/ID_Module
|
/simulator/example1.rb
|
UTF-8
| 623
| 2.796875
| 3
|
[] |
no_license
|
#!/home/osaka/.rvm/rubies/ruby-1.9.3-p551/bin/ruby
require 'json'
def norm_rand(mu=0,sigma=1.0)
r1,r2=Random.rand(),Random.rand();
Math::sqrt(-1*Math::log(r1))*Math::cos(2*Math::PI*r2)*sigma+mu
end
# x0=ARGV[0].to_f
# x1=ARGV[1].to_f
# x2=ARGV[2].to_f
# x3=ARGV[3].to_f
# x4=ARGV[4].to_f
# x5=ARGV[5].to_f
# x6=ARGV[6].to_f
parsed = JSON.load(open('./_input.json'))
x0 = parsed["x0"]
x1 = parsed["x1"]
x2 = parsed["x2"]
x3 = parsed["x3"]
x4 = parsed["x4"]
x5 = parsed["x5"]
x6 = parsed["x6"]
result = { "y" => 100*x0+100*x1+100*x3*x4+norm_rand(mu=0,sigma=0.3*x5+1) }
JSON.dump(result, open('./_output.json','w'))
| true
|
870e66e6fd82c567ef64e53dea1640acefecbccf
|
Ruby
|
prashulsingh/COEN_278_Fall_2020
|
/Assignment/1/Problem5.rb
|
UTF-8
| 1,012
| 2.765625
| 3
|
[] |
no_license
|
class Webpage
attr_accessor :template
def initialize(str)
@template = str
end
def filter
newStr = ""
@template.split("\n").each do |line|
tempLine = line.strip
# ^<% starts with % ans %>$ ends with , similary ^% means start of string contains %s
if !( ( tempLine.match?(/^<%/) and tempLine.match?(/%>$/) ) or tempLine.match?(/^%/) )
newStr << line + "\n"
end
end
return newStr
end
end
# str =<<END_MARK
# <%= simple_form_for @project do |f| %>
# f.input :name %>
# <%= f.input :description %>
# <h3%>Tasks</h3>
# <div id='tasks'>
# <%= f.simple_fields_for :tasks do |task| %>
# <%= render 'task_fields', :f => task %>
# <% end %>
# <div class='links'>
# <%= link_to_add_association 'add task', f, :tasks %>
# </div>
# </div>
# <%= f.submit 'Save' >
# <% end %>
# END_MARK
# webpage = Webpage.new(str)
# print( webpage.filter() )
| true
|
0c49182e5dece5dfca32cb66bd7f8acb6fab871b
|
Ruby
|
eay/ruby-scripts
|
/projecteuler.net/euler-76-80.rb
|
UTF-8
| 5,285
| 3.3125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# Taken from http://projecteuler.net
require_relative 'primes.rb'
require_relative 'groupings.rb'
# Brute force recursive - 3m.
# This is a customised version of Integer#groupings
# There must be a better way.
# 190569291
def problem_76a
num = 100
solve = lambda do |a,off,max|
n = 0
while a[off] < max && (a.length-off) >= 2
a[off] += a.pop
n += 1
n += solve.call(a.dup,off+1,a[off]) if a.length - off > 1
end
n
end
puts 1 + solve.call([1] * num, 0,num-1)
end
# 0.05 seconds, the secret is caching :-)
# For 100, we cache 4851 values
# http://mathworld.wolfram.com/PartitionFunctionP.html
def problem_76
return 100.partitions - 1
end
# Brute force again - 4min
# There must be a better way.
def problem_77a
primes = Primes.upto(100)
# off is the offset in the prime array, we can work down :-)
solve = lambda do |a,off,max|
n = 0
while a[off] < max && (a.length-off) >= 2
a[off] += a.pop
n += 1 if (a & primes).length == a.uniq.length
n += solve.call(a.dup,off+1,a[off]) if a.length - off > 1
end
n
end
m = 0
(2..100).each do |num|
break if (m = solve.call([1] * num,0,num-1)) > 5000
puts "#{num} => #{m}"
end
m
end
# The fast version :-), 0.2sec
# I should look at
# http://mathworld.wolfram.com/EulerTransform.html
# Simplar problem to 31. Need to work from the top down,
# for 76 to speed things up
def problem_77
primes = Primes.upto(120)
# num is the value we want and
# off is the index in primes to use next
hits = 0
solve = lambda do |num, off|
return 1 if num == 0
return 0 if num == 1
ret = 0
p = primes[off]
ret += 1 if num % p == 0 # Add if a multiple
ret += solve.call(num,off-1) if off > 0
n = num / p
if n > 0 # Do each multiple
1.upto(n) do |i|
left = num - i*p
ret += solve.call(left,off-1) if off > 0 && left > 1
end
end
ret
end
#(2..100).each do |num|
num = 0
(2..100).each do |num|
off = primes.index {|i| i > num } - 1
hits = solve.call(num,off)
puts "#{num} => #{hits}"
return num if hits >= 5000
end
end
# hmm... ugly, needed the generator from
# http://en.wikipedia.org/wiki/Partition_(number_theory)
# runtime is about 6 sec.
# The trick is to cache the previous values so the sumation is quick.
# A bit of a weird generator function.
def problem_78
n = 1
p_cache = [1]
generate = lambda do |k|
ret = 0
sign = 0
Integer.generalized_pentagonals do |gp|
if k < gp
false # Need to exit ruby1.8, can't break...
else
if sign >= 0
ret += p_cache[k-gp]
else
ret -= p_cache[k-gp]
end
sign += (sign == 1) ? -3 : 1 # 4 states + + - -
end
end
p_cache[k] = ret % 100_000_000
ret
end
p = 1
loop do
r = generate.call(p)
# puts "#{p} #{generate.call(p)}"
break if r % 1_000_000 == 0
p += 1
end
p
end
# Quite simple, grab the first elements of the input triples,
# then remove any that appear in the second place.
# If there is only one, then that number is output, removed from any
# triples with it as their first element (which is must be; the remaining
# elements are shuffled up). Repeat.
# If there were 2 valid values, the algorithm needs to be re-worked.
# 73162890
#
# Another algorithm is to collect all second digits, none can be in the
# first list, use this to work out the string
def problem_79
digits = []
lines = open("keylog.txt").reduce([]) do |a,l|
a << l.chomp.split(//).map(&:to_i)
end
p = lines.transpose
loop do
first = (p[0] - p[1]).uniq
if first.length == 1
d = first[0]
digits << d
puts "Remove #{d}"
# shift off leading 'd' values
lines.select {|l| l[0] == d}.map {|l| l.shift; l.push nil }
# Rebuild out first, second, third arrays
p = lines.transpose
return digits.map(&:to_s).join if p.flatten.compact.length == 0
puts "len = #{p.flatten.compact.length}"
else
raise "Trouble - 2 candidates : #{first.inspect}, rework algorithm"
end
end
end
# Quite simple, just generate the fraction to a good level, then
# add the digits. # Use code developed in question_66
# 100 digits 0.07sec 40886
# 1000 digits 1.23sec 405200
# 10000 digits 35.36sec 4048597
#
# Some-ones solution using ruby libraries
def problem_80a(size = 100)
require 'bigdecimal'
((1..100).inject(0) do |sum,num|
if !(Math.sqrt(num)%1==0)
digits = BigDecimal.new(num.to_s).sqrt(size).to_s[2,size]
sum += digits.split(//).inject(0) do |digsum,n|
digsum + n.to_i
end
end
sum
end)
end
# Using problem_66 continious fractions
def problem_80(size = 100)
total = 0
(2..100).each do |n|
n,d = n.sqrt_frac(2*size)
next unless n
r = n * (10 ** (size * 1.1).to_i) / d
r = r.to_s[0,size].split(//).map(&:to_i).reduce(&:+)
total += r
# puts r.inspect
end
total
end
# Using base 10 sqrt
def problem_80b(size = 100)
total = 0
(2..100).each do |n|
r = n.sqrt_digits(size+1)
next if r.length == 1
r = r[0,size].reduce(&:+)
total += r
# puts "#{n} #{r.inspect}"
end
total
end
if __FILE__ == $0
p problem_79
end
| true
|
1bdcf5c9beb37e349d36c48e35f085c546b7920c
|
Ruby
|
RafaelAlonso/batch-446-mvc-class
|
/view.rb
|
UTF-8
| 352
| 3.21875
| 3
|
[] |
no_license
|
class View
def ask_task_name_for_user
# perguntar para o usuário qual o nome da task que ele quer adicionar
puts "Qual o nome da tarefa que deseja adicionar, mestre?"
return gets.chomp
end
def show_all_tasks(all_tasks)
all_tasks.each_with_index do |task, pos|
puts "#{pos + 1} - #{task.name}"
end
end
end
| true
|
a38da056cc6b80110ceb8d2f4e2edc6df7e4908c
|
Ruby
|
salmanhoque/ruby_oop_rspec_test
|
/rspec/test_movie.rb
|
UTF-8
| 931
| 3.015625
| 3
|
[] |
no_license
|
require File.expand_path('lib/movie.rb')
require File.expand_path('lib/store.rb')
describe "#MovieClass" do
describe "initilizing the movie class" do
before :each do
@a = Movie.new("Super Man",2013,8.5)
end
context "its a movie instance" do
it { @a.should be_an_instance_of Movie }
end
context "its should have movie_name, release_date and rating attribute" do
it { @a.should respond_to :movie_name, :release_date, :rating}
end
end
describe "Should able to store data into file" do
before :each do
@a = [ "Super Man",2013,8.5 ]
Store.set_file = 'movie.txt'
end
context "by using add_movie method" do
it { Movie.add_movie(@a).should be_true }
end
end
describe "Should able to restore data from file" do
before :each do
Store.set_file = 'movie.txt'
end
context "by using get_all_movies method" do
it { Movie.get_all_movies.should be_kind_of(Array) }
end
end
end
| true
|
c9e41fd577233e5a072e167b9620a7f0df2b156f
|
Ruby
|
n0918k/Dokosukagram
|
/spec/models/user_spec.rb
|
UTF-8
| 3,158
| 2.53125
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー登録' do
context 'ユーザー登録できるとき' do
it '全て入力されていたら登録できる' do
expect(@user).to be_valid
end
end
context 'ユーザー登録できないとき' do
it 'ニックネームがないと登録できない' do
@user.nickname = nil
@user.valid?
expect(@user.errors.full_messages).to include('ニックネームを入力してください')
end
it 'メールアドレスがなければ登録できない' do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include('Eメールを入力してください')
end
it 'メールアドレスに@がないと登録できない' do
@user.email = '1111111'
@user.valid?
expect(@user.errors.full_messages).to include('Eメールは不正な値です')
end
it 'メールアドレスが重複していたら登録できない' do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include('Eメールはすでに存在します')
end
it 'パスワードが空だと登録できない' do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include('パスワードを入力してください')
end
it 'パスワードに全角が含まれていると登録できない' do
@user.password = '123CCC'
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは不正な値です')
end
it 'パスワードが5文字以下と登録できない' do
@user.password = '11111'
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは6文字以上で入力してください')
end
it 'パスワードが全て数字だと登録できない' do
@user.password = '111111'
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは不正な値です')
end
it 'パスワードが全て英字だと登録できない' do
@user.password = 'aaaaaa'
@user.valid?
expect(@user.errors.full_messages).to include('パスワードは不正な値です')
end
it 'パスワード確認用が空だと登録できない' do
@user.password_confirmation = ''
@user.valid?
expect(@user.errors.full_messages).to include('パスワード(確認用)とパスワードの入力が一致しません')
end
it 'パスワード確認用がパスワードと異なると登録できない' do
@user.password_confirmation = '12adfgh'
@user.valid?
expect(@user.errors.full_messages).to include('パスワード(確認用)とパスワードの入力が一致しません')
end
end
end
end
| true
|
1cf8992363a88e445fb38b1085b89eec5aa3e840
|
Ruby
|
mqgmaster/uam-eps-das
|
/Exe1/Exe1/domain/message/ConferenceMessage.rb
|
UTF-8
| 422
| 3
| 3
|
[] |
no_license
|
require "domain/message/Message"
#conferenceDate
#conferenceLocation
class ConferenceMessage < Message
def initialize(author, topic, date, location)
super(author, topic)
@conferenceDate = date
@conferenceLocation = location
end
def to_s
return super.to_s +
" | Fecha de la reunión: " + @conferenceDate.to_s +
" | Ubicación de la reunión: " + @conferenceLocation
end
end
| true
|
cd5fc9ecce15fea719a303eac73cb9e018403688
|
Ruby
|
getschomp/email_scraper
|
/lib/email_scraper_app/email_collection.rb
|
UTF-8
| 330
| 2.828125
| 3
|
[] |
no_license
|
require 'valid_email'
class EmailCollection
attr_reader :all
def initialize
@all = []
end
def all=(collection)
@all = collection
validate_email_domains
end
def validate_email_domains
@all.select! do |email|
ValidateEmail.valid?(email)
ValidateEmail.mx_valid?(email)
end
end
end
| true
|
4e8f8b0f19f74ef7b13bfde107123b082b7cf45b
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz51_sols/solutions/Anthony Moralez/discard_player.rb
|
UTF-8
| 329
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
class DiscardPlayer < Player
def initialize
@data = ""
super
end
def show( game_data )
@data << game_data
end
def move
if @data.include?("Draw from?")
"n"
else
if @data =~ /Hand: (.+?)\s*$/
"d#{$1.split.first.sub(/nv/,"")}"
end
end
ensure
@data = ""
end
end
| true
|
409a8018c10802cb34c8bbb32a42ed113564891b
|
Ruby
|
KillerDesigner/mzl
|
/spec/collections_spec.rb
|
UTF-8
| 4,906
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe 'Class.mzl' do
let(:klass) { Class.new { mzl.override_new } }
let(:child_klass) {
Class.new(klass) do
mzl.def(:i_am) { |val| @identity = val }
mzl.def(:who_am_i?, persist: true) { @identity }
def initialize(opts = {}) @opts = opts; end
attr_reader :opts
end
}
describe '.array' do
let(:parent_klass) {
klass.mzl.array(:thing, child_klass)
klass
}
it 'defines a method to add a child to an array' do
instance = parent_klass.new do
thing
end
instance.should respond_to(:things)
instance.should_not respond_to(:thing)
instance.things.should be_a(Array)
instance.things.size.should == 1
expect { instance.mzl {
4.times { thing }
}}.to change { instance.things.size }.by(4)
end
it 'stores childs in an array' do
parent_klass.new do
5.times { thing }
end
end
it 'stores values' do
parent_klass.new do
5.times { |i| thing { i_am i } }
end.things.collect(&:who_am_i?).should == [0, 1, 2, 3, 4]
end
it 'can be empty' do
parent_klass.new.things.should == []
end
it 'can be nested' do
inner = Class.new(child_klass)
middle = Class.new(child_klass) { mzl.array(:thing, inner) }
outer = Class.new(klass) { mzl.array(:thing, middle) }
instance = outer.new do
thing do
thing { i_am :one_one }
thing { i_am :one_two }
end
thing do
thing { i_am :two_one }
thing { i_am :two_two }
end
end
instance.things.first.things.last.who_am_i?.should == :one_two
instance.things.last.things.first.who_am_i?.should == :two_one
end
it 'can be mzl-only' do
klass.mzl.array(:thing, child_klass, persist: false)
instance = klass.new do
thing { i_am :me }
things[0].who_am_i?.should == :me
end
instance.should_not respond_to(:things)
instance.instance_variable_get(:@things)[0].who_am_i?.should == :me
end
end
describe '.hash' do
let(:parent_klass) {
klass.mzl.hash(:thing, child_klass)
klass
}
it 'defines a method to add a child to a hash with a key' do
instance = parent_klass.new do
thing(:one) { i_am :first_thing }
thing(:two) { i_am :second_thing }
end
instance.things.should be_a(Hash)
instance.things.size.should == 2
instance.things.keys.should == [:one, :two]
instance.things[:one].who_am_i?.should == :first_thing
instance.things[:two].who_am_i?.should == :second_thing
end
it 'allows arbitrary keys and values' do
instance = parent_klass.new do
thing(:one) { i_am :thing_one }
thing('one') { i_am 'thing_one' }
end
instance.things.size.should == 2
instance.things.keys.should == [:one, 'one']
instance.things[:one].who_am_i?.should == :thing_one
instance.things['one'].who_am_i?.should == 'thing_one'
end
it 'can be nested' do
inner = Class.new(child_klass)
middle = Class.new(child_klass) { mzl.hash(:thing, inner) }
outer = Class.new(klass) { mzl.hash(:thing, middle) }
instance = outer.new do
thing :one do
thing(:one_one) { i_am :one_one }
thing(:one_two) { i_am :one_two }
end
thing :two do
thing(:two_one) { i_am :two_one }
thing(:two_two) { i_am :two_two }
end
end
instance.things[:one].things[:one_one].who_am_i?.should == :one_one
instance.things[:two].things[:two_two].who_am_i?.should == :two_two
end
it 'passes options to instantiated item in hash' do
thing_class = Class.new(klass) do
attr_reader :args
def initialize(args)
@args = args
end
end
parent = Class.new(klass) do
mzl.hash(:thing, thing_class)
end
instance = parent.new do
thing :one, :this => 'that'
thing :two, :these => 'those'
end
instance.things[:one].args.should == {this: 'that'}
instance.things[:two].args.should == {these: 'those'}
end
end
describe 'collection opacity' do
let(:parent_klass) { Class.new(klass) {
mzl.def(:foo) { |val| @foo = val }
}}
it 'works as expected' do
opaque_parent, transparent_parent = 2.times.collect { Class.new(parent_klass) }
opaque_parent.mzl.array(:thing, child_klass, :opaque)
transparent_parent.mzl.array(:thing, child_klass)
expect {
opaque_parent.new do
thing do
foo :bar
end
end
}.to raise_exception
instance = transparent_parent.new do
thing do
foo :bar
end
end
instance.instance_variable_get(:@foo).should == :bar
end
end
end
| true
|
9addccc444e9fa6c1b63fda27bb559101d313ef8
|
Ruby
|
paulorades/synthea
|
/lib/generic/logic.rb
|
UTF-8
| 8,758
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
module Synthea
module Generic
module Logic
class Condition
include Synthea::Generic::Metadata
include Synthea::Generic::Hashable
metadata 'condition_type', ignore: true
def initialize(condition)
from_hash(condition)
end
def compare(lhs, rhs, operator)
case operator
when '<'
return lhs < rhs
when '<='
return lhs <= rhs
when '=='
return lhs == rhs
when '>='
return lhs >= rhs
when '>'
return lhs > rhs
when '!='
return lhs != rhs
when 'is nil'
return lhs.nil?
when 'is not nil'
return !lhs.nil?
else
raise "Unsupported operator: #{operator}"
end
end
def find_referenced_type(entity, name)
if codes
# based on state.symbol
codes.first.display.gsub(/\s+/, '_').downcase.to_sym
elsif referenced_by_attribute
entity[referenced_by_attribute] || entity[referenced_by_attribute.to_sym]
else
raise "#{name} condition must be specified by code or attribute"
end
end
end
class GroupedCondition < Condition
attr_accessor :conditions
required_field :conditions
metadata 'conditions', type: 'Logic::Condition', polymorphism: { key: 'condition_type', package: 'Logic' }, min: 1, max: Float::INFINITY
end
class And < GroupedCondition
def test(context, time, entity)
conditions.each do |c|
return false unless c.test(context, time, entity)
end
true
end
end
class Or < GroupedCondition
def test(context, time, entity)
conditions.each do |c|
return true if c.test(context, time, entity)
end
false
end
end
class AtLeast < GroupedCondition
attr_accessor :minimum
required_field :minimum
def test(context, time, entity)
minimum <= conditions.count { |c| c.test(context, time, entity) }
end
end
class AtMost < GroupedCondition
attr_accessor :maximum
required_field :maximum
def test(context, time, entity)
maximum >= conditions.count { |c| c.test(context, time, entity) }
end
end
class Not < Condition
attr_accessor :condition
required_field :condition
metadata 'condition', type: 'Logic::Condition', polymorphism: { key: 'condition_type', package: 'Logic' }, min: 1, max: 1
def test(context, time, entity)
!condition.test(context, time, entity)
end
end
class Gender < Condition
attr_accessor :gender
required_field :gender
def test(_context, _time, entity)
gender == entity[:gender]
end
end
class Age < Condition
attr_accessor :quantity, :unit, :operator
required_field and: [:quantity, :unit, :operator]
def test(_context, time, entity)
birthdate = entity.event(:birth).time
age = Synthea::Modules::Lifecycle.age(time, birthdate, nil, unit.to_sym)
compare(age, quantity, operator)
end
end
class SocioeconomicStatus < Condition
attr_accessor :category
required_field :category
def test(_context, _time, entity)
raise "Unsupported category: #{category}" unless %w(High Middle Low).include?(category)
ses_category = Synthea::Modules::Lifecycle.socioeconomic_category(entity)
compare(ses_category, category, '==')
end
end
class Race < Condition
attr_accessor :race
required_field :race
def test(_context, _time, entity)
race.downcase.to_sym == entity[:race]
end
end
class Date < Condition
attr_accessor :year, :operator
required_field and: [:year, :operator]
def test(_context, time, _entity)
compare(time.year, year, operator)
end
end
class Attribute < Condition
attr_accessor :attribute, :value, :operator
required_field and: [:attribute, :operator] # value is allowed to be omitted if operator is 'is nil'
def test(_context, _time, entity)
entity_value = entity[attribute] || entity[attribute.to_sym]
compare(entity_value, value, operator)
end
end
class Symptom < Condition
attr_accessor :symptom, :value, :operator
required_field and: [:symptom, :value, :operator]
def test(_context, _time, entity)
compare(entity.get_symptom_value(symptom), value, operator)
end
end
class Observation < Condition
attr_accessor :codes, :referenced_by_attribute, :operator, :value
required_field and: [:operator, or: [:codes, :referenced_by_attribute]] # value is allowed to be omitted if operator is 'is nil'
metadata 'codes', type: 'Components::Code', min: 0, max: Float::INFINITY
def test(_context, _time, entity)
# find the most recent instance of the given observation
obstype = find_referenced_type(entity, 'Observation')
obs = entity.record_synthea.observations.select { |o| o['type'] == obstype }
if obs.empty?
if ['is nil', 'is not nil'].include?(operator)
compare(nil, value, operator)
else
raise "No observations exist for type #{obstype}, cannot compare values"
end
else
compare(obs.last['value'], value, operator)
end
end
end
class VitalSign < Condition
attr_accessor :vital_sign, :value, :operator
required_field and: [:vital_sign, :operator] # value is allowed to be omitted if operator is 'is nil'
def test(_context, _time, entity)
vs = entity.vital_sign(vital_sign) || {}
compare(vs[:value], value, operator)
end
end
class ActiveCondition < Condition
attr_accessor :codes, :referenced_by_attribute
required_field or: [:codes, :referenced_by_attribute]
metadata 'codes', type: 'Components::Code', min: 0, max: Float::INFINITY
def test(_context, _time, entity)
contype = find_referenced_type(entity, 'Active Condition')
entity.record_synthea.present[contype]
end
end
class ActiveAllergy < Condition
attr_accessor :codes, :referenced_by_attribute
required_field or: [:codes, :referenced_by_attribute]
metadata 'codes', type: 'Components::Code', min: 0, max: Float::INFINITY
def test(_context, _time, entity)
contype = find_referenced_type(entity, 'Active Allergy')
entity.record_synthea.present[contype]
end
end
class PriorState < Condition
attr_accessor :name, :since, :within
required_field :name
metadata 'name', reference_to_state_type: 'State', min: 1, max: 1
metadata 'since', reference_to_state_type: 'State', min: 0, max: 1
metadata 'within', type: 'Components::ExactWithUnit', min: 0, max: 1
def test(context, time, _entity)
context.history.reverse_each do |h|
return false if within && h.exited && h.exited < (time - within.value)
return true if h.name == name
return false if h.name == since
end
false
end
end
class ActiveCareplan < Condition
attr_accessor :codes, :referenced_by_attribute
required_field or: [:codes, :referenced_by_attribute]
metadata 'codes', type: 'Components::Code', min: 0, max: Float::INFINITY
def test(_context, _time, entity)
contype = find_referenced_type(entity, 'Active Careplan')
entity.record_synthea.careplan_active?(contype)
end
end
class ActiveMedication < Condition
attr_accessor :codes, :referenced_by_attribute
required_field or: [:codes, :referenced_by_attribute]
metadata 'codes', type: 'Components::Code', min: 0, max: Float::INFINITY
def test(_context, _time, entity)
medtype = find_referenced_type(entity, 'Active Medication')
entity.record_synthea.medication_active?(medtype)
end
end
class True < Condition
def test(_context, _time, _entity)
true
end
end
class False < Condition
def test(_context, _time, _entity)
false
end
end
end
end
end
| true
|
272c1b229c67a88ba4f6526491f7d92b12d52657
|
Ruby
|
lazoxco/national_parks_california
|
/lib/national_parks_california/cli.rb
|
UTF-8
| 314
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
class NationalParksCalifornia::CLI
def call
puts "Welcome to the National Parks Gem"
puts "You can look up National Parks by State.\n"
puts "Please pick a state to learn more about it's National Parks:"
list_states
end
def list_states
State.all
end
end
| true
|
6ff056b53f46b47a6fdb6f2c76a169b1dc925586
|
Ruby
|
marlonsingleton/crimson-stone
|
/practice/ttt_game.rb
|
UTF-8
| 4,913
| 4
| 4
|
[] |
no_license
|
class CellMoves
attr_accessor :moves, :human_wins, :computer_wins
def initialize
@moves = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
@human_wins = ["X", "X", "X"]
@computer_wins = ["O", "O", "O"]
end
end
class Board < CellMoves
def ttt_board
puts ""
puts " #{moves[0]} | #{moves[1]} | #{moves[2]} "
puts "-----------"
puts " #{moves[3]} | #{moves[4]} | #{moves[5]} "
puts "-----------"
puts " #{moves[6]} | #{moves[7]} | #{moves[8]} "
puts ""
end
end
class Plays < Board
attr_accessor = :row, :cell
def computer_selection
random = (0..8).to_a.sample
if moves[random] == " "
moves[random] = "O"
else
self.computer_selection
end
end
def human_selection
puts "Please choose a row(1, 2 or 3)!"
@row = gets.chomp
self.good_row?
end
def cell_selection
puts "Please select (l)eft, (m)iddle or (r)ight cell."
@cell = gets.chomp.downcase
self.good_cell?
end
def good_row?
if ("123").include?(@row) && @row.size == 1
self.cell_selection
else
puts "Not valid, try again!"
puts ""
self.human_selection
end
end
def good_cell?
if ("lmr").include?(@cell) && @cell.size == 1
self.decide_row
else
puts "Not valid, try again!"
puts ""
self.cell_selection
end
end
def decide_row
# will rethink this logic when refactoring
if @row == "1" && moves[0, 3].include?(" ")
self.row_one
elsif @row == "2" && moves[3, 3].include?(" ")
self.row_two
elsif @row == "3" && moves[6, 3].include?(" ")
self.row_three
else
puts "That row is full!"
self.human_selection
end
end
def row_one
copy = moves[0, 3]
moves[0] = "X" if @cell == "l" && moves[0] == " "
moves[1] = "X" if @cell == "m" && moves[1] == " "
moves[2] = "X" if @cell == "r" && moves[2] == " "
puts "That move is taken!" if copy == moves[0, 3]
self.human_selection if copy == moves[0, 3]
end
def row_two
copy = moves[3, 3]
moves[3] = "X" if @cell == "l" && moves[3] == " "
moves[4] = "X" if @cell == "m" && moves[4] == " "
moves[5] = "X" if @cell == "r" && moves[5] == " "
puts "That move is taken!" if copy == moves[3, 3]
self.human_selection if copy == moves[3, 3]
end
def row_three
copy = moves[6, 3]
moves[6] = "X" if @cell == "l" && moves[6] == " "
moves[7] = "X" if @cell == "m" && moves[7] == " "
moves[8] = "X" if @cell == "r" && moves[8] == " "
puts "That move is taken!" if copy == moves[6, 3]
self.human_selection if copy == moves[6, 3]
end
end
class Game < Plays
attr_accessor :human, :computer
attr_reader :welcome
def welcome
system "clear"
puts "Welcome to Tic Tac Toe!"
puts ""
self.ask_names
system "clear"
puts "Greetings #{@human}! Your opponent is #{@computer}!"
puts "Let's begin!"
end
def ask_names
puts "What is your name?"
@human = gets.chomp.capitalize
@computer = ["Mark V", "Sonny", "Hal", "Linux"].sample
end
def all_outcomes
return true if self.human_outcomes
return true if self.computer_outcomes
return true if self.board_full
end
def human_outcomes
# will try to refactor and enumerate possible outcomes
return true if moves[0, 3] == @human_wins
return true if moves[3, 3] == @human_wins
return true if moves[6, 3] == @human_wins
return true if moves.values_at(0, 3, 6) == @human_wins
return true if moves.values_at(1, 4, 7) == @human_wins
return true if moves.values_at(2, 5, 8) == @human_wins
return true if moves.values_at(0, 4, 8) == @human_wins
return true if moves.values_at(2, 4, 6) == @human_wins
end
def computer_outcomes
# will try to refactor and enumerate possible outcomes
return true if moves[0, 3] == @computer_wins
return true if moves[3, 3] == @computer_wins
return true if moves[6, 3] == @computer_wins
return true if moves.values_at(0, 3, 6) == @computer_wins
return true if moves.values_at(1, 4, 7) == @computer_wins
return true if moves.values_at(2, 5, 8) == @computer_wins
return true if moves.values_at(0, 4, 8) == @computer_wins
return true if moves.values_at(2, 4, 6) == @computer_wins
end
def board_full
return true if moves.include?(" ") == false
end
def who_won?
puts "#{@human}, You won!" if human_outcomes
puts "#{@computer} won!" if computer_outcomes
if human_outcomes == nil && computer_outcomes == nil
puts "It's a draw!"
end
end
def goodbye
puts "Thanks for playing!"
end
def play
welcome
loop do
ttt_board
human_selection
break if all_outcomes
computer_selection
system "clear"
break if all_outcomes
end
system "clear"
ttt_board
who_won?
goodbye
end
end
game = Game.new
game.play
| true
|
32e0006f872b0b50dbb1a2bd56b40831597dfc7e
|
Ruby
|
khoomelvin/bitrise-step-ipa-info
|
/step.rb
|
UTF-8
| 4,612
| 2.78125
| 3
|
[] |
no_license
|
require 'json'
require 'ipa_analyzer'
require 'optparse'
require 'zip'
require 'zip/filesystem'
require 'pngdefry'
# -----------------------
# --- functions
# -----------------------
def fail_with_message(message)
puts "\e[31m#{message}\e[0m"
exit(1)
end
def get_ios_ipa_info(ipa_path)
parsed_ipa_infos = {
mobileprovision: nil,
info_plist: nil
}
ipa_analyzer = IpaAnalyzer::Analyzer.new(ipa_path)
begin
ipa_analyzer.open!
parsed_ipa_infos[:mobileprovision] = ipa_analyzer.collect_provision_info
parsed_ipa_infos[:info_plist] = ipa_analyzer.collect_info_plist_info
fail 'Failed to collect Info.plist information' if parsed_ipa_infos[:info_plist].nil?
rescue => ex
puts
puts "Failed: #{ex}"
puts
raise ex
ensure
puts ' => Closing the IPA'
ipa_analyzer.close
end
ipa_file_size = File.size(ipa_path)
icon_zip_path = ''
ipa_zipfile = Zip::File.open(ipa_path)
ipa_zipfile.dir.entries("Payload").each do |dir_entry|
ipa_zipfile.dir.entries("Payload/#{dir_entry}").each do |file_entry|
if file_entry =~ /^AppIcon.*png$/
icon_zip_path = "Payload/#{dir_entry}/#{file_entry}"
end
end
end
if !icon_zip_path.empty?
icon_file_path = "#{File.dirname(ipa_path)}/icon.png"
ipa_zipfile.extract(icon_zip_path, icon_file_path){ override = true }
Pngdefry.defry(icon_file_path, icon_file_path)
end
info_plist_content = parsed_ipa_infos[:info_plist][:content]
mobileprovision_content = parsed_ipa_infos[:mobileprovision][:content]
ipa_info_hsh = {
file_size_bytes: ipa_file_size,
icon_path: icon_file_path,
app_info: {
app_title: info_plist_content['CFBundleName'],
app_display_name: info_plist_content['CFBundleDisplayName'],
bundle_id: info_plist_content['CFBundleIdentifier'],
version: info_plist_content['CFBundleShortVersionString'],
build_number: info_plist_content['CFBundleVersion'],
min_OS_version: info_plist_content['MinimumOSVersion'],
device_family_list: info_plist_content['UIDeviceFamily']
},
provisioning_info: {
creation_date: mobileprovision_content['CreationDate'],
expire_date: mobileprovision_content['ExpirationDate'],
team_name: mobileprovision_content['TeamName'],
profile_name: mobileprovision_content['Name'],
provisions_all_devices: mobileprovision_content['ProvisionsAllDevices'],
}
}
puts "=> IPA Info: #{ipa_info_hsh}"
return ipa_info_hsh
end
# ----------------------------
# --- Options
options = {
ipa_path: nil,
}
parser = OptionParser.new do|opts|
opts.banner = 'Usage: step.rb [options]'
opts.on('-a', '--ipapath PATH', 'IPA Path') { |d| options[:ipa_path] = d unless d.to_s == '' }
opts.on('-h', '--help', 'Displays Help') do
exit
end
end
parser.parse!
fail_with_message('No ipa_path provided') unless options[:ipa_path]
options[:ipa_path] = File.absolute_path(options[:ipa_path])
if !Dir.exist?(options[:ipa_path]) && !File.exist?(options[:ipa_path])
fail_with_message('IPA path does not exist: ' + options[:ipa_path])
end
puts "=> IPA path: #{options[:ipa_path]}"
# ----------------------------
# --- Main
begin
ipa_info_hsh = ""
if options[:ipa_path].match('.*.ipa')
ipa_info_hsh = get_ios_ipa_info(options[:ipa_path])
end
# - Success
fail 'Failed to export IOS_IPA_PACKAGE_NAME' unless system("envman add --key IOS_IPA_PACKAGE_NAME --value '#{ipa_info_hsh[:app_info][:bundle_id]}'")
fail 'Failed to export IOS_IPA_FILE_SIZE' unless system("envman add --key IOS_IPA_FILE_SIZE --value '#{ipa_info_hsh[:file_size_bytes]}'")
fail 'Failed to export IOS_APP_NAME' unless system("envman add --key IOS_APP_NAME --value '#{ipa_info_hsh[:app_info][:app_title]}'")
fail 'Failed to export IOS_APP_DISPLAY_NAME' unless system("envman add --key IOS_APP_DISPLAY_NAME --value '#{ipa_info_hsh[:app_info][:app_display_name]}'")
fail 'Failed to export IOS_APP_VERSION_NAME' unless system("envman add --key IOS_APP_VERSION_NAME --value '#{ipa_info_hsh[:app_info][:version]}'")
fail 'Failed to export IOS_APP_VERSION_CODE' unless system("envman add --key IOS_APP_VERSION_CODE --value '#{ipa_info_hsh[:app_info][:build_number]}'")
fail 'Failed to export IOS_ICON_PATH' unless system("envman add --key IOS_ICON_PATH --value '#{ipa_info_hsh[:icon_path]}'")
fail 'Failed to export IOS_APP_PROFILE_NAME' unless system("envman add --key IOS_APP_PROFILE_NAME --value '#{ipa_info_hsh[:provisioning_info][:profile_name]}'")
rescue => ex
fail_with_message(ex)
end
exit 0
| true
|
3733d78ff155aa66b40e08c104a65764551a4d97
|
Ruby
|
Seraff/pandoraea
|
/ko_parser.rb
|
UTF-8
| 1,404
| 3.0625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require 'csv'
class Organism
attr_accessor :name, :kos
def initialize(name)
@name = name
@kos = []
load_data
end
def load_data
f = File.open(filename, 'r')
result = []
f.read.each_line do |line|
ko = parse_ko(line)
result << ko if ko
end
@kos = result.compact.uniq
end
protected
def parse_ko(line)
splitted = line.split(/\s+/)
splitted[1].downcase == 'no' ? nil : splitted[1]
end
def filename
"data/#{name}"
end
end
class Novymonadis < Organism
protected
def parse_ko(line)
line.split(/\s+/)[1]
end
def filename
"data/pandoraea_novymonadis.ko"
end
end
KEGG_ORGANISMS = ['T02936',
'T03067',
'T03411',
'T02950',
'T03553',
'T03554',
'T03588',
'T03688',
'T03840',
'T03947',
'T03972',
'T04226']
organisms = []
KEGG_ORGANISMS.each do |org|
organisms << Organism.new(org)
end
organisms << Novymonadis.new('P_NOV')
all_kos = organisms.map(&:kos).flatten.uniq
CSV.open("output.csv", "wb") do |csv|
csv << [nil] + organisms.map(&:name)
all_kos.each do |ko|
row = [ko]
organisms.each do |org|
row << (org.kos.include?(ko) ? '1' : '0')
end
csv << row
end
end
| true
|
c9f2c4b687ea7e12dde1b1f2297aaa5c6eadea59
|
Ruby
|
davemaurer/ruby-practice
|
/turing_resources/mythical-creatures/medusa/person.rb
|
UTF-8
| 227
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
require_relative 'medusa'
class Person
attr_reader :name
attr_accessor :victims
def initialize(name)
@name = name
@stoned = false
@victims = []
end
def stoned?
@victims.include?(self)
end
end
| true
|
7b9f9e75606fc696a5fe755d413ccc212c86031d
|
Ruby
|
bloopletech/retryable
|
/lib/reretryable.rb
|
UTF-8
| 631
| 2.796875
| 3
|
[] |
no_license
|
module Retryable
def retryable(options = {}, &block)
opts = { :tries => 1,
:on => StandardError,
:sleep => 0,
:matching => /.*/ }.merge(options)
return nil if opts[:tries] == 0
retry_exception = [opts[:on]].flatten
tries = opts[:tries]
message_pattern = opts[:matching]
sleep_time = opts[:sleep]
begin
return yield
rescue *retry_exception => exception
raise unless exception.message =~ message_pattern
if (tries -= 1) > 0
sleep sleep_time
retry
end
end
yield
end
end
| true
|
33c45c2b1fbfac30bf6d6a9e65bb05543760cc36
|
Ruby
|
jalyna/oakdex-pokemon
|
/lib/oakdex/pokemon/growth_events/base.rb
|
UTF-8
| 671
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'forwardable'
class Oakdex::Pokemon
module GrowthEvents
# Represents Base GrowthEvent
class Base
def initialize(pokemon, options = {})
@pokemon = pokemon
@options = options
end
def read_only?
possible_actions.empty?
end
def possible_actions
[]
end
def message
raise 'implement me'
end
def execute(_action = nil)
remove_event
end
def to_h
{
name: self.class.name,
options: @options
}
end
private
def remove_event
@pokemon.remove_growth_event
end
end
end
end
| true
|
0347aa8a731cfa2b9fb90eaea4722d45bfc732dd
|
Ruby
|
nbielak/event_site
|
/db/seeds.rb
|
UTF-8
| 12,101
| 2.625
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Event.delete_all
User.delete_all
Ticket.delete_all
Category.delete_all
EventCategory.delete_all
#USERS
demo = User.create!(
email: "demo@demo.com",
password: "123456",
first_name: "Demo",
last_name: "Demosthenes"
)
nick = User.create!(
email: "nick@nick.com",
password: "123123",
first_name: "Nick",
last_name: "Nick"
)
john = User.create!(
email: "john@john.com",
password: "123123",
first_name: "John",
last_name: "Doe"
)
jane = User.create!(
email: "jane@jane.com",
password: "123123",
first_name: "Jane",
last_name: "Doe"
)
sahar = User.create!(
email: "sahar@sahar.com",
password: "123123",
first_name: "Sahar",
last_name: "Sahar"
)
# Categories
music = Category.create!(
name: "Music",
description: "Sound!"
)
party = Category.create!(
name: "Party",
description: "Fun!"
)
food = Category.create!(
name: "Food & Drink",
description: "Yum!"
)
arts = Category.create!(
name: "Arts",
description: "Wow!"
)
business = Category.create!(
name: "Business",
description: "Networking!"
)
health = Category.create!(
name: "Health",
description: "Good!"
)
#EVENTS & EVENT_CATEGORIES
a = Event.new(
title: "It's Sahar's Birthday",
description: "Come to Memorial Glade this Tuesday for an event you aren't likely to forget! Once a year, we get a chance to celebrate Sahar and all that she has accomplished, and the time has finally come.
There will be Cheeseboard pizza provided, but come early because we will run out",
venue_name: "Memorial Glade",
address: "University Drive",
city: "Berkeley",
state: "CA",
zip: "94708",
country: "United States of America",
start_time: Time.parse("23:00"),
start_date: Date.parse("August 21"),
organizer_name: "Nick",
organizer_description: "Nick loves throwing events for Sahar!",
user_id: nick[:id]
)
photofile = File.open("app/assets/images/birthday.jpg")
a.photo.attach(io: photofile, filename: "birthday.jpg")
a.save!
EventCategory.create!(
event_id: a.id,
category_id: party.id
)
b = Event.new(
title: "San Francisco Pirate Party",
description: "Yo Ho Ho! While the 1700s were by far one of the best centuries of our existence. The sea-faring fashion was uhh-mayy-zing. The lingo was super dope, savvy? And the shanty's were better than watching a landlubber get hornswaggled. So don't be an old Sea Dog, flying the yellow jack! Stike ye colors, splice the mainbrace, and grab a pint o' grog! Even the old salts will be three sheets to the wind, ye scallywag!
Network with the Scourges of the Seven Seas themselves, and win a chance to visit Davey Jones' Locker! So bring that spring upon 'er, and batten down the hatches for one great party, bucko!",
venue_name: "The Docks",
address: "1 Dock Place",
city: "San Francisco",
state: "CA",
zip: "94321",
country: "United States of America",
start_time: Time.parse("14:00"),
start_date: Date.parse("September 30"),
organizer_name: "Jolly Roger Industries",
organizer_description: "Helping worthless maggots go on account since 1646!",
user_id: nick[:id]
)
photofile = File.open("app/assets/images/map.jpg")
b.photo.attach(io: photofile, filename: "map.jpg")
b.save!
EventCategory.create!(
event_id: b.id,
category_id: party.id
)
c = Event.new(
title: "Kitten Parade",
description: "All of the Kittens in San Francisco will be parading through the city this Sunday. The parade will start on the golden gate bridge, and from there, they will disperse in any direction they choose! This year, we will be providing laser pointers to all attendees in an effort to keep the parade more cohesive!",
venue_name: "The Golden Gate Bridge",
address: "321 Golden Gate Bridge Boulevard",
city: "San Francisco",
state: "CA",
zip: "94117",
country: "United States of America",
start_time: Time.parse("02:00"),
start_date: Date.parse("August 19"),
organizer_name: "The SPCA",
organizer_description: "CATS CATS CATS",
user_id: jane[:id]
)
photofile = File.open("app/assets/images/kittens.jpg")
c.photo.attach(io: photofile, filename: "kittens.jpg")
c.save!
EventCategory.create!(
event_id: c.id,
category_id: arts.id
)
d = Event.new(
title: "Dance Party",
description: "Dance the night away!",
venue_name: "Church of 8 Wheels",
address: "554 Fillmore St",
city: "San Francisco",
state: "CA",
zip: "94117",
country: "United States of America",
start_time: Time.parse("13:00"),
start_date: Date.parse("August 19"),
organizer_name: "Fun Company",
organizer_description: "We only serve fun!",
user_id: jane[:id]
)
photofile = File.open("app/assets/images/mosh.jpg")
d.photo.attach(io: photofile, filename: "mosh.jpg")
d.save!
EventCategory.create!(
event_id: d.id,
category_id: party.id
)
e = Event.new(
title: "Pizza Networking Social",
description: "Pizza is the future! Come find your way into this budding marker and talk with industry greats!",
venue_name: "Golden Boy Pizza",
address: "542 Green St",
city: "San Francisco",
state: "CA",
zip: "94133",
country: "United States of America",
start_time: Time.parse("06:00"),
start_date: Date.parse("September 4"),
organizer_name: "The Pizza Conglomerate",
organizer_description: "Controlling the pizza business by hostile take overs since 1983!",
user_id: demo[:id]
)
photofile = File.open("app/assets/images/audience.jpg")
e.photo.attach(io: photofile, filename: "audience.jpg")
e.save!
EventCategory.create!(
event_id: e.id,
category_id: business.id
)
f = Event.new(
title: "Painting Class",
description: "This is a finger-painting only event.",
venue_name: "SF MOMA",
address: "151 3rd St",
city: "San Francisco",
state: "CA",
zip: "94103",
country: "United States of America",
start_time: Time.parse("09:00"),
start_date: Date.parse("August 21"),
organizer_name: "Let's Paint!",
organizer_description: "Painting! It's not boring anymore!",
user_id: john[:id]
)
photofile = File.open("app/assets/images/balloons.jpg")
f.photo.attach(io: photofile, filename: "balloons.jpg")
f.save!
EventCategory.create!(
event_id: f.id,
category_id: arts.id
)
g = Event.new(
title: "Hamburger City",
description: "In every person's lifetime, they are given a chance to witness something incredible. For many, their chance has come. From October 12 through the end of May, The Palace of Fine Arts will be showing the world reknowned 'Hamburger City'. Many have described it as 'awe-inspiring' and 'life-changing,' leaving the exhibit with their notion of reality shifted.
Critics around the world are saying the same thing, 'Mere words could never capture the earth-shaking gravity of this work'. Philosophers from all over are retiring, claiming that after seeing 'Hamburger City', there are no more questions that need answers. Tickets are limited so buy soon. Black tie only.",
venue_name: "The Palace of Fine Arts",
address: "3301 Lyon St",
city: "San Francisco",
state: "CA",
zip: "94123",
country: "United States of America",
start_time: Time.parse("02:00"),
start_date: Date.parse("October 12"),
organizer_name: "Magna Opera and More!",
organizer_description: "We know art.",
user_id: john[:id]
)
photofile = File.open("app/assets/images/bike.jpg")
g.photo.attach(io: photofile, filename: "bike.jpg")
g.save!
EventCategory.create!(
event_id: g.id,
category_id: arts.id
)
h = Event.new(
title: "Burrito and Beer Festival",
description: "All you can eat burritos and beer! Enjoy the final days of summer the best way possible, relaxing and eating in the sun (or fog)!",
venue_name: "Mission Dolores Park",
address: "Dolores St & 19th St",
city: "San Francisco",
state: "CA",
zip: "94114",
country: "United States of America",
start_time: Time.parse("05:00"),
start_date: Date.parse("September 15"),
organizer_name: "The San Francisco Advisory Council on Beer and Burritos",
organizer_description: "Protecting the City by the Bay from subpar beer and burritos since 1946.",
user_id: john[:id]
)
photofile = File.open("app/assets/images/concert.jpg")
h.photo.attach(io: photofile, filename: "concert.jpg")
h.save!
EventCategory.create!(
event_id: h.id,
category_id: food.id
)
i = Event.new(
title: "SoMa Yogathon",
description: "Greet the dawn at AT&T park for our monthly Yogathon with Rep. Nancy Pelosi!",
venue_name: "AT&T Park",
address: "24 Willie Mays Plaza",
city: "San Francisco",
state: "CA",
zip: "94107",
country: "United States of America",
start_time: Time.parse("22:00"),
start_date: Date.parse("December 13"),
organizer_name: "The Office of Nancy Pelosi",
organizer_description: "Yay yoga!",
user_id: demo[:id]
)
photofile = File.open("app/assets/images/dj.jpg")
i.photo.attach(io: photofile, filename: "dj.jpg")
i.save!
EventCategory.create!(
event_id: i.id,
category_id: health.id
)
j = Event.new(
title: "Vote",
description: "Literally, please just vote.",
venue_name: "Your Polling Place",
address: "1 Your Polling Place Rd",
city: "San Francisco",
state: "CA",
zip: "94123",
country: "United States of America",
start_time: Time.parse("00:00"),
start_date: Date.parse("November 9"),
organizer_name: "Please Vote",
organizer_description: "It's your civc duty!",
user_id: demo[:id]
)
photofile = File.open("app/assets/images/food.jpg")
j.photo.attach(io: photofile, filename: "food.jpg")
j.save!
EventCategory.create!(
event_id: j.id,
category_id: business.id
)
k = Event.new(
title: "Midnight Marathon",
description: "Everyone's favorite marathon is back! Despite permit set backs due to last year's glowstick incident, we're back and better than ever! BYOhead-lamp and reflective gear.",
venue_name: "The Bay Bridge",
address: "1 Bay Bridge Park",
city: "San Francisco",
state: "CA",
zip: "94123",
country: "United States of America",
start_time: Time.parse("04:00"),
start_date: Date.parse("September 3"),
organizer_name: "The Marathon Brothers",
organizer_description: "Party like it's 490 BCE!",
user_id: demo[:id]
)
photofile = File.open("app/assets/images/skateboard.jpg")
k.photo.attach(io: photofile, filename: "skateboard.jpg")
k.save!
EventCategory.create!(
event_id: k.id,
category_id: health.id
)
l = Event.new(
title: "How Many Times Can You Watch 'The Room'?",
description: "Last person standing wins a TGIFriday's gift card.",
venue_name: "The Metreon",
address: "135 4th St",
city: "San Francisco",
state: "CA",
zip: "94103",
country: "United States of America",
start_time: Time.parse("04:00"),
start_date: Date.parse("September 3"),
organizer_name: "Movies R Us",
organizer_description: "We're big picture people!",
user_id: demo[:id]
)
photofile = File.open("app/assets/images/spin.jpg")
l.photo.attach(io: photofile, filename: "spin.jpg")
l.save!
EventCategory.create!(
event_id: l.id,
category_id: arts.id
)
m = Event.new(
title: "Lucyfest",
description: "Lucy is the best dog ever and deserves to be celebrated",
venue_name: "The Fillmore",
address: "1805 Geary Blvd",
city: "San Francisco",
state: "CA",
zip: "94115",
country: "United States of America",
start_time: Time.parse("04:00"),
start_date: Date.parse("September 3"),
organizer_name: "Sahar",
organizer_description: "I love Lucy.",
user_id: sahar[:id]
)
photofile = File.open("app/assets/images/ticket.jpg")
m.photo.attach(io: photofile, filename: "ticket.jpg")
m.save!
EventCategory.create!(
event_id: m.id,
category_id: music.id
)
#Tickets
Event.all.each do |event|
Ticket.create!(
event_id: event.id,
price: 10,
quantity: 1000,
name: "General Admission"
)
end
| true
|
711431a5bdf082a237167414fc77ef3142e6ab8b
|
Ruby
|
newfront/dailyhacking
|
/word_problems/strstr.rb
|
UTF-8
| 664
| 3.734375
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
def strstr(haystack, needle)
# haystack is of a particular length
# needle is of a particular length
h_len = haystack.size
n_len = needle.size
unless h_len >= n_len
return false
end
# continue
# how many test cycles must we run to compare haystack against needle
#num_tests = (h_len / n_len).ceil
(0..h_len).each do |position|
test = haystack[position, n_len]
if test == needle
puts "needle: #{needle} is equal to haystack substr: #{test}"
return position
end
end
return false
end
puts strstr("san francisco", "ran")
| true
|
688bda0c1144c8416d79316aeb781613e11424fd
|
Ruby
|
matbgn/rails-longest-word-game
|
/app/controllers/games_controller.rb
|
UTF-8
| 2,432
| 3.171875
| 3
|
[] |
no_license
|
require 'open-uri'
require 'json'
class GamesController < ApplicationController
def new
@letters = generate_grid(10)
end
def score
@attempt = params[:attempt]
@letters = params[:letters].delete(' ').chars
@result = final_score(@attempt, @letters)
end
private
def generate_grid(grid_size)
# TODO: generate random grid of letters
arr = []
(0...grid_size).each do
arr << ("A".."Z").to_a.sample
end
return arr
end
def english_word?(word)
# create a method to ctrl if the word given is an english one
# the given word is not an english one
# a) should compute score of zero for non-english word
# b) it should build a custom message for an invalid word
# => not an english word
url = "https://wagon-dictionary.herokuapp.com/#{word}"
user_serialized = open(url).read
api_dict_response = JSON.parse(user_serialized)
return api_dict_response["found"]
end
def in_the_grid?(word, grid)
# the given word is not in the grid
# a) should compute score of zero for word not in the grid
# b) should build a custom message for a word not in the grid
# => not in the grid
# the given word has the correct letters but not in sufficient number
# a) should compute score of zero
# b) should tell it s not in the grid
# => not in the grid
# should allow success when answer has repetitive letters
# :repetitive "season", %w(S S A Z O N E L) Time.now + 1.0
return false if word.gsub(/\W/, "").chars.length > grid.length
result = true
grid_hash = create_hash_from_string(grid.join.downcase)
create_hash_from_string(word).each do |key, value|
result &= value <= grid_hash[key].to_i
end
return result
end
def create_hash_from_string(word)
hash_word = {}
(0...word.gsub(/\W/, "").length).each do |i|
hash_word[word.gsub(/\W/, "").downcase[i]] = hash_word[word.gsub(/\W/, "").downcase[i]].to_i + 1
end
return hash_word
end
def final_score(attempt, letters)
result = {type: 0, attempt: '', letters: ''}
result = {type: 1, attempt: @attempt.upcase, letters: @letters.join(',')} unless in_the_grid?(@attempt, @letters)
result = {type: 2, attempt: @attempt.upcase, letters: ''} unless english_word?(@attempt)
result = {type: 3, attempt: @attempt.upcase, letters: ''} if result[:type].zero?
return result
end
end
| true
|
5227b6b2f0e5cb73b6bfe13af50cba8f86ca0cd0
|
Ruby
|
ShelbyTV/shelby_gt
|
/app/helpers/roll_helper.rb
|
UTF-8
| 480
| 2.5625
| 3
|
[] |
no_license
|
module RollHelper
# This is used in the context: "Dan is following your <title_for_roll_on_follow>"
def title_for_roll_on_follow(roll)
case roll.roll_type
when Roll::TYPES[:special_watch_later]
"Likes Roll"
when Roll::TYPES[:special_public_real_user], Roll::TYPES[:special_public], Roll::TYPES[:special_public_upgraded]
"Personal Roll"
when Roll::TYPES[:special_upvoted]
"Likes Roll"
else
"roll: #{roll.title}"
end
end
end
| true
|
6a70bd875a94b988b446bdfe72e4cd46c2beb86d
|
Ruby
|
Naveen1789/ruby_code
|
/leetcode/algorithms/length_of_last_word_58.rb
|
UTF-8
| 157
| 3.265625
| 3
|
[] |
no_license
|
# @param {String} s
# @return {Integer}
def length_of_last_word(s)
arr = s.split(" ").compact
return arr.size < 1 ? 0 : arr[arr.size - 1].length
end
| true
|
1e03e3e1bc08ad5e990739e1aa01cbab80148da4
|
Ruby
|
mgoodhart5/sorting_cards
|
/lib/guess.rb
|
UTF-8
| 322
| 3.59375
| 4
|
[] |
no_license
|
require 'pry'
class Guess
attr_reader :response, :card
def initialize(response, card)
@response = response
@card = card
end
def correct?
@response.split(" of ") == [ @card.value, @card.suit ]
end
def feedback
if correct?
"You win!"
else
"You're wrong."
end
end
end
| true
|
5bcbb2fafa270d7d98353848b42782d281be0574
|
Ruby
|
Algorithms-DrBaharav/alg-ramanujan1729-student-cyoce
|
/ramanujan.rb
|
UTF-8
| 211
| 3.046875
| 3
|
[] |
no_license
|
def ramanujan(n=1729)
out = []
(1..Math.cbrt(n).floor).each do |i|
(i..Math.cbrt(n).floor).each do |j|
out << [i,j].sort! if i**3 + j**3 == n
end
end
out
end
| true
|
ba4de4acab4091723a7bcc4218ac0d8fc5cf8ce8
|
Ruby
|
Sevos83/Lesson-10
|
/cargo_carriage.rb
|
UTF-8
| 444
| 3.1875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
class CargoCarriage
attr_reader :total_volume, :filled_volume, :free_volume
def initialize(number, total_volume)
@number = number
@type = :cargo
@total_volume = total_volume
@free_volume = total_volume
end
def fill_volume(volume)
self.filled_volume += volume
self.free_volume = total_volume - self.filled_volume
end
protected
attr_writer :filled_volume, :free_volume
end
| true
|
f980f580b133530269a1abdd505494be72a430e5
|
Ruby
|
velvelshteynberg/rubymethods
|
/rubymethodassignmentintro.rb
|
UTF-8
| 651
| 4.3125
| 4
|
[] |
no_license
|
# # Question-what does the command class do to an integer and to a string
#puts "pragramming".class
#puts 12.class
# #question- When do you use a = and when do you use ==?
# def my_first_method
# return 1 + 1
# end
# puts my_first_method
# def reverse_sign (num)
# return num * 8 /8
# end
# puts reverse_sign (56)
# num_1 = 20
# def plus_one (num_2)
# return num_2 + 1
# end
# puts plus_one (num_1)
#question - putting the puts statement at the end is not resulting in nil
# def favourite_number (fav_num)
# sum = fav_num + 100
# return sum
# puts sum
# end
# his_fav_num = 5
# puts favourite_number (his_fav_num)
| true
|
5a2460000a4cf0e7545aa65b487f262f90e9fcde
|
Ruby
|
dailybeast/subreddit_analysis
|
/app/models/base.rb
|
UTF-8
| 880
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
class Base
def initialize(props = {})
props.each { |name, value| instance_variable_set("@#{name}", value) }
end
def self.quote(s)
if s.nil?
return 'null'
elsif s.is_a? Numeric
return s
else
return "'#{s.gsub("'", "''")}'"
end
end
def quote(s)
Base.quote(s)
end
def self.connections(db)
@@db = db
end
def self.reddit_client(reddit_client)
@@reddit_client = reddit_client
end
def self.find_one(query)
rows = @@db.execute(query)
if rows && rows.length > 0
row = rows.first
end
return row
end
def self.destroy_table
begin
@@db.execute "drop table #{self.tablename}"
rescue
#noop
end
end
def self.tablename
t = self.name.downcase
t.gsub!(/^user(\w)/, 'user_\1')
t.gsub!(/^subreddit(\w)/, 'subreddit_\1')
t += 's'
return t
end
end
| true
|
7a4c9c1e9297d2d545135abafa10e9276f3c8a49
|
Ruby
|
Mariana-21/Enigma
|
/test/shift_test.rb
|
UTF-8
| 908
| 3.078125
| 3
|
[] |
no_license
|
require './test/test_helper'
require './lib/enigma'
require './lib/shift'
require 'date'
require 'minitest/autorun'
require 'minitest/pride'
require 'mocha/minitest'
class ShiftTest < Minitest::Test
def setup
@shift = Shift.new('020320', '15234')
end
def test_it_exsits
assert_instance_of Shift, @shift
end
def test_it_has_attributes
@shift.stubs(:rand).returns(15234)
@shift.stubs(:date).returns('020320')
assert_equal '15234', @shift.key
assert_equal '020320', @shift.date
end
def test_it_can_get_offset_key
assert_equal [2, 4, 0, 0], @shift.offset_key('020320')
end
def test_it_can_put_key_numbers_in_pairs
assert_equal [15, 52, 23, 34], @shift.key_pairs
end
def test_it_can_combine_date_and_offset
assert_equal [17, 56, 23, 34], @shift.date_and_offset
end
def test_it_can_rotate
assert_equal 17, @shift.rotate_shift
end
end
| true
|
0c0e8e2066999daf10142c8bcb73be1371370d9a
|
Ruby
|
19WH1A0578/BVRITHYDERABAD
|
/CSE/Scripting Languages Lab/18WH1A05A0/LabProgram4.rb
|
UTF-8
| 378
| 3.109375
| 3
|
[] |
no_license
|
#file = "/home/sravani/Desktop/SL/LabProgram3.rb"
puts "Enter the file name"
file = gets.chomp
#file name
fbname = File.basename file
puts "File Name : "+fbname
#base name
bname = File.basename file,".rb"
puts "Base Name : "+bname
#file extension
fextn = File.extname file
puts "File Extension : "+fextn
#path name
pathname = File.dirname file
puts "Path Name : "+pathname
| true
|
c680cacc169c63ce2b5d84fda1c64f79e44db8d6
|
Ruby
|
sploving/shogun
|
/examples/undocumented/ruby_modular/library_fisher2x3_modular.rb
|
UTF-8
| 568
| 2.84375
| 3
|
[] |
no_license
|
# this was trancekoded by the awesome trancekoder
require 'narray'
require 'modshogun'
require 'load'
require 'pp'
x=array([[20.0,15,15],[10,20,20]])
y=array([[21,21,18],[19,19,22]])
z=array([[15,27,18],[32,5,23]])
parameter_list = [[x,concatenate((x,y,z),1)],[y,concatenate((y,y,x),1)]]
def library_fisher2x3_modular(table, tables)
pval=Math_fishers_exact_test_for_2x3_table(table)
pvals=Math_fishers_exact_test_for_multiple_2x3_tables(tables)
return (pval,pvals)
end
if __FILE__ == $0
print 'Fisher 2x3'
library_fisher2x3_modular(*parameter_list[0])
end
| true
|
c928f1f2d489cc6995a6bded59f6438299791471
|
Ruby
|
nchambe2/phase-0
|
/week-8/ruby-review/ruby_review.rb
|
UTF-8
| 6,122
| 4.5
| 4
|
[
"MIT"
] |
permissive
|
# Create a Bingo Scorer (SOLO CHALLENGE)
# I spent [#] hours on this challenge.
# Pseudocode
#CREATE a class called BingoScorer
#CREATE a method called initialize which takes in a nested collection object of numbers
# Create a method to generate a letter ( b, i, n, g, o) and a number (1-100)
#Select a random letter from letters and store it in an instance variable called letter
#Select a random number and store it in an instance variable called number
# Check the called column for the number called.
# If the number is in the column, replace with an 'x' THEN
#store the new board
#Check each row for 5 Xs across
#If there are 5 xs horizontally in a row THEN
#return bingo and true
#Else say guess again
#What the class knows about itself
#board
#call letter
#call number
#What the class does
#checks if number exists in column
#changes that numbe to x if it does
#keeps track of the num of xs in each row
# sample boards
horizontal = [[47, 44, 71, 8, 88],
[100, 54, 5, 2, 19],
[83, 85, 97, 89, 57],
[25, 31, 96, 68, 51],
[75, 70, 54, 80, 83]]
# vertical = [[47, 44, 71, 'x', 88],
# [22, 69, 75, 'x', 73],
# [83, 85, 97, 'x', 57],
# [25, 31, 96, 'x', 51],
# [75, 70, 54, 'x', 83]]
# right_to_left = [['x', 44, 71, 8, 88],
# [22, 'x', 75, 65, 73],
# [83, 85, 'x', 89, 57],
# [25, 31, 96, 'x', 51],
# [75, 70, 54, 80, 'x']]
# left_to_right = [[47, 44, 71, 8, 'x'],
# [22, 69, 75, 'x', 73],
# [83, 85, 'x', 89, 57],
# [25, 'x', 96, 68, 51],
# ['x', 70, 54, 80, 83]]
=begin
# Initial Solution
class BingoScorer
def initialize(horizontal)
@bingo_board = horizontal
@call_letter = nil
@call_number = 0
@column_b = nil
@column_i = nil
@column_n = nil
@column_g = nil
@column_o = nil
p "This is your bingo board #{@bingo_board}."
end
def generate_bingo_number
letters = ['b', 'i', 'n', 'g', 'o']
@call_letter= letters.sample
@call_number = rand(1..100)
p "#{@call_letter} #{@call_number}."
check_row_for_match
end
def check_row_for_match
p @column_b = @bingo_board[0]
p @column_i = @bingo_board[1]
p @column_n = @bingo_board[2]
p @column_g = @bingo_board[3]
p @column_o = @bingo_board[4]
if (@call_letter == 'b')
@column_b.map! do |num|
if num == @call_number
num = 'x'
else
num
end
end
end
if (@call_letter == 'i')
@column_i.map! do |num|
if num == @call_number
num = 'x'
else
num
end
end
end
if (@call_letter == 'n')
@column_n.map! do |num|
if num == @call_number
num = 'x'
else
num
end
end
end
if (@call_letter == 'g')
@column_g.map! do |num|
if num == @call_number
num = 'x'
else
num
end
end
end
if (@call_letter == 'o')
@column_o.map! do |num|
if num == @call_number
num = 'x'
else
num
end
end
end
bingo?
end
def bingo?
if (@column_b.count("x") == 5)
p "You won the game"
elsif(@column_i.count("x") == 5)
p "You won the game"
elsif(@column_n.count("x") == 5)
p "You won the game"
elsif(@column_g.count("x") == 5)
p "You won the game"
elsif(@column_o.count("x") == 5)
p "You won the game"
else
p "Keep playing"
generate_bingo_number
end
end
def return_bingo_board
p @bingo_board
end
end
=end
# Refactored Solution
class BingoScorer
def initialize(horizontal)
@bingo_board = horizontal
@call_letter = nil
@call_number = 0
@column_b = @bingo_board[0]
@column_i = @bingo_board[1]
@column_n = @bingo_board[2]
@column_g = @bingo_board[3]
@column_o = @bingo_board[4]
p "This is your bingo board :"
@bingo_board.each { |row| p row }
end
def generate_bingo_number
letters = ['b', 'i', 'n', 'g', 'o']
@call_letter= letters.sample
@call_number = rand(1..100)
p "#{@call_letter} #{@call_number}."
check_row_for_match
end
def check_row_for_match
case @call_letter
when 'b' then @column_b.map! { |num| num == @call_number ? num = 'x' : num}
when 'i' then @column_i.map! { |num| num == @call_number ? num = 'x' : num}
when 'n' then @column_n.map! { |num| num == @call_number ? num = 'x' : num}
when 'g' then @column_g.map! { |num| num == @call_number ? num = 'x' : num}
when 'o' then @column_o.map! { |num| num == @call_number ? num = 'x' : num}
end
bingo?
end
def bingo?
case
when @column_b.count("x").eql?(5) then p "BINGO!", return_bingo_board
when @column_i.count("x").eql?(5) then p "BINGO!", return_bingo_board
when @column_n.count("x").eql?(5) then p "BINGO!", return_bingo_board
when @column_g.count("x").eql?(5) then p "BINGO!", return_bingo_board
when @column_o.count("x").eql?(5) then p "BINGO!", return_bingo_board
else p "No Bingo. Keep playing"
generate_bingo_number
end
end
def return_bingo_board
p "This is your final bingo board:"
@bingo_board.each { |row| p row }
end
end
# DRIVER TESTS GO BELOW THIS LINE
bingo = BingoScorer.new(horizontal)
bingo.generate_bingo_number
# Reflection
=begin
What concepts did you review or learn in this challenge?
I reviewed using case statements.
Previously, I had only used when and then while utilizing case statements
I had never used else statements though.
So I had to look up was that allowable, then figured out how to use it.
Also, having methods call other methods.
What is still confusing to you about Ruby?
In this situation I was unsure if I need to add attr_reader to my class.
Might have to go to office hours to clarify.
What are you going to study to get more prepared for Phase 1?
Hashes, enumerable/enumerators, and working on some extra algorithm problems.
=end
| true
|
78be4ec99d0c9dc18c1f50325e396899f6842b31
|
Ruby
|
imarkwick/rock_paper_scissors
|
/spec/game_spec.rb
|
UTF-8
| 792
| 3.078125
| 3
|
[] |
no_license
|
require 'game'
describe Game do
let(:game) { Game.new }
let(:player) { double :player }
it "can have a player" do
game.add_player(player)
expect(game.player).to eq (player)
end
it "knows how many move options" do
expect(game.move_count).to eq 3
end
it "the robot move is either - rock paper scissor" do
expect(["rock","paper","scissor"]).to include(game.robot_move)
end
it "returns draw if player move equals robot move" do
expect(game.results("rock", "rock")).to eq "draw"
end
it "returns player wins if player move beats robot move" do
expect(game.results("rock", "paper")).to eq "robot wins"
end
it "returns robot wins if player move loses to robot move" do
expect(game.results("paper", "rock")).to eq "player wins"
end
end
| true
|
d9f2e1eafcb420abb10693d455990d9772bd3da2
|
Ruby
|
OrangeCrush/pluralizer.rb
|
/heuristic.rb
|
UTF-8
| 3,238
| 3.6875
| 4
|
[
"MIT"
] |
permissive
|
# This class is used as a base class for heuristics
# determining whether or not a word is plural
class Heuristic
# @data will be the training set in the following format
# [...[singular_word, plural_word], ...]
# Rules will be /regexp1/ => [ /regexp2/, replace_str]
# Where
# regexp1 is the regex defining how to match a word to thisn rule
# regexp2 is the regex that defines what part of the word needs to be replaced with the string replace_str
def initialize(training_set)
@training_set = training_set
@rules = {}
@metrics = {}
end
# train should read @training_set and then build @rules
def train
raise "Calling Abstract method train on class Heuristic."
end
# Guess the plural form of singular word using @rules!
def guess(singular_word)
raise "Calling Abstract method guess(#{singular_word}) on class Heuristic."
end
# Helper method to return an array in the form of
# [string_to_replace, replace_str]
def stringDiff(singular, plural)
if !singular.empty? && !plural.empty? && singular[0] == plural[0]
stringDiff(singular[1..-1], plural[1..-1])
else
return [singular, plural]
end
end
# Should display random metrics
def report
raise "Calling Abstract method report on class Heuristic."
end
end
class Last_N_Letters_Heuristic < Heuristic
attr_accessor :name
def initialize(training_set, numLetters)
@N = numLetters #The greatest number of letters to look back
@name = "Last_#{@N}_Letters_Heuristic"
super(training_set)
end
def train
@training_set.each do |x|
regex_str = ""
singular = x[0]
plural = x[1]
if singular.size < @N
regex_str = singular
else
regex_str = singular[-@N..-1]
end
regex = Regexp.new("#{regex_str}$")
if @rules[regex].nil?
# push the fitness on to 1
@rules[regex] = stringDiff(singular, plural).push(1)
else
# add one to the fitness
@rules[regex][2] += 1
end
end
end
def guess(singular_word)
matches = []
@rules.keys.each do |x|
if singular_word =~ x
matches << x
end
end
possible_matches = []
matches.each do |x|
#@rules[x][0] is the string to replace, [x][1] is the string what to replace it with
if @rules[x][0].empty?
possible_matches << singular_word + @rules[x][1]
else
# might not replace last occurence..
possible_matches << singular_word.replacelast!(@rules[x][0], @rules[x][1])
end
end
return possible_matches.empty? ? "No matches found for #{singular_word}" : "#{singular_word}: #{fitness(possible_matches)}"
end
# will determine which match to used based on the fitness
def fitness(matches)
max_match = matches[0]
matches.each do |match|
if max_match[2] < match[2]
max_match = match
end
end
return max_match
end
end
class String
def replacelast!(old, new)
self.reverse.sub!(old.reverse, new.reverse).reverse
end
end
| true
|
e11f4fcc38bd759960461e63f82e23614213f92b
|
Ruby
|
Project-ShangriLa/shangrila-sdk-ruby
|
/lib/shangrila/sora.rb
|
UTF-8
| 2,777
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
require 'net/http'
require 'uri'
require 'json'
require 'httpclient'
module Shangrila
class Sora
def initialize(hostname = 'api.moemoe.tokyo')
@url = "http://#{hostname}/anime/v1/master"
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @return [JSON] アニメのマスターデータすべて
def get_master_data_raw(year, cours)
response = HTTPClient.get(sprintf("%s/%s/%s", @url, year, cours))
response.body
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @return [JSON->RubyHash] アニメのマスターデータすべて
def get_master_data(year, cours)
response = HTTPClient.get(sprintf("%s/%s/%s", @url, year, cours))
JSON.load(response.body)
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @return [JSON] アニメのマスターデータのタイトルリスト
def get_title_list(year, cours)
master_list = get_master_data(year, cours)
master_list.map{|master| master['title']}
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @param [property] データ取得対象のプロパティ
# @return [HASH] タイトルをkey、propertyに対応する値をValueとしたハッシュ
def get_map_with_key_title(year, cours, property)
master_list = get_master_data(year, cours)
master_map = {}
master_list.each{|master| master_map[master['title']] = master[property]}
master_map
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @return [HASH] idをkeyとしたハッシュデータ
def get_map_key_id(year, cours)
master_list = get_master_data(year, cours)
master_map = {}
master_list.each{|master| master_map[master['id']] = master}
master_map
end
# @param [Int] year データ取得対象のアニメの年
# @param [Int] cours データ取得対象のアニメの年のクール番号 1-4
# @param [property] データ取得対象のプロパティリスト
# @return [Array] 1タイトル1配列としたフラット配列
def get_flat_data(year, cours, property_list)
master_list = get_master_data(year, cours)
records = master_list.map{|master| property_list.map{|p|master[p]} }
records
end
end
end
| true
|
b7562c6019d1c3f1f3ef8a22ee340cb1e12325d9
|
Ruby
|
OwenKLenz/Codewars
|
/4_kyu/count_squares_on_chess_board.rb
|
UTF-8
| 8,812
| 3.90625
| 4
|
[] |
no_license
|
# Input: a 2d array representing a chess board (of varying sizes)
# Output: a hash with keys representing the dimensions of the squares, contained
# in the board (a key of 2 would represent a 2 x 2 square). The value is an
# integer representing the number of squares of key size.
# Rules: Find all of the squares (2 x 2 or greater) comprised of no chess pieces
# (represented by the number 1 as an array element) and return them in a hash.
# Board will be 2 <= size <= 130
# Ideas:
# Iterate over all possible subsquares of length 2 to maxlength. If all squares
# are a 1, increment the hash value for that square size
# Considerations:
# Don't keep looking at squares originating from a given corner square once an
# non empty square is found (move to next corner square)
# Algorithm:
# Create a hash with values defaulting to 0
#
# Set counter to 0
# Look at squares from index 0-1, 0-2, 0-3 up to maxlength - 1
# If square is empty (all 1s) increment hash on value and continue to 0-2, 0-3, etc.
# Once a square with a piece is found, you're done with that starting index (0, 0 to begin)
# incremenet counter
# Now look at 1-2, 1-3, 1-4, up to max length
# maxlength needs to be decremented by 1 for every square you move right and
# every squre you move down.
# Starting simple:
# Checking a single 2x2 square:
# create a transposed version of the board and save it
# init left_corner counter to 0
# init right corner counter to 1
# check if board[left_corner..right_corner] includes 0
# if so break
# check if transposed_board[left_corner..right_corner] includes 0
# if so break
#
# New idea:
# Grabbing the whole sub matrix that we want to examine for 0s.
# We want to acquire a submatrix
# submatrix will be from left_corner_index to left_corner_index + n (until left_corner_index + n == dimensions)
# in left_corner_index rows
require 'pry'
def count(board)
squares_hash = Hash.new(0)
dimensions = board[0].size
left_corner_index = 0
right_corner_index = 1
top_row = 0
bottom_row = 1
until top_row == dimensions - 1
until right_corner_index == dimensions || bottom_row == dimensions
until right_corner_index == dimensions || bottom_row == dimensions
# binding.pry
size = bottom_row - top_row + 1
break if square_contains_zero?(board, top_row, bottom_row, left_corner_index, right_corner_index)
squares_hash[size] += 1
right_corner_index += 1
bottom_row += 1
end
left_corner_index += 1
right_corner_index = left_corner_index + 1
bottom_row = top_row + 1
end
left_corner_index = 0
right_corner_index = 1
top_row += 1
bottom_row = top_row + 1
end
squares_hash
end
def square_contains_zero?(board, top_row, bottom_row, left_corner_index, right_corner_index)
(top_row).upto(bottom_row) do |row|
board[row][left_corner_index..right_corner_index].each { |el| return true if el == 0 }
end
false
end
# p count([[1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# [13, 14, 15, 16]])
p count(Array.new(130) { Array.new(130) {1} })
p count([
[0,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0,1,1,0,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1,1,1,1,1,1,1, 1, 1, 1, 1, 1,1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
])
# Keep working left to right until first index([1][3]) + max dimensions == maxlength (5 in case below)
# this one ^
# index 0, 0:
# 2x2 to 5x5
# index 0, 1:
# 2x2 to 4x4
# etc.
# index 1, 0:
# 2x2 to 4x4
# index 1, 1:
# 2x2 to 4x4
# index 1, 2:
# 2x2 to 3x3
# etc.
# index 2, 0:
# 2x2 to 3x3
# index 2, 1:
# 2x2 to 3x3
# index 2, 2:
# 2x2 to 3x3
# index 2, 3:
# 2x2
chessboard = [
[0,1,1,1,1],
[1,1,1,1,1],
[1,1,1,1,1],
[0,1,1,0,1],
[1,1,1,1,1]
]
chessboard = [
[0,1],
[1,1]
]
chessboard = [
[1,1,1],
[1,0,1],
[1,1,1]
]
| true
|
9deac4f4f0f52a0da572d6c604fbc814867e78b4
|
Ruby
|
andrely/Norwegian-NLP-models
|
/scripts/processors/test/normalization_processor_test.rb
|
UTF-8
| 1,674
| 2.65625
| 3
|
[] |
no_license
|
require 'test/unit'
require_relative '../normalization_processor'
require_relative '../../test/data_repository'
require_relative '../../sources/array_source'
class NormalizationProcessorTest < Test::Unit::TestCase
def test_normalization_processor
proc = NormalizationProcessor.new(proc_map: { :form => lambda { |form| form.reverse } })
src = ArraySource.new(DataRepository.sample5, processor: proc)
result = src.to_a
assert_not_nil(result)
assert_equal(1, result.size)
assert_not_nil(result[0][:words])
assert_equal(3, result[0][:words].size)
assert_equal('ab', result[0][:words][0][:form])
assert_equal('ab', result[0][:words][1][:form])
assert_equal('.', result[0][:words][2][:form])
end
def test_ob_normalization_processor
proc = NormalizationProcessor.ob_normalization_processor
src = ArraySource.new(DataRepository.sample6, processor: proc)
result = src.to_a
assert_not_nil(result)
assert_not_nil(result[0][:words])
assert_equal(4, result[0][:words].size)
assert_equal('"', result[0][:words][0][:form])
assert_equal('anf', result[0][:words][0][:pos])
assert_equal('"', result[0][:words][0][:lemma])
assert_equal('ba', result[0][:words][1][:form])
assert_equal('foo', result[0][:words][1][:pos])
assert_equal('ba', result[0][:words][1][:lemma])
assert_equal('ba', result[0][:words][2][:form])
assert_equal('foo', result[0][:words][2][:pos])
assert_equal('ba', result[0][:words][2][:lemma])
assert_equal('"', result[0][:words][3][:form])
assert_equal('anf', result[0][:words][3][:pos])
assert_equal('"', result[0][:words][3][:lemma])
end
end
| true
|
266d22a34ba58549eb150301e3ed85afac0c8ab6
|
Ruby
|
brennancheung/prie
|
/lib/prie/main_parser.rb
|
UTF-8
| 8,099
| 3.53125
| 4
|
[] |
no_license
|
require "prie/parser"
module Prie
class MainParser < Prie::Parser
attr_accessor :words
def run(input_text)
result = self.parse(input_text)
self.execute_loop(result)
end
def return(input_text)
self.run(input_text)
@stack.pop
end
# Mechanism to allow words to be declared into the parser.
# See the examples in 'initialize' for example usage.
def def_word(declaration, automap_values=:both, &block)
parts = declaration.split(' ')
name = parts[0]
state = :input
input = []
input_escapes = []
output = []
output_escapes = []
parts[1..-1].each do |x|
next if ['(', ')'].include?(x)
if x == '--'
state = :output
next
end
escapes = []
escaped = x[0] == '`' # prefix stack types with '`' to get original object (as oposed to escaped value)
value = escaped ? x[1..-1] : x
if state == :input
input.push(value)
input_escapes.push(escaped)
else
output.push(value)
output_escapes.push(escaped)
end
end
self.words[name] = {
:input => (input.map &:intern),
:output => (output.map &:intern),
:automap_values => automap_values,
:input_escapes => input_escapes,
:output_escapes => output_escapes,
:block => block
}
true
end
def initialize
super
self.words ||= {}
# Declaring new words takes the following format:
# name ( input* -- output* ) {|*input, params| block code goes here}
# name = name of the word
# input = 0 or more input types
# output = 0 or more output types
# Note: the spaces around '(' and ')' are critical
# Input parameters will be passed into the block
# Output parameters will be pushed back onto the stack using the type(s) specified
# By default, the input values are unwrapped and the output values wrapped.
# Prefixing an input/output parameter with a '`' (backquote) will prevent unwrapping (input) and wrapping (output).
# This frequently used when we don't know the object's type and want to preserve it. It can also be used when
# the output type(s) are not known until the block is executed.
def_word("1+ ( scope string -- )") {|scope, field| scope[field] = StackObject.new(:integer, scope[field].value + 1) }
def_word("1- ( scope string -- )") {|scope, field| scope[field] = StackObject.new(:integer, scope[field].value - 1) }
def_word("<< ( scope string `any -- )") {|scope, string, value| scope[string] = value }
def_word(">> ( scope string -- `any )") {|scope, string| scope[string] }
def_word("= ( any any -- boolean )") {|a, b| a == b }
def_word("!= ( any any -- boolean )") {|a, b| a != b }
def_word("< ( any any -- boolean )") {|a, b| a < b }
def_word("> ( any any -- boolean )") {|a, b| a > b }
def_word("<= ( any any -- boolean )") {|a, b| a <= b }
def_word(">= ( any any -- boolean )") {|a, b| a >= b }
def_word("+ ( numeric numeric -- `numeric )") {|a, b| numeric_stack_object(a + b) }
def_word("- ( numeric numeric -- `numeric )") {|a, b| numeric_stack_object(a - b) }
def_word("* ( numeric numeric -- `numeric )") {|a, b| numeric_stack_object(a * b) }
def_word("/ ( numeric numeric -- `numeric )") {|a, b| numeric_stack_object(a / b) }
def_word("and ( boolean boolean -- boolean )") {|a, b| a && b }
def_word("append ( array `any -- array )") {|arr, value| arr + [ value ] }
def_word("append! ( array `any -- )") {|arr, value| arr.push( value ) }
def_word("call ( array -- )") {|quot| execute_loop(quot) }
def_word("clear ( -- )") { @stack = [] }
def_word("concat ( array array -- array )") {|arr1, arr2| arr1 + arr2 }
def_word("concat! ( array array -- )") {|arr1, arr2| arr1.concat(arr2) }
def_word("count ( array -- integer )") {|arr| arr.count }
def_word("debugger ( -- )") { debugger ; "you are entering the debugger" }
def_word("dec ( scope string integer -- )") {|scope, field, amount| scope[field] = StackObject.new(:integer, scope[field].value - amount)}
def_word("drop ( `any -- )") {}
def_word("dup ( `any -- `any `any)") {|x| [ x, x ] }
def_word("get-scope ( string -- scope )") {|scope_name| self.scopes[scope_name] }
def_word("each ( array array -- )") do |seq, quot|
seq.each do |x|
@stack.push(x)
execute_loop(quot)
end
end
def_word("first ( array -- `any )") {|arr| arr.first }
def_word("if ( boolean array array -- )") {|cond, tquot, fquot| execute_loop(cond ? tquot : fquot) }
def_word("inc ( scope string integer -- )") {|scope, field, amount| scope[field] = StackObject.new(:integer, scope[field].value + amount) }
def_word("join ( array string -- string )") {|arr, delim| arr.map(&:value).join(delim) }
def_word("last ( array -- `any )") {|arr| arr.last }
def_word("length ( array -- integer )") {|arr| arr.length }
def_word("make-time ( string -- time )") {|time_str| Time.new(time_str) }
def_word("map ( array array -- array )") do |seq, quot|
seq.inject([]) do |acc, x|
@stack.push(x)
execute_loop(quot)
acc.push(@stack.pop)
end
end
def_word("new-scope ( string -- )") {|scope_name| self.scopes[scope_name] = Prie::Scope.new}
def_word("not ( boolean -- boolean )") {|bool| !bool }
def_word("now ( -- time )") { Time.now }
def_word("nth ( array integer -- `any )") {|arr, index| arr[index] }
def_word("or ( boolean boolean -- boolean )") {|a, b| a || b }
def_word("prepend ( array `any -- array )") {|arr, value| [ value ] + arr }
def_word("prepend! ( array `any -- )") {|arr, value| arr.unshift( value ) }
def_word("print ( string -- )") {|str| print str }
def_word("puts ( string -- )") {|str| puts str }
def_word("split ( string string -- array )") {|str, delim| str.split(delim).map {|x| StackObject.new(:string, x)} }
def_word("str-concat ( string string -- string )") {|str1, str2| str1 + str2 }
def_word("swap ( `any `any -- `any `any )") {|a, b| [b, a] }
def_word("times ( integer array -- )") {|i, quot| i.times { execute_loop(quot) } }
def_word("type ( any -- string )") {|value| StackObject.infer_type(value).to_s }
def_word("w ( string -- array )") {|str| str.split(' ').map {|x| StackObject.new(:string, x)} }
end
# You can create your own "vocabulary" for your parser by subclassing
# Prie::Parser and adding your own "words" (API).
def extended_base(word)
word_hash = self.words[word.value]
if word_hash
# automatically grab the stack values
stack_input_types = word_hash[:input]
from_stack = from_stack(word.value, *stack_input_types)
input_params = []
if [:both, :input].include?(word_hash[:automap_values])
from_stack.each_with_index do |x, i|
input_params.push( word_hash[:input_escapes][i] ? x : x.value )
end
end
output_types = word_hash[:output]
output_params = word_hash[:block].call(*input_params)
output_params = [ output_params ] if output_types.length == 1
output_types.each_with_index do |value, i|
value = word_hash[:output_escapes][i] ? output_params[i] : StackObject.new(output_types[i], output_params[i])
@stack.push( value )
end
return true
end
case word.value
when "accum>stack"
# debugger
# @stack.push(@parse_accums.last.last)
true
else
return false
end
true
end
# Put this in a subclass to provide API hooks for 3rd party developers
def extended_api(word)
case word.value
when "blah"
true
else
raise "word '#{word.value}' not defined"
end
end
end
end
| true
|
2b577640cff9fb99b9503c1041c873decc886976
|
Ruby
|
jclif/ruby-primitives
|
/iteration/factors.rb
|
UTF-8
| 158
| 3.453125
| 3
|
[] |
no_license
|
def factors(number)
factors = []
1.upto(number) do |factor|
factors << factor if number % factor == 0
end
factors
end
p factors(8)
p factors (13)
| true
|
18e5d60e34077f1406469cbee9cd570030f2a26f
|
Ruby
|
chrisvel/Dijkstra-maze-solver
|
/lib/mazesolver.rb
|
UTF-8
| 7,320
| 3.78125
| 4
|
[] |
no_license
|
##
# 2d matrix maze solver
#
# The story:
# The program parses the maze as a string when the object is initialized and
# saves it in an array. The nodes are saved in series, so we need to reverse
# the table in order to use the matrix as a table [x,y].
#
# For the calculations to be easier, the reversed table's nodes are merged and
# then given an incremental number: [0,0] becomes 1, [1,0] becomes 8 etc.
#
# We are marking the nodes which are not walls (X) and save the start node (S).
# We've been said that the Goal node's location is unknown, so we leave it for
# the robot to discover. Then we save each node's neighbours in a hash, after
# checking that none of them is outside of the edges of the matrix.
#
# Then we iterate over the node list, picking up the neighbour node with the
# smallest distance value and move on. In order to keep track of what we' ve
# discovered and what' s left to be done, we keep an unvisited nodes list and a
# queue (FIFO).
#
# If we find a node with a "G" as a value then we' ve reached our goal, so we
# backtrack our solution, following the previous nodes inside of each hash/node
# and then return the final array.
#
# Dijkstra 's algorithm is being used in order to solve the maze puzzle.
#
# Web references that have been used for the solution:
# * https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
# * Various youtube lecture videos on Dijkstra's algorithm
#
##
class MazeSolver
attr_reader :table_merged, :table_x, :start_node, :goal_node, :shortest_path, :backtrack, :node_list, :nodes
attr_accessor :data, :table
def initialize(data, table, table_reversed)
@data = data
@nodes = nodes
@table = table
@table_reversed = table_reversed
@table_merged = []
@table_convert = []
@step = 1
@start_node = 999
@goal_node = 999
@current_node = 999
@table_x = 0
@table_y = 0
@unvisited_set = []
@node_list = []
@shortest_path = []
@shortest_path_coords = []
@backtrack = []
parse_maze
create_nodes
create_unvisited_set
set_table_size
create_node_list
end
# searches for start node but not for the goal node
# the robot does not know where the goal node is but we need to find out
# where to start at
def parse_maze
x = 0
y = 0
z = 0 # will be used as a node number
@table_reversed.each do |row|
row.each do |item|
@start_node = z if item == "S"
# create a simple array with all values
@table_merged << item
@table_convert << [item, [x, y]]
y += 1
z += 1
end
x += 1
y = 0
end
end # parse_maze
# set table size values
def set_table_size
@table_x = @table_reversed[0].size
@table_y = @table_reversed.size
end
# append an incremental number for each node, for example
# [0,0] becomes 0, [0,1] becomes 1, [0,2] becomes 2 etc.
def create_nodes
@nodes = [*0...@table.flatten.length]
end
# create the unvisited set of nodes but remove walls
def create_unvisited_set
@unvisited_set = @nodes.map { |r| r if @table_merged[r] != "X" }
@unvisited_set.delete(nil)
@unvisited_set
end
# initialize nodes structure
def create_node_list
previous_node = nil
# set the current node as the start one
@current_node = @start_node
# create a copy of the instance set
unvisited_set = @unvisited_set.dup
# iterate until there are no unvisited nodes
while unvisited_set.size > 0 do
# set the current node as the first element of the list and remove it
@current_node = unvisited_set.shift
# check If the current node is the goal node
@goal_node = @current_node if @table_merged[@current_node] == "G"
# We should assign to every node a tentative distance value: set it to
# zero for our initial node and to Float::INFINITY for all other nodes.
# In our case we know that there is a standard distance between
# neighbours (1).
@current_node == @start_node ? @distance = 0 : @distance = @step
# Create a Hash for current node and append each node to a table.
# For the current node, consider all of its unvisited neighbors and
# calculate their tentative distances. In the current solver
# all distances of the neighbour nodes are 1.
@node_list << {
id: @current_node,
neighs: check_edges(@current_node),
dist: @distance,
prev: previous_node
}
end
end # create nodes
# check neighbours for edges
def check_edges(current_node)
# set values for neighbours
neighbours = []
left_node = current_node - @step
top_node = current_node + @table_x
right_node = current_node + @step
bottom_node = current_node - @table_x
# check If neighbours are not in the edges
if left_node > 0 && current_node % @table_x != 0 && @table_merged[left_node] != "X"
neighbours << left_node
end
if top_node < (@table_x * @table_y) && @table_merged[top_node] != "X"
neighbours << top_node
end
if bottom_node - @table_x >= 0 && @table_merged[bottom_node] != "X"
neighbours << bottom_node
end
if (current_node + @step) % @table_x != 0 && @table_merged[right_node] != "X"
neighbours << right_node
end
return neighbours
end # check_edges
# does what it says !
def solve_dijkstra
unvisited_set = @unvisited_set.dup
# create a queue for nodes to check
@queue = []
current_node = @start_node
@queue << current_node
# Stop If there are no unvisited nodes or the queue is empty
while unvisited_set.size > 0 && @queue.size > 0 do
# set the current node as visited and remove it from the unvisited set
current_node = @queue.shift
# remove visited node from the list of unvisited nodes
unvisited_set.delete(current_node)
# find the current node's neighbours and add them to the queue
rolling_node = @node_list.find { |hash| hash[:id] == current_node }
rolling_node[:neighs].each do |p|
# only add them if they are unvisited and they are not in the queue
if unvisited_set.index(p) && !@queue.include?(p)
@queue << p
# set the previous node as the current for its neighbours
change_node = @node_list.find { |hash| hash[:id] == p }
change_node[:prev] = current_node
# increase the distance of each node visited
change_node[:dist] = rolling_node[:dist] + @step
end
end
if current_node == @goal_node
find_shortest_path(rolling_node)
break
end
end
return @shortest_path_coords
end # solve_dijkstra
# Retrieves the shortest path by backtracking
def find_shortest_path(rolling_node)
@backtrack = []
@backtrack << @goal_node
# iterate until we arrive at the start node
while rolling_node[:prev] != nil do
temp_node = @node_list.find { |hash| hash[:id] == rolling_node[:prev] }
@backtrack << temp_node[:id]
rolling_node = temp_node
end
# create a table with the 1d and the 2d array node values
@shortest_path = []
@backtrack.each do |p|
@shortest_path << [p, @table_convert[p]]
@shortest_path_coords << @table_convert[p][1]
end
end # find_shortest_path
end
| true
|
2b3b03a5aec628b634833af045ab8b01b73ba088
|
Ruby
|
afrikanhut/smsbazar
|
/lib/tasks/add.rake
|
UTF-8
| 1,210
| 2.625
| 3
|
[] |
no_license
|
desc "Console Gateway"
task :add => :environment do
require "config/environment"
require "lib/sms_session_tracker"
require "lib/menu_browser"
session_tracker = SmsSessionTracker.new
menu_browser = MenuBrowser.new
print "Enter your phone number "
phone = STDIN.gets.chomp
print "Enter your sms message "
sms = STDIN.gets.chomp
session = session_tracker.get_session phone.to_s
if session == nil
menu_item = menu_browser.get_root
puts menu_item.menu_text_items
else
node_id = session.node_id
node = menu_browser.get_node node_id
menu_item = menu_browser.get_menu_by_item_number node, sms.to_i
if menu_item.node.leaf?
if session.put_adv
adv = Adv.new
adv.content = sms
adv.phone = phone
adv.node_id = menu_item.node.id.to_s
adv.save
puts "Спасибо блин большое!"
else
puts "Напишите объявление"
put_adv = 1
end
else
puts menu_item.menu_text_items
end
end
sms_session = SmsSession.new
sms_session.put_adv = put_adv
sms_session.node_id = menu_item.node.id.to_s
session_tracker.save_session phone, sms_session
end
| true
|
7603bc3338a699fb62d200a943409ce680053fd8
|
Ruby
|
EliasGolubev/stack_overflow
|
/app/models/search.rb
|
UTF-8
| 439
| 2.625
| 3
|
[] |
no_license
|
class Search
RESOURSES = %w[All Questions Answers Comments Users].freeze
def self.find(query, resourse)
return nil if query.try(:blank?) || !RESOURSES.include?(resourse)
query = ThinkingSphinx::Query.escape(query)
resourse == 'All' ? ThinkingSphinx.search(query) : ThinkingSphinx.search(query, classes: [model_klass(resourse)])
end
private
def self.model_klass(resourse)
resourse.classify.constantize
end
end
| true
|
d43bca6a4287a9264930b49dab636e97aa93363c
|
Ruby
|
reddavis/NLP-Backpack
|
/lib/nlp_backpack/classifiers/base.rb
|
UTF-8
| 563
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module NLPBackpack
module Classifier
class Base
class << self
def load(db_path)
data = ""
File.open(db_path) do |f|
while line = f.gets
data << line
end
end
Marshal.load(data)
end
end
attr_accessor :db_filepath
def save
raise "You haven't set a db_filpath, I dont know where to save" if @db_filepath.nil?
File.open(@db_filepath, "w+") do |f|
f.write(Marshal.dump(self))
end
end
end
end
end
| true
|
b70c1dd780492ad858ab5a5ac4ca4a658e9cb147
|
Ruby
|
fajarachmadyusup13/Playgrounds-Web
|
/Ruby/Intro/strings.rb
|
UTF-8
| 1,166
| 3.921875
| 4
|
[] |
no_license
|
# puts "Add Them #{4+3} \n\n"
# puts 'Add Them #{4+3} \n\n'
# multiline_string = <<EOM
# this is a very long string
# that contains interpolation
# like #{4 + 5} \n\n
# EOM
# puts multiline_string
# -----------------------------------------------
first_name = "Boo"
last_name = "Zoo"
middle_name = "Moo"
# full_name = first_name + last_name
full_name = "#{first_name} #{middle_name} #{last_name}"
# puts full_name.include?("Moo")
# puts full_name.size
# puts "Vowels: " + full_name.count("aiueo").to_s
# puts "Consonants: " + full_name.count("^aiueo").to_s
# puts full_name.start_with?('Bo')
# puts full_name.index("Moo").to_s
# puts ("a".equal?"a")
# puts first_name.equal?first_name
# puts first_name.upcase
# puts first_name.downcase
# puts first_name.swapcase
# full_name = full_name.lstrip
# full_name = full_name.rstrip
# full_name = full_name.strip
# puts full_name.ljust(20, '.')
# puts full_name.rjust(20, '.')
# puts full_name.center(20, '.')
# puts full_name.chop
# puts full_name.chomp("oo")
nameArray = full_name.split(//)
puts nameArray
nameArray = full_name.split(/ /)
puts nameArray
# -----------------------------------------------
| true
|
a8f684ed43430a19e08a2eba0abcd1db9d26930f
|
Ruby
|
alinadin09/phase-0-tracks
|
/ruby/gps2_2.rb
|
UTF-8
| 2,281
| 4.53125
| 5
|
[] |
no_license
|
# Method to create a list
# input: string of items separated by spaces (example: "carrots apples cereal pizza")
# steps:
# set default quantity to 1
# print the list to the console [can you use one of your methods here?]
# output: [what data type goes here, array or hash?] a hash
def create_list(items)
# Make an empty hash for grocery_list:
p grocery_list = {}
# Takes the string of items that user puts in the create_list method, and turns it into an array:
p items = items.split
# Iterate through each item in the array. This step turns the array into a hash buy asking if it has an item from the array as a key. If the item appears more than once in the array, it will count it as one key and give it a value of +1.
items.each do | item |
if grocery_list.has_key?(item)
grocery_list[item] += 1
else
grocery_list[item] = 1
end
end
grocery_list
end
current_list = create_list("pineapples pineapples apples bananas cucumbers")
# Method to add an item to a list
# input: item name and optional quantity
# steps: add item name and desired quantity
# output: item => quantity
def add_item(current_list, item_added, quantity)
current_list[item_added] = quantity
current_list
end
add_item(current_list, "milk", 2)
# Method to remove an item from the list .delete(item)
# input: item_to_be_deleted
# steps: add item that you want to delete in parameter
# output: new list
def delete_item(current_list, item)
current_list.delete(item)
current_list
end
delete_item(current_list, "pineapples")
# Method to update the quantity of an item
# input: item, value
# steps: add item that you want to update, enter quantity desired
# output: new list with updated quantity
def update_quant(current_list, item, quantity)
current_list[item] = quantity
current_list
end
final_list = update_quant(current_list, "bananas", 4)
# Method to print a list and make it look pretty
# input: final_list
# steps: Use interpolation to list out the keys as grocery items, and values as their respective quantitites.
# output: a clean list that shows an organized breakdown of our grocery bag.
def printed_list(grocery_list)
grocery_list.each {|item, quantity|
puts "#{item}: #{quantity}" }
end
printed_list(final_list)
| true
|
6b8d55651cce68c1ed27d5f6d49aa98f35e2d2cb
|
Ruby
|
FranklinZhang1992/unity-learning
|
/ruby/demo_tests/array_test.rb
|
UTF-8
| 544
| 3.578125
| 4
|
[] |
no_license
|
arr = nil
begin
puts "arr = nil, empty?: #{arr.empty?}"
rescue => err
puts "arr = nil, empty?: #{err}"
end
arr = []
puts "arr = [], empty?: #{arr.empty?}"
str = nil
begin
arr = str.split(' ')
p arr
rescue => err
puts "error: #{err}"
end
str = ""
arr = str.split(' ')
p arr
str = "0 1 2"
arr = str.split(' ')
p arr
arr = ["1", "a", "c", 2, "a"]
p arr
p arr.uniq
arr1 = ["1", "a", "3"].sort
arr2 = ["3", "1", "a"].sort
eql = arr1.eql?(arr2)
puts "arr1 == arr2 ? => #{eql}"
var1 = "v1"
var2 = "v2"
arr = [var1, var2]
p arr
| true
|
ea6846bc65b516e4c626fca5353eddb18fc0234a
|
Ruby
|
kg-coderta/atcoder
|
/abc/153.rb
|
UTF-8
| 265
| 3.25
| 3
|
[] |
no_license
|
A
a,b = gets.split.map(&:to_i)
if a % b == 0
puts a/b
else
puts (a/b) +1
end
B
a,b = gets.split.map(&:to_i)
c = gets.split.map(&:to_i)
d = c.length
attack = 0
for num in 0..d-1 do
attack += c[num]
end
if a <= attack
puts "Yes"
else
puts "No"
end
C
D
E
F
| true
|
4d0b97b59ec3c4d0bb16bc4561a7451d46dbd9ce
|
Ruby
|
feigningfigure/WDI_NYC_Apr14_String
|
/w02/d02/Emmanuel_Tucker/homework_d01_w02/sinatra_1.rb
|
UTF-8
| 649
| 2.84375
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader'
get '/' do
'Hello world'
end
get '/name/:name' do
"hello #{params[:name]}"
end
# Example:
# Request: '/tea/neel/omar'
# Response: 'neel and omar are having a lovely tea ceremony'
# Request: '/battle/matt/omar'
# Response: omar beats neel.
# note: the winner should be randomly generated.
get '/tea/:name_2/:name_1' do
" #{params[:name_2]} and #{params[:name_1]} will have a awesome tea party"
end
get '/battle/:name_2/:name_1' do
if rand(2) == 0
" #{params[:name_2]} beats #{params[:name_1]}."
else
" #{params[:name_1]} beats #{params[:name_2]}."
end
end
| true
|
ee0549bd5f7163c2023dc78aaa7c7f79106c2841
|
Ruby
|
beslnet/desafiosruby
|
/3.rb
|
UTF-8
| 149
| 3.0625
| 3
|
[] |
no_license
|
a = [1,2,3]
b = [:azul, :rojo, :amarillo]
c = ["Tacos", "Quesadillas", "Hamburguesas"]
abc = [a, b, c]
nuevo_arreglo = abc.flatten
p nuevo_arreglo
| true
|
ebdb1b6ca569ccb261b9ca34dea7c9a62e25c6fd
|
Ruby
|
GabrielRMorales/hangman
|
/hangman.rb
|
UTF-8
| 2,062
| 3.84375
| 4
|
[] |
no_license
|
require "csv"
require "yaml"
class Hangman
def initialize
list=File.readlines "5desk.csv"
@word=list.sample
while @word.length<5 || @word.length>12
@word=list.sample
end
@display_word=String.new
(@word.length-1).times do
@display_word<<"_"
end
@wrong_letters=[]
@counter=@word.length
ask_to_load
puts "#{@word}"
gameplay
end
def ask_to_load
puts "Welcome to hangman"
puts "Want to load your previous game? Y/N"
choice=gets.chomp
if choice.upcase=="Y"
load
gameplay
else
gameplay
end
end
def gameplay
while @display_word.include? "_"
display
puts "Want to save this game? Y/N"
choice=gets.chomp
if choice.upcase=="Y"
save
guess
else
guess
end
end
puts "Congratulations. The word was #{@word}"
end
def save
saved_game={ :word=>@word,
:display_word=>@display_word,
:wrong_letters=>@wrong_letters,
:counter=>@counter
}
File.open("save-file.yml","w") do |f|
f.write(saved_game.to_yaml)
end
end
def load
loaded_game=YAML.load_file("save-file.yml")
@word=loaded_game[:word]
@display_word=loaded_game[:display_word]
@wrong_letters=loaded_game[:wrong_letters]
@counter=loaded_game[:counter]
end
def display
if @counter<1
puts "GAME OVER"
else
puts "#{@display_word}"
puts "Wrong letters: #{@wrong_letters}"
puts "Remaining guess: #{@counter}"
@counter-=1
end
end
def guess
puts "Guess a letter"
user_guess=gets.chomp
puts "You guessed #{user_guess}"
word_check=@word.clone
if @word.include? (user_guess.downcase)||(user_guess.upcase)
@word.each_char do |char|
if char==user_guess.upcase || char==user_guess.downcase
@display_word[word_check.index(char)]=char
word_check[word_check.index(char)]="_"
end
end
else
@wrong_letters.push(user_guess)
end
end
end
game=Hangman.new
game.ask_to_load
| true
|
42bd9122b2ab259ad3f213672f3baa1ddb1f96ae
|
Ruby
|
JLHill84/firstDayTest
|
/mod1/aug8/self.rb
|
UTF-8
| 298
| 3.546875
| 4
|
[] |
no_license
|
class Dog
attr_accessor :name, :owner
def initialize(name)
@name = name
end
def get_adopted(owner_name)
self.owner = owner_name
end
end
fido = Dog.new("fido")
# adopted(fido, "Steve")
puts fido.get_adopted("Cheesus")
# puts fido.name = "FIDO"
| true
|
0ba6c57816ddf8316479a406f0c188c322af53b8
|
Ruby
|
halogenandtoast/nhk-reader
|
/lib/base64_image.rb
|
UTF-8
| 310
| 2.953125
| 3
|
[] |
no_license
|
class Base64Image
def initialize(content_type, data)
@content_type = content_type
@data = data
end
def to_s
"data:#{content_type};base64,#{encoded_content}"
end
private
attr_reader :content_type, :data
def encoded_content
@_encoded_content ||= Base64.encode64(data)
end
end
| true
|
8e2cd566562714a47b6895101cbcd7bafebdc3b4
|
Ruby
|
gee-forr/mentoring_with_citizen428
|
/exercise01_card_game/card_dealer_tests.rb
|
UTF-8
| 1,922
| 3.25
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# Need a newer version of minitest for assert_output, these two lines do that.
require 'rubygems'
gem 'minitest'
require 'minitest/autorun'
require './card_dealer'
class TestCardGame < MiniTest::Unit::TestCase
def setup
srand(1) # Seed the randomizer so that deck shuffles are always the same
@games = {
std_game: CardGame.new,
four_player: CardGame.new,
six_player: CardGame.new(2)
}
end
def test_class_loads
@games.each_value do |value|
assert_instance_of CardGame, value
end
end
def test_num_of_cards_dealt_and_display # These methods are linked, they need to be run together
assert_equal 5, @games[:std_game].deal
assert_equal 20, @games[:four_player].deal(4)
assert_equal 60, @games[:six_player].deal(6, 10)
# if you want indentation in heredocs you can use <<-eod
std_game = <<eod
Player1: Th | Ah | Td | Qc | Js
Cards used: 5
Cards remaining: 47
eod
four_player = <<eod
Player1: Qs | 4h | 5d | Ac | 2d
Player2: 2h | 7c | As | Ah | 9h
Player3: Kc | Ks | 5h | Jd | 8c
Player4: 4c | 7d | Td | Qc | 3s
Cards used: 20
Cards remaining: 32
eod
six_player = <<eod
Player1: 5c | 8s | Jc | Ks | Ad | 8c | 5s | Qd | 9c | Kc
Player2: As | 7d | Td | 9c | 5d | Kd | Th | 3h | Qh | 8s
Player3: Tc | 3s | 7s | Jd | Ac | Qh | 3s | Jc | 9h | 8h
Player4: 4h | 7s | 2h | 6c | 2s | Th | Jh | 5h | 8c | 8h
Player5: 6d | 4d | 6d | 4c | 5d | 9h | 7d | 2c | Qs | Ah
Player6: 9s | 4c | Jd | 4s | Jh | 9d | 2d | 3h | 2h | Ts
Cards used: 60
Cards remaining: 44
eod
assert_output std_game do
@games[:std_game].display
end
assert_output four_player do
@games[:four_player].display
end
assert_output six_player do
@games[:six_player].display
end
end
end
| true
|
76dcc58033efc6911179f896b763532e4d117112
|
Ruby
|
rodhilton/console_table
|
/examples/stocks.rb
|
UTF-8
| 1,490
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require 'console_table'
require 'json'
require 'net/http'
require 'open-uri'
require 'colorize'
symbols = ["YHOO", "AAPL", "GOOG", "MSFT", "C", "MMM", "KO", "WMT", "GM", "IBM", "MCD", "VZ", "HD", "DIS", "INTC"]
params = symbols.collect{|s| "\"#{s}\"" }.join(",")
url = "http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol in (#{params})&env=http://datatables.org/alltables.env&format=json"
uri = URI.parse(URI::encode(url))
response = Net::HTTP.get_response(uri)
json = JSON.parse(response.body)
table_config = [
{:key=>:symbol, :title=>"Symbol", :size=>6},
{:key=>:name, :title=>"Name", :size=>17},
{:key=>:price, :title=>"Price", :size=>5, :justify=>:right},
{:key=>:change, :title=>"Change", :size=>7, :justify=>:right},
{:key=>:recommendation, :title=>"Recommendation", :size=>15, :justify=>:right}
]
ConsoleTable.define(table_config, :title=>"Stock Prices") do |table|
json["query"]["results"]["quote"].each do |j|
change = j["ChangeRealtime"]
if change.start_with?("+")
change = change.green
else
change = change.red
end
recommendation = (rand() <= 0.5) ? "BUY!".white.on_green.bold.underline : "Sell".yellow
table << [
j["Symbol"].magenta,
j["Name"],
j["LastTradePriceOnly"],
change,
recommendation
]
end
table.footer << "Recommendations randomly generated"
end
| true
|
1f15bdd0810fb65a2dd623a2f2e12e323eda1052
|
Ruby
|
ellehallal/ruby-refresher
|
/modules/length-conversions.rb
|
UTF-8
| 440
| 3.6875
| 4
|
[] |
no_license
|
module LengthConversions
WEBSITE = "http://website.com" #constant
def self.miles_to_feet(miles) #method
miles * 5280
end
def self.miles_to_inches(miles)
feet = miles_to_feet(miles)
feet * 12
end
def self.miles_to_cm(miles)
inches = miles_to_inches(miles)
inches / 2.5
end
end
puts LengthConversions.miles_to_feet(100)
puts LengthConversions.miles_to_inches(200)
puts LengthConversions.miles_to_cm(300)
| true
|
0463cf42663d37d985e279335761f660b2160847
|
Ruby
|
Dexter1210/Rubyidea
|
/metaprogramming/finders.rb
|
UTF-8
| 1,968
| 3.140625
| 3
|
[] |
no_license
|
require "active_support/inflector"
$db={
users: [{id:1,username:"user1"},
{id:2,username:"user2"}],
tasks:[
{id:1,title:"task1",completed:true},
{id:2,title:"task1",completed:false},
{id:3,title:"task3",completed:true}
],
projects: [
{ id: 1, title: "Project 1", owner: "devesh"},
{ id: 2, title: "Project 2", owner: "yogesh"},
{ id: 3, title: "Project 3", owner: "shritesh"},
{ id: 4, title: "Project 4", owner: "khushboo"},
],
technologies:[
{id:1, tech:"BlockChain"},
{id:2, tech:"Random Forest Regression"},
{id:3, tech:"Web API"},
{id:4, tech:"Neural Networks"}
]
}
class Model
def initialize
puts "#{self} #{class_name} is getting initialized...."
end
def self.connect
class_name= to_s.downcase.pluralize
@data=$db[:"#{class_name}"]
end
def self.data
@data
end
def self.method_missing(method,*args,&block)
method_tokens=method.to_s.split("_")
search_field=method_tokens[2]
if method_tokens[0]=="find"
results=[]
self.data.each do |row|
if row.key?(search_field.to_sym)
if args[0]==row[search_field.to_sym]
results<<row
end
end
end
results
else
super
end
end
end
class User < Model
connect
end
class Task < Model
connect
end
class Project < Model
connect
end
class Technology < Model
connect
end
puts "Find task by id1"
task=Task.find_by_id(1){
puts "Successful found it"
}
p task
tasks=Task.find_by_completed(true)
p tasks
tasks=Task.find_by_title("task1")
p tasks
user1=User.find_by_id(2)
p user1
technology_used1=Technology.find_by_id(1)
p technology_used1
technology_used2=Technology.find_by_tech("BlockChain")
p technology_used2
| true
|
1f6eaa2f1648e60fe7970e0eafc7966f32b828a8
|
Ruby
|
XohoTech/RubyTest
|
/spec/word_list/count_frequency_spec.rb
|
UTF-8
| 838
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
require_relative '../../word_list/word_list.rb'
require_relative '../../helpers/words_from_string.rb'
RSpec.describe WordList, "#count_frequency" do
before(:each) do
raw_text = %{Array of multiple string values from string of words.}
word_list = words_from_string(raw_text)
@word_list = WordList.new(word_list)
end
context "with word list" do
let(:expected_frequency_count) { {"array"=>1, "of"=>2, "multiple"=>1, "string"=>2, "values"=>1, "from"=>1, "words"=>1} }
let(:expected_top_three) { ["of: 2", "string: 2", "values: 1"] }
it "counts frequency of duplicate words correctly" do
expect(@word_list.count_frequency).to eq expected_frequency_count
end
it "returns top 3 frequency counts in descending order" do
expect(@word_list.top_three).to eq expected_top_three
end
end
end
| true
|
6f5c3f6fdc66af12bb710a18eb123f6dad2b4362
|
Ruby
|
greytape/learn_to_program_exercises
|
/program_logger.rb
|
UTF-8
| 511
| 3.515625
| 4
|
[] |
no_license
|
$nesting_depth = 0
def log block_description, &block
$nesting_depth += 1
$nesting_depth.times {print" "}
puts "Block Started!"
output = block.call
$nesting_depth.times {print" "}
puts "Block finished!"
$nesting_depth -= 1
end
log "outer_block" do
log "little block" do
$nesting_depth.times {print" "}
puts "small"
end
log "another block" do
$nesting_depth.times {print" "}
puts "again"
end
$nesting_depth.times do
print " "
end
puts "Big one."
end
| true
|
d2484792654b6cea592adea1f68d8425c2f17db9
|
Ruby
|
dineshkummarc/ads
|
/sales.iheart.com/_lib/dump.rb
|
UTF-8
| 231
| 2.671875
| 3
|
[] |
no_license
|
require 'yaml'
conf = YAML.load_file("_config.yml")
type = ARGV[0]
if type == 'css' || type == 'js'
conf[type].each do |i|
print File.open("_site/assets/#{type}/#{i}").read
end
else
puts "C'mon, give me something here!"
end
| true
|
1fcbdc50e4787ac3de87a7063745d3e7fdaef7d5
|
Ruby
|
sandrods/legenda
|
/app/models/legendas.rb
|
UTF-8
| 623
| 2.59375
| 3
|
[] |
no_license
|
require 'open-uri'
class Legendas
def self.destaques
ret = extract("http://www.legendas.tv/destaques.php")
ret << extract("http://www.legendas.tv/destaques.php?start=24")
ret.flatten
end
private
def self.extract(url)
doc = Hpricot(open(url))
leg = []
(doc/"div.Ldestaque").each do |d|
nome = $1 if d.attributes['onmouseover']=~/gpop\('(?:.*','){2}(.*)','(.*','){5}/
id = $1 if d.attributes['onclick']=~/javascript:abredown\('(.*)'\);/
img = (d/"img")[0].attributes['src']
leg << { :nome => nome[0..35], :id => id, :image => img }
end
leg
end
end
| true
|
c36f80f4f5a8f01ab9eea31adfd66e05235d7942
|
Ruby
|
pkb4112/learn_ruby
|
/02_calculator/calculator.rb
|
UTF-8
| 606
| 3.484375
| 3
|
[] |
no_license
|
#write your code here
def add(a,b)
return a + b
end
def subtract (a,b)
return a-b
end
def sum (ray)
ray_sum = 0
if ray[0]==nil
return 0
else
ray.each do |i|
ray_sum=ray_sum+i
end
return ray_sum
end
end
def multiply (a)
product = 1
if a[0] != nil
a.each do |i|
product = product*i
end
return product
else
return 0
end
end
def power (a,b)
return a**b
end
def factorial(a)
if a!=0
product = 1
ray=[]
(a+1).times do |i|
ray << i
end
ray=ray-[0]
ray.each do |j|
product=product*j
end
return product
else
return 0
end
end
| true
|
af5637834abed355de54fcb07853eab85131b301
|
Ruby
|
todesking/power_assert-ruby
|
/lib/power_assert.rb
|
UTF-8
| 1,868
| 2.71875
| 3
|
[] |
no_license
|
require 'ripper'
require 'patm'
require 'typedocs'
module PowerAssert
include Typedocs::DSL
tdoc.typedef :@AST, 'Array'
tdoc.typedef :@Bool, 'TrueClass|FalseClass'
def self.current_context
Thread.current[:power_assert_context] ||= Context.new
end
class Context
def add(expr, value)
end
end
class Extractor
include Typedocs::DSL
tdoc 'String -> Numeric -> @AST'
def extract(path, line_no)
whole_ast = Ripper.sexp(File.read(path))
extract_from_ast(whole_ast, line_no)
end
tdoc '@AST -> Numeric -> ?@AST|nil -> @AST|nil'
def extract_from_ast(ast, line_no, block_ast = nil)
p = ::Patm
_1 = p._1
_2 = p._2
__ = p._any
case ast
when m = p.match([p.or(:do_block, :brace_block), p._any, p._any[:exprs]])
m[:exprs].each do|expr|
found = extract_from_ast(expr, line_no, ast)
return found if found
end
when m = p.match([:binary, _1, __, _2])
found =extract_from_ast(m._1, line_no, block_ast) ||
extract_from_ast(m._2, line_no, block_ast)
return found if found
when m = p.match([:@int, __, [_1, __]])
return block_ast if block_ast && m._1 == line_no
else
if ast.is_a?(Array) && ast.size > 0
exprs =
if ast[0].is_a?(Symbol) # some struct
ast[1..-1]
else
ast
end
exprs.each do|expr|
next unless expr.is_a?(Array)
found = extract_from_ast(expr, line_no, nil)
return found if found
end
end
end
nil
end
end
class Injector
include Typedocs::DSL
tdoc '@AST -> Tree'
def parse(ast)
Tree.new
end
end
class Tree
include Typedocs::DSL
tdoc 'String'
def to_source
""
end
end
end
| true
|
6c922c77cfd97a7243a20faf1a14c0e27ce26363
|
Ruby
|
tuzz/pbrt
|
/lib/pbrt/statement/variadic.rb
|
UTF-8
| 305
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module PBRT
class Statement
class Variadic
def initialize(directive, kind, parameter_list)
@directive = directive
@kind = kind
@parameter_list = parameter_list
end
def to_s
%(#@directive "#@kind" #@parameter_list).strip
end
end
end
end
| true
|
6f28c4a508d80c1e3cb959f4197de06cfb8a1597
|
Ruby
|
ksolomon7/ruby-oo-object-relationships-my-pets-nyc04-seng-ft-071220
|
/lib/cat.rb
|
UTF-8
| 145
| 2.703125
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require 'pry'
class Cat
attr_accessor :name,:owner
def initialize(name_par,owner_par)
@name=name_par
end
end
# binding.pry
0
| true
|
e7bf38c7790681dfb5beea1e0a6337a432d10f91
|
Ruby
|
vickiticki/ruby-exercises
|
/ruby_basics/11_nested_collections/exercises/nested_array_exercises.rb
|
UTF-8
| 2,658
| 3.921875
| 4
|
[
"MIT"
] |
permissive
|
def blank_seating_chart(number_of_rows, seats_per_row)
# return a 2d array to represent a seating chart that contains
# number_of_rows nested arrays, each with seats_per_row entries of nil to
# represent that each seat is empty.
# Example: blank_seating_chart(2, 3) should return:
# [
# [nil, nil, nil],
# [nil, nil, nil]
# ]
# NOTE: if one of the nested arrays is changed, the others should **not**
# change with it
Array.new(number_of_rows){Array.new(seats_per_row)}
end
def add_seat_to_row(chart, row_index, seat_to_add)
# take a chart (2d array) and add seat_to_add to the end of the row that is
# at row_index index of the chart, then return the chart
chart[row_index].push(seat_to_add)
chart
end
def add_another_row(chart, row_to_add)
# take a chart and add row_to_add to the end of the chart,
# then return the chart.
chart.push(row_to_add)
chart
end
def delete_seat_from_row(chart, row_index, seat_index)
# take a chart and delete the seat at seat_index of the row at row_index of
# the chart, then return the chart
# Hint: explore the ruby docs to find a method for deleting from an array!
chart[row_index].delete_at(seat_index)
chart
end
def delete_row_from_chart(chart, row_index)
# take a chart and delete the row at row_index of the chart,
# then return the chart
chart.delete_at(row_index)
chart
end
def count_empty_seats(chart)
# take a chart and return the number of empty (nil) seats in it
# NOTE: `chart` should **not** be mutated
num = 0
chart.each_with_index do |row, row_index|
row.each_with_index do |chair, col_index|
if chair == nil
num += 1
end
end
end
return num
end
def find_favorite(array_of_hash_objects)
# take an array_of_hash_objects and return the hash which has the key/value
# pair :is_my_favorite? => true. If no hash returns the value true to the key
# :is_my_favorite? it should return nil
# array_of_hash_objects will look something like this:
# [
# { name: 'Ruby', is_my_favorite?: true },
# { name: 'JavaScript', is_my_favorite?: false },
# { name: 'HTML', is_my_favorite?: false }
# ]
# TIP: there will only be a maximum of one hash in the array that will
# return true to the :is_my_favorite? key
# array_of_hash_objects.each do |hash = nil|
# hash.select { |key, value| value == true}
# return hash
# end
# array_of_hash_objects.each do |hash|
# hash.select do |key, value|
# if value == true
# return hash
# else
# return nil
# end
# end
# end
array_of_hash_objects.find{|hash| hash[:is_my_favorite?] == true}
end
| true
|
a46a2de54bfb579b3ad8f4739ed016d99a54da31
|
Ruby
|
Krolmir/ruby-exercises
|
/intro_to_programming/methods/greeting.rb
|
UTF-8
| 211
| 4.46875
| 4
|
[] |
no_license
|
#Program that prints a greeting message after asking a user to input their name
def greeting(name)
puts "Welcome #{name} to my greeting program!"
end
puts "Please enter your name:"
n = gets.chomp
greeting(n)
| true
|
522632dffd622c5370a1fd43726eec1a6b12580d
|
Ruby
|
djones/pound-append
|
/pound_append
|
UTF-8
| 4,896
| 3.375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
# == Synopsis
# Allows you to programmatically add new sites to a pound configuration file
#
# == Examples
# This will add a new site to the configuration file running port 10200 matching requests "(www\.|)site\.com"
# So this would link both requests coming from www.site.com and site.com to go to 127.0.0.1:10200
#
# pound_append "(www\.|)site\.com" 10200
# == Usage
# pound_append site_match local_port [options]
#
# For help use: pound_append -h
#
# == Options
# -c, --config-path [NOT COMPLETED] Defaults to /etc/pound/pound.cfg
# -h, --help Displays help message
# -v, --version Display the version, then exit
# -q, --quiet Output as little as possible, overrides verbose
# -V, --verbose Verbose output
#
# == Author
# David Jones, http://www.d-jones.com
# Credits to Todd Weth (http://blog.infinitered.com) for the command-line application skeleton
#
# == Copyright
# Copyright (c) 2008 David Jones. Licensed under the MIT License:
# http://www.opensource.org/licenses/mit-license.php
require 'optparse'
require 'rdoc/usage'
require 'ostruct'
require 'date'
class App
VERSION = '0.0.1'
attr_reader :options
def initialize(arguments, stdin)
@arguments = arguments
@stdin = stdin
# Set defaults
@options = OpenStruct.new
@options.verbose = false
@options.quiet = false
end
# Parse options, check arguments, then process the command
def run
if parsed_options? && arguments_valid?
puts "Start at #{DateTime.now}\\n\\n" if @options.verbose
output_options if @options.verbose # [Optional]
process_arguments
process_command
puts "\\nFinished at #{DateTime.now}" if @options.verbose
else
output_usage
end
end
protected
def parsed_options?
# Specify options
opts = OptionParser.new
opts.on('-v', '--version') { output_version ; exit 0 }
opts.on('-h', '--help') { output_help }
opts.on('-V', '--verbose') { @options.verbose = true }
opts.on('-q', '--quiet') { @options.quiet = true }
opts.parse!(@arguments) rescue return false
process_options
true
end
# Performs post-parse processing on options
def process_options
@options.verbose = false if @options.quiet
end
def output_options
puts "Options:\\n"
@options.marshal_dump.each do |name, val|
puts " #{name} = #{val}"
end
end
# True if required arguments were provided
def arguments_valid?
true if @arguments.size > 1
end
# Setup the arguments
def process_arguments
# TO DO - place in local vars, etc
end
def output_help
output_version
RDoc::usage() #exits app
end
def output_usage
RDoc::usage('usage') # gets usage from comments above
end
def output_version
puts "#{File.basename(__FILE__)} version #{VERSION}"
end
def process_command
site_match = @arguments[0]
port = @arguments[1]
config = @options.confg || "/etc/pound/pound.cfg"
if @options.verbose
puts "The site to match is: #{site_match}"
puts "Request matching that site will be calling 127.0.0.1:#{port}"
puts "The configuration file is located at #{config}"
puts "Opening pound configuration file"
end
# Open the configuration file into an array of lines
config_lines = IO.readlines(config)
# Pop lines off the end until we pop the last "end" off
result = ""
while(!(result =~ /.*(e|E)nd.*/)) do
result = config_lines.pop
end
puts "Removed the last 'end' in the configuration" if @options.verbose
# adds the configuration
config_lines << " \n"
config_lines << " Service\n"
config_lines << " HeadRequire \"Host: #{site_match}\"\n"
config_lines << " \n"
config_lines << " BackEnd\n"
config_lines << " Address 127.0.0.1\n"
config_lines << " Port #{port}\n"
config_lines << " End\n"
config_lines << " end\n"
config_lines << "end\n"
puts "Writing to the pound configuration file:" if @options.verbose
File.open(config, "w") do |file|
config_lines.each do |line|
puts "Wrote: #{line}" if @options.verbose
file.write(line)
end
end
puts "Configuration complete."
puts "#{site_match} will now call 127.0.0.1:#{port}"
end
def process_standard_input
input = @stdin.read
end
end
# Create and run the application
app = App.new(ARGV, STDIN)
app.run
| true
|
9418cfe1c921782fe7b7a506282581605c236c80
|
Ruby
|
sforsell/phase-0-tracks
|
/ruby/gps6/my_solution.rb
|
UTF-8
| 4,421
| 3.890625
| 4
|
[] |
no_license
|
# Virus Predictor
# I worked on this challenge [by myself].
# I spent [3] hours on this challenge.
# EXPLANATION OF require_relative
# file exists in same directory hence the "relative"
# fetches the file in qoutes.
require_relative 'state_data'
class VirusPredictor
# pulls in data for each instance upon initialization.
def initialize(state_of_origin, population_density, population)
@state = state_of_origin
@population = population
@population_density = population_density
end
# virus effects outputs a string, one from each method inside.
def virus_effects
predicted_deaths
speed_of_spread
end
private
# checks for density and based on density level number of deaths go up. Number
# of deaths are based on population times a float.
def predicted_deaths
# predicted deaths is solely based on population density
if @population_density > 199
total_deaths = (@population * 0.4)
elsif @population_density > 149
total_deaths = (@population * 0.3)
elsif @population_density > 99
total_deaths = (@population * 0.2)
elsif @population_density > 49
total_deaths = (@population * 0.1)
else
total_deaths = (@population * 0.05)
end
print "#{@state} will lose #{total_deaths.floor} people in this outbreak"
end
# again checks for population density and based on that returns a number: speed.
def speed_of_spread #in months
# We are still perfecting our formula here. The speed is also affected
# by additional factors we haven't added into this functionality.
if @population_density > 199
speed = 0.5
elsif @population_density > 149
speed = 1
elsif @population_density > 99
speed = 1.5
elsif @population_density > 49
speed = 2
else
speed = 2.5
end
puts " and will spread across the state in #{speed} months.\n\n"
end
end
#=======================================================================
# DRIVER CODE
# initialize VirusPredictor for each state
# iteration would get the state "strings" a key and the hash as the value.
=begin
## iteration practice ##
outerHash = {
"ONE" => {one: "*1*", eleven: "*11*", hundredeleven: "*111*"},
"TWO" => {two: "*2*", twentytwo: "*22*", two0022: "*222*"},
"THREE" => {three: "*3*", thirtythree: "*33*", three0033: "*333*"},
"FOUR" => {four: "*4*", fortyfour: "*44*", four0044: "*444*"},
"FIVE" => {five: "*5*", fiftyfive: "*55*", five0055: "*555*"}
}
outerHash.each do | outer_key , outer_value|
puts "#{outer_key}"
outerHash[outer_key].each do | inner_key, inner_value |
puts " #{inner_key} + #{inner_value}"
end
end
puts outerHash["ONE"][:one]
=end
STATE_DATA.each_key do | state |
VirusPredictor.new(state, STATE_DATA[state][:population_density], STATE_DATA[state][:population]).virus_effects
end
=begin
alabama = VirusPredictor.new("Alabama", STATE_DATA["Alabama"][:population_density], STATE_DATA["Alabama"][:population])
alabama.virus_effects
jersey = VirusPredictor.new("New Jersey", STATE_DATA["New Jersey"][:population_density], STATE_DATA["New Jersey"][:population])
jersey.virus_effects
california = VirusPredictor.new("California", STATE_DATA["California"][:population_density], STATE_DATA["California"][:population])
california.virus_effects
alaska = VirusPredictor.new("Alaska", STATE_DATA["Alaska"][:population_density], STATE_DATA["Alaska"][:population])
alaska.virus_effects
=end
#=======================================================================
# Reflection Section
# the difference in syntax is that the state key is a string and references to its
# value with a rocket => and the population_density and population are symbols.
# also, the states are all on a new line whereas the state hash is on one line.
# require_relative: you can give require_relitve a relative path (not required if
# in the same directory).
# require searches by an absolute path from your top directory.
# you can iterate over hashes using .each, .each_key, .each_pair and .each_value.
# At first, just the amount of variables stood out to me, but the second thing was
# that they weren't instance variables and when I looked at the methods
# in virus_effects they weren't even using the method parameters, they were using
# the instance variables.
# The concept I mostly solidified was iteration, but nested data also got a refresher.
| true
|
f19341e58fff9beb7655e1eac58832b2677431c8
|
Ruby
|
dalspok/LS101-lesson-2
|
/rps_advanced.rb
|
UTF-8
| 2,184
| 4.0625
| 4
|
[] |
no_license
|
CHOICES_TO_KEYS = { "r" => ["Rock", 5],
"p" => ["Paper", 3],
"s" => ["Scissors", 1],
"l" => ["Lizard", 2],
"o" => ["spOck", 4] }
VALID_CHOICES = CHOICES_TO_KEYS.values.map { |item| item[0] }
VALID_INPUTS = CHOICES_TO_KEYS.keys
score = [0, 0]
def prompt(message)
puts "=> #{message}"
end
def print_result(difference)
prompt case difference
when (3..4)
"You win!"
when (1..2)
"Computer wins!"
else
"It's a tie"
end
end
def print_choices(user_choice, computer_choice)
output_user_choice = CHOICES_TO_KEYS[user_choice][0].upcase
output_computer_choice = CHOICES_TO_KEYS[computer_choice][0].upcase
puts "\nYou chose #{output_user_choice}, " \
"computer chose #{output_computer_choice}"
end
def compute_results(user_choice, computer_choice, score)
print_choices(user_choice, computer_choice)
difference = (CHOICES_TO_KEYS[user_choice][1] -
CHOICES_TO_KEYS[computer_choice][1]) % 5
print_result(difference)
change_score(difference, score)
end
def change_score(difference, score)
case difference
when (3..4)
score[0] += 1
when (1..2)
score[1] += 1
end
end
# Main program
puts "-------------------------------------------"
puts "Welcome to rock-paper-scissors-lizard-Spock"
puts "-------------------------------------------"
puts "For your choice, type first letter only (or 'o' for SpOck)\n"
loop do
user_choice = ""
# User choice
loop do
prompt VALID_CHOICES.join(", ") + "?"
user_choice = gets.chomp.strip.downcase
if VALID_INPUTS.include?(user_choice)
break
else
prompt "Not a valid choice. type first letter only (or 'o' for SpOck)"
end
end
# Computer choice and results
computer_choice = VALID_INPUTS.sample
compute_results(user_choice, computer_choice, score)
# Score?
prompt "SCORE (you:computer) #{score[0]}:#{score[1]}"
break if score[0] == 5 || score[1] == 5
end
puts "-----------------------------------"
puts "#{score[0] == 5 ? 'Congratulations, you' : 'Computer'} won. Game over."
puts "-----------------------------------"
| true
|
25cc6864d11c3ce3547a0626241e9f03f00a7961
|
Ruby
|
alex-choy/a-A_notes
|
/01_week/03_day/nauseating_numbers/test/04_nn_test.rb
|
UTF-8
| 1,801
| 3.984375
| 4
|
[] |
no_license
|
require "../lib/04_nauseating_numbers"
### mersenne_prime
p "Mersenne Prime"
p mersenne_prime(1) # 3
p mersenne_prime(2) # 7
p mersenne_prime(3) # 31
p mersenne_prime(4) # 127
p mersenne_prime(6) # 131071
### triangular_word
puts "\n\nTriangular Word"
p triangular_word?("abc") # true
p triangular_word?("ba") # true
p triangular_word?("lovely") # true
p triangular_word?("question") # true
p triangular_word?("aa") # false
p triangular_word?("cd") # false
p triangular_word?("cat") # false
p triangular_word?("sink") # false
### consecutive_collapse
puts "\n\nConsecutive Collapse"
p consecutive_collapse([3, 4, 1]) # [1]
p consecutive_collapse([1, 4, 3, 7]) # [1, 7]
p consecutive_collapse([9, 8, 2]) # [2]
p consecutive_collapse([9, 8, 4, 5, 6]) # [6]
p consecutive_collapse([1, 9, 8, 6, 4, 5, 7, 9, 2]) # [1, 9, 2]
p consecutive_collapse([3, 5, 6, 2, 1]) # [1]
p consecutive_collapse([5, 7, 9, 9]) # [5, 7, 9, 9]
p consecutive_collapse([13, 11, 12, 12]) # []
### pretentious_primes
puts "\n\nPretentious Primes"
p pretentious_primes([4, 15, 7], 1) # [5, 17, 11]
p pretentious_primes([4, 15, 7], 2) # [7, 19, 13]
p pretentious_primes([12, 11, 14, 15, 7], 1) # [13, 13, 17, 17, 11]
p pretentious_primes([12, 11, 14, 15, 7], 3) # [19, 19, 23, 23, 17]
p pretentious_primes([4, 15, 7], -1) # [3, 13, 5]
p pretentious_primes([4, 15, 7], -2) # [2, 11, 3]
p pretentious_primes([2, 11, 21], -1) # [nil, 7, 19]
p pretentious_primes([32, 5, 11], -3) # [23, nil, 3]
p pretentious_primes([32, 5, 11], -4) # [19, nil, 2]
p pretentious_primes([32, 5, 11], -5) # [17, nil, nil]
| true
|
08027036f97474bebc4e0a0778c4210b2012131c
|
Ruby
|
enogrob/axe-engine
|
/lib/axe_engine.rb
|
UTF-8
| 2,299
| 2.6875
| 3
|
[] |
no_license
|
#!C:\Program Files\ruby-1.8\bin\ruby.exe
#--
# Copyright (C) 2006 by Ericsson, GSDC Brazil, SW Deployment C.C.
# KSTool : Ruby Programming community
# Prepared : EBS/HD/SB Roberto Nogueira
# Date : 2006-08-07
# Version : 0.0.1
# Ruby : 1.8.4
# Windows : 2000
# File : axe_engine.rb
# Purpose : A package for handling Ericsson AXE printouts.
#++
require 'rubygems'
require 'axe_clip'
=begin
=List AXE commands specifications contained in a command log file.
== * Input is the full specificcation of command log file.
== * Output is an sorted array of AXE command specifications.
==
== e.g. cmdlist('C:\SAB01_pre-study.log')
== => ['IOEXP;', 'CACLP;', ..]
==
== Note: The output is also copied to Clipboard.
=end
def cmd_list(a_cmdfile)
clip = Clipboard.instance
if !File.exist?(a_cmdfile)
clip.paste("=> File: #{a_cmdfile} do not exist !\r\n")
puts "=> File: #{a_cmdfile} do not exist !"
return
end
result =[]
File.open(a_cmdfile, 'r') do |file|
file.each do |line|
result << line.slice(/(\w{5,5})(:|;)((\w|:|=|;|,|\s|-)*)/).upcase.chomp.rstrip if line =~ /\A(\<|:)(\w{5,5})(:|;)/
end
end
clip.paste(result.sort.join("\r\n"))
result.sort
end
=begin
=Get an AXE command printout contained in a command log file.
== * Input is the full specificcation of command log file, and the AXE
== command.
== * Output is an array of AXE command printout.
== e.g. cmdget('C:\SAB01_pre-study.log', 'CACLP;')
== => ['<CACLP;', ..]
==
== Note: The output is also copied to Clipboard.
=end
def cmd_get(a_cmdfile, a_command)
clip = Clipboard.instance
if !File.exist?(a_cmdfile)
clip.paste("=> File: #{a_cmdfile} do not exist !\r\n")
puts "=> File: #{a_cmdfile} do not exist !"
return
end
result = []
File.open(a_cmdfile, 'r') do |file|
while line = file.gets
line.upcase!
next if ! line.include?(a_command.upcase)
result << line.chomp.rstrip
break line
end
while line = file.gets
line.upcase!
result << line.chomp.rstrip
next if ! (line =~ /^END/)
break line
end
end
clip.paste(result.join("\r\n"))
result
end
def cmd_methods
(self.methods - Object.methods).sort
end
| true
|
0ba51e5e4759519580296e069e7dbcdbecacc127
|
Ruby
|
denvercm/serviceinch-rails
|
/app/models/user.rb
|
UTF-8
| 1,554
| 2.515625
| 3
|
[] |
no_license
|
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
cattr_reader :per_page
@@per_page = 10
has_one :user_access
validates :login, :presence => true,
:length => {:within => 3..40},
:uniqueness => true,
:format => {:with => Authentication.login_regex, :message => Authentication.bad_login_message}
validates :name, :length => {:maximum => 100},
:format => {:with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true}
validates :email, :presence => true,
:length => {:within => 6..100},
:uniqueness => true,
:format => {:with => Authentication.email_regex, :message => Authentication.bad_email_message}
# HACK HACK HACK -- how to do attr_accessible from here?
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :name, :password, :password_confirmation
def self.authenticate(login, password)
return nil if login.blank? || password.blank?
u = where(:login => login.downcase).includes(:user_access).first # need to get the salt
u && u.authenticated?(password) ? u : nil
end
def login=(value)
self[:login] = value ? value.downcase : nil
end
def email=(value)
self[:email] = value ? value.downcase : nil
end
end
| true
|
87e7467329899aa8bbff298ba301c14f43930217
|
Ruby
|
sadah/AtCoder
|
/BeginnersSelection/abs/abc085b/Main.rb
|
UTF-8
| 191
| 2.65625
| 3
|
[] |
no_license
|
def solve(n, y)
ret = [-1, -1, -1]
(0..n).each do |i|
(0..(n - i)).each do |j|
k = n - i - j
if()
end
end
end
n, y = gets.strip.split.map(&:to_i)
puts solve(n, y)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.