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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
16273bf45c3aa515175ed339690790395e2d7e70
|
Ruby
|
luciolang/lucio
|
/spec/times_spec.rb
|
UTF-8
| 943
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
describe Lucio do
context 'times' do
before :each do
@lucio = Lucio.new
end
it 'without parameters should return zero' do
@lucio.eval('(*)').should == 1
end
it 'with one value should return that value' do
@lucio.eval('(* 3)').should == 3
end
it 'with two values should return the multiplication' do
@lucio.eval('(* 3 5)').should == 15
end
it 'with nested lists should eval the list before return the multiplication' do
@lucio.eval('(* 3 (* 3 2))').should == 18
end
it 'with neeeeeeesteeeeeeeed freeeeezy!' do
@lucio.eval('(* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 (* 3 2))))))))))))))').should == (3 ** 14) * 2
end
it 'with invalid operator should raise error' do
lambda {@lucio.eval('((* 3 4))')}.should raise_error UnboundSymbolException
end
end
end
| true
|
b87251372c07a86bc15e725f7d926e42f725b1a9
|
Ruby
|
threeifbywhiskey/houston
|
/rb/10.rb
|
UTF-8
| 107
| 3
| 3
|
[] |
no_license
|
require 'prime'
gen = Prime.each
sum = 0
while (n = gen.next) < 2e6
sum += n unless n > 2e6
end
p sum
| true
|
c6fcecd38afbad4abb4cd87e59f7474d964549c4
|
Ruby
|
ncalibey/Launch_School
|
/exercises/challenges/med_01/med_106.rb
|
UTF-8
| 306
| 3.671875
| 4
|
[] |
no_license
|
# med_106.rb - Grade School
class School
def initialize
@roster = Hash.new { |roster, grade| roster[grade] = [] }
end
def to_h
@roster.sort.to_h
end
def add(name, grade)
(@roster[grade] << name).sort!
end
def grade(grade)
@roster[grade] || []
end
end
| true
|
659b32864275f3b7e901c3b80a3ceffca92ccc14
|
Ruby
|
AgileVentures/shf-project
|
/app/services/adapters/company_to_schema_local_business.rb
|
UTF-8
| 2,345
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby
require Rails.root.join( 'app/models/concerns/company_hmarkt_url_generator')
module Adapters
#--------------------------
#
# @class Adapters::CompanyToSchemaLocalBusiness
#
# @desc Responsibility: (an Adapter) takes a Company and creates a
# schema.org local business
# Note that we need to create a local business so that we can have multiple
# locations (places).
#
# Pattern: Adapter
# @adaptee: Company
# target: SchemaDotOrg::LocalBusiness https://schema.org/LocalBusiness
#
#
# @author Ashley Engelund (ashley.engelund@gmail.com weedySeaDragon @ github)
# @date 2019-02-19
#
# @file company_to_schema_local_business.rb
#
#--------------------------
class CompanyToSchemaLocalBusiness < AbstractSchemaOrgAdapter
include CompanyHMarktUrlGenerator
def initialize(adaptee, url: '')
super(adaptee)
@target_url = url
end
def target_class
SchemaDotOrg::LocalBusiness
end
def set_target_attributes(target)
target.name = @adaptee.name
target.description = @adaptee.description
target.url = @target_url
target.email = @adaptee.email
target.telephone = @adaptee.phone_number
target.image = company_h_markt_url(@adaptee) # TODO this needs to be a permanent image and URL
target = AddressesIntoSchemaLocalBusiness.set_address_properties(@adaptee.addresses,
@adaptee.main_address,
target)
target.knowsLanguage = 'sv-SE'
target.knowsAbout = adapt_business_categories(@adaptee)
target
end
# TODO - this should come from a helper or someplace else, not be hardcoded. Fix when images are implemented
def url_for_co_hbrand_image(company)
"#{I18n.t('shf_medlemssystem_url')}/hundforetag/#{company.id}/company_h_brand"
end
# --------------------------------------------------------------------------------------------
private
def adapt_business_categories(adaptee)
return nil if adaptee.current_categories.empty?
adaptee.current_categories.map { |category| "#{I18n.t('dog').capitalize} #{category.name}" }
end
end
end
| true
|
f8cbea3885fee7c775546f7ef7fa6d7902381531
|
Ruby
|
lacie-unlam/robolucha
|
/app/helpers/application_helper.rb
|
UTF-8
| 498
| 2.625
| 3
|
[] |
no_license
|
module ApplicationHelper
def not_found(klass)
content_tag :p, content_tag(:em, "No se encontraron #{klass.model_name.human.pluralize}")
end
def format_time(time)
time ||= 0
mins, secs = time/60, time%60
"#{mins < 10 ? "0#{mins}" : mins}:#{secs < 10 ? "0#{secs}" : secs}"
end
def mins(time, format = nil)
m = time/60
format.nil? || m > 9 ? m : "0#{m}"
end
def secs(time, format = nil)
s = time%60
format.nil? || s > 9 ? s : "0#{s}"
end
end
| true
|
94c1df7cdbed15db798867ec09c5bc99f72de7b7
|
Ruby
|
danieled39/Ruby
|
/introduction.rb
|
UTF-8
| 181
| 3.15625
| 3
|
[] |
no_license
|
puts "Je Mapelle Daniele, et toi?"
name = gets.chomp
while name != "Jacob"
puts "Merci, enchante, #{name.capitalize}"
puts "Comment allez vu?"
name = gets.chomp.downcase
puts "Enchante"
end
| true
|
21e6a979f9b6e41963885aa4481a534105892e76
|
Ruby
|
parzydlo/darwin
|
/test/test_sentence_generator.rb
|
UTF-8
| 956
| 3.03125
| 3
|
[] |
no_license
|
require_relative '../cfg.rb'
require_relative '../grammar_rule.rb'
require_relative '../grammar_symbol.rb'
require_relative '../sentence_generator.rb'
# AB grammar in GNF:
# S -> a B
# S -> b A
# A -> a
# A -> a S
# A -> b A A
# B -> b
# B -> b S
# B -> a B B
nt_s = GrammarSymbol.new(:nonterminal, 'S')
nt_a = GrammarSymbol.new(:nonterminal, 'A')
nt_b = GrammarSymbol.new(:nonterminal, 'B')
t_a = GrammarSymbol.new(:terminal, 'a')
t_b = GrammarSymbol.new(:terminal, 'b')
r0 = GrammarRule.new(nt_s, [t_a, nt_b])
r1 = GrammarRule.new(nt_s, [t_b, nt_a])
r2 = GrammarRule.new(nt_a, [t_a])
r3 = GrammarRule.new(nt_a, [t_a, nt_s])
r4 = GrammarRule.new(nt_a, [t_b, nt_a, nt_a])
r5 = GrammarRule.new(nt_b, [t_b])
r6 = GrammarRule.new(nt_b, [t_b, nt_s])
r7 = GrammarRule.new(nt_b, [t_a, nt_b, nt_b])
rules = [r0, r1, r2, r3, r4, r5, r6, r7]
ab_source = CFG.new(rules, nt_s)
ab_gen = SentenceGenerator.new(ab_source, 0.25)
10.times {
p ab_gen.get_random
}
| true
|
ea6b3496a6aece9e81287408568e2c775f515985
|
Ruby
|
brianjscoles/App-Academy
|
/Coding Challenge practice problems/Challenge 2/01_no_repeats.rb
|
UTF-8
| 191
| 3.453125
| 3
|
[] |
no_license
|
def no_repeats(year_start, year_end)
def all_uniq?(num)
return num.to_s.split("").uniq.length == num.to_s.length
end
return (year_start..year_end).select{|year| all_uniq?(year)}
end
| true
|
9c45cddb1f0d120c3377fb43b3f4312071a71ac5
|
Ruby
|
redis/redis-rb
|
/examples/list.rb
|
UTF-8
| 474
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'rubygems'
require 'redis'
r = Redis.new
r.del 'logs'
puts
p "pushing log messages into a LIST"
r.rpush 'logs', 'some log message'
r.rpush 'logs', 'another log message'
r.rpush 'logs', 'yet another log message'
r.rpush 'logs', 'also another log message'
puts
p 'contents of logs LIST'
p r.lrange('logs', 0, -1)
puts
p 'Trim logs LIST to last 2 elements(easy circular buffer)'
r.ltrim('logs', -2, -1)
p r.lrange('logs', 0, -1)
| true
|
12e81a66dd7377db4051b3f192a06c78b7765000
|
Ruby
|
altairioffe/ar-exercises
|
/exercises/exercise_7.rb
|
UTF-8
| 908
| 3.328125
| 3
|
[] |
no_license
|
require_relative '../setup'
require_relative './exercise_1'
require_relative './exercise_2'
require_relative './exercise_3'
require_relative './exercise_4'
require_relative './exercise_5'
require_relative './exercise_6'
puts "Exercise 7"
puts "----------"
# Your code goes here ...
class Employee
validates :first_name, :last_name, :hourly_rate, presence: true
belongs_to :store
validates :hourly_rate, numericality: { greater_than_or_equal_to: 40 }
validates :hourly_rate, numericality: { less_than_or_equal_to: 200 }
end
class Store
validates :name, :annual_revenue, presence: true
validates :name, length: { minimum: 3 }
validates :annual_revenue, numericality: {greater_than_or_equal_to: 0}
end
# puts @store1.employees.create(first_name: "todd").valid?
puts "Enter a store name"
@user_store = gets.chomp
@new_store = Store.create(name: @user_store)
puts @new_store.errors.messages
| true
|
de8059787a3bc6764e3fd3d65772b3222dccf4df
|
Ruby
|
raisking/ga-final-project
|
/app/controllers/api/items_controller.rb
|
UTF-8
| 1,749
| 2.59375
| 3
|
[] |
no_license
|
class Api::ItemsController < ApplicationController
#display all items
def index
#get all items from db and save to instance variable
@items = Item.all
render json: @items
end
#display a specific item
def show
#get the item id from the url params
item_id = params[:id]
#use `item_id` to find the item in the database
#and save it to an instance variable
@item = Item.find_by_id(item_id)
render json: @item
# @item = City.find(params[:id])
# @item = Item.joins(:posts).includes(:posts).find(params[:id])
# puts @item
# render json: {
# item: @item
# }
end
#create a new item in the database
def create
#whitelist params and save them to a variable
item_params = params.require(:item).permit(:name, :category, :image, :price)
#create a new item from 'item_params'
@item = Item.new(item_params)
#if item saves, render the new item in JSON
if @item.save
render json: @item
end
end
def destroy
#get the item id from the url params
item_id = params[:id]
@item = Item.find_by_id(item_id)
@item.destroy
render json: {
msg: "Successfully Deleted"
}
end
def update
item_id = params[:id]
@item = Item.find_by_id(item_id)
item_params = params.require(:item).permit(:name, :category, :image, :price)
#update the item
@item.update_attributes(item_params)
render json: @item
end
def update
item_id = params[:id]
@item = Item.find_by_id(item_id)
@item.update_attributes(item_params)
render json: @item
end
private
def item_params
params.require(:item).permit(:name, :category, :image, :price)
end
end
| true
|
80884b9ecfa7dd94c119ada26bef4e5e0106b35b
|
Ruby
|
garrett-codes/Bakery
|
/Bakery/app/models/ingredient.rb
|
UTF-8
| 639
| 3.28125
| 3
|
[] |
no_license
|
class Ingredient
@@all = []
attr_reader :name, :calories
def initialize (name, calories)
@name = name
@calories = calories
@@all << self
end
def ingredients
DessertIngredient.all.select {|dessert_ingredeint| dessert_ingredeint.ingredient == self}
end
def dessert
self.ingredients.map {|dessert_ingredeint| dessert_ingredeint.dessert}
end
def bakery
self.ingredients.map {|dessert_ingredeint| dessert_ingredeint.bakery}
end
def self.all
@@all
end
def self.find_by_name (ingredient_name)
self.all.select{|ingredient_obj| ingredient_obj.name.include?(ingredient_name)}
end
end
| true
|
94f1c364b311c9b165a1d9c9a47c546132da7a8d
|
Ruby
|
ianslai/seven-langs
|
/1-ruby/day-2.rb
|
UTF-8
| 1,097
| 3.71875
| 4
|
[] |
no_license
|
# Exercise 1.
arr = (1..16).to_a
(0..3).each { |i| puts arr[(i * 4)..(i * 4 + 3)].join(' ') }
arr.each_slice(4) {|i| puts i.join(' ') }
# Exercise 2.
class Tree
attr_accessor :children, :node_name
def initialize(structure={})
if structure.size == 1 then
singleton = structure.first
@node_name = singleton.first
@children = singleton.last.map { |name, children| Tree.new(name => children) }
else
@node_name = 'Undefined'
@children = structure.map { |child| Tree.new(child) }
end
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
def to_s
"#{self.node_name}#{children_string}"
end
def children_string
children_names = children.collect {|child| child.to_s}
" ( #{children_names.join(', ')} )" unless children.empty?
end
end
ruby_tree = Tree.new({
'grandpa' => {
'dad' => {
'child 1' => {},
'child 2' => {},
},
'uncle' => {
'child 3' => {},
'child 4' => {},
},
},
})
| true
|
3c600f2f23f95129f13ba996c65c89fb4e3c6539
|
Ruby
|
arafatm/ruby-binary-tree
|
/lib/binary_search_tree.rb
|
UTF-8
| 3,536
| 4.21875
| 4
|
[] |
no_license
|
# Binary Search Tree
class BinarySearchTree
class Node
attr_reader :key, :left, :right
# On initialization, the @key variable is set. This is used in the insert
# method below as the parent for the @left and @right nodes.
def initialize( key )
@key = key
@left = nil
@right = nil
end
# Inserting at the node level will check what the new key is in order to
# insert it in the appropriate place. The restriction being that the key in
# any node is larger than the keys in all nodes in that nodes left sub-tree
# and smaller than the keys in all nodes in that nodes right sub-tree.
def insert( new_key )
if new_key <= @key
@left.nil? ? @left = Node.new( new_key ) : @left.insert( new_key )
elsif new_key > @key
@right.nil? ? @right = Node.new( new_key ) : @right.insert( new_key )
end
end
end
# Initialize the @root variable to nil.
def initialize
@root = nil
end
# Inserting at the BinarySearchTree level looks if there is a @root node, if
# not it creates one. If there is then the insert is delegated the the Node
# level.
def insert( key )
if @root.nil?
@root = Node.new( key )
else
@root.insert( key )
end
end
# This is in order traversal (recursive implementation). Notice hold the
# yield for visting the node is in between the two recursive calls for left
# and right nodes respectively.
def in_order(node=@root, &block)
return if node.nil?
in_order(node.left, &block)
yield node
in_order(node.right, &block)
end
# This is pre order traversal (recursive implementation). Notice hold the
# yield for visting the node is before the two recursive calls for left and
# right nodes respectively.
def pre_order(node=@root, &block)
return if node.nil?
yield node
in_order(node.left, &block)
in_order(node.right, &block)
end
# This is post order traversal (recursive implementation). Notice hold the
# yield for visting the node is after the two recursive calls for left and
# right nodes respectively.
def post_order(node=@root, &block)
return if node.nil?
in_order(node.left, &block)
in_order(node.right, &block)
yield node
end
# This is where you get to see the binary search tree shine. A recursive
# approach is taken to traverse the tree, each time disregarding half of the
# nodes in the tree. With this you will get O( log n ) time.
def search( key, node=@root )
return nil if node.nil?
if key < node.key
search( key, node.left )
elsif key > node.key
search( key, node.right )
else
return node
end
end
def check_height(node)
return 0 if node.nil?
leftHeight = check_height(node.left)
return -1 if leftHeight == -1
rightHeight = check_height(node.right)
return -1 if rightHeight == -1
diff = leftHeight - rightHeight
if diff.abs > 1
-1
else
[leftHeight, rightHeight].max + 1
end
end
def is_balanced?(node=@root)
check_height(node) == -1 ? false : true
end
end
tree = BinarySearchTree.new
tree.insert(50)
tree.insert(25)
tree.insert(75)
tree.insert(12)
tree.insert(37)
tree.insert(87)
tree.insert(63)
puts "---"
puts tree.inspect
puts "---"
puts "tree.is_balanced? #{tree.is_balanced?}"
puts "pre_order"
tree.pre_order do |node|
puts node.key
end
puts "in_order"
tree.in_order do |node|
puts node.key
end
puts "post_order"
tree.post_order do |node|
puts node.key
end
| true
|
70a41e781b54e5b1afbc139b841f271730a7b9ff
|
Ruby
|
houtanf/Event-Schedular-DSL
|
/Ruby/src/schedular.rb
|
UTF-8
| 1,085
| 3.046875
| 3
|
[
"Apache-2.0"
] |
permissive
|
class Meeting
attr_reader :meeting_name, :start_time, :end_time, :date, :participant_list
def name(meeting_name)
@meeting_name = meeting_name
end
def convert_time(time)
('%.2f' % time).sub('.', ':')
end
def start(start_time)
@start_time = convert_time(start_time)
end
def finish(end_time)
@end_time = convert_time(end_time)
end
def on(month, day, year)
@date = "#{month}/#{day}/#{year}"
end
def participants(participants)
@participant_list = participants
end
def meeting_duration()
date_split = @date.split('/')
start_split = @start_time.to_s.split(":")
start = Time.new(date_split[2], date_split[0], date_split[1], start_split[0], start_split[1])
finish_split = @end_time.to_s.split(":")
finish = Time.new(date_split[2], date_split[0], date_split[1], finish_split[0], finish_split[1])
Time.at(finish - start).utc.strftime("%H:%M")
end
end
def schedule(event)
event
end
def meeting(&block)
scheduled_meeting = Meeting.new
scheduled_meeting.instance_eval(&block)
scheduled_meeting
end
| true
|
c584f03bd7eb47bd0a8c9d2ed0ec61274ffa547a
|
Ruby
|
aldoshin/ruby-calisthenics
|
/lib/rock_paper_scissors.rb
|
UTF-8
| 764
| 3.421875
| 3
|
[] |
no_license
|
class RockPaperScissors
RULES = { "R" => 1, "P" => 2, "S" => 3 }
# Exceptions this class can raise:
class NoSuchStrategyError < StandardError ; end
def self.winner(player1, player2)
raise NoSuchStrategyError, "Strategy must be one of R,P,S" unless RULES.key?(player1[1]) and RULES.key?(player2[1])
diff = (RULES[player1[1]] - RULES[player2[1]]) % 3
if diff == 0
player1
elsif diff < 2
player1
else
player2
end
end
def self.tournament_winner(tournament)
player1 = tournament[0]
player2 = tournament[1]
if player1[0].is_a?(String) && player2[0].is_a?(String)
return winner(player1, player2)
else
winner(tournament_winner(player1), tournament_winner(player2))
end
end
end
| true
|
60078cb2ba4c72f67e3e30ec90ef928d25cb1b73
|
Ruby
|
maykev/assistant_tournament_director
|
/app/models/bracket_configuration.rb
|
UTF-8
| 327
| 2.640625
| 3
|
[] |
no_license
|
class BracketConfiguration < ApplicationRecord
serialize :bye_pattern, Array
serialize :loser_pattern, Array
def loser_position(winner_position)
bracket_positions = loser_pattern.select { |pattern| pattern.split('->').first == winner_position }
bracket_positions.first.split('->').last
end
end
| true
|
0c41ec7f38c740cf0aa9b0cf1165fa02afbbc2dc
|
Ruby
|
cloudfoundry/bosh
|
/src/bosh-director/spec/unit/ext_spec.rb
|
UTF-8
| 1,168
| 2.515625
| 3
|
[
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"LicenseRef-scancode-unicode-mappings",
"Artistic-2.0",
"LGPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-or-later",
"GPL-2.0-or-later",
"GPL-3.0-only",
"MPL-1.1",
"Artistic-1.0",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"Artistic-1.0-Perl",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"Apache-2.0",
"Ruby",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
require 'spec_helper'
describe 'Monkey Patches' do
describe '#to_openstruct' do
it 'should convert a complex object to an openstruct' do
hash = {
foo: [{ list: 'test' }],
test: 'bad',
nested: { hash: 3 },
}
result = hash.to_openstruct
ostruct = OpenStruct.new(
'foo' => [OpenStruct.new('list' => 'test')],
'test' => 'bad',
'nested' => OpenStruct.new('hash' => 3),
)
expect(result).to eq(ostruct)
end
end
describe '#recursive_merge' do
it 'should recursively merge hashes' do
a = { foo: { bar: 5, foz: 17 } }
b = { test: 'value', foo: { baz: 1, bar: 'hi' } }
expect(a.recursive_merge(b)).to eq(test: 'value', foo: { bar: 'hi', foz: 17, baz: 1 })
end
it 'should always use the new value type, even if it\'s not a hash' do
a = { foo: { bar: 1 } }
b = { foo: 'value' }
expect(a.recursive_merge(b)).to eq(foo: 'value')
end
it 'should not mutate the hashes being merged' do
a = { foo: { bar: 1 } }
b = { foo: 'value' }
a.recursive_merge(b)
expect(a).to eq(foo: { bar: 1 })
end
end
end
| true
|
cb7c0e9ad5b2338061d6dd69b73fdd2465decd04
|
Ruby
|
matheusfig90/codility-lessons
|
/lesson-1_binary-gap.rb
|
UTF-8
| 1,766
| 3.8125
| 4
|
[] |
no_license
|
=begin
A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at
both ends in the binary representation of N.
For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary
representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary
representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no
binary gaps.
Write a function:
def solution(n)
that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N
doesn't contain a binary gap.
For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its
longest binary gap is of length 5.
Assume that:
- N is an integer within the range [1..2,147,483,647].
Complexity:
- expected worst-case time complexity is O(log(N));
- expected worst-case space complexity is O(1).
Results:
Test score: 100%
Correctness: 100%
Performance: not assessed
Link: https://codility.com/demo/results/trainingC9YQDK-4FN/
=end
def solution(n)
binary = n.to_s(2) # Convert to binary
zeros = binary.split('1')
zeros.pop if n % 2 == 0 # Ignoring last zeros
# The function should return 0 if N doesn't contain a binary gap
return 0 if zeros.empty?
zeros.map { |zero| zero.length }.max
end
# Testing
require 'minitest/autorun'
class TaskTest < MiniTest::Unit::TestCase
def test_example
assert_equal 5, solution(1041)
end
def test_without_zeros
assert_equal 0, solution(15)
end
def test_zeros_in_the_end
assert_equal 0, solution(6)
end
end
| true
|
d23621ccd28a9bb77b7c6f782c095ff06147f455
|
Ruby
|
kn0/Plerus
|
/evo/mutagens/x86/add_nop_push_pop_joined.rb
|
UTF-8
| 822
| 2.890625
| 3
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"BSD-2-Clause-Views"
] |
permissive
|
module Plerus
class Evo < Mutagen
def initialize
super({
title: "Addition Mutation - push pop nop (joined)",
scope: SINGLE_MUTAGEN,
change: ASM_ADDITION,
targets: nil,
safe: true
})
end
def mutate(instruction)
# Create an array of possible nops
nops = []
nops << "5058" # push eax,pop eax
nops << "5159" # push ecx,pop ecx
nops << "525a" # push edx,pop edx
nops << "535b" # push ebx,pop ebx
nops << "545c" # push esp,pop esp
nops << "555d" # push ebp,pop ebp
nops << "565e" # push esi,pop esi
nops << "575f" # push edi,pop edi
# Randomly add one nop to the end of the instruction
instruction << nops.sample
# Return the instruction
return instruction
end
end
end
| true
|
3581965d4da4174539f4b7e2e4ca27695b431188
|
Ruby
|
fatcatt316/UniversityRenter
|
/config/initializers/to_ascii.rb
|
UTF-8
| 78
| 2.640625
| 3
|
[] |
no_license
|
class String
def to_ascii
bytes.map{|byte| "&\##{byte};"}.join
end
end
| true
|
00288546f1fc9d871a59ae69bf66b24665214411
|
Ruby
|
theodoro/rubybasico
|
/test_for.rb
|
UTF-8
| 73
| 2.953125
| 3
|
[] |
no_license
|
class TestFor
for i in (1..3)
x = 1
end
puts x
end
| true
|
b642eaeda50f73341e401f410a704d8cfe16b725
|
Ruby
|
carltonf/carltonf-blog-source
|
/_plugins/gen-tag-page.rb
|
UTF-8
| 849
| 2.828125
| 3
|
[] |
no_license
|
# Based on: http://jekyllrb.com/docs/plugins/#generators
#
# Usage: Use the tags/index.html as an template for generating each tag page
module Jekyll
class TagPage < Page
def initialize(site, base, dir, tag)
@site = site
@base = base
@dir = dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, 'tags'), 'index.html')
self.data['tag'] = tag
tag_title_prefix = site.config['tag_title_prefix'] || 'Tag: '
self.data['title'] = "#{tag_title_prefix}#{tag}"
end
end
class TagPageGenerator < Generator
safe true
def generate(site)
dir = site.config['tag_dir'] || 'tags'
site.tags.each_key do |tag|
site.pages << TagPage.new(site, site.source, File.join(dir, tag), tag)
end
end
end
end
| true
|
130dafd0402ef09e3d62799f54e325f59e318fc5
|
Ruby
|
cjwales/bus_stop_work
|
/spec/BusStop_spec.rb
|
UTF-8
| 580
| 2.8125
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../BusStop.rb')
require_relative('../Person.rb')
class BusStopTest < MiniTest::Test
def setup()
@busstop1 = BusStop.new("George Street")
@person1 = Person.new("Stuart", 52)
@person2 = Person.new("Neil", 32)
@person3 = Person.new("Jamie", 12)
end
#
# def test_add_person_to_queue()
# assert_equal(1, @busstop1.)
# end
def test_add_person_to_queue()
@busstop1.add_person_to_queue(@person3)
assert_equal(1, @busstop1.queue.length())
end
def test_board_all_passengers()
assert_equal(3,@bus.)
end
end
| true
|
7a2f4d579af2a31915b3c8e0dfb72903ce5b11ce
|
Ruby
|
DanMcDonald91/Week2WeekendHW
|
/specs/Rooms_spec.rb
|
UTF-8
| 797
| 2.609375
| 3
|
[] |
no_license
|
require('minitest/autorun')
require_relative('../Rooms.rb')
require_relative('../Songs.rb')
require_relative('../Guests.rb')
class TestRooms < Minitest::Test
def setup
@room_1 = Rooms.new("Volcano" , 4)
@room_2 = Rooms.new("The Worst Toilet In Scotland" , 2 )
@room_3 = Rooms.new("Mother Superior's Place," , 3)
@song_1 = Songs.new("Don't Stop Me Now", "Queen")
@song_2 = Songs.new("Ain't No Sunshine", "Bill Withers")
@song_3 = Songs.new("Perfect Day", "Lou Reed")
@song_4 = Songs.new("Common People" , "Pulp")
@song_5 = Songs.new("Buddy Holly", "Weezer")
@song_6 = Songs.new("Lust For Life" , "Iggy Pop")
@guest_1 = Guests.new("Renton" ,160)
@guest_2 = Guests.new("Spud" , 50)
guest_3 = Guests.new("Sick Boy" , 20)
guest_4 = Guests.new("Begbie" , 20)
end
end
| true
|
7ced8f7191cc7821e8d996796a7cfa761f205ca7
|
Ruby
|
isaacsanders/mini_java_compiler
|
/lib/nonterminals.rb
|
UTF-8
| 13,699
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
# -*- coding: utf-8 -*-
require_relative 'terminals'
require_relative 'intermediate'
class Nonterminal
include Terminals
def epsilon?
not @epsilon.nil?
end
end
class Program < Nonterminal
def fill_slots(table_entry)
@main_class_decl, @class_decl_list = table_entry
end
def to_ir
main_class_ir = @main_class_decl.to_ir
other_classes_ir = @class_decl_list.to_ir
Intermediate::Program.new(main_class_ir, other_classes_ir)
end
end
class MainClassDecl < Nonterminal
def fill_slots(table_entry)
_, @id, _, _, _, _, _, _, _, _, _, @arg_id, _, _, @stmt_list, _, _ = table_entry
end
def to_ir
field_list = []
method_list = [Intermediate::Method.new(main_rw, [], void_rw, @stmt_list.to_ir, nil)]
opt_extends = nil
Intermediate::Class.new(@id, method_list, field_list, opt_extends)
end
end
class ClassDeclList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@class_decl, @class_decl_list = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@class_decl.to_ir] + @class_decl_list.to_ir
end
end
class ClassDecl < Nonterminal
def fill_slots(table_entry)
_, @id, @class_decl_prime = table_entry
end
def to_ir
@class_decl_prime.to_ir(@id)
end
end
class ClassDeclPrime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 4
_, @class_var_decl_list, @method_decl_list, _ = table_entry
else
_, @extends_id, _, @class_var_decl_list, @method_decl_list, _ = table_entry
end
end
def to_ir(id)
field_list = @class_var_decl_list.to_ir
method_list = @method_decl_list.to_ir
opt_extends = @extends_id
Intermediate::Class.new(id, method_list, field_list, opt_extends)
end
end
class ClassVarDeclList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@class_var_decl, @class_var_decl_list = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@class_var_decl.to_ir] + @class_var_decl_list.to_ir
end
end
class ClassVarDecl < Nonterminal
def fill_slots(table_entry)
@type, @id, _ = table_entry
end
def to_ir
Intermediate::Field.new(@type.to_ir, @id)
end
end
class MethodDeclList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@method_decl, @method_decl_list = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@method_decl.to_ir] + @method_decl_list.to_ir
end
end
class MethodDecl < Nonterminal
def fill_slots(table_entry)
_, @type, @id, _, @formal_list, _, _, @stmt_list, _, @expr, _, _ = table_entry
end
def to_ir
formals = @formal_list.to_ir
stmts = @stmt_list.to_ir
return_type = @type.to_ir
return_expr = @expr.to_ir
Intermediate::Method.new(@id, formals, return_type, stmts, return_expr)
end
end
class FormalList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@formal, @formal_list_prime = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@formal.to_ir] + @formal_list_prime.to_ir
end
end
class FormalListPrime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
_, @formal, @formal_list_prime = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@formal.to_ir] + @formal_list_prime.to_ir
end
end
class Formal < Nonterminal
def fill_slots(table_entry)
@type, @id = table_entry
end
def to_ir
Intermediate::Formal.new(@type.to_ir, @id)
end
end
class Type < Nonterminal
def fill_slots(table_entry)
@type = table_entry.first
end
def to_ir
case @type
when TypeNotID
@type.type
when Lexer::ID
@type
end
end
end
class TypeNotID < Nonterminal
attr_reader :type
def fill_slots(table_entry)
@type = table_entry.first
end
end
class StmtList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 2
@stmt, @stmt_list = table_entry
else
@epsilon = table_entry.first
end
end
def to_ir
Intermediate::Procedure.new(self.to_ir!)
end
def to_ir!
return [] if self.epsilon?
[@stmt.to_ir] + @stmt_list.to_ir!
end
end
class Stmt < Nonterminal
def fill_slots(table_entry)
case table_entry.first
when StmtNoSemi
@stmt_type = :stmt_no_semi
@stmt_no_semi, _ = table_entry
when open_brace_d
@stmt_type = :block
_, @stmt_list, _ = table_entry
when if_rw
@stmt_type = :ifelse
_, _, @test, _, @true_case, _, @false_case = table_entry
when while_rw
@stmt_type = :while
_, _, @test, _, @body = table_entry
when for_rw
@stmt_type = :for
_, _, @init, _, @test, _, @iter, _, @body = table_entry
when until_rw
@stmt_type = :until
_, _, @test, _, @body = table_entry
end
end
def to_ir
case @stmt_type
when :stmt_no_semi
@stmt_no_semi.to_ir
when :block
Intermediate::BlockStatement.new(@stmt_list.to_ir)
when :ifelse
Intermediate::IfElseStatement.new(@test.to_ir, @true_case.to_ir, @false_case.to_ir)
when :while
Intermediate::WhileStatement.new(@test.to_ir, @body.to_ir)
when :for
init = @init.to_ir
init = if init
[init]
else
[]
end
test = @test.to_ir
iter = @iter.to_ir
iter = if iter
[iter]
else
[]
end
iter = [Intermediate::ContinueLabelHelper.new] + iter
body = @body.to_ir
while_body = Intermediate::Procedure.new([body] + iter)
while_loop = Intermediate::WhileStatement.new(test, while_body, for_mode=true)
Intermediate::Procedure.new(init + [while_loop])
when :until
test = Intermediate::PrefixExpr.new(bang_o, @test.to_ir)
Intermediate::WhileStatement.new(test, @body.to_ir)
end
end
end
class OptStmtNoSemi < Nonterminal
def fill_slots(table_entry)
@stmt_no_semi = table_entry.first
end
def to_ir
unless @stmt_no_semi == :epsilon
@stmt_no_semi.to_ir
end
end
end
class StmtNoSemi < Nonterminal
def fill_slots(table_entry)
case table_entry.first
when TypeNotID
@stmt_type = :init
@type_not_id, @id, _, @expr, _ = table_entry
when system_out_println_rw
@stmt_type = :println
_, _, @print_expr, _, _ = table_entry
when Lexer::ID
@stmt_type = :assign
@id, @stmt_prime_id = table_entry
when break_rw
@stmt_type = :break
when continue_rw
@stmt_type = :continue
end
end
def to_ir
case @stmt_type
when :init
Intermediate::InitStatement.new(@type_not_id.type, @id, @expr.to_ir)
when :println
Intermediate::PrintlnStatement.new(@print_expr.to_ir)
when :assign
@stmt_prime_id.to_ir(@id)
when :break
Intermediate::BreakStatement.new
when :continue
Intermediate::ContinueStatement.new
end
end
end
class StmtPrimeID < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 2
_, @expr = table_entry
else
@id, _, @expr = table_entry
end
end
def to_ir(id)
if @id.nil?
Intermediate::AssignStatement.new(id, @expr.to_ir)
else
Intermediate::InitStatement.new(id, @id, @expr.to_ir)
end
end
end
class Expr < Nonterminal
def fill_slots(table_entry)
@expr7, @expr_prime = table_entry
end
def to_ir
@expr_prime.to_ir(@expr7)
end
end
class ExprPrime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr7, @expr_prime = table_entry
end
end
def to_ir(expr7_lhs)
if self.epsilon?
expr7_lhs.to_ir
else
Intermediate::InfixExpr.new(expr7_lhs.to_ir, @op, @expr_prime.to_ir(@expr7))
end
end
end
class Expr7 < Nonterminal
def fill_slots(table_entry)
@expr6, @expr7_prime = table_entry
end
def to_ir
@expr7_prime.to_ir(@expr6)
end
end
class Expr7Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr6, @expr7_prime = table_entry
end
end
def to_ir(expr6_lhs)
if self.epsilon?
expr6_lhs.to_ir
else
Intermediate::InfixExpr.new(expr6_lhs.to_ir, @op, @expr7_prime.to_ir(@expr6))
end
end
end
class Expr6 < Nonterminal
def fill_slots(table_entry)
@expr5, @expr6_prime = table_entry
end
def to_ir
@expr6_prime.to_ir(@expr5)
end
end
class Expr6Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr5, @expr6_prime = table_entry
end
end
def to_ir(expr5_lhs)
if self.epsilon?
expr5_lhs.to_ir
else
Intermediate::InfixExpr.new(expr5_lhs.to_ir, @op, @expr6_prime.to_ir(@expr5))
end
end
end
class Expr5 < Nonterminal
def fill_slots(table_entry)
@expr4, @expr5_prime = table_entry
end
def to_ir
@expr5_prime.to_ir(@expr4)
end
end
class Expr5Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr4, @expr5_prime = table_entry
end
end
def to_ir(expr4_lhs)
if self.epsilon?
expr4_lhs.to_ir
else
Intermediate::InfixExpr.new(expr4_lhs.to_ir, @op, @expr5_prime.to_ir(@expr4))
end
end
end
class Expr4 < Nonterminal
def fill_slots(table_entry)
@expr3, @expr4_prime = table_entry
end
def to_ir
@expr4_prime.to_ir(@expr3)
end
end
class Expr4Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr3, @expr4_prime = table_entry
end
end
def to_ir(expr3_lhs)
if self.epsilon?
expr3_lhs.to_ir
else
Intermediate::InfixExpr.new(expr3_lhs.to_ir, @op, @expr4_prime.to_ir(@expr3))
end
end
end
class Expr3 < Nonterminal
def fill_slots(table_entry)
@expr2, @expr3_prime = table_entry
end
def to_ir
@expr3_prime.to_ir(@expr2)
end
end
class Expr3Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr2, @expr3_prime = table_entry
end
end
def to_ir(expr2_lhs)
if self.epsilon?
expr2_lhs.to_ir
else
Intermediate::InfixExpr.new(expr2_lhs.to_ir, @op, @expr3_prime.to_ir(@expr2))
end
end
end
class Expr2 < Nonterminal
def fill_slots(table_entry)
@expr2_prime, @expr1 = table_entry
end
def to_ir
@expr2_prime.to_ir(@expr1)
end
end
class Expr2Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@op, @expr2_prime = table_entry
end
end
def to_ir(expr1)
if self.epsilon?
expr1.to_ir
else
Intermediate::PrefixExpr.new(@op, @expr2_prime.to_ir(expr1))
end
end
end
class Expr1 < Nonterminal
def fill_slots(table_entry)
@expr0, @expr1_prime = table_entry
end
def to_ir
@expr1_prime.to_ir(@expr0)
end
end
class Expr1Prime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
_, @method, _, @arg_list, _, @expr1_prime = table_entry
end
end
def to_ir(expr0)
if self.epsilon?
expr0.to_ir
else
@expr1_prime.to_ir!(Intermediate::MethodCallExpr.new(expr0.to_ir, @method, @arg_list.to_ir))
end
end
def to_ir!(expr0)
if self.epsilon?
expr0
else
@expr1_prime.to_ir!(Intermediate::MethodCallExpr.new(expr0, @method, @arg_list.to_ir))
end
end
end
class ArgList < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
@expr, @arg_list_prime = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@expr.to_ir] + @arg_list_prime.to_ir
end
end
class ArgListPrime < Nonterminal
def fill_slots(table_entry)
if table_entry.length == 1
@epsilon = table_entry.first
else
_, @expr, @arg_list_prime = table_entry
end
end
def to_ir
return [] if self.epsilon?
[@expr.to_ir] + @arg_list_prime.to_ir
end
end
class Expr0 < Nonterminal
def fill_slots(table_entry)
case table_entry.first
when Lexer::ID
@expr_type = :id
@value = table_entry.first
when Lexer::Integer
@expr_type = :integer
@value = table_entry.first
when this_rw
@expr_type = :this
@value = table_entry.first
when null_rw
@expr_type = :null
@value = table_entry.first
when true_rw
@expr_type = :true
@value = table_entry.first
when false_rw
@expr_type = :false
@value = table_entry.first
when new_rw
@expr_type = :init
_, @class, _, _ = table_entry
when open_paren_d
@expr_type = :parens
_, @expr, _ = table_entry
end
end
def to_ir
case @expr_type
when :id
Intermediate::IDExpr.new(@value)
when :integer
Intermediate::IntLiteralExpr.new(@value)
when :this
Intermediate::ThisExpr.new
when :null
Intermediate::NullExpr.new
when :true, :false
Intermediate::BooleanLiteralExpr.new(@value)
when :init
Intermediate::InitExpr.new(@class)
when :parens
@expr.to_ir
end
end
end
| true
|
15fd7ece06e5df8aacdb9078091f87b94c0cf111
|
Ruby
|
JoshuaRogers/ConfBot
|
/lib/application.rb
|
UTF-8
| 1,933
| 2.765625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require 'rubygems'
require 'sqlite3'
require_relative 'connection'
require_relative 'message'
require_relative 'plugin'
class Application
def initialize
@connections = []
@plugins = []
end
def start
start_database
start_plugins
start_connections
end
def stop
@db.close
end
def db
@db
end
private
def start_database
@db = SQLite3::Database.new("assets/confbot.db")
@db.results_as_hash = true
# Create the database if it doesn't exist.
unless @db.execute("SELECT * FROM sqlite_master").length > 0
@db.execute %q{
CREATE TABLE connections (
id INTEGER AUTO_INCREMENT,
host VARCHAR(256),
port INTEGER,
username VARCHAR(256),
password VARCHAR(256)
)
}
@db.execute %q{
CREATE TABLE plugins (
class VARCHAR(256),
version INTEGER
)
}
end
end
def start_connections
@db.execute("SELECT * FROM connections").each do |c|
connection = Connection.new(c["host"], c["port"]).connect(c["username"], c["password"])
connection.available
connection.message_callback = lambda do |m| process_message(connection, m) end
@connections << connection
end
end
def start_plugins
Dir.new("plugin").each do |file|
require_relative "plugin/#{file}" if file =~ /\.rb$/
end
Plugin.list.each do |class_type|
plugin = class_type.new(self)
plugin.activate
@plugins << plugin
end
@plugins = @plugins.sort { |x,y| x.sort_order <=> y.sort_order }
end
def process_message(connection, message)
@plugins.each do |p|
message = p.send message
end
return if message.invalid?
message.reciptients.each do |r|
connection.send(r.jid, message.print)
end
end
end
$application = Application.new
$application.start
gets
| true
|
c041b5f340721794c7134967b375a172c230944f
|
Ruby
|
morrxy/ltp
|
/5/favnum.rb
|
UTF-8
| 117
| 3.09375
| 3
|
[] |
no_license
|
# encoding: UTF-8
puts 'your favorite number?'
fav = gets.chomp
puts "#{ fav.to_i + 1 } is a better favorite number"
| true
|
99ef0df8b1f536b48c3db5284edd9747a21e23c0
|
Ruby
|
sa-adebayo/RubyTrack
|
/Factorial/lib/integer.rb
|
UTF-8
| 105
| 3.15625
| 3
|
[] |
no_license
|
class Integer
def calculate_factorial
(1..self).inject {|result, value| result * value }
end
end
| true
|
d5916854dad454ab58a83bb62e54d1953822fb15
|
Ruby
|
cedricdlb/fast_pencil_quiz
|
/spec/fast_pencil_quiz_spec.rb
|
UTF-8
| 5,018
| 2.546875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require_relative File.join('..', 'lib', 'fast_pencil_quiz')
describe FastPencilQuiz do
before(:each) do
@fast_pencil_quiz = FastPencilQuiz.new
subject { @fast_pencil_quiz }
end
context "when not yet #run" do
subject { @fast_pencil_quiz.q_and_a_candidates }
it { should be_a Hash }
it { should be_empty }
end
context "when #run with bad input, should report an error" do
it "when no input file is given" do
@fast_pencil_quiz.should_receive(:dictionary_file_name).any_number_of_times.and_return(nil)
@fast_pencil_quiz.should_receive(:record_bad_input).with(FastPencilQuiz::FILE_NOT_SPECIFIED).and_return(false)
@fast_pencil_quiz.run
end
context "when input file is given" do
before(:each) do
@dictionary_file_name = "foo"
ARGV.insert(0, @dictionary_file_name)
end
it "but it does not exist" do
File.should_receive(:exists?).with(@dictionary_file_name).and_return(false)
@fast_pencil_quiz.should_receive(:record_bad_input).with(FastPencilQuiz::FILE_NOT_EXISTANT).and_return(false)
@fast_pencil_quiz.run
end
it "but it is not a proper file" do
File.should_receive(:exists?).with(@dictionary_file_name).and_return(true)
File.should_receive(:file?).with(@dictionary_file_name).and_return(false)
@fast_pencil_quiz.should_receive(:record_bad_input).with(FastPencilQuiz::FILE_NOT_PROPER).and_return(false)
@fast_pencil_quiz.run
end
it "but it is not readable" do
File.should_receive(:exists?).with(@dictionary_file_name).and_return(true)
File.should_receive(:file?).with(@dictionary_file_name).and_return(true)
File.should_receive(:readable?).with(@dictionary_file_name).and_return(false)
@fast_pencil_quiz.should_receive(:record_bad_input).with(FastPencilQuiz::FILE_NOT_READABLE).and_return(false)
@fast_pencil_quiz.run
end
end
end
context "when #run" do
before(:each) do
@dictionary_file_name = "dictionary_file.txt"
@questions_file_name = "./dictionary_file.questions.txt"
@answers_file_name = "./dictionary_file.answers.txt"
ARGV.insert(0, @dictionary_file_name)
@dictionary_mock_file = mock(File)
@questions_mock_file = mock(File)
@answers_mock_file = mock(File)
File.should_receive(:exists?).with(@dictionary_file_name).and_return(true)
File.should_receive(:file?).with(@dictionary_file_name).and_return(true)
File.should_receive(:readable?).with(@dictionary_file_name).and_return(true)
File.should_receive(:open).with(@dictionary_file_name, "r").and_return(@dictionary_mock_file)
File.should_receive(:open).with(@questions_file_name, "w").and_return(@questions_mock_file)
File.should_receive(:open).with(@answers_file_name, "w").and_return(@answers_mock_file)
@dictionary_mock_file.should_receive(:close).and_return(true)
@questions_mock_file.should_receive(:close).and_return(true)
@answers_mock_file.should_receive(:close).and_return(true)
end
context "with an empty word list" do
before(:each) do
@words = []
@dictionary_mock_file.stub(:each).with(any_args).and_return nil
@fast_pencil_quiz.run
end
it { should_not_receive(:determine_unique_sequences) }
context "q_and_a_candidates" do
subject { @fast_pencil_quiz.q_and_a_candidates }
it { should be_a Hash }
it { should be_empty }
end
end
context "with a valid word list" do
before(:each) do
@words = %w[arrows food carrots give me food]
@sequences = %w[arro carr food give rots rows rrot rrow]
@unique_sequences = @sequences - %w[arro food]
@containing_words = [
%w[arrows carrots],
%w[carrots],
%w[food food],
%w[give],
%w[carrots],
%w[arrows],
%w[carrots],
%w[arrows],
]
@unique_words = (@containing_words - [%w[arrows carrots], %w[food food]]).flatten.sort
@questions = []
@answers = []
@dictionary_mock_file.should_receive(:each).with(no_args).and_yield("arrows").and_yield("food").and_yield("carrots").and_yield("give").and_yield("me").and_yield("food")
@questions_mock_file.stub(:puts) {|sequence| @questions << sequence }
@answers_mock_file.stub(:puts) {|word| @answers << word }
@fast_pencil_quiz.run
end
context "q_and_a_candidates" do
subject { @fast_pencil_quiz.q_and_a_candidates }
it { should be_a Hash }
it { should_not be_empty }
its(:size) { should == 8 }
end
specify { @fast_pencil_quiz.q_and_a_candidates.keys.sort.should == @sequences }
(0...8).each do |i|
context "when testing sequence " + i.to_s do
specify { @fast_pencil_quiz.q_and_a_candidates[@sequences[i]].should == @containing_words[i] }
end
end
context "when #determine_unique_sequences is run" do
it "only unique sequences should be written to the questions file" do
@questions.sort.should == @unique_sequences
end
it "only words for unique suequences should be written to the answers file" do
@answers.sort.should == @unique_words
end
end
end
end
end
| true
|
f17044f2d3e6967ef31b0c83831619ee5be68928
|
Ruby
|
txus/rexpl
|
/lib/rexpl/output.rb
|
UTF-8
| 2,696
| 3.453125
| 3
|
[
"MIT"
] |
permissive
|
require 'ansi'
module Rexpl
# Utility module to abstract output-related stuff, like printing banners or
# graphically representing stacks.
class Output
extend ANSI::Code
class << self
# Prints the welcome banner and a bit of instructions on how to use the
# interactive console.
def print_banner
puts
puts bold { red { "rexpl" } } + bold { " v#{Rexpl::VERSION}" } + " - interactive bytecode console for Rubinius"
puts bold { "--------------------------------------------------------" }
puts
print_rationale
end
# Prints the console prompt.
def print_prompt
print bold { '> ' }
end
# Prints a message indicating that the instruction set has been resetted.
def print_reset
puts "Reseted!"
end
# Prints the current size of the stack and the topmost value.
def print_debug_info(size, value)
puts "=> [" + bold { "Stack size: #{size}"} + "] " + "[" + bold { "Topmost value: #{value}" } + "]"
end
# Prints an instruction in a single row.
def print_instruction(instruction, idx)
puts bold { "[" } + blue { idx.to_s } + bold { "]" } + ": " + green { instruction.first } + " " + bold { instruction[1..-1].map(&:inspect) }
end
# Prints a stack out of an array of stack cells.
#
# @param [Array] cells the cells of the stack containing its values.
def print_stack(cells)
puts
puts "\t#{bold { 'Current stack' }.center(33, ' ')}"
puts "\t" + blue { "-------------------------" }
cells.reverse.each do |element|
puts "\t#{blue {"|"} }#{bold { element.inspect.center(23, ' ') }}#{blue {"|"}}"
puts "\t" + blue { "-------------------------" }
end
puts
end
# Prints a little readme to get people started when firing up the
# interactive console.
def print_rationale
puts "To start playing, just start typing some Rubinius VM instructions."
puts "You can find a complete list with documentation here:"
puts
puts "\thttp://rubini.us/doc/en/virtual-machine/instructions/"
puts
puts "To introspect the program you are writing, use the following commands,"
puts "or type " + bold { "exit" } + " to exit:"
puts
puts " " + bold { "list" } + " lists the instruction set of the current program."
puts " " + bold { "reset" } + " empties the instruction set and starts a new program."
puts " " + bold { "draw" } + " prints a visual representation of the stack after each instruction."
puts
end
end
end
end
| true
|
3dffa945c3dd3bcd2793703a9972bef3c22fb5be
|
Ruby
|
gitter-badger/ossert
|
/lib/ossert/presenters/project_v2.rb
|
UTF-8
| 4,090
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Ossert
module Presenters
module ProjectV2
CLASSES = %w(
ClassE
ClassD
ClassC
ClassB
ClassA
).freeze
KLASS_2_GRADE = {
'ClassA' => 'A',
'ClassB' => 'B',
'ClassC' => 'C',
'ClassD' => 'D',
'ClassE' => 'E'
}.freeze
def preview_reference_values_for(metric, section) # maybe automatically find section?
metric_by_grades = @reference[section][metric.to_s]
grades = CLASSES.reverse
sign = reversed_metrics.include?(metric) ? '<' : '>'
grades.each_with_object({}) do |klass, preview|
preview[KLASS_2_GRADE[klass]] = "#{sign} #{metric_by_grades[klass][:threshold].to_i}"
end
end
REFERENCES_STUB = {
'ClassA' => { threshold: '0', range: [] },
'ClassB' => { threshold: '0', range: [] },
'ClassC' => { threshold: '0', range: [] },
'ClassD' => { threshold: '0', range: [] },
'ClassE' => { threshold: '0', range: [] }
}.freeze
# Tooltip data:
# {
# title: '',
# description: '',
# ranks: [
# {"type":"a","year":100,"total":300},
# {"type":"b","year":80,"total":240},
# {"type":"c","year":60,"total":120},
# {"type":"d","year":40,"total":100},
# {"type":"e","year":20,"total":80}
# ]
# }
def tooltip_data(metric)
classes = CLASSES.reverse
section = Ossert::Stats.guess_section_by_metric(metric)
ranks = classes.inject([]) do |preview, klass|
base = { type: KLASS_2_GRADE[klass].downcase, year: ' N/A ', total: ' N/A ' }
preview << [:year, :total].each_with_object(base) do |section_type, result|
next unless (metric_data = metric_tooltip_data(metric, section, section_type, klass)).present?
result[section_type] = metric_data
end
end
{ title: Ossert.t(metric), description: Ossert.descr(metric), ranks: ranks }
end
def metric_tooltip_data(metric, section, section_type, klass)
return if section == :not_found # this should not happen
reference_section = [section, section_type].join('_')
return unless (metric_by_grades = @reference[reference_section.to_sym][metric.to_s])
[
reversed_metrics.include?(metric) ? '< ' : '> ',
decorator.value(metric, metric_by_grades[klass][:threshold])
].join(' ')
end
def reversed_metrics
@reversed_metrics ||= Ossert::Classifiers::Growing.config['reversed']
end
# Fast preview graph
# [
# {"title":"Jan - Mar 2016","type":"a","values":[10,20]},
# {"title":"Apr - Jun 2016","type":"b","values":[20,25]},
# {"title":"Jul - Sep 2016","type":"c","values":[25,35]},
# {"title":"Oct - Dec 2016","type":"d","values":[35,50]},
# {"title":"Next year","type":"e","values":[50,10]}
# ]
def fast_preview_graph_data(lookback = 5, check_results = nil)
graph_data = { popularity: [], maintenance: [], maturity: [] } # replace with config
check_results.each_with_index do |check_result, index|
check_result.each do |check, results|
sum_up_checks(graph_data, check, results, index, lookback - index)
end
end
graph_data.map { |k, v| [k, MultiJson.dump(v)] }.to_h
end
def sum_up_checks(graph_data, check, results, index, offset)
gain = results[:gain]
graph_data[check] << {
title: last_quarters_bounds(offset),
type: results[:mark].downcase,
values: [gain, gain]
}
graph_data[check][index - 1][:values][1] = gain if index.positive?
end
def last_quarters_bounds(last_year_offset)
date = Time.current.utc - ((last_year_offset - 1) * 3).months
[date.beginning_of_quarter.strftime('%b'),
date.end_of_quarter.strftime('%b %Y')].join(' - ')
end
end
end
end
| true
|
8f9b779bebcf5be3bccb558e8075c5fefc0890e5
|
Ruby
|
semahawk/euler
|
/ruby/18.rb
|
UTF-8
| 771
| 4.25
| 4
|
[] |
no_license
|
#!/usr/bin/env ruby
# The items (values to make the biggest numbah), sum (answer, actually) and the triangle
items = []
sum = 0
striangle = <<TRIANGLE
3
7 4
2 4 6
8 5 9 3
TRIANGLE
# Transform this TRIANGLE shown above, into array(s)
#
# 3
# 7 4 ==> [[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]
# 2 4 6
# 8 5 9 3
#
triangle = striangle.split("\n").collect do |e|
e.split(" ").collect do |n|
n.to_i
end.delete_if { |i| i == 0 }
end
# Add the first one to the sum
sum += triangle[0][0]
# Position of present number
pos = nil
row = triangle.size - 1
triangle.each do |i|
max = triangle[row].max
puts "#{triangle[row - 1][triangle[row].index(max)]} #{triangle[row - 1][triangle[row].index(max) - 1]} [#{row}]"
row -= 1
end
#puts "yer answerrr be: #{sum}"
| true
|
cceaa9fedff6d676acd579ba0d8fe590f6c72030
|
Ruby
|
Zacharae/spring16ruby
|
/lib/string_calculator.rb
|
UTF-8
| 245
| 3.65625
| 4
|
[] |
no_license
|
class StringCalculator
def self.add(input)
if input.empty?
0
else
numbers = input.split(",").map { |integer| integer.to_i }
numbers.inject(0) { |sum, number| sum + number }
end
end
end
# x = StringCalculator.new
# x.add("55")
| true
|
bc103cf3935f09f924e345bff2118f8188a9d425
|
Ruby
|
hannahlcameron/api-muncher
|
/lib/edamam_api_wrapper.rb
|
UTF-8
| 933
| 2.703125
| 3
|
[] |
no_license
|
require 'httparty'
class EdamamApiWrapper
class EdamamError < StandardError; end
BASE_URL = "https://api.edamam.com/search"
ID = ENV["EDAMAM_API_ID"]
KEY = ENV["EDAMAM_API_KEY"]
def self.list_recipes(query)
full_url = URI.encode(BASE_URL + "?q=" + query + "&app_id=" + ID + "&app_key=" + KEY + "&from=0&to=50")
response = HTTParty.get(full_url)
raise_on_error(response)
return response["hits"].map do |raw_recipe|
Recipe.from_api(raw_recipe['recipe'])
end
end
def self.display_recipe(uri)
full_url = URI.encode(BASE_URL + "?r=http://www.edamam.com/ontologies/edamam.owl#recipe_" + uri + "&app_id=" + ID + "&app_key=" + KEY)
response = HTTParty.get(full_url)
raise_on_error(response)
return Recipe.from_api(response[0])
end
private
def self.raise_on_error(response)
unless response["more"]
raise EdamamError.new(response["error"])
end
end
end
| true
|
8648cb9b65e09925550c68f13838c805bec7f031
|
Ruby
|
hasumikin/mrubyc
|
/mrblib/numeric.rb
|
UTF-8
| 599
| 3.21875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#
# Integer, mrubyc class library
#
# Copyright (C) 2015-2021 Kyushu Institute of Technology.
# Copyright (C) 2015-2021 Shimane IT Open-Innovation Center.
#
# This file is distributed under BSD 3-Clause License.
#
class Integer
# times
def times
i = 0
while i < self
yield i
i += 1
end
self
end
# upto
def upto(max, &block)
i = self
while i <= max
block.call i
i += 1
end
return self
end
# downto
def downto(min, &block)
i = self
while min <= i
block.call i
i -= 1
end
return self
end
end
| true
|
37b62914d1de816a1cb58408d1b1b4262b9b2c11
|
Ruby
|
liptiavenica/tugas_ruby_basic
|
/player.rb
|
UTF-8
| 241
| 3.296875
| 3
|
[] |
no_license
|
class Player
attr_accessor :nama, :blood, :manna
def initialize nama
@blood=100
@manna=40
@nama = nama
end
def serang
@manna -=20
end
def diserang
@blood -=20
end
def game_over
@manna == 0 || @blood == 0
end
end
| true
|
4002e9c39985da9f866f21bdfb85667bd5d5ca0d
|
Ruby
|
aishwaryaramachandran/jungle-rails
|
/app/models/user.rb
|
UTF-8
| 604
| 2.5625
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
has_secure_password
has_many :reviews
has_many :orders
validates :email, presence: true, uniqueness: {case_sensitive: false}
validates :name, presence: true
validates :password, confirmation: true, length: { minimum: 6 }
def self.authenticate_with_credentials(email, password)
user = User.find_by_email(email)
# If the user exists AND the password entered is correct.
if user && user.authenticate(password)
user
else
nil
end
end
def self.ignore_case(email)
User.where("lower(email) = ?", email.downcase)
end
end
| true
|
b4ac849be8b1dc705caa8874c80d6258114c376b
|
Ruby
|
jmmastey/code_tests
|
/multi_armed_bandit/lib/strategies/epsilon_greedy_strategy.rb
|
UTF-8
| 359
| 3.15625
| 3
|
[] |
no_license
|
class EpsilonGreedyStrategy
attr_accessor :name, :epsilon
def initialize(name: "EpsilonGreedy", epsilon: 10)
@name = name
@epsilon = epsilon
end
def choose_variant(variants)
if exploring?
variants.sample
else
variants.sort_by(&:expectation).last
end
end
def exploring?
rand(1..100) <= epsilon
end
end
| true
|
a015b8c3ea22e22b1ea35752811659c2084ae51b
|
Ruby
|
shiba6v/test_sim
|
/app/controllers/home_controller.rb
|
UTF-8
| 1,973
| 2.8125
| 3
|
[] |
no_license
|
class HomeController < ApplicationController
def top
end
def result
#手の名前、ステータスの管理
@hand = ["グー","チョキ","パー"]
#プレイヤー(必殺の手,体力,攻撃,テクニック)
#プレイヤー1を@a、プレイヤー2を@bと置く。
@a = [params[:num1],params[:hpt1],params[:atk1],params[:tec1]].map{|w| w=w.to_i}
@b = [params[:num2],params[:hpt2],params[:atk2],params[:tec2]].map{|w| w=w.to_i}
#攻撃と必殺技
def attack(playerx,playery)
playery[1] -= (playerx[2]*0.3).round
playery[1] = 0 if playery[1] < 0
end
def special(playerx,playery)
playery[1] -= (playerx[3]*0.6).round
playery[1] = 0 if playery[1] < 0
end
@log=["戦闘ログ"]
#じゃんけんメソッドの定義
#このnum1,num2はプレイヤーの必殺技でなく、それぞれのゲームごとの出した手である。
@num1=[]
@num2=[]
@var=[]
4.times do |n|
@num1[n]=params[:a[0]]["#{n}"].to_i
@num2[n]=params[:b[0]]["#{n}"].to_i
#a[0]の0はじゃんけんの手の入力ということ。なぜかこうなっただけで特に意味は無い。num1[0]と["0"]における0は、1回目のバトルということ
@log<< "1Pの手は" + @hand[@num1[n]]+ "です。"
@log<< "2Pの手は" + @hand[@num2[n]]+ "です。"
@var[n] = @num1[n] - @num2[n]
if @var[n] == -1 || @var[n] == 2
if @num1[n]==@a[n]
special(@a,@b)
@log<<"1Pの必殺技だ!"
else
attack(@a,@b)
@log<<"1Pの攻撃!"
end
elsif @var[n] == 1 || @var[n] == -2
if @num2[n]==@b[n]
special(@b,@a)
@log<<"2Pの必殺技だ!"
else
attack(@b,@a)
@log<<"2Pの攻撃!"
end
elsif @var[n] == 0
@log<<"あいこです"
end
@log<<"1Pの残り体力" + @a[1].to_s
@log<<"2Pの残り体力" + @b[1].to_s
break if @a[1]==0||@b[1]==0
end
end
end
| true
|
f617bcc903a3910de63277c707c4fd4f3ffb2bd2
|
Ruby
|
MatLock/batalla_naval
|
/batalla_naval/features/step_definitions/disparo_step.rb
|
UTF-8
| 1,567
| 2.890625
| 3
|
[] |
no_license
|
require_relative '../../app/models/Tablero.rb'
require_relative '../../app/models/Barco.rb'
Given(/^a board with dimension "(.*?)" x "(.*?)"$/) do |x, y|
#@tablero = Tablero.new(x.to_i,y.to_i)
visit '/mipagina'
fill_in(:ancho, :with => x)
fill_in(:alto, :with => y)
click_button "crearTablero"
end
Given(/^a large ship in position "(.*?)"$/) do |coords|
#@barco_largo = BarcoLargo.new("Alpha",2)
#@tablero.ponerBarcoEn(coords,@barco_largo)
fill_in(:coordenadas, :with => coords)
fill_in(:nombreBarco, :with => "Delta")
fill_in(:tamanio, :with => "2")
click_button "crearBarco"
end
Given(/^I shoot to position "(.*?)"$/) do |coord|
#@resultado = @tablero.dispararEn(coord)
fill_in(:coordDisparo,:with => coord)
click_button "disparo"
end
Then(/^I get "(.*?)"$/) do |water|
#expect(@resultado).to eq water
page.should have_content(water)
end
Given(/^I shoot to position "(.*?)" and assert the hit$/) do |coord|
#@resultado2 = @tablero.dispararEn(coord)
fill_in(:coordDisparo,:with => coord)
click_button "disparo"
end
Then(/^I got "(.*?)"$/) do |hit|
#expect(@resultado2).to eq hit
page.should have_content(hit)
end
Given(/^I shoot the positions "(.*?)" "(.*?)"$/) do |coord1, coord2|
#@tablero.dispararEn(coord1)
#@resultado = @tablero.dispararEn(coord2)
fill_in(:coordDisparo,:with => coord1)
click_button "disparo"
fill_in(:coordDisparo,:with => coord2)
click_button "disparo"
end
Then(/^this time I got "(.*?)"$/) do |sink|
#expect(@resultado).to eq sink
page.should have_content(sink)
end
| true
|
870a940dfe07c11f36ce3798dcc56a739fd186e4
|
Ruby
|
eijimine/object-oriented-programming-class-methods-and-class-variables
|
/vampires.rb
|
UTF-8
| 1,215
| 3.6875
| 4
|
[] |
no_license
|
require 'pry'
class Vampire
attr_accessor :name, :age, :in_coffin, :drank_blood_today
@@coven = []
def initialize(name, age)
@name = name
@age = age
@in_coffin = true
@drank_blood_today = true
end
def self.create(name, age)
new_vamp = Vampire.new(name, age)
@@coven << new_vamp
return new_vamp
end
def self.all
@@coven
end
def self.sunrise
#remove vamps from coven who are out of their coffins and haven't drank blood
@@coven.each do |cov|
if cov.in_coffin == false || cov.drank_blood_today == false
@@coven.delete(cov)
end
end
end
def self.sunset
#which sets drank_blood_today and in_coffin to false for the entire coven as they go out in search of blood
@@coven.each do |cov|
cov.in_coffin = false
cov.drank_blood_today = false
end
end
def self.go_home
#sets vamps in coffins to true
@@coven.each do |cov|
cov.in_coffin == true
end
end
def drink_blood
@drank_blood_today = true
return @@coven
end
end
# a = Vampire.new('vamp1', 4)
# b = Vampire.new('vamp2', 5)
# c = Vampire.new('vamp3', 34)
# d = Vampire.new('vamp4', 454)
# e = Vampire.new('vamp5', 2)
| true
|
57b922a02b6e49d594fda7b7ea4bf33c57ec1ae7
|
Ruby
|
caok/knowledge
|
/ruby/error127/badcmd-redir.rb
|
UTF-8
| 785
| 2.75
| 3
|
[] |
no_license
|
# Lo and behold this works.{{{shot(3b)}}}
# It seems like it has validated our theory.
# In fact, though, this is a false positive. And if we continued forward
# with this incorrect understanding, it could send us down some blind
# alleys in the future. And yes, I speak from experience.
# We can start to see that our understanding of the situation is false
# if we try a different redirection. According to our theory, if we
# instead redirect standard output to =/dev/null=, we should no longer
# see an error message, since we are no longer routing the standard
# error stream to standard output.{{{shot(4)}}}
# But in fact, we see the same error message.{{{shot(5)}}}
system "pigmentize -o out.html in.html 1>/dev/null" # => false
# !> sh: 1: pigmentize: not found
| true
|
caec03310725169bb0896510aeecccac873918b8
|
Ruby
|
kawamataryo/eratos
|
/lib/eratos.rb
|
UTF-8
| 492
| 3.328125
| 3
|
[] |
no_license
|
require 'set'
def eratos(max_num)
# ステップ1 探索リストの作成
search_list = []
(2..max_num).each do |num|
search_list << num
end
# ステップ2, 3 探索リストのふるい落とし
i = 0
while search_list[i] < Math.sqrt(max_num)
search_list.each do |composit_num|
if composit_num > search_list[i] && (composit_num % search_list[i]).zero?
search_list.delete(composit_num)
end
end
i+= 1
end
search_list.join(', ')
end
| true
|
0130fb7c4e4f7b867210a1c8e4b40042185be567
|
Ruby
|
SpiderStrategies/sensu-resque-stale-jobs
|
/stale-resque-jobs.rb
|
UTF-8
| 1,980
| 2.625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
#
# A sensu plugin to determine if there are jobs sitting in the timestamps set too long
#
require 'rubygems' if RUBY_VERSION < '1.9.0'
require 'sensu-plugin/check/cli'
require 'redis'
class RedisChecks < Sensu::Plugin::Check::CLI
option :host,
:short => "-h HOST",
:long => "--host HOST",
:description => "Redis hostname",
:required => true
option :port,
:short => "-p PORT",
:long => "--port PORT",
:description => "Redis port",
:default => "6379"
option :password,
:short => "-P PASSWORD",
:long => "--password PASSWORD",
:description => "Redis Password to connect with"
option :namespace,
:description => "Resque namespace",
:short => "-n NAMESPACE",
:long => "--namespace NAMESPACE",
:default => "resque"
option :warn,
:short => "-w MINUTES",
:long => "--warn MINUTES",
:description => "Warn when timestamp has been stale so many minutes",
:proc => proc {|p| p.to_i },
:required => true
option :crit,
:short => "-c MINUTES",
:long => "--crit MINUTES",
:description => "Critical when timestamp has been stale for so many minutes",
:proc => proc {|p| p.to_i },
:required => true
def run
redis = Redis.new(:host => config[:host], :port => config[:port], :password => config[:password])
staleCrit = Time.now - config[:crit] * 60
staleWarn = Time.now - config[:warn] * 60
redis.keys(config[:namespace] + ':timestamps:*').each do |key|
# puts key, redis.smembers(key)
#TODO This is expensive for lots of timestamps
redis.smembers(key).each do |timestamp|
t = Time.at(timestamp.split(':')[1].to_i)
if (t < staleCrit)
critical "CRITICAL: Resque queue timestamp #{key}, has a timestamp of #{t}!"
elsif (t < staleCrit)
warning "WARNING: Resque queue timestamp #{key}, has a timestamp of #{t}!"
end
end
end
ok "No stale timestamps"
end
end
| true
|
5592a5b251a45156cf0ff7664d97950bd4e294db
|
Ruby
|
JamRamPage/CRICKETLEAGUE
|
/app/models/batting_innings.rb
|
UTF-8
| 3,504
| 2.984375
| 3
|
[] |
no_license
|
class BattingInnings < ApplicationRecord
#BattingInnings is linker table between Innings and Player:
belongs_to :Innings
belongs_to :Player
#BattingInnings also has two other Player fields (representing up to two)
#members of other team that got the current batsman out.
belongs_to :bowler, :class_name => 'Player', :foreign_key => 'bowler_id', optional: true
belongs_to :fielder, :class_name => 'Player', :foreign_key => 'fielder_id', optional: true
#The ways in which a batsman can get out in cricket:
enum howout: [:NotOut, :DNB, :Bowled, :Caught, :LBW, :RunOut, :Stumped, :Retired, :HitBallTwice, :HitWicket, :ObstructingField, :TimedOut]
#We do not necessarily require a bowler/fielder because a batsman may not have been out:
#Also, some ways of getting out only involve one or the other, e.g.:
# being bowled only involves a bowler
# being run out only involves a fielder
validates :Innings, :Player, :batsman_number, :runs, :balls, :fours, :sixes, :howout, :batsman_number, presence: true
#All these must be >=0 and integers
validates :runs, :balls, :fours, :sixes, :batsman_number, numericality: {only_integer: true, greater_than_or_equal_to: 0}
# A batsman cannot be the "zeroth" batsman! This determines the order in which the players batted:
validates :batsman_number, numericality: {only_integer: true, greater_than: 0}
#A batsman can't hit more fours or sixes than the number of deliveries they are bowled!
validates :fours, :sixes, :numericality => {:less_than_or_equal_to => :balls}
#Returns the correctly formatted way of describing how a batsman was out:
#Used in displaying the scorecards:
def outDescription
begin
if (self.howout_before_type_cast == 0 || self.howout_before_type_cast == 1 || self.howout_before_type_cast > 7) then
#description is enough, as these ways of getting out do
# not relate to any fielders.
howout
elsif (self.howout_before_type_cast == 2) then
#bowled out
"b #{self.bowler.name}"
elsif (self.howout_before_type_cast == 3) then
if (self.bowler.name != self.fielder.name) then
#caught by a different fielder to the bowler
"c #{self.fielder.name} b #{self.bowler.name}"
else
#caught and bowled both by the bowler
"c & b #{self.bowler.name}"
end
elsif (self.howout_before_type_cast == 4) then
"lbw b #{self.bowler.name}"
elsif (self.howout_before_type_cast == 5) then
"run out (#{self.fielder.name})"
else
"stumped #{self.fielder}"
end
rescue NoMethodError
#Something went wrong - perhaps the user entered an invalid
#combination, such as Caught, but left the bowler field blank
"ERROR - PLEASE EDIT THIS INNINGS AND CORRECT IT"
end
end
#The set of batting inningses given a match object:
scope :setFromMatch, -> (match) {joins(:Innings => :match).where("Innings.match_id" => match)}
#ONLY USE WITH ABOVE! Returns the batting inningses for each of the home and away teams:
scope :home, -> {where("Innings.hometeambatted" => true).order(:batsman_number)}
scope :away, -> {where("Innings.hometeambatted" => false).order(:batsman_number)}
#The number of fours * 4 plus sixes * 6 must be <= number of runs
validate :four_six_limit
private
def four_six_limit
if fours*4+sixes*6 > runs
errors.add(:fours, "Too many fours")
errors.add(:sixes, "Too many sixes")
end
end
end
| true
|
eb7d4b934e409fea6825fb5b2a7462a54b5120c2
|
Ruby
|
vrthra/clone-unit-coverage
|
/graphs/bin/coverage.rb
|
UTF-8
| 1,155
| 2.96875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require 'rubygems'
require 'SVG/Graph/Plot'
# Data sets are x,y pairs
# Note that multiple data sets can differ in length, and that the
# data in the datasets needn't be in order; they will be ordered
# by the plot along the X-axis.
projection = []
begin
File.open('summary/coverage-data.txt').each_line do | l |
case l
when /(\d+)\/(\d+) [^ ]+$/
cov = $1.to_i
total = $2.to_i
next if total == 0
#next if total == 866152155
projection << Math.log(total)
projection << cov*100/total
else
raise l
end
end
rescue Exception => e
puts e.message
puts e.backtrace
exit 1
end
#projection = [
# 6, 11, 0, 5, 18, 7, 1, 11, 13, 9, 1, 2, 19, 0, 3, 13,
# 7, 9
#]
#actual = [
# 0, 18, 8, 15, 9, 4, 18, 14, 10, 2, 11, 6, 14, 12,
# 15, 6, 4, 17, 2, 12
#]
graph = SVG::Graph::Plot.new({
:height => 500,
:width => 800,
:key => false,
:scale_x_integers => true,
:scale_y_integerrs => true,
})
graph.add_data({
:data => projection,
:title => 'Projected',
})
#graph.add_data({
# :data => actual,
# :title => 'Actual',
#})
print graph.burn()
| true
|
400bef1301fe5baf368c76896cc5d04d28ce22e3
|
Ruby
|
MaryBLee/Employee-Departments
|
/development.rb
|
UTF-8
| 1,838
| 3.703125
| 4
|
[] |
no_license
|
require './department.rb'
#Create a new department
sales = Department.new(name: 'Sales')
finance = Department.new(name: 'Finance')
marketing = Department.new(name: 'Marketing')
#Create a new employee
rizzo = Employee.new(name: 'Rizzo', email: 'rizzo@gmail.com', phone: '919-123-4567', salary: 60000)
sandy = Employee.new(name: 'Sandy', email: 'sandra.d@gmail.com', phone: '523-123-1234', salary: 50000)
danny = Employee.new(name: 'Danny', email: 'greaser4life@gmail.com', phone: '345-123-3456', salary: 40000)
kenickie = Employee.new(name: 'Kenickie', email: 'kenick@gmail.com', phone: '980-123-1234', salary: 45000)
frenchy = Employee.new(name: 'Frenchy', email: 'beautyschooldropout@gmail.com', phone: '678-345-1234', salary: 65000)
jan = Employee.new(name: 'Jan', email: 'jan@gmail.com', phone: '987-456-7890', salary: 40000)
tom = Employee.new(name: 'Tom', email: 'tom@gmail.com', phone: '675-453-8976', salary: 20000)
#Add an employee to a department
sales.add_employee(kenickie)
sales.add_employee(danny)
sales.add_employee(rizzo)
finance.add_employee(sandy)
finance.add_employee(jan)
finance.add_employee(tom)
marketing.add_employee(frenchy)
#Get an employee's name
puts rizzo.name
#Get an employee's salary
puts rizzo.salary
#Get a department's name
puts sales.name
#Get a total salary for all employees in a department
puts sales.total_salaries
#Add employee review text
rizzo.add_review('Rizzo is great.')
puts rizzo.review
#Mark whether an employee is performing satisfactorily
rizzo.add_grade('Pass')
puts rizzo.grade
#Give a raise to an individual
rizzo.give_raise(5000)
puts rizzo.salary
#Give raises to a department's employees
puts danny.name
puts danny.salary
puts kenickie.name
puts kenickie.salary
danny.add_grade('Pass')
kenickie.add_grade('Fail')
sales.give_raise(2000)
puts rizzo.name
puts rizzo.salary
puts danny.name
puts danny.salary
puts kenickie.name
puts kenickie.salary
| true
|
09829eec13148e17bd320a0c349b857d1735c1dc
|
Ruby
|
rmamdouh/final
|
/features/sales_filter_feature.rb
|
UTF-8
| 843
| 2.578125
| 3
|
[] |
no_license
|
Feature: display list of good filtered by check box
As a concerned parent
So that I can quickly browse movies appropriate for my family
I want to see movies matching only certain MPAA ratings
Background: sales in database
Given the following movies exist:
| good | price | city | date |
| good1 | 11 | Cairo | 1977-05-25 |
| good1 | 22 | Alex | 1988-05-25 |
| good1 | 33 | Aswan | 1999-05-25 |
| good1 | 33 | Mansoura | 1999-05-25 |
Scenario: filter sales by city
When I check the following cities: Cairo, Alex
When I uncheck the following ratings: Mansoura, Aswan
And I press "Refresh"
Then I should see "Cairo"
Then I should see "Alex"
Then I should not see "Mansoura"
Then I should not see "Mansoura"
| true
|
2ec64e7c597937c1990a82af6fdddd0fdac86df3
|
Ruby
|
Apemb/ruby_connect_4
|
/app/view.rb
|
UTF-8
| 150
| 2.625
| 3
|
[] |
no_license
|
class View
def initialize console
@console = console
end
def get_player_input grid, player
@console.puts 'C\'est au joueur 1'
end
end
| true
|
bdb56bc445e69388d9809cb291aeccc16e46be2e
|
Ruby
|
j-rods/lrthw
|
/Chap14/ex14.rb
|
UTF-8
| 694
| 4.25
| 4
|
[] |
no_license
|
#To run, ruby ex14.rb <yourname>
# gets the first argument / used to get 1 argument
user_name = ARGV.first
#variable prompt
prompt = 'answer below '
puts "Hi #{user_name}."
puts "I'd like to ask you a few questions."
puts "Do you like me #{user_name}? "
puts prompt
likes = $stdin.gets.chomp
puts "Where do you live #{user_name}? "
puts prompt
lives = $stdin.gets.chomp
# a comma for puts is like using it twice
puts "What kind of computer do you have? ", prompt
computer = $stdin.gets.chomp
#using """ triple-double-quote escape sequence
puts """
Alright, so you said #{likes} about liking me.
You live in #{lives}. Not sure where that is.
And you have a #{computer} computer. Nice.
"""
| true
|
a9fb4b0fae25dd11097a1fabf2e943de11893810
|
Ruby
|
MrPowers/project_euler
|
/020/code.rb
|
UTF-8
| 176
| 3.546875
| 4
|
[] |
no_license
|
def factorial(n)
(1..n).to_a.inject(&:*)
end
def sum_digits(n)
n.to_s.split("").inject(0) do |memo, n|
memo += n.to_i
memo
end
end
p sum_digits(factorial(100))
| true
|
49dc8372fccc1d9a2e45fee181a5565c8eb0b9f2
|
Ruby
|
Yves53/Yves53.github.io
|
/Project Euler/ProblemSix/problem_six.rb
|
UTF-8
| 296
| 3.4375
| 3
|
[] |
no_license
|
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
multi_sum = 0
add_sum = 0
(1..100).each do |i|
multi_sum += i**2
add_sum += i
end
puts "The difference between the two is #{(add_sum**2) - multi_sum}"
# answer = 25164150
| true
|
f52692450295da39477cf1dcde9f132bd188884e
|
Ruby
|
h55nick/project3
|
/app/models/question.rb
|
UTF-8
| 2,013
| 2.8125
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: questions
#
# id :integer not null, primary key
# q :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# interest_id :integer
#
class Question < ActiveRecord::Base
attr_accessible :q
has_and_belongs_to_many :users
has_one :interest
def Question.ask(question, interest)
q = Question.create( q: question)
q.interest = Interest.create( realistic: 0, investigative: 0, social: 0, artistic: 0, conventional: 0, enterprising: 0)
Question.up_score(q, interest, 5)
end
def Question.choose_class
count = Random.rand(4) + 1
return 'modern' if count == 1
return 'serious' if count == 2
return 'bookish' if count == 3
return 'classic' if count == 4
end
def Question.up_score(owner, interest, value)
case interest
when 'realistic'
owner.interest.update_attributes( realistic: (owner.interest.realistic + value))
when 'investigative'
owner.interest.update_attributes( investigative: (owner.interest.investigative + value))
when 'social'
owner.interest.update_attributes( social: (owner.interest.social + value))
when 'conventional'
owner.interest.update_attributes( conventional: (owner.interest.conventional + value))
when 'artistic'
owner.interest.update_attributes( artistic: (owner.interest.artistic + value))
when 'enterprising'
owner.interest.update_attributes( enterprising: (owner.interest.enterprising + value))
end
owner.interest.save
owner.update_attributes( total: (owner.total + 5)) if owner.is_a?(User)
end
def topic
return 'realistic' if self.interest.realistic > 0
return 'investigative' if self.interest.investigative > 0
return 'social' if self.interest.social > 0
return 'conventional' if self.interest.conventional > 0
return 'artistic' if self.interest.artistic > 0
return 'enterprising' if self.interest.enterprising > 0
end
end
| true
|
964d387315495a36dd402eb0077a7e23127bac16
|
Ruby
|
ryanttb/internet_monitor
|
/lib/retrievers/hdi_parser.rb
|
UTF-8
| 701
| 2.609375
| 3
|
[] |
no_license
|
class HDIParser
require 'csv'
include Amatch
def data(options = {})
data = []
filename = options[:filename]
csv = CSV.read(filename, { :headers => true })
csv.each do |row|
country = Country.find_by_iso3_code(row['ISO Code'])
next unless country
['1980','1990','2000','2005','2009','2010','2011'].each do |year|
next if row[year] == '..'
start_date = Date.new(year.to_i, 1, 1)
i = Indicator.new(:start_date => start_date, :original_value => row[year].to_f)
i.country = country
data << i
end
end
data
end
end
| true
|
f63fd90104519e2e16cf9d610565ead5d353235b
|
Ruby
|
aimeesophia/pair-programming
|
/spec/arrays_spec.rb
|
UTF-8
| 1,253
| 3.671875
| 4
|
[] |
no_license
|
require 'pairing.rb'
describe 'plus_1' do
it 'returns +1 to each entry in the array' do
expect(plus_1([1, 2, 3, 4, 5])).to eq [2, 3, 4, 5, 6]
end
end
describe 'arr_sort' do
it 'returns the array sorted' do
expect(arr_sort([1, 3, 5, 4, 2])).to eq [1, 2, 3, 4, 5]
end
end
describe 'plus_1_and_sort' do
it 'adds 1 and sorts' do
expect(plus_1_and_sort([1, 3, 5, 4, 2])).to eq [2, 3, 4, 5, 6]
end
end
describe 'arr_sum' do
it 'returns the sum of all numbers in the array' do
expect(arr_sum([1, 2, 3, 4, 5])).to eq 15
end
end
describe 'twice' do
it 'returns twice the sum of all numbers in the array' do
expect(twice([1, 2, 3, 4, 5])).to eq 30
end
end
describe 'hash_plus_1' do
it 'returns the hash with value +1' do
input = { a: 1, b: 2 }
output = { a: 2, b: 3 }
expect(hash_plus_1(input)).to eq output
end
end
describe 'hash_reverse' do
it 'change value output to hash input' do
input = { a: 2, b: 5, c: 1 }
output = { a: 1, b: 2, c: 5 }
expect(hash_reverse(input)).to eq output
end
end
describe 'return_hash_values' do
it 'returns the hash values only' do
input = { a: 2, b: 5, c: 1 }
output = [1, 2, 5]
expect(return_hash_values(input)).to eq output
end
end
| true
|
56d820699ab7a92116564244c6bd93549a49bd74
|
Ruby
|
haolhaol/rake-builder
|
/lib/rake/once_task.rb
|
UTF-8
| 560
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require 'rake/tasklib'
module Rake
# A task whick is no longer needed after its first invocation
class OnceTask < Task
attr_accessor :invoked
attr_accessor :timestamp
def self.define_task(*args, &block)
task = super(*args, &block)
task.timestamp = nil
task.invoked = false
task
end
def execute(*args)
@timestamp = Time.now
@invoked = true
super(*args)
end
def needed?
! @invoked
end
end
end
def once_task(*args, &block)
Rake::OnceTask.define_task(*args, &block)
end
| true
|
5e367b509b1b36003a0e1cb7ac1a5f4b05956342
|
Ruby
|
MarcRF/RUBY1
|
/ex2.rb
|
UTF-8
| 531
| 3.4375
| 3
|
[] |
no_license
|
def grr(x,y)
lettres =[]
lettres = x.split("")
print lettres
lettresHSC=[]
lettres.each { |string| lettresHSC << string.ord
}
puts lettresHSC
lettresHSC.each {|x|
x += y
print "#{x.chr}"
}
end
grr("ab!bc", 1)
puts " What a string! Bmfy f xywnsl!"
=begin
mots = x.split("!")
print mots
["ryan", "jane"].each {|string| puts "#{string[0].upcase}#{string[1..-1]}"}
def cdc(x,z)
y=0
y = x.ord + z
puts y.chr
end
cdc("b",4) =end
# a.each { |a| puts "v" }
#cdc("a",2)
#for
String[]
tab=[1,4,0]
=end
| true
|
e5ada7b70b517d08131f47641df1625183981dc3
|
Ruby
|
jacqueline-lam/project-euler-multiples-3-5-online-web-pt-090919
|
/lib/multiples.rb
|
UTF-8
| 507
| 3.796875
| 4
|
[] |
no_license
|
# Enter your procedural solution here!
# list all natural numbers below limit that are multiples of 3 or 5
# collects correct multiples of natural numbers below limit
def collect_multiples(limit)
multiples = []
(1...limit).each do |num|
multiples << num if (num % 3 == 0 || num % 5 == 0)
end
return multiples
end
# returns correct sum of multiples of 10
def sum_multiples(limit)
multiples = collect_multiples(limit)
# return multiples.sum
return multiples.inject(0){|sum,n| sum + n }
end
| true
|
bb6d8dc6d1d75b2ce7ea9edf2a8be036f304d90b
|
Ruby
|
bachya/cliutils
|
/lib/cliutils/ext/hash_extensions.rb
|
UTF-8
| 4,658
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
# Hash Class
# Contains many convenient methods borrowed from Rails
# http://api.rubyonrails.org/classes/Hash.html
class Hash
# Deep merges a hash into the current one. Returns
# a new copy of the hash.
# @param [Hash] other_hash The hash to merge in
# @return [Hash] The original Hash
def deep_merge(other_hash)
self.merge(other_hash) do |key, oldval, newval|
oldval = oldval.to_hash if oldval.respond_to?(:to_hash)
newval = newval.to_hash if newval.respond_to?(:to_hash)
oldval.class.to_s == 'Hash' && newval.class.to_s == 'Hash' ?
oldval.deep_merge(newval) : newval
end
end
# Deep merges a hash into the current one. Does
# the replacement inline.
# @param [Hash] other_hash The hash to merge in
# @return [Hash] The original Hash
def deep_merge!(other_hash)
replace(deep_merge(other_hash))
end
# Recursively turns all Hash keys into strings and
# returns the new Hash.
# @return [Hash] A new copy of the original Hash
def deep_stringify_keys
deep_transform_keys { |key| key.to_s }
end
# Same as deep_stringify_keys, but destructively
# alters the original Hash.
# @return [Hash] The original Hash
def deep_stringify_keys!
deep_transform_keys! { |key| key.to_s }
end
# Recursively turns all Hash keys into symbols and
# returns the new Hash.
# @return [Hash] A new copy of the original Hash
def deep_symbolize_keys
deep_transform_keys { |key| key.to_sym rescue key }
end
# Same as deep_symbolize_keys, but destructively
# alters the original Hash.
# @return [Hash] The original Hash
def deep_symbolize_keys!
deep_transform_keys! { |key| key.to_sym rescue key }
end
# Generic method to perform recursive operations on a
# Hash.
# @yield &block
# @return [Hash] A new copy of the original Hash
def deep_transform_keys(&block)
_deep_transform_keys_in_object(self, &block)
end
# Same as deep_transform_keys, but destructively
# alters the original Hash.
# @yield &block
# @return [Hash] The original Hash
def deep_transform_keys!(&block)
_deep_transform_keys_in_object!(self, &block)
end
# Allows for dot-notation getting/setting within
# a Hash.
# http://ceronio.net/2012/01/javascript-style-object-value-assignment-in-ruby/
# @param [<String, Symbol>] meth The method name
# @param [Array] args Any passed arguments
# @yield if a block is passed
def method_missing(meth, *args, &block)
meth_name = meth.to_s
if meth_name[-1,1] == '='
self[meth_name[0..-2].to_sym] = args[0]
else
self[meth] || self[meth_name]
end
end
# Recursively searches a hash for the passed
# key and returns the value (if there is one).
# http://stackoverflow.com/a/2239847/327179
# @param [<Symbol, String>] key The key to search for
# @yield
# @return [Multiple]
def recursive_find_by_key(key)
# Create a stack of hashes to search through for the needle which
# is initially this hash
stack = [ self ]
# So long as there are more haystacks to search...
while (to_search = stack.pop)
# ...keep searching for this particular key...
to_search.each do |k, v|
# ...and return the corresponding value if it is found.
return v if (k == key)
# If this value can be recursively searched...
if (v.respond_to?(:recursive_find_by_key))
# ...push that on to the list of places to search.
stack << v
end
end
end
end
private
# Modification to deep_transform_keys that allows for
# the existence of arrays.
# https://github.com/rails/rails/pull/9720/files?short_path=4be3c90
# @param [Object] object The object to examine
# @yield &block
# @return [Object]
def _deep_transform_keys_in_object(object, &block)
case object
when Hash
object.each_with_object({}) do |(key, value), result|
result[yield(key)] = _deep_transform_keys_in_object(value, &block)
end
when Array
object.map { |e| _deep_transform_keys_in_object(e, &block) }
else
object
end
end
# Same as _deep_transform_keys_in_object, but
# destructively alters the original Object.
# @param [Object] object The object to examine
# @yield &block
# @return [Object]
def _deep_transform_keys_in_object!(object, &block)
case object
when Hash
object.keys.each do |key|
value = object.delete(key)
object[yield(key)] = _deep_transform_keys_in_object!(value, &block)
end
object
when Array
object.map! { |e| _deep_transform_keys_in_object!(e, &block) }
else
object
end
end
end
| true
|
edb9756d775ac6bba8e70cad2a4183ef19019522
|
Ruby
|
neilma/survey
|
/lib/models/response.rb
|
UTF-8
| 490
| 2.609375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module Models
class Response
attr_reader :email, :participant, :submitted_at, :answers
def initialize(email:, employee_id:, submitted_at:, answers:)
@participant = assign_participant(email: email, participant_id: employee_id)
@submitted_at = submitted_at
@answers = answers
end
private
def assign_participant(email:, participant_id:)
Models::Participant.new(email: email, id: participant_id)
end
end
end
| true
|
88d5164adef062e3904556e534eae513d2448b21
|
Ruby
|
mjthompsgb/angel_api_gem
|
/app/models/angel_api_gem/role.rb
|
UTF-8
| 640
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module AngelApiGem
class Role
attr_accessor :id, :role, :confirmed, :name, :type, :user_id, :bio, :followers, :angel_url, :image_url
def initialize(role)
@id = role["id"]
@role = role["role"]
@confirmed = role["confirmed"]
@name = role["tagged"]["name"]
@type = role["tagged"]["type"]
@user_id = role["tagged"]["id"]
@bio = role["tagged"]["bio"]
@followers = role["tagged"]["follower_count"]
@angel_url = role["tagged"]["angellist_url"]
@image_url = role["tagged"]["image"]
end
end
end
| true
|
d89cbb7a2727d0d38e90340da2229fdd1a924d08
|
Ruby
|
brandonseroyer/buy_car
|
/lib/buy_car.rb
|
UTF-8
| 620
| 3.375
| 3
|
[] |
no_license
|
class Vehicle
define_method(:initialize) do |make, model, year|
@make = make
@year = year
@model = model
end
define_method(:age) do
current_year = Time.new().year()
age = current_year.-(@year)
end
define_method(:worth_buying?) do
american_cars = ["Chrysler", "Ford", "GM", "Chevrolet", "Cadillac", "Buick", "Dodge", "Jeep", "Tesla", "Pontiac"]
american = american_cars.include?(@make)
new_enough = age().<=(15)
american.&(new_enough)
if american.&(new_enough) == true
return "Yes, buy this car!"
else
return "No, don't buy this car!"
end
end
end
| true
|
c5df5e7070bbfcdb74b77920020262d4e416fd76
|
Ruby
|
gionaufal/rubymonk
|
/chapters/hashes.rb
|
UTF-8
| 574
| 3.765625
| 4
|
[] |
no_license
|
# iterate with a hash via #each. Remember that hashes have keys and values
restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 }
restaurant_menu.each do |item, price|
restaurant_menu[item] = price * 1.1
end
# one can use the keys and values methods in hashes. They produce arrays
restaurant_menu = { "Ramen" => 3, "Dal Makhani" => 4, "Coffee" => 2 }
restaurant_menu.keys
# an alternative way to create hashes
def artax
a = [:punch, 0]
b = [:kick, 72]
c = [:stops_bullets_with_hands, false]
key_value_pairs = [a, b, c]
Hash[key_value_pairs]
end
p artax
| true
|
4ab939c46209fbef92a8a25c06944202bf40fa98
|
Ruby
|
huyha85/method_caching
|
/lib/method_caching.rb
|
UTF-8
| 1,601
| 2.5625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module MethodCaching
module ClassMethods
def method_caching(identifier_attr = :id)
@identifier = identifier_attr.to_sym
self.send(:include, InstanceMethods)
end
def cache_method(method, options = {})
old = "_#{method}".to_sym
alias_method old, method
define_method method do |*args|
Rails.cache.fetch(cache_key_name(method)) do
send(old, *args)
end
end
clear_methods = [options[:clear_on]].flatten.compact
clear_methods.each do |clear_method|
cache_method_clear_on(clear_method, method)
end
end
def cache_method_clear_on(clear_method, cache_method)
original_method = "_cache_method_clear_on_#{clear_method}"
alias_method original_method, clear_method
define_method clear_method do |*args, &blk|
self.clear_cache_on cache_method
send(original_method, *args, &blk)
end
end
def identifier
@identifier
end
end
module InstanceMethods
def clear_cache_on(method)
Rails.cache.delete(cache_key_name(method))
end
def cache_key_name(method)
identifier_method = self.class.send(:identifier)
"#{self.class.to_s}_#{self.send(identifier_method)}_#{method.to_s}"
end
end
module Generic
include ::MethodCaching::InstanceMethods
def self.included(klass)
klass.send(:extend, ::MethodCaching::ClassMethods)
end
end
end
if defined?(ActiveRecord)
ActiveRecord::Base.send(:include, MethodCaching::InstanceMethods)
ActiveRecord::Base.send(:extend, MethodCaching::ClassMethods)
end
| true
|
3c47ee560b681cbee50a69493c37eca192fe3a55
|
Ruby
|
taiki45/unfav-counter
|
/unfav.rb
|
UTF-8
| 1,991
| 2.65625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
require 'json'
require 'yaml'
require 'twitter/json_stream'
require 'twitter'
require 'ykk'
module UnfavCounter
class << self
def config
@config ||= Hash[YAML.load(open(File.expand_path('../config.yaml', __FILE__))).map {|k, v| [k.to_sym, v] }]
end
def client
@client ||= Client.new(config)
end
def run!
Signal.trap :INT do
puts "\nexitting.."
exit 0
end
puts 'starting...'
start_stream
end
def start_stream
EventMachine::run do
stream = Twitter::JSONStream.connect(
host: 'userstream.twitter.com',
path: '/1.1/user.json',
port: 443,
ssl: true,
oauth: {
consumer_key: config[:consumer_key],
consumer_secret: config[:consumer_secret],
access_key: config[:oauth_token],
access_secret: config[:oauth_token_secret]
}
)
stream.each_item do |item|
client.respond JSON.parse(item)
end
stream.on_error do |message|
puts message
end
stream.on_max_reconnects do |timeout, retries|
puts "max reconnected. timeout: #{timeout}, retries: #{retries}"
end
end
end
end
class Client
def initialize(config)
@client = Twitter::Client.new config
@store = YKK.new(dir: File.expand_path('../data', __FILE__))
end
def save(id)
@store[id.to_s] ||= 0
@store[id.to_s] += 1
end
def count_of(id)
@store[id.to_s]
end
def respond(event)
respond_unfav event if event['event'] == 'unfavorite'
end
def respond_unfav(event)
from = event['source']['screen_name']
id = event['source']['id']
save id
update "@#{from} |◞‸◟ ) あんふぁぼされた… (#{count_of(id)}回目)"
end
def update(msg)
@client.update msg
end
end
end
UnfavCounter.run! if $0 == __FILE__
| true
|
4711f9554defafd2bd6d9365586016f19b32ccc4
|
Ruby
|
freecode23/RubyProjects
|
/solutions_and_lives/animals-master/spec/lion_spec.rb
|
UTF-8
| 360
| 2.65625
| 3
|
[] |
no_license
|
require_relative '../lion'
describe Lion do
describe '#initialize' do
it 'should create instance of an lion' do
lion = Lion.new("scar")
expect(lion).to be_an(Lion)
end
end
describe '#talk' do
it 'should return the roar of the lion' do
lion = Lion.new("scar")
expect(lion.talk).to eq("scar roars")
end
end
end
| true
|
479449ee71b33f3d7e99c5f5995edad639fe90b9
|
Ruby
|
h0m3brew/Evaluarium
|
/app/services/project_program_summary_updater.rb
|
UTF-8
| 2,385
| 2.671875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
#
# This class manages the logic behind determining how a Summary's scores (JSONB) should
# be updated, and then performs the update.
#
class ProjectProgramSummaryUpdater
PROGRAM_TYPE_METHODS = {
project_follow_up: :take_latest_evaluation,
competition: :take_all_evaluations
}.with_indifferent_access
def initialize(project_id, evaluation_program_id)
@summary = ProjectProgramSummary.find_by(
project_id: project_id, evaluation_program_id: evaluation_program_id
)
return unless @summary
@type = @summary.program_type
end
def run
assign_summary_scores
assign_average_score
@summary.save!
end
private
def assign_summary_scores
@summary.scores_summary['evaluation_count'] = evaluations.count
@summary.scores_summary['criteria'] = generate_criteria_summary
end
def assign_average_score
@summary.average_score = evaluations.average(:total_score)
end
def evaluations
@evaluations ||= send(PROGRAM_TYPE_METHODS[@type])
end
def take_latest_evaluation
@summary.project_evaluations.order(timestamp: :desc).limit(1)
end
def take_all_evaluations
@summary.project_evaluations
end
def generate_criteria_summary
sql = <<-SQL
SELECT
evaluation_criteria.name,
program_criteria.weight,
evaluation_programs.criteria_scale_max AS maximum,
evaluation_programs.criteria_scale_min AS minimum,
AVG(evaluation_scores.total) AS total,
AVG(evaluation_scores.weighed_total) AS weighed_total
FROM evaluation_scores
LEFT JOIN program_criteria
ON evaluation_scores.program_criterium_id = program_criteria.id
LEFT JOIN evaluation_programs
ON program_criteria.evaluation_program_id = evaluation_programs.id
LEFT JOIN evaluation_criteria
ON program_criteria.evaluation_criterium_id = evaluation_criteria.id
WHERE evaluation_scores.project_evaluation_id IN (#{evaluations.pluck(:id).join(', ')})
GROUP BY
evaluation_criteria.name, program_criteria.weight,
evaluation_programs.criteria_scale_max,
evaluation_programs.criteria_scale_min
ORDER BY
evaluation_criteria.name
SQL
scores = EvaluationScore.connection.execute(sql).to_a
scores.inject({}) { |hash, score| hash.merge(score['name'] => score) }
end
end
| true
|
e2773b63b7af554dccf2824184bb08a4ab310ff7
|
Ruby
|
mike-shock/Ruby-Raspberry_Pi_IoT
|
/demo/demo_bh1750.rb
|
UTF-8
| 275
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby
$LOAD_PATH << "../lib" unless ARGV[0] == "gem"
require 'iot/bh1750'
sensor = IoT::BH1750.new(0x23, 1)
printf "=== %s DEMO ===\n", sensor.name
t = 6
t.times do |n|
printf "%02d Luminosity Level: %f lx (%f)\n", n, sensor.read, sensor.lux
sleep(0.5)
end
| true
|
f86483d56d5f00f980a7d850af32b5d2826903ab
|
Ruby
|
chaecramb/weekend2_homework
|
/main.rb
|
UTF-8
| 1,201
| 2.953125
| 3
|
[] |
no_license
|
require 'pry-byebug'
require_relative 'methods'
require_relative 'chain'
require_relative 'hotel'
require_relative 'room'
require_relative 'person'
chain = Chain.new("Vault Tec's Wasteland Fallout Shelter Network")
hotels = [
["Vault 13", "West of Shady Sands, Capital Wasteland, California"],
["Vault 101", "North West of Megaton, Washington D.C."],
["Vault 106", "Southeast of Arefu, Capital Wasteland, California"],
["Vault 111", "Mojave Wasteland"]
]
room_prices = [30.00, 50.00, 15.00, 100.00, 2000.00, 130.00, 85.00, 70.00, 65.00]
beds = [1,2]
rooms = [4,5,6,8,10,12,]
hotels.each do |hotel|
chain.add_hotel( name: hotel[0], address: hotel[1], id: hotel[0].split[1].to_i)
end
chain.hotels.each do |id, hotel|
rooms.sample.times { hotel.add_room( price: room_prices.sample, beds: beds.sample)}
end
response = menu
until response == 0
case response
when 1
list_hotels(chain)
when 2
check_in(chain)
# add option to choose room by price?
when 3
vacate_room(chain)
when 4
occupancy_report(chain)
when 5
revenue_report(chain)
end
puts
puts "Press enter to continue"
gets
response = menu
end
binding.pry
'a'
| true
|
efcac2b624becd4993f3e4a48fc2579913b2f596
|
Ruby
|
jbcden/tic-tac-toe
|
/lib/tic_tac_toe/game_errors.rb
|
UTF-8
| 450
| 2.546875
| 3
|
[] |
no_license
|
class GameErrors
class InvalidActionError < StandardError
def initialize(msg="This space has already been marked")
super
end
end
class InvalidCoordinateError < StandardError
def initialize(msg="An invalid coordinate was passed in, please try again")
super
end
end
class InvalidCharacterError < StandardError
def initialize(msg='Only "x" and "o" are valid character choices.')
super
end
end
end
| true
|
dad48566a45b9549cd17136509cae69750a228ae
|
Ruby
|
alexvicegrab/tangoLyricsDB
|
/rails_app/app/models/translation.rb
|
UTF-8
| 2,143
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
class Translation < ActiveRecord::Base
include Filterable
include UrlHelper
belongs_to :song, counter_cache: true
belongs_to :language, counter_cache: true
belongs_to :translator, counter_cache: true
# Scopes
# Next line overrides scoping in song Model, hence commented out
# default_scope { order('created_at') }
scope :language_is, -> (language_id) { Translation.where("language_id = ?", language_id) }
scope :translator_is, -> (translator_id) { Translation.where("translator_id = ?", translator_id) }
# Validations
validates :link,
presence: true,
length: { minimum: 15 },
url: true, # Custom URL validator in app/validators
uniqueness: { case_sensitive: false, :scope => [ :language_id, :song_id ], message: "+ language combination must be unique" } # Sometimes a page may contain several translations (in different languages)
validates :language_id,
presence: true,
numericality: { only_integer: true, greater_than_or_equal_to: 1 }
# Callbacks
before_validation :normalise_translation, on: [ :create, :update ]
after_validation :define_translator, :check_link
def self.save_all
# Useful to check that all translations are valid
Translation.all.each { |translation| translation.save! }
end
protected
def check_link
self.active = check_url(self.link) unless self.link.blank?
end
def normalise_translation
# Remove white space, replace https with http, unescape "#" character
unless self.link.blank?
self.link = self.link.strip
self.link = URI.encode(URI.decode(self.link))
#self.link = self.link.gsub('https', 'http')
self.link = self.link.gsub('%23', '#') # Hash incorrectly rendered
self.link = self.link.gsub('%20', '') # %20 sign creeping into links (e.g. YouTube links split at "=" sign)
end
end
def define_translator
# Check which translator this translation belongs to
@translators = Translator.all
unless self.link.blank?
@translators.each do |t|
if self.link.include?(t.site_link)
self.translator_id = t.id
end
end
end
end
end
| true
|
e4f94637363ce0d8aa3fc29be3cdb2f4bded694f
|
Ruby
|
chris-parker/learn_to_program
|
/ch12-new-classes-of-objects/party_like_its_roman_to_integer_mcmxcix.rb
|
UTF-8
| 578
| 3.703125
| 4
|
[] |
no_license
|
def roman_to_integer roman
roman = roman.upcase
roman.gsub!("IX", "9 ")
roman.gsub!("IV", "4 ")
roman.gsub!("XC", "90 ")
roman.gsub!("XL", "40 ")
roman.gsub!("CM", "900 ")
roman.gsub!("CD", "400 ")
roman.gsub!("M", "1000 ")
roman.gsub!("D", "500 ")
roman.gsub!("C", "100 ")
roman.gsub!("L", "50 ")
roman.gsub!("X", "10 ")
roman.gsub!("V", "5 ")
roman.gsub!("I", "1 ")
numbers = roman.split(" ")
sum = []
numbers.each do |n|
sum << n.to_i
end
return sum.reduce(:+)
end
puts roman_to_integer "i"
| true
|
f5bcce2e68cd52a42f7ab409081e3b1a86a6dc55
|
Ruby
|
pikesley/correctiondose
|
/spec/presenters/presenters_spec.rb
|
UTF-8
| 3,263
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
describe CarbohydrateIntakePresenter do
before :each do
DatabaseCleaner.clean
end
let(:carbs) { create :carbohydrate_intake }
let(:decorated_carbs) { CarbohydrateIntakePresenter.new carbs }
it 'presents as a whole table row' do
expect(decorated_carbs.to_tr).to eq (
"<tr class='carbohydrate-intake'><td><a title=\"Edit Carbs\" href=\"/carbs/1/edit\">21:25</a></td><td>Carbs</td><td class='carbohydrate-intake-weight'><div class='value' data-toggle='tooltip' data-placement='top' title='70.0 grams'><span class='number'>70</span> <span class='units'>g</span></div></td><td class='carbohydrate-intake-description'>pasta bolognese</td></tr>"
)
end
end
describe PhysicalExercisePresenter do
before :each do
DatabaseCleaner.clean
end
let(:exercise) { create :physical_exercise }
let(:decorated_exercise) { PhysicalExercisePresenter.new exercise }
it 'presents as a whole table row' do
expect(decorated_exercise.to_tr).to eq (
"<tr class='physical-exercise'><td><a title=\"Edit Exercise\" href=\"/exercise/1/edit\">15:45</a></td><td>Exercise</td><td class='physical-exercise-duration'><div class='value' data-toggle='tooltip' data-placement='top' title='90.0 Minutes'><span class='number'>90</span> <span class='units'>mins</span></div></td><td class='physical-exercise-description'>drumming</td></tr>"
)
end
end
describe GlycatedHaemoglobinPresenter do
before :each do
DatabaseCleaner.clean
end
let(:hba1c) { create :glycated_haemoglobin }
let(:decorated_hba1c) { GlycatedHaemoglobinPresenter.new hba1c }
it 'presents as a whole table row' do
expect(decorated_hba1c.to_tr padding: 1).to eq (
"<tr class='glycated-haemoglobin'><td><a title=\"Edit HbA1c\" href=\"/hba1c/1/edit\">17:11</a></td><td>HbA1c</td><td class='glycated-haemoglobin-percentage'><div class='value' data-toggle='tooltip' data-placement='top' title='6.0 percent'><span class='number'>6</span><span class='units'>%</span></div></td><td class='filler'></td></tr>"
)
end
end
describe BloodPressurePresenter do
before :each do
DatabaseCleaner.clean
end
let(:bp) { create :blood_pressure }
let(:decorated_bp) { BloodPressurePresenter.new bp }
it 'presents as a whole table row' do
expect(decorated_bp.to_tr padding: 1).to eq (
"<tr class='blood-pressure'><td><a title=\"Edit Blood Pressure\" href=\"/bp/1/edit\">15:53</a></td><td>Blood Pressure</td><td class='blood-pressure-reading'><div class='value' data-toggle='tooltip' data-placement='top' title='130/82 Systolic/Diastolic'><span class='number'>130/82</span> <span class='units'>mmHg</span></div></td><td class='filler'></td></tr>"
)
end
it 'knows how wide it is' do
expect(decorated_bp.width).to eq 3
end
end
describe MetricPresenter do
context 'round numbers for display' do
it 'leaves a straight integer alone' do
expect(described_class.rounder 10).to eq 10
end
it 'does not fuck about with blood-pressure readings' do
expect(described_class.rounder '140/32').to eq '140/32'
end
it 'trims a .0' do
expect(described_class.rounder 6.0).to eq 6
end
it 'retains other decimal parts' do
expect(described_class.rounder 12.3).to eq 12.3
end
end
end
| true
|
ec27708df3e505c4f326ed67918f431d27df3538
|
Ruby
|
shujishigenobu/genome_annot
|
/app/AEGeAn/parse_parseval_by_locus.rb
|
UTF-8
| 1,408
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
in_locus_data = false
seqid, range = nil
next_is_ref = false
next_is_pred = false
ref_gene, pred_gene = nil
data = []
File.open(ARGV[0]).each do |l|
# p next_is_ref
if m = /\|---- Locus:/.match(l)
seqid, range = nil
next_is_ref = false
next_is_pred = false
ref_gene, pred_gene = nil
data << {:seqid => nil,
:range => nil,
:ref_gene => nil,
:pred_gene => nil,
}
## (ex) seqid=scaffold_321 range=73416-81010\n
s = m.post_match.strip
m2 = /seqid\=(.+)\s+range\=(.+)$/.match(s)
data.last[:seqid] = m2[1]
data.last[:range] = m2[2]
elsif m = /^\| reference genes:/.match(l)
data.last[:ref_gene] = []
next_is_ref = true
elsif next_is_ref == true
if /^\|\n/.match(l)
next_is_ref = false
next
else
data.last[:ref_gene] << /^\|\s+(\S+)/.match(l)[1]
end
elsif m = /^\| prediction genes:/.match(l)
data.last[:pred_gene] = []
next_is_pred = true
elsif next_is_pred == true
if /^\|\n/.match(l)
next_is_pred = false
next
else
data.last[:pred_gene] << /^\|\s+(\S+)/.match(l)[1]
end
else
end
end
## output
puts "# source: #{ARGV[0]}"
puts "# date: #{Time.now}"
puts "#"
puts "# " + %w{seqid range ref_gene pred_gene}.join("\t")
data.each do |d|
outdata = [d[:seqid], d[:range], d[:ref_gene].join(","), d[:pred_gene].join(",")]
puts outdata.join("\t")
end
| true
|
ead8b6e72c20fb91042c6d699aaa32c3bde1feb8
|
Ruby
|
TheNova22/algorithms
|
/leetcode/Ruby/No150.evaluate_reverse_polish_notation.rb
|
UTF-8
| 1,631
| 4.34375
| 4
|
[] |
no_license
|
=begin
Difficulty:
Medium
Desc:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid.
That means the expression would always evaluate to a result and there won't be any divide by zero operation.
Example:
Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example:
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example:
Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
=end
# @param {String[]} tokens
# @return {Integer}
def eval_rpn(tokens)
queue = []
while tokens.size > 0 do
item = tokens.shift
n1 = queue.pop()
n2 = queue.pop()
case item
when "*" then queue.push(n2 * n1)
when "/" then
(n2 / n1) > 0 ? queue.push((n2 / n1).floor) : queue.push((n2 / n1).ceil)
when "+" then queue.push(n2 + n1)
when "-" then queue.push(n2 - n1)
else
if n2 != nil then
queue.push(n2)
end
if n1 != nil then
queue.push(n1)
end
queue.push(item.to_f)
end
end
queue.shift.to_i
end
# Test case
puts eval_rpn(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])
puts eval_rpn(["4", "13", "5", "/", "+"])
puts eval_rpn(["2", "1", "+", "3", "*"])
| true
|
d272563c634c51875206234af46406e7b1f2f39c
|
Ruby
|
Uchoosecode/badges-and-schedules-online-web-ft-120919
|
/conference_badges.rb
|
UTF-8
| 710
| 3.59375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def badge_maker(name)
i = 0
while i < name.length
puts "Hello, my name is #{name}."
i += 1
end
return "Hello, my name is #{name}."
end
def batch_badge_creator(array)
badges = []
array.each do |name|
badges << "Hello, my name is #{name}."
end
return badges
end
def assign_rooms(speakers)
r_a = 1
room_assignments = []
speakers.each do |room_assign|
room_assignments << "Hello, #{room_assign}! You'll be assigned to room #{r_a}!"
r_a += 1
end
return room_assignments
end
def printer(attendees)
i = 0
while i < attendees.length
puts batch_badge_creator(attendees)[i]
puts assign_rooms(attendees)[i]
i += 1
end
end
# Write your code here.
| true
|
4d3898c998541bddc49dba14077273da58090acc
|
Ruby
|
pedz/Snapper
|
/lib/parse_error.rb
|
UTF-8
| 577
| 2.9375
| 3
|
[] |
no_license
|
class ParseError < RuntimeError
def self.from_exception(e, history)
return e if e.is_a?(ParseError)
n = ParseError.new(e.message, history)
n.set_backtrace(e.backtrace)
n.set_class(e)
n
end
def initialize(text, history)
@history = history
@text = [ text ]
@klass = self.class
end
def add_message(text)
@text.insert(1, text)
end
def message
[ @text, "", "Context:", @history, "", "Stack", self.backtrace[0 .. 5] ].flatten.join("\n")
end
def class
@klass
end
def set_class(e)
@klass = e.class
end
end
| true
|
1c1ba244f9e65e69afa1d847275d34736f26b966
|
Ruby
|
hindenbug/puzzles
|
/battle_ship/spec/ship_spec.rb
|
UTF-8
| 1,411
| 3.140625
| 3
|
[] |
no_license
|
require "rspec"
require_relative "../battle_field"
require_relative "../ship"
describe Ship do
let(:field) { BattleField.new(10, 10) }
let(:ship) { Ship.new(field, :aircraft_carrier, 1, 1, :h) }
it "should deploy a new ship of the given type" do
ship.ship_type.should eql :aircraft_carrier
ship.direction.should eql :h
field = ship.warzone
field[1][1..5].each do |cell|
cell.should eql "A"
end
end
describe "#hit?" do
before :each do
ship.warzone[2][2] = "C"
ship.warzone[2][3] = "-"
end
it "should check if the ship was hit or not" do
ship.hit?(2,2).should be_true
ship.hit?(2,3).should_not be_true
end
end
describe "#hit!" do
context "when the ship is hit? " do
before do
ship.warzone[2][2] = "C"
ship.hits.should eql 0
ship.hit?(2,2).should be_true
end
it "should mark the ship as hit" do
expect { ship.hit!(2,2) }.to change{ship.hits}.by(1)
ship.warzone[2][2].should eql "*"
end
end
end
describe "#sunk?" do
context "when hits equal the ship size" do
before { ship.hits = 5 }
it "ship has sunk?" do
ship.should be_sunk
end
end
context "when hits not equal to size of ship" do
before { ship.hits = 3}
it "ship should sink" do
ship.should_not be_sunk
end
end
end
end
| true
|
7144b564bae430fb8f0ec800e7bdc6536ffc8210
|
Ruby
|
LehmRob/tmp
|
/rb/block/proc1.rb
|
UTF-8
| 933
| 4.3125
| 4
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/env ruby
# Simple panda example
myproc = Proc.new do |animal|
puts "I love #{animal}!"
end
myproc.call("Panda")
# Show example
def make_show_name(show)
Proc.new{|host| show + " mit " + host}
end
show1 = make_show_name("Wetten das")
show2 = make_show_name("Schlag den Raab")
puts show1.call("Thomas Gottschalk")
puts show1.call("Jörg Pilawa")
puts show2.call("Stefan Raab")
# Using the lambda operator
myproc2 = lambda do |x|
puts "Argument " + x
end
myproc2.call("deine")
myproc2.call("Mutter")
# difference between lambda and procs
lproc = lambda {|a,b| puts "#{a+b} <- sum"}
nproc = Proc.new {|a,b| puts "#{a+b} <- sum"}
nproc.call(1, 2, 3)
# Will throw an ArgumentError
#lproc.call(1, 2, 3)
def procnew
newproc = Proc.new{return "I got here"}
newproc.call
return "Procnew returns"
end
def lambdaproc
newproc = lambda{return "You got there"}
newproc.call
return "Lambdaproc returns"
end
puts procnew
puts lambdaproc
| true
|
0f620620465a8b0278b8caa4b295ca899e3248dc
|
Ruby
|
vaiorabbit/JumpPointSearch
|
/JumpPointSearch.rb
|
UTF-8
| 17,685
| 3.203125
| 3
|
[
"Zlib"
] |
permissive
|
# coding: utf-8
#
# Ref.: Online Graph Pruning for Pathfinding on Grid Maps [D. Harabor and A. Grastien. (2011)]
# http://users.cecs.anu.edu.au/~dharabor/data/papers/harabor-grastien-aaai11.pdf
#
# Usage: $ ruby JumpPointSearch.rb road_map.txt [-dijkstra] [-astar]
class String
# Ref.: http://stackoverflow.com/questions/1489183/colorized-ruby-output
def black; "\033[30m#{self}\033[0m" end
def red; "\033[31m#{self}\033[0m" end
def green; "\033[32m#{self}\033[0m" end
def brown; "\033[33m#{self}\033[0m" end
def blue; "\033[34m#{self}\033[0m" end
def magenta; "\033[35m#{self}\033[0m" end
def cyan; "\033[36m#{self}\033[0m" end
def gray; "\033[37m#{self}\033[0m" end
def bg_black; "\033[40m#{self}\033[0m" end
def bg_red; "\033[41m#{self}\033[0m" end
def bg_green; "\033[42m#{self}\033[0m" end
def bg_brown; "\033[43m#{self}\033[0m" end
def bg_blue; "\033[44m#{self}\033[0m" end
def bg_magenta; "\033[45m#{self}\033[0m" end
def bg_cyan; "\033[46m#{self}\033[0m" end
def bg_gray; "\033[47m#{self}\033[0m" end
def bold; "\033[1m#{self}\033[22m" end
def reverse_color; "\033[7m#{self}\033[27m" end
def no_colors; self.gsub(/\033\[\d+m/, "") end
def start_color; self.bg_green.gray end
def goal_color; self.bg_magenta.gray end
def path_color; self.blue end
def obstacle_color; self.bg_black.gray end
def visited_color; self.cyan end
end
def clamp(x, min, max)
[[x, max].min, min].max
end
class JPSAlgorithm
class Node
attr_accessor :id, :edges, :x, :y
def initialize(node_id)
@id = node_id
@edges = []
end
def neighbors
return Hash[@edges.collect {|edge| [edge.other(self), edge.cost] }] # node => edge.cost
end
#↓↓↓ for JPS ↓↓↓#
def neighbor_at(dx, dy) # d{x|y} = {-1, 0, 1}
if dx == 0 && dy == 0
return nil
else
edge = @edges.find {|edge| edge.other(self).x == (@x + dx) && edge.other(self).y == (@y + dy)}
return edge == nil ? nil : [edge.other(self), edge.cost]
end
end
def obstacle_at(dx, dy) # d{x|y} = {-1, 0, 1}
return neighbor_at(dx, dy) == nil
end
private :obstacle_at
CENTER = [ 0, 0]
NORTH = [ 0, -1] # ↑
NORTHEAST = [ 1, -1] # ↗
EAST = [ 1, 0] # →
SOUTHEAST = [ 1, 1] # ↘
SOUTH = [ 0, 1] # ↓
SOUTHWEST = [ -1, 1] # ↙
WEST = [ -1, 0] # ←
NORTHWEST = [ -1, -1] # ↖
def direction(dx, dy)
return case
when dx == -1 && dy == -1; NORTHWEST
when dx == -1 && dy == 0; WEST
when dx == -1 && dy == 1; SOUTHWEST
when dx == 0 && dy == -1; NORTH
when dx == 0 && dy == 0; CENTER
when dx == 0 && dy == 1; SOUTH
when dx == 1 && dy == -1; NORTHEAST
when dx == 1 && dy == 0; EAST
when dx == 1 && dy == 1; SOUTHEAST
end
end
private :direction
def natural_neighbors(dx, dy)
return neighbors() if dx == 0 && dy == 0 # self == Start Node, parent_node == nil
dirs = case direction(dx, dy)
when NORTHWEST; [NORTHWEST, NORTH, WEST] # NW
when WEST; [WEST] # W
when SOUTHWEST; [SOUTHWEST, SOUTH, WEST] # SW
when NORTH; [NORTH] # N
when SOUTH; [SOUTH] # S
when NORTHEAST; [NORTHEAST, NORTH, EAST] # NE
when EAST; [EAST] # E
when SOUTHEAST; [SOUTHEAST, SOUTH, EAST] # SE
end
nn = Hash.new
dirs.each do |dir|
neighbor = neighbor_at(*dir) # n = node => cost
nn.store(neighbor[0], neighbor[1]) unless neighbor == nil
end
return nn
end
private :natural_neighbors
def forced_neighbors(dx, dy)
return neighbors() if dx == 0 && dy == 0 # self == Start Node, parent_node == nil
forced = [] # Array of [node, node_cost] information
case direction(dx, dy)
when NORTHWEST
forced << neighbor_at(*NORTHEAST) if obstacle_at(*WEST) # if West is obstacle then mark NorthEast as forced
forced << neighbor_at(*SOUTHWEST) if obstacle_at(*SOUTH) # if South is obstacle then mark SouthWest as forced
when WEST
forced << neighbor_at(*NORTHWEST) if obstacle_at(*NORTH) # if North is obstacle then mark NorthWest as forced
forced << neighbor_at(*SOUTHWEST) if obstacle_at(*SOUTH) # if South is obstacle then mark SouthWest as forced
when SOUTHWEST
forced << neighbor_at(*NORTHWEST) if obstacle_at(*NORTH) # if North is obstacle then mark NorthWest as forced
forced << neighbor_at(*SOUTHEAST) if obstacle_at(*EAST) # if East is obstacle then mark SouthEast as forced
when NORTH
forced << neighbor_at(*NORTHEAST) if obstacle_at(*EAST) # if East is obstacle then mark NorthEast as forced
forced << neighbor_at(*NORTHWEST) if obstacle_at(*WEST) # if West is obstacle then mark NorthWest as forced
when SOUTH
forced << neighbor_at(*SOUTHEAST) if obstacle_at(*EAST) # if East is obstacle then mark SouthEast as forced
forced << neighbor_at(*SOUTHWEST) if obstacle_at(*WEST) # if West is obstacle then mark SouthWest as forced
when NORTHEAST
forced << neighbor_at(*SOUTHEAST) if obstacle_at(*SOUTH) # if South is obstacle then mark SouthEast as forced
forced << neighbor_at(*NORTHWEST) if obstacle_at(*WEST) # if West is obstacle then mark NorthWest as forced
when EAST
forced << neighbor_at(*NORTHEAST) if obstacle_at(*NORTH) # if North is obstacle then mark NorthEast as forced
forced << neighbor_at(*SOUTHEAST) if obstacle_at(*SOUTH) # if South is obstacle then mark SouthEast as forced
when SOUTHEAST
forced << neighbor_at(*NORTHEAST) if obstacle_at(*NORTH) # if North is obstacle then mark NorthEast as forced
forced << neighbor_at(*SOUTHWEST) if obstacle_at(*WEST) # if West is obstacle then mark SouthWest as forced
end
fn = Hash.new
forced.each do |node_and_cost| # node => cost
fn.store(node_and_cost[0], node_and_cost[1]) unless node_and_cost == nil
end
return fn
end
def pruned_neighbors(parent_node)
dx = parent_node == nil ? 0 : clamp(@x - parent_node.x, -1, 1)
dy = parent_node == nil ? 0 : clamp(@y - parent_node.y, -1, 1)
nn = natural_neighbors(dx, dy)
fn = forced_neighbors(dx, dy)
return nn.merge(fn)
end
#↑↑↑ for JPS ↑↑↑#
end
################################################################################
class Edge
attr_accessor :cost, :node_id, :nodes
def initialize(cost, node_id0, node_id1)
@cost = cost
@node_id = [node_id0, node_id1]
@nodes = [nil, nil]
end
def other(node)
return node == @nodes[0] ? @nodes[1] : @nodes[0]
end
end
################################################################################
class Route
attr_accessor :found, :start_id, :goal_id
attr_reader :map_width, :map_height
def initialize
@parents = Hash.new # child -> parent
@real_costs = Hash.new # child -> real cost
@heuristic_costs = Hash.new # child -> heuristic cost
reset()
end
def reset
@parents.clear
@real_costs.clear
@heuristic_costs.clear
@found = false
@start_id = ""
@goal_id = ""
end
def record(child, parent, real_cost, heuristic_cost)
@parents[child] = parent
@real_costs[child] = real_cost
@heuristic_costs[child] = heuristic_cost
end
def parent(child)
return @parents.has_key?(child) ? @parents[child] : nil
end
def cost(node, eval_heuristic: true)
if @real_costs.has_key?(node)
return eval_heuristic ? @real_costs[node] + @heuristic_costs[node] : @real_costs[node]
else
return Float::MAX
end
end
def estimated_cost(node); return cost(node, eval_heuristic: true); end
def real_cost(node); return cost(node, eval_heuristic: false); end
def get_path()
return [] if not @found
path = []
parent = @parents.keys.find {|child| child.id == @goal_id}
while parent != nil
path.unshift(parent)
parent = @parents[parent]
end
return path
end
end
################################################################################
def initialize
@road_map = [] # Array of Edge
@nodes = Hash.new
@route = Route.new
@use_heuristic = true
@search_iter = 0
@obstacles = [] # Array of Node ID
@visited = [] # Node ID
end
def read_roadmap(roadmap_input)
csv_lines = roadmap_input.readlines
nodes_count, edges_count, obstacles_count = csv_lines.shift.split(",").collect{|val| val.strip.to_i}
# Nodes
nodes_count.times do |i|
id, x, y = csv_lines.shift.split(",")
@nodes[id] = Node.new(id)
@nodes[id].x = x.to_i
@nodes[id].y = y.to_i
end
@render_map_width = @nodes.values.map{|n| n.x }.max + 1
@render_map_height = @nodes.values.map{|n| n.y }.max + 1
@render_cell_width = @nodes.values.map{|n| n.id.length }.max + 1
# Edges
edges_count.times do |i|
cost, node0_id, node1_id = csv_lines.shift.split(",")
@road_map << Edge.new(cost.to_f, node0_id.strip, node1_id.strip)
end
# Obstacles
@obstacles.clear
obstacles_count.times do |i|
@obstacles << csv_lines.shift.strip
end
@obstacles.each do |node_id|
@road_map = @road_map.reject {|edge| edge.node_id.include?(node_id)}
end
end
def setup_route
@road_map.each do |edge|
edge.node_id.each_with_index do |id, index|
@nodes[id] = Node.new(id) unless @nodes.has_key? id
edge.nodes[index] = @nodes[id]
end
end
@road_map.each do |edge|
@nodes[edge.node_id[0]].edges << edge
@nodes[edge.node_id[1]].edges << edge
end
end
@@heuristic_Zero = Proc.new { |node, goal| 0.0 } # Always 0 (Dijkstra's algorithm)
@@heuristic_MaxDiff = Proc.new { |node, goal| [(node.x - goal.x).abs, (node.y - goal.y).abs].max } # h = max(|dx|, |dy|)
@@heuristic_Manhattan = Proc.new { |node, goal| (node.x - goal.x).to_f.abs + (node.y - goal.y).to_f.abs } # Manhattan Distance (for non-diagonal map only)
@@heuristic_Pythagorean = Proc.new { |node, goal| Math.sqrt((node.x - goal.x)**2 + (node.y - goal.y)**2) } # Pythagorean theorem
def reset(start_id, goal_id, use_heuristic: true, use_jps: true)
@route.reset
@route.start_id = start_id
@route.goal_id = goal_id
@route.record(@nodes[start_id], nil, 0.0, 0.0)
@use_heuristic = use_heuristic
@heuristic = use_heuristic ? @@heuristic_MaxDiff : @@heuristic_Zero
@use_jps = use_jps
@visited.clear
@search_iter = 0
end
#↓↓↓ for JPS ↓↓↓#
# See "Algorithm 2 Function jump"
def jump(x, dx, dy)
node_and_cost = x.neighbor_at(dx, dy)
return nil if node_and_cost == nil
n = node_and_cost[0]
return n if n == @nodes[@route.goal_id]
return n if n.forced_neighbors(dx, dy).length > 0
if dx != 0 && dy != 0
return n if jump(n, dx, 0) != nil
return n if jump(n, 0, dy) != nil
end
return jump(n, dx, dy)
end
#
# Jump Point Search (JPS) Implementation
#
def search_jps
open_list = [@nodes[@route.start_id]]
close_list = []
goal = @nodes[@route.goal_id]
until open_list.empty?
n = open_list.min_by { |node| @route.estimated_cost(node) }
if n == goal
@route.found = true
break
end
close_list.push( open_list.delete(n) )
adjacents_of_n = n.pruned_neighbors(@route.parent(n))
adjacents_of_n.keys.each do |m|
j = jump(n, clamp(m.x - n.x, -1, 1), clamp(m.y - n.y, -1, 1))
next if j == nil or close_list.include?(j)
h = @heuristic.call(j, goal)
new_real_cost_j = @route.real_cost(n) + Math.sqrt((n.x-j.x)**2 + (n.y-j.y)**2) # g
new_estimated_cost_j = new_real_cost_j + h # f = g + h
if open_list.include?(j)
# If estimated costs are equal then use real costs for more precise comparison (or we may get less optimal path).
next if new_estimated_cost_j > @route.estimated_cost(j)
next if new_estimated_cost_j == @route.estimated_cost(j) && new_real_cost_j >= @route.real_cost(j)
@route.record(j, n, new_real_cost_j, h)
else
open_list.push(j)
@route.record(j, n, new_real_cost_j, h)
end
@visited << j.id unless @visited.include? j.id # stats
end
@search_iter += 1 # stats
end
end
#↑↑↑ for JPS ↑↑↑#
#
# A* Implementation
#
def search_astar
open_list = [@nodes[@route.start_id]]
close_list = []
goal = @nodes[@route.goal_id]
until open_list.empty?
n = open_list.min_by { |node| @route.estimated_cost(node) }
if n == goal
@route.found = true
break
end
close_list.push( open_list.delete(n) )
adjacents_of_n = n.neighbors # Hash [neighbor_node => edge.cost]
adjacents_of_n.each do |m, edge_cost|
next if close_list.include?(m)
h = @heuristic.call(m, goal)
new_real_cost_m = @route.real_cost(n) + edge_cost # g
new_estimated_cost_m = new_real_cost_m + h # f = g + h
if open_list.include?(m)
# If estimated costs are equal then use real costs for more precise comparison (or we may get less optimal path).
next if new_estimated_cost_m > @route.estimated_cost(m)
next if new_estimated_cost_m == @route.estimated_cost(m) && new_real_cost_m >= @route.real_cost(m)
@route.record(m, n, new_real_cost_m, h)
else
open_list.push(m)
@route.record(m, n, new_real_cost_m, h)
end
end
# stats
adjacents_of_n.each_key {|n| @visited << n.id unless @visited.include? n.id}
@search_iter += 1
end
end
def search
@use_jps ? search_jps : search_astar
end
def found; return @route.found; end
def get_path; return @route.get_path; end
def goal_id; return @route.goal_id; end
def direction_symbol(next_node, current_node)
case
when next_node.x < current_node.x
case
when next_node.y < current_node.y; "↖" # U+2196
when next_node.y == current_node.y; "←"
when next_node.y > current_node.y; "↙" # U+2199
end
when next_node.x == current_node.x
case
when next_node.y < current_node.y; "↑"
when next_node.y == current_node.y; " "
when next_node.y > current_node.y; "↓"
end
when next_node.x > current_node.x
case
when next_node.y < current_node.y; "↗" # U+2197
when next_node.y == current_node.y; "→"
when next_node.y > current_node.y; "↘" # U+2198
end
end
end
private :direction_symbol
def render_cell(path, n)
if n == nil
print "_" * (@render_cell_width - 1)
else
colorizer = case
when n.id == @route.start_id; :start_color
when n.id == @route.goal_id; :goal_color
when @obstacles.include?(n.id); :obstacle_color
when path.find{|node| node.id == n.id} != nil; :path_color
when @visited.include?(n.id); :visited_color
else :no_colors
end
path_index = path.find_index(n)
symbol = n.id + case
when path_index == nil; ""
when n.id == @route.start_id || colorizer == :path_color; direction_symbol(path[path_index+1], n)
when n.id == @route.goal_id; "•" # U+2022
else ""
end
print %Q{#{symbol}#{" " * (@render_cell_width - symbol.length)}}.send(colorizer)
end
end
private :render_cell
def render
puts "#iteration = #{@search_iter} [@use_heuristic == #{@use_heuristic}, @use_jps == #{@use_jps}]"
path = self.get_path
if path != nil
@render_map_height.times do |h|
@render_map_width.times do |w|
n = @nodes.values.find{|n| n.x == w && n.y == h}
render_cell(path, n)
end # End : @render_map_width.times do |w|
puts
end # End : @render_map_height.times do |h|
end
end
end
if __FILE__ == $0
jps = JPSAlgorithm.new
File.open(ARGV[0]) do |file|
jps.read_roadmap(file)
end
jps.setup_route
heuristic_flag = true
jps_flag = true
if ARGV.include?("-dijkstra")
heuristic_flag = false
jps_flag = false
elsif ARGV.include?("-astar")
heuristic_flag = true
jps_flag = false
end
jps.reset("N481", "N502", use_heuristic: heuristic_flag, use_jps: jps_flag)
# jps.reset("N24", "N575", use_heuristic: heuristic_flag, use_jps: jps_flag)
# jps.reset("N1", "N2303", use_heuristic: heuristic_flag, use_jps: jps_flag)
# jps.reset("N1", "N3905", use_heuristic: heuristic_flag, use_jps: jps_flag)
jps.search
if jps.found
jps.get_path.each do |node|
print node.id
print node.id == jps.goal_id ? "\n" : " → "
end
end
jps.render
end
| true
|
222e07008f383271f77a89f8480abc6618e6ee40
|
Ruby
|
shokai/linda-ruby
|
/lib/linda/test/tuple.rb
|
UTF-8
| 2,705
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
module Linda
module Test
module Tuple
def test_array_tuple
tuple = target_tuple.new([1,2,:a])
assert_equal tuple.data, [1,2,:a]
assert_equal tuple.type, Array
assert_equal JSON.parse(tuple.to_json), [1,2,"a"]
end
def test_hash_tuple
tuple = target_tuple.new(:a => 1, :b => 2)
assert_equal tuple.data, {:a => 1, :b => 2}
assert_equal tuple.type, Hash
assert_equal JSON.parse(tuple.to_json), {"a" => 1, "b" => 2}
end
def test_match_array_tuple
tuple = target_tuple.new [1,2,3]
assert tuple.match? target_tuple.new [1,2,3]
assert tuple.match? target_tuple.new [1,2,3,4]
assert !tuple.match?(target_tuple.new [1,2])
assert !tuple.match?(target_tuple.new [1,"a",3])
assert !tuple.match?(target_tuple.new :a => 1, :b => 2)
tuple = target_tuple.new ["a","b","c"]
assert tuple.match? target_tuple.new ["a","b","c"]
assert tuple.match? target_tuple.new ["a","b","c","d","efg",123,"h"]
assert !tuple.match?(target_tuple.new ["a","b"])
assert !tuple.match?(target_tuple.new ["a","b",789])
assert !tuple.match?(target_tuple.new :foo => 1, :bar => 2)
end
def test_match_array
tuple = target_tuple.new [1,2,3]
assert tuple.match? [1,2,3]
assert tuple.match? [1,2,3,4]
assert !tuple.match?([1,2])
assert !tuple.match?([1,"a",3])
assert !tuple.match?(:a => 1, :b => 2)
tuple = target_tuple.new ["a","b","c"]
assert tuple.match? ["a","b","c"]
assert tuple.match? ["a","b","c","d","efg",123,"h"]
assert !tuple.match?(["a","b"])
assert !tuple.match?(["a","b",789])
assert !tuple.match?(:foo => 1, :bar => 2)
end
def test_match_hash_tuple
tuple = target_tuple.new :a => 1, :b => 2
assert tuple.match? target_tuple.new :a => 1, :b => 2
assert tuple.match? target_tuple.new :a => 1, :b => 2, :c => 3
assert tuple.match? target_tuple.new :a => 1, :b => 2, :c => {:foo => "bar"}
assert !tuple.match?(target_tuple.new :a => 0, :b => 2)
assert !tuple.match?(target_tuple.new :b => 2, :c => 3)
assert !tuple.match?(target_tuple.new [1,2,3])
end
def test_match_hash
tuple = target_tuple.new :a => 1, :b => 2
assert tuple.match? :a => 1, :b => 2
assert tuple.match? :a => 1, :b => 2, :c => 3
assert tuple.match? :a => 1, :b => 2, :c => {:foo => "bar"}
assert !tuple.match?(:a => 0, :b => 2)
assert !tuple.match?(:b => 2, :c => 3)
assert !tuple.match?([1,2,3])
end
end
end
end
| true
|
62f8831aab5ab3a3adea0131e9fe640bcb89993e
|
Ruby
|
vagmi/spell_checker
|
/mangle.rb
|
UTF-8
| 123
| 2.5625
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
$:.unshift("./lib")
require 'mangler'
Mangler.new.mangle_line(ARGV.first).each { |word|
puts word
}
| true
|
e8b87dd885ee040a682cf48be181fc887362abd5
|
Ruby
|
gervolinotm/WK2_CodeClanCaraoke
|
/room.rb
|
UTF-8
| 690
| 3.28125
| 3
|
[] |
no_license
|
class Room
attr_reader :room_limit
attr_accessor :guests, :song_list
def initialize(guests, song_list, room_limit)
@guests = guests
@song_list = song_list
@room_limit = room_limit
end
def check_in_guests(guest_name)
@guests.push(guest_name)
end
def check_out_guest(guest_name)
@guests.find_all { |guest|
if guest == guest_name
@guests.delete(guest_name)
end
}
return @guests
end
def add_song_to_room(song_name)
@song_list.push(song_name)
end
# def number_of_guests_in_room
# return @guests.length
# end
#
# def is_room_full(room)
# return true if number_of_guests_in_room() == room.room_limit
# end
end
| true
|
475bd386cd52ab1c84d4e78ddc9b1d32d40a9a81
|
Ruby
|
Cireou/ruby-oo-practice-flatiron-zoo-exercise-yale-web-yss-052520
|
/run.rb
|
UTF-8
| 577
| 3.34375
| 3
|
[] |
no_license
|
require_relative "lib/Animal.rb"
require_relative "lib/Zoo.rb"
require 'pry'
#Test your code here
dog1 = Animal.new("Dog", 1, "bobbers")
dog2 = Animal.new("Dog", 2, "hi")
zoo1 = Zoo.new("Zoo1", "New York")
zoo2 = Zoo.new("Zoo2", "New York")
dog1.nickname
dog1.weight
dog1.species
dog1.weight = 5
dog1.zoo = zoo1
dog2.zoo = zoo1
Animal.all()
Animal.find_by_species("Dog")
binding.pry()
zoo1.name
zoo1.location
zoo1.animals()
zoo1.animal_species()
zoo1.find_by_species("dog")
zoo1.animal_nicknames()
Zoo.all()
Zoo.find_by_location("New York")
binding.pry
puts "done"
| true
|
0af498997470dfb1e6aa8ab667158c5bb43981c1
|
Ruby
|
knomedia/yesman
|
/lib/yesman/templater.rb
|
UTF-8
| 397
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
require 'erb'
class Templater
def merge class_type, template_path
@class_type = class_type
@template_path = template_path
load_template
apply_class_to_template
@output
end
def load_template
@loaded_template = ERB.new File.read( @template_path )
end
def apply_class_to_template
@output = @loaded_template.result( @class_type.get_binding )
end
end
| true
|
f232777dd0eee47451951d852edf69ce56f7f211
|
Ruby
|
robotscissors/quizbot
|
/app/models/score.rb
|
UTF-8
| 1,073
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
class Score < ActiveRecord::Base
belongs_to :user
belongs_to :question
def self.overall_score(user)
# calculate the overall score
@current_place = Score.current_place(user.id)
@points = Score.where(:user_id => user.id).sum(:point)
@possible_points = Score.where(:user_id => user.id).where.not(:point => nil).count
@percent_correct = ((@points.to_f / @possible_points.to_f)*100.00).round(2)
"Your total score for all quizzes is: #{@points} out of #{@possible_points}. That's #{@percent_correct}% correct! "
end
def self.quiz_score(user,topic_id)
@current_place = Score.current_place(user.id)
@array_of_items = Question.select(:id).where(:topic_id => topic_id)
@points = Score.where(:user_id => user.id, :question_id => @array_of_items).sum(:point)
"You got #{@points}/#{@array_of_items.length} on this quiz. "
end
def self.current_place(user_id)
self.where(:user_id => user_id).last
end
def self.played_before?(user_id)
return true if Score.where(:user_id => user_id).count > 0
false
end
end
| true
|
e5a84445d3729fd1cd0fd830b62a77a0710b5a64
|
Ruby
|
denineguy/binary_search
|
/binary_search.rb
|
UTF-8
| 1,311
| 4.15625
| 4
|
[] |
no_license
|
#Binary vs Linear Searching
#Write an example demonstrating Binary Search. Write an example demonstrating Linear Search.
# Hint: A linear search looks down a list, one item at a time, without jumping. in complexity
# terms this is an O(n) search - the time taken to search the list gets bigger at the same rate
# as the list does. A binary search is when you start with the middle of a sorted list, and see
# whether that's greater than or less than the value you're looking for, which determines whether
# the value is in the first or second half of the list
def binary(array, low, high, num)
if array.empty?
nil
else
# low=0
# high=array.length
sorted_array = array.sort
if low == high
array[low]==num ? array[low] : nil
else
mid = (low+high)/2
if array[mid]>num
binary(array,low,mid-1,num)
else
binary(array,mid,high,num)
end
end
end
end
binary([1,2,3,4,5,6,8,9],0,7,6)
def linear(array, num) #method if they want the number
# array = [1,4,5,7]
# num = 5
array.select do |a|
if a == num
a
end
end
end
linear([1,4,5,7], num)
def linear(array, num) #method if they want the index of the array with matching number
# array = [1,4,5,7]
# num = 5
array.index{|a| a==num}
end
linear([1,4,5,7], num)
| true
|
3939e10ce16548d7e894f65e77e1ce5bf2ab4515
|
Ruby
|
Luniak/mctechtree
|
/lib/item.rb
|
UTF-8
| 2,118
| 2.640625
| 3
|
[] |
no_license
|
# encoding: utf-8
class UndefinedItemError < StandardError; end
class CraftBuilder < SimpleDelegator
def makes count, machine, ingredients, extra
craft = Craft.create(machine, __getobj__, count, ingredients, extra)
self.crafts << craft
craft
end
end
class PendingItem
attr_accessor :name
def initialize name
@name = name
end
def hash
to_s.hash
end
def <=> other
self.name <=> other.name
end
def to_s
"!#{name}"
end
def safe_name
"!#{ActiveSupport::Inflector.underscore name}".gsub(' ', '_')
end
end
class Item
attr_accessor :name, :primitive, :cost, :stacks, :group, :compatible
attr_reader :crafts
def initialize attrs={}
attrs.each do |key, val|
self.send "#{key}=", val
end
@crafts = []
stacks = 64 if stacks.nil?
end
def to_s
[
(primitive ? name.upcase : name),
("@#{cost}" unless cost.nil?)
].join('')
end
def safe_name
# ostatni gsub bo dot marudzi
ActiveSupport::Inflector.underscore(name).gsub(' ', '_').gsub(/(^[0-9])/, "n_\\1")
end
def stack_info count
return nil if @stacks == false
num, rem = count.divmod(@stacks)
plural = 's' if num > 1
if num == 0
nil
elsif rem == 0
# NOTE: marne i18n
"#{num} stack#{plural}"
else
"#{num} stack#{plural} + #{rem}"
end
end
def <=> other
self.name <=> other.name
end
def self.primitive name, cost, stacks, group
self.new(name: name, primitive: true, cost: cost, stacks: stacks, group: group)
end
def self.crafted name, group, extra={}
self.new({name: name, primitive: false, group: group}.merge(extra)).tap do |obj|
crafts = CraftBuilder.new(obj)
yield(crafts)
end
end
def self.pending name
PendingItem.new(name)
end
def add_craft
yield(CraftBuilder.new(self))
end
def resolver
ItemResolver.new(self)
end
end
| true
|
8792578671f06ebd34548d3fd965b82142cfba90
|
Ruby
|
Lastbastian/Ruby-me
|
/Week_17/hitchhikersguide.cgi
|
UTF-8
| 310
| 2.59375
| 3
|
[] |
no_license
|
#!/usr/local/bin/ruby
# Name: Chris Bastian - peacethrubeats@gmail.com
# Date: 2015-12-20 Sunday
# File: hitchhikersguide.cgi
# Desc: Final Test Problem
puts "Content-type: text/html"
puts
require "open-uri"
string = ""
url = "/users/dputnam/greetings.txt"
open(url) do |content|
content.each_line { |line| string += line }
end
| true
|
eb3a58d3d14c773a8dc9f48873f4a1456865ed0e
|
Ruby
|
shuito1992/grokking_algorithms
|
/dijkstra.rb
|
UTF-8
| 2,012
| 3.390625
| 3
|
[] |
no_license
|
@graph = {
start:{ a: 2,
b: 6 },
a: { fin: 1 },
b: { a: 3,
fin: 5 },
fin: {}
}
@costs = {
a: 6,
b: 2,
fin: Float::INFINITY
}
@parents = {
a: :start,
b: :start,
fin: nil
}
@processed = []
def find_lowest_cost_node(costs)
min = @costs.select{|node,cost| !@processed.include?(node)}.
min_by{|node, cost| cost}
min[0] if !min.nil?
end
def dijkstra
node = find_lowest_cost_node(@costs)
while !node.nil?
cost = @costs[node]
neighbors = @graph[node]
neighbors.each do |n, c|
new_cost = cost + neighbors[n]
if @costs[n] > new_cost
@costs[n] = new_cost
@parents[n] = node
end
end
@processed << node
node = find_lowest_cost_node(@costs)
end
end
dijkstra
puts @costs
puts @parents
puts "-"*10
puts "Exercise A"
@graph = {
start:{ a: 5,
b: 2 },
a: { c: 4,
d: 2 },
b: { a: 8,
d: 7 },
c: { d: 6,
fin: 3 },
d: { fin: 1 },
fin: {}
}
@costs = {
a: 5,
b: 2,
c: Float::INFINITY,
d: Float::INFINITY,
fin: Float::INFINITY
}
@parents = {
a: :start,
b: :start,
c: nil,
d: nil,
fin: nil
}
@processed = []
dijkstra
puts @costs
puts @parents
puts "-"*10
puts "Exercise B"
@graph = {
start: { a: 10 },
a: { b: 20 },
b: { c: 1,
fin: 30 },
c: { a: 1 },
fin: {}
}
@costs = {
a: 10,
b: Float::INFINITY,
c: Float::INFINITY,
fin: Float::INFINITY
}
@parents = {
a: :start,
b: nil,
c: nil,
fin: nil
}
@processed = []
dijkstra
puts @costs
puts @parents
puts "-"*10
puts "Exercise C"
@graph = {
start: { a: 2,
b: 2 },
a: { c: 2,
fin: 2 },
b: { a: 2 },
c: { b: -1,
fin: 2 },
fin: {}
}
@costs = {
a: 2,
b: 2,
c: Float::INFINITY,
fin: Float::INFINITY
}
@parents = {
a: :start,
b: :start,
c: nil,
fin: nil
}
@processed = []
dijkstra
puts @costs
puts @parents
| true
|
76cff98c17f073d74dfe7e4e732ed19f915fd1fc
|
Ruby
|
dantecrovetto/modulo2-prueba
|
/prueba.rb
|
UTF-8
| 1,072
| 2.9375
| 3
|
[] |
no_license
|
require 'net/http'
require 'openssl'
require 'json'
url = 'https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_'
key = 'key=jwW2RykNrevmb9HjNeYzR2rnxkB0DL0yQIRDczc5'
def request(url,key)
uri = URI(url+key)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.request(request)
JSON.parse(response.read_body)
end
def build_web_page(data)
html = "<html>\n<head>\n</head>\n<body>\n<ul>\n"
data['photos'].size.times do |i|
data['photos'][i]['img_src']
html += "\t<li><img src=\"#{data['photos'][i]['img_src']}\"></li>\n"
end
html += "<ul>\n</body>\n</html>"
File.write('./index.html',html)
end
def photos_count(data)
cam = {}
data['photos'].size.times do |i|
camera = data['photos'][i]['camera']['name']
photos = data['photos'][i]['rover']['total_photos']
cam[camera] = photos
end
puts cam
end
data = request(url,key)
build_web_page(data)
photos_count(data)
| true
|
d8569f2291af2b2a8b73415264521b6925f06650
|
Ruby
|
JannikWibker/tm_vm
|
/src/tm_re.rb
|
UTF-8
| 1,427
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
module TM
ID = '[_a-zA-Z]+[_a-zA-Z0-9]*'
def TM.array(contents)
inner = '((?:' + contents + '\s*,\s*)*(?:' + contents + '))?'
'\[\s*' + inner + '\s*\]'
end
def TM.array_no_capture(contents)
inner = '(?:(?:' + contents + '\s*,\s*)*(?:' + contents + '))?'
'\[\s*' + inner + '\s*\]'
end
def TM.object(contents)
inner = '((?:(' + TM::ID + '):\s*' + contents + '\s*,\s*)*(?:(' + TM::ID + '):\s*' + contents + '))?'
'\{\s*' + inner + '\s*\}'
end
def TM.assignment(lefthandside, righthandside)
lefthandside + '\s*=\s*' + righthandside
end
def TM.string()
'(?:"([^"]*)")|(?:\'([^\']*)\')'
end
def TM.string_no_capture()
'(?:"[^"]*")|(?:\'[^\']*\')'
end
def TM.number()
'([0-9]+)'
end
def TM.section(ident)
'\n?%\s?' + ident + '\s?%\n'
end
def TM.transition()
'((?:' + TM.string_no_capture() + '|' + TM::ID + ')\s*\|\s*(?:' + TM.string_no_capture() + '|' + TM::ID + ')\s*)' +
'(?:(?:->\s*' + TM::ID + '\s*)|' +
'(?:<>\s*' + '))' +
'(?:\+|\-|\/)'
end
def TM.transition_no_capture()
'(?:(?:' + TM.string_no_capture() + '|' + TM::ID + ')\s*\|\s*(?:' + TM.string_no_capture() + '|' + TM::ID + ')\s*)' +
'(?:(?:->\s*' + TM::ID + '\s*)|' +
'(?:<>\s*' + '))' +
'(?:\+|\-|\/)'
end
def TM.parse_array(str, type_re)
str.split(Regexp.new '(' + type_re + ')\s*,\s*')
end
end
| true
|
cf84ae6e452e24a4af0a690c63c0e5205d94cbc8
|
Ruby
|
fabientownsend/echoserver
|
/spec/echo_server_spec.rb
|
UTF-8
| 552
| 2.703125
| 3
|
[] |
no_license
|
require 'spec_helper'
require 'echo_server'
RSpec.describe EchoServer do
before(:each) do
@input = StringIO.new("a\nb\nexit\n")
@output = StringIO.new
@server = EchoServer.new(@input, @output)
end
it "reads first input" do
expect(@server.read).to eq("a\n")
end
it "prints last input" do
@server.write("test output")
expect(@output.string).to eq("test output\n")
end
it "read and displays input until it reads exit" do
@server.read_and_display_stream
expect(@output.string).to eq("a\nb\n")
end
end
| true
|
53fb6b69f251cd6338fdbb3904663045dbc41fae
|
Ruby
|
brandonjyuhas/wdi-practicework
|
/superheroes/seeds.rb
|
UTF-8
| 3,894
| 2.984375
| 3
|
[] |
no_license
|
require_relative './hero'
Hero.create(
[
{ alt: "Salvador Hernandez", name: "Brooklyn Boolean", super_power: "True/False Vision", cape: true, role: "hero", img: "/images/1.jpg", weakness: "Gray Area"
},
{ alt: "Brandon Yuhas", name: "The Triple Data Distiller", super_power: "Argues with Data and returns delicious Data-Flavoured Vodka!", cape: true, role: "hero", img: "images/18.jpg", weakness: "Sobriety"
},
{ alt: "Mandy Moore", name: "Ubuntu Ultimate", super_power: "Doesn't 'buy in' to mainstream developer computers!", cape: false, role: "hero", img: "/images/2.jpg", weakness: "Doesn't fit in at StarBucks"
},
{ alt: "Paul Miller", name: "JavaScript Justicar", super_power: "Makes awesome hit counters on websites!", cape: true, role: "hero", img: "/images/3.jpg", weakness: "New CSS functions"
},
{ alt: "Pam Assogba", name: "Rails Rebounder", super_power: "Scaffolds apps in record time!", cape: false, role: "hero", img: "/images/4.jpg", weakness: "Configuration over convention!"
},
{ alt: "Andy Kim", name: "HTML Hero", super_power: "Super structured content!", cape: true, role: "hero", img: "/images/5.jpg", weakness: "No style whatsoever!"
},
{ alt: "Ansoo Chang", name: "Giterminalator", super_power: "Never loses any data!", cape: false, role: "hero", img: "/images/6.jpg", weakness: "Merge conflicts!"
},
{ alt: "Christopher Pollock", name: "Merge Master", super_power: "Doesn't have to save files after merging!", cape: false, role: "hero", img: "/images/7.jpg", weakness: "Group projects!"
},
{ alt: "Clare Politano", name: "Operator Opportunist", super_power: "Strings equal to things other than 0!", cape: true, role: "hero", img: "/images/8.jpg", weakness: "Comparing Nil Class!"
},
{ alt: "Daniel Kim", name: "Data Type Terror", super_power: "Super String Strength!", cape: false, role: "hero", img: "/images/9.jpg", weakness: "Doesn't know his SuperClass."
},
{ alt: "Erica Geiser", name: "Righteous Rspector", super_power: "Tests everything that she's ever done!", cape: true, role: "hero", img: "/images/10.jpg", weakness: "Takes more time to do anything due to rigerous testing!"
},
{ alt: "Jake Catt", name: "Sinatra Silencer", super_power: "Launches a web server without a single word!", cape: false, role: "hero", img: "/images/11.jpg", weakness: "Not knowing 'this Ditty'!"
},
{ alt: "Lisa Snider", name: "Magnificent Macbook", super_power: "Very popular in Starbucks!", cape: true, role: "hero", img: "/images/12.jpg", weakness: "Cost efficiency!"
},
{ alt: "Martin Johnson", name: "Courageous Commenter", super_power: "Code reads like a George R. R. Martin novel!", cape: true, role: "hero", img: "/images/13.jpg", weakness: "Still uses '//' in CSS!"
},
{ alt: "Stephen Neubig", name: "Terrific TDD", super_power: "Gets awesome visual confirmation on everything!", cape: false, role: "hero", img: "/images/14.jpg", weakness: "\"undefined method '.to' \""
},
{ alt: "Wade Buckland", name: "CSS Sorceror", super_power: "Styles real life objects with code!", cape: false, role: "hero", img: "/images/15.jpg", weakness: "In-line styling."
},
{ alt: "Sam Barrientos", name: "Relentless Rubyist", super_power: "Writes code in plain langauge!", cape: false, role: "hero", img: "/images/16.jpg", weakness: "Compiled languages!"
},
{ alt: "Liz Wendling", name: "Red Green Refractorer", super_power: "Everything eventually gets passed with one line of code!", cape: true, role: "hero", img: "/images/17.jpg", weakness: "Div soup!"
},
{ alt: "Mikael Davis", name: "Mentoring Mike", cape: false, role: "leader", img: "/images/mike.jpg"
},
{ alt: "Sean Shannon", name: "Stuttering Sean", cape: true, role: "leader", img: "images/sean.jpg"
},
{ alt: "Jon Rojas", name: "Jolly Jon", cape: false, role: "hero", img: "/images/jon.jpg"
}
]
| true
|
975afdb7f174e334a6ea1a644bba71e6b2c60b2a
|
Ruby
|
lucasluitjes/midi_bank_controller
|
/main.rb
|
UTF-8
| 981
| 2.515625
| 3
|
[] |
no_license
|
require 'unimidi'
require 'pp'
require 'pry'
# patch
module AlsaRawMIDI
class Input
def gets
sleep 0.01 until enqueued_messages?
msgs = enqueued_messages
@pointer = @buffer.length
msgs
end
end
end
class Reader
def initialize
reload_controller
@input = UniMIDI::Input.use(:first)
start_loop
end
def reload_controller
@mtime = File.mtime('controller.rb')
load('./controller.rb')
@controller = Controller.new(testing: false)
end
def start_loop
File.open('log', 'w') do |f|
f.sync = true
loop do
begin
reload_controller unless File.mtime('controller.rb') == @mtime
rescue SyntaxError => e
puts e.inspect
puts e.backtrace
end
data = @input.gets_data
next unless data[0] == 176
raw = data[1] || 0
f.puts raw
puts "data: #{data}"
@controller.process(raw)
end
end
end
end
Reader.new
| true
|
e646345581ac1c1c7ec30dfffbc77ab1517584f5
|
Ruby
|
mgurbanzade/thinknetica
|
/Ruby_Idioms_Style_Guide/routes.rb
|
UTF-8
| 607
| 3.171875
| 3
|
[] |
no_license
|
require_relative 'instance_counter'
require_relative 'validation'
class Route
include InstanceCounter
include Validation
attr_reader :stations, :name
def initialize(first, last)
@stations = [first, last]
validate!
@name = "#{first.name} - #{last.name}"
register_instance
end
def add_station(station)
stations.insert(-2, station)
end
def remove_station(station)
stations.delete(station)
end
private
def validate!
has_stations = stations.find { |station| !station.empty? }
raise EX_MESSAGES[:route_stations] if has_stations.nil?
true
end
end
| true
|
84970f9362b0c25724f262c37297b262d48a728d
|
Ruby
|
jacekwargol/odin-project
|
/connect_four/lib/game.rb
|
UTF-8
| 664
| 3.5625
| 4
|
[] |
no_license
|
require_relative 'board'
class Game
attr_reader :board
WHITE_DISC = "\u26AA"
BLACK_DISC = "\u26AB"
@player1 =
def initialize
@board = Board.new
end
def start_game
puts "Player 1, choose color:\n1.Black\n2.White"
until (player_choice = gets.chomp.to_i).between?(1, 2) do
puts "Incorrect choice. Choose color:\n1.Black\n2.White"
end
puts player_choice
end
def add_disc(col, color)
return nil if @board.grid[0][col]
@board.grid.each_with_index do |row, i|
if @board.grid[i][col]
@board.grid[i-1][col] = color
break
end
@board.grid[i][col] = color if i == 5
end
end
end
| true
|
4ad67488fce30c953243307b811a970bb6cabfe4
|
Ruby
|
IIIIIIIIll/RubyQuizess
|
/Quiz10/question5.rb
|
UTF-8
| 220
| 3.328125
| 3
|
[] |
no_license
|
class Something
def meaning_of_life
@result ||= result
"The meaning of life is the number #{@result}"
end
def result
50
end
def initialize
@result=20
end
end
p Something.new.meaning_of_life
| true
|
38a778f7082d2bd7242bf46ef16ee9bfc390b83a
|
Ruby
|
asnr/algorithm-design-manual
|
/all_subsets.rb
|
UTF-8
| 713
| 3.546875
| 4
|
[] |
no_license
|
def all_subsets(set_size, current_subset, next_idx)
if next_idx == set_size
print_subset current_subset
return
end
[true, false].each do |include_element|
current_subset[next_idx] = include_element
all_subsets(set_size, current_subset, next_idx + 1)
end
end
def print_subset(subset)
print '{'
first_element_to_print = true
subset.each_with_index do |include_element, element|
next unless include_element
print ', ' unless first_element_to_print
print element + 1
first_element_to_print = false
end
puts '}'
end
unless ARGV.length == 1
puts 'Usage: ruby all_subsets.rb set_size'
exit 1
end
set_size = ARGV[0].to_i
all_subsets(set_size, [nil] * set_size, 0)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.