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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c0da9d9c0f32e634e85077ae4b01b954dfce0da9
|
Ruby
|
suryagaddipati/linqr
|
/examples/linqr2enumerable/ordering_operators_spec.rb
|
UTF-8
| 1,512
| 2.90625
| 3
|
[] |
no_license
|
require 'linqr'
require 'spec_helper'
describe "order by" do
Item = Struct.new(:name , :price, :discount_price)
it "should order by the order by operator" do
words = [ "cherry", "apple", "blueberry" ]
sorted_words = __{
from word in_ words
order_by word
select word
}
sorted_words.should == ["apple", "blueberry","cherry" ]
end
it "simple-2" do
words = [ "cherry", "apple", "blueberry" ]
sorted_words = __{
from word
in_ words
order_by word.length
select word
}
sorted_words.should == ["apple", "cherry", "blueberry"]
end
it "descending" do
doubles = [ 1.7, 2.3, 1.9, 4.1, 2.9 ]
desc_doubles = __{
from d
in_ doubles
order_by d => descending
select d
}
desc_doubles.should == [4.1, 2.9, 2.3, 1.9, 1.7]
end
it "then-by-descending" do
products = [Item.new("bag", 9.00,5.00),Item.new("shoes", 5.00,2.00), Item.new("apple", 5.00,4.00), Item.new("cup", 25.00,14.00)]
__{
from p
in_ products
order_by p.price, p.discount_price
select p
}.collect(&:name).should == ["shoes","apple", "bag", "cup"]
end
it "then-by" do
products = [Item.new("bag", 9.00,5.00),Item.new("apple", 5.00,2.00), Item.new("shoes", 5.00,4.00), Item.new("cup", 25.00,5.00)]
__{
from p
in_ products
order_by p.price, p.discount_price => descending
select p
}.collect(&:name).should == ["cup","bag","shoes","apple"]
end
end
| true
|
e4e5fe032ee732f8a6c374157a210d5f71f5d696
|
Ruby
|
learningearnings/Mayhem
|
/app/models/importers/le/local_rewards_importer.rb
|
UTF-8
| 3,404
| 2.6875
| 3
|
[] |
no_license
|
require_relative './base_importer'
# NOTE: This importer assumes there is a directory at /tmp/le_images, with a structure like:
#
# $ tree -d /tmp/le_images
# /tmp/le_images
# └── images
# ├── localrewards
# └── rewardimage
#
# To test it out:
#
# i = Importers::Le::LocalRewardsImporter.new("/home/jadams/Downloads/accurate_local_rewards_FINAL_smaller.csv")
# i.call
module Importers
class Le
class LocalRewardsImporter < BaseImporter
protected
def run
find_or_create_local_rewards_category
merged_local_rewards_data.each do |datum|
execute_teachers_reward_on(datum.except(:id))
end
end
def execute_teachers_reward_on(datum)
school_id = datum.delete(:school_id)
teacher_id = datum.delete(:teacher_id)
image_path = datum.delete(:image_path)
legacy_reward_local_id = datum.delete(:legacy_reward_local_id)
rwd = Teachers::Reward.new(datum)
rwd.school = existing_school(school_id)
rwd.teacher = existing_teacher(teacher_id)
image = image_for(image_path)
if(image)
rwd.image = image
end
rwd.save
rwd.set_property("legacy_reward_local_id", legacy_reward_local_id)
end
def merged_local_rewards_data
output = []
local_rewards_data.each do |reward|
existing_record = output.detect{|r| r[:id] == reward[:id] }
if(existing_record)
existing_record[:classrooms] = existing_record[:classrooms] + reward[:classrooms]
else
output << reward
end
end
output
end
def local_rewards_data
parsed_doc.map do |reward|
{
id: reward["reward_local_id"],
legacy_reward_local_id: reward["reward_local_id"],
name: reward["name"],
description: reward["desc"],
category: category_id_for(reward["category"]),
on_hand: reward["quantity"],
classrooms: [classroom_id_for(reward["classroom_id"])].compact,
school_id: reward["school_id"],
teacher_id: reward["teacher_id"],
image_path: reward["image_path"],
min_grade: reward["min_grade"],
max_grade: reward["max_grade"],
price: reward["points"]
}
end
end
def category_id_for(category_name)
@category.id # We're just putting them all in one category...
end
def classroom_id_for(legacy_classroom_id)
existing_classroom(legacy_classroom_id).id rescue nil
end
def existing_classroom(legacy_classroom_id)
Classroom.where(legacy_classroom_id: legacy_classroom_id).first
end
def existing_school(legacy_school_id)
School.where(legacy_school_id: legacy_school_id).first
end
def existing_teacher(legacy_teacher_id)
Person.where(legacy_user_id: legacy_teacher_id).first
end
def find_or_create_local_rewards_category
taxonomy = Spree::Taxonomy.where(name: "Categories").first
@category = taxonomy.taxons.find_or_create_by_name("My Local Rewards")
end
def images_directory
"/tmp/le_images/"
end
def image_for(image_path)
File.open(images_directory + image_path) rescue nil
end
end
end
end
| true
|
efde98de2edcc9ab1a1ac69b470f807e9fa09812
|
Ruby
|
bilus/Mary
|
/www/lib/project.rb
|
UTF-8
| 207
| 2.546875
| 3
|
[] |
no_license
|
class Project
def self.initialize!(project_name)
@names ||= {}
token = rand.to_s
@names[token] = project_name
token
end
def self.name(access_token)
@names[access_token]
end
end
| true
|
aba2080fad5dee8500496b175e3ed45a11030b6e
|
Ruby
|
david-boyd/connect_four
|
/lib/connect_four/computer.rb
|
UTF-8
| 815
| 3.390625
| 3
|
[] |
no_license
|
require_relative 'player'
require 'tty-spinner'
class Computer < Player
def get_move(valid_columns)
valid_columns = Array(valid_columns)
#Pick a random column
column_choice = valid_columns[Random.rand(valid_columns.length)]
#show computer is thinking to user if there is a prompt
unless prompt.nil?
simulate_computer_thinking
prompt.say("Computer picks column: #{column_choice}")
end
column_choice
end
#Nice little method to make it seem the computer is thinking
def simulate_computer_thinking
spinner = TTY::Spinner.new("[:spinner] Computer Thinking ...", format: :pulse_2)
spinner.auto_spin # Automatic animation with default interval
sleep(2) # Perform task
spinner.stop('Done!') # Stop animation
end
def name
"The Computer"
end
end
| true
|
5c066c3ce1b90b2d3cc0a40f8377556fdda46c45
|
Ruby
|
I3uckwheat/web_guesser
|
/web_guesser.rb
|
UTF-8
| 1,217
| 3.125
| 3
|
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader'
@@secret_number = rand(100)
@@guesses_left = 5
get '/' do
guess = params['guess'].to_i
color = color_choice(guess)
@@guesses_left -= 1
number = select_number
message = @@guesses_left.zero? ? reset : check_guess(guess)
puts @@guesses_left
erb :index, locals: { number: number, message: message, color: color }
end
def select_number
return @@secret_number if params['guess'] == @@secret_number ||
params['cheat'] == 'true' ||
@@guesses_left.zero?
end
def check_guess(guess)
if guess < @@secret_number
return 'Way Too Low!' if guess < @@secret_number - 5
'Too Low!'
elsif guess > @@secret_number
return 'Way Too High!' if guess > @@secret_number + 5
'Too High!'
else
reset
"You're Right! Resetting..."
end
end
def color_choice(guess)
if guess < @@secret_number
return 'red' if guess < @@secret_number - 5
'#ff5050'
elsif guess > @@secret_number
return 'red' if guess > @@secret_number + 5
'#ff5050'
else
'green'
end
end
def reset
fail = @@guesses_left.zero?
@@guesses_left = 5
@@secret_number = rand(100)
'Resetting' if fail
end
| true
|
18d41db858538e385e90a76b68172d1260c6c4b8
|
Ruby
|
gevann/advent-of-code-2019
|
/ruby/lib/operations/multiply.rb
|
UTF-8
| 254
| 2.515625
| 3
|
[] |
no_license
|
require 'operations/binary_operation'
module Operations
class Multiply < BinaryOperation
def self.call(tape, instruction, _output_stream)
BinaryOperation.(tape, instruction)
end
def self.evaluate(a, b)
a * b
end
end
end
| true
|
67dc60381df9a50608f196336a37afee107b48a2
|
Ruby
|
TheCSpider/GLOBO_Queueing_Project
|
/AgentProcessor/agentProcessor.rb
|
UTF-8
| 1,848
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
#agentProcessor.rb
# Asks for Clients of the Client Queues it has connected to
# @author = Shad Scarboro
#---------------------------------------------------------------------------
# Existing Ruby Gems
require 'socket'
require 'json'
# Locally defined files/classes/modules
require_relative '../Client/clientCommunications.rb'
require_relative '../AgentProcessor/agent.rb'
#---------------------------------------------------------------------------
#Connect with a Client Queue
#---------------------------------------------------------------------------
#An actual Agent's client would allow this to be specified
queue_name = 'localhost'
#If socket creation failed exit
#????
#Send authentication
#????
#Set up timing for time outs
time_out = 180 #If we haven't heard anything for 180 seconds, exit
last_time = Time.now
loop do
#Open out socket
socket = TCPSocket.new(queue_name,ClientCommunication::port)
socket.setsockopt(:SOCKET, :KEEPALIVE, true)
#Request a new client
handler_response = Agent::send_client_request( socket )
#Check the response and handle appropriatly
case handler_response.class.name
when ClientCommunication.name #Handle the message
client_shutdown = Agent::process_message(handler_response)
# If told to shutdown, break out of the loop
break if client_shutdown
last_time = Time.now #Update that we know the server still exists
when Client.name #Handle the Client
Agent::process_client(handler_response)
last_time = Time.now #Update that we know the server still exists
puts "Agent:Recieved client response #{handler_response}"
else
#Report Error
puts "WARNING! - Recieved a response of an unsupported type " + handler_response.class.name
end
#Check for timeout condition
break if (Time.now - last_time) > time_out
end
puts "AgentProcessor - Exiting"
| true
|
e5950ab82278746e31848ee63d54956a2b74fe05
|
Ruby
|
arnavgup/Attendify_iOS
|
/AttendifyAPI(Swagger)/app/models/student.rb
|
UTF-8
| 392
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
class Student < ApplicationRecord
has_many :photos
has_many :enrollments
validates_presence_of :andrew_id
validates :andrew_id, uniqueness: true
scope :alphabetical, -> { order(:last_name, :first_name) }
scope :active, -> {where(active: true)}
scope :inactive, -> {where(active: false)}
def name
return first_name + " " + last_name
end
end
| true
|
a0fb11ca94b6b8d78584b2f89da9c4f918df103e
|
Ruby
|
evanphx/talon
|
/lib/talon/environment.rb
|
UTF-8
| 1,505
| 2.78125
| 3
|
[] |
no_license
|
require 'talon/templated_class'
require 'talon/ops'
module Talon
class Environment
def initialize(parent=Environment.toplevel)
@identifiers = {}
@parent = parent
end
@toplevel = nil
def self.toplevel
return @toplevel if @toplevel
t = Environment.new(nil)
t.add "int", Type.new("talon.lang.Int")
t.add "String", Type.new("talon.lang.String")
ary = TemplateType.new("talon.lang.Array")
ary.add_operation "new", Op::ArrayNew.new
t.add "Array", ary
@toplevel = t
end
def import(node)
Array(node).each do |n|
case n
when AST::ClassDefinition
name = n.name
if name.kind_of? AST::TemplatedName
obj = TemplatedClass.new(self, n)
name = name.name
else
obj = Class.new(self, n)
end
@identifiers[name] = obj
end
end
end
def find(n)
@identifiers[n]
end
def add(name, obj)
@identifiers[name] = obj
end
def lookup(name)
if v = @identifiers[name]
return v
end
return @parent.lookup(name) if @parent
end
def resolve(ast)
case ast
when AST::TemplatedType
base = resolve(ast.base)
args = ast.arguments.map { |i| resolve(i) }
base.instance args
when AST::NamedType
lookup ast.identifier
else
raise "unsupported ast : #{ast.class}"
end
end
end
end
| true
|
fda947292d59e1cf52c20501ab85e8787c42f690
|
Ruby
|
davidpdrsn/underscore-as-a-service
|
/app/services/underscorer.rb
|
UTF-8
| 203
| 2.8125
| 3
|
[] |
no_license
|
class Underscorer
def self.call(text)
new(text).call
end
def initialize(text)
@text = text
end
def call
RustUnderscorer.underscore(text)
end
private
attr_reader :text
end
| true
|
31d168ce98c087ead53753b811b3442637671bad
|
Ruby
|
varesc90/nycda-rails-homework
|
/homework-3/problem-2/problem-2.rb
|
UTF-8
| 169
| 3.53125
| 4
|
[] |
no_license
|
class Animal
def speak
puts "Moo Moo"
end
end
class Dog < Animal
def speak
puts "Woof Woof"
end
end
cow = Animal.new
cow.speak
jumbo = Dog.new
jumbo.speak
| true
|
ec1f5c7244b3a9ea277962d6cc5e80ea9b8e7aed
|
Ruby
|
norrise120/grocery-store
|
/lib/customer.rb
|
UTF-8
| 604
| 3.359375
| 3
|
[] |
no_license
|
require "csv"
class Customer
attr_reader :id
attr_accessor :email, :address
def initialize(id, email, address)
@id = id
@email = email
@address = address
end
def self.all
customers = []
CSV.read("data/customers.csv").each do |row|
customer_address = {street: row[2], city: row[3], state: row[4], zip: row[5]}
customers.push(Customer.new(row[0].to_i, row[1], customer_address))
end
return customers
end
def self.find(id)
self.all.each do |customer|
if customer.id == id
return customer
end
end
return nil
end
end
| true
|
6a37bb95f2d0eaccbb143bdb9db40e1d26dbbf1c
|
Ruby
|
styliii/RubyJobScraper
|
/employer_3.rb
|
UTF-8
| 488
| 3.125
| 3
|
[] |
no_license
|
# Let's try to implement the save method, which basically interacts with the Database object
# first step?
# Employer's responsibility should include what table it belongs to
require 'sqlite3'
class Employer
attr_accessor :name, :url, :about
def initialize(name="", url="", about="")
@name = name
@url = url
@about = about
end
def self.table
@@table ||= "employers"
end
def save
Database.new.insert_record(table, attribute_names, attributes)
end
end
| true
|
914dce5012b397261ae11cb227bd56045274df75
|
Ruby
|
jamccarty99/go_fish_rails
|
/spec/models/user_spec.rb
|
UTF-8
| 1,426
| 2.59375
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#name' do
before do
@user = User.new(name: "Example User", password: "foobar", password_confirmation: "foobar")
end
it 'is required' do
@user.name = ""
expect(@user.valid?).not_to be(true)
end
it "should be valid" do
expect(@user.valid?).to be(true)
end
it "name should be present" do
@user.name = " "
expect(@user.valid?).to_not be(true)
end
it "name should not be too long" do
@user.name = "a" * 51
expect(@user.valid?).to_not be(true)
end
# it 'must be unique' do
# @user
# new_user = User.new(name: "Example User", password: "foobar", password_confirmation: "foobar")
#
# expect(new_user.valid?).not_to be(true)
# expect {
# new_user.save!
# }.to raise_error ActiveRecord::RecordInvalid
# end
end
describe '#password' do
before do
@user = User.new(name: "Example User", password: "foobar", password_confirmation: "foobar")
end
it "password should be present (nonblank)" do
@user.password = @user.password_confirmation = " " * 6
expect(@user.valid?).to be(false)
end
it "password should have a minimum length" do
@user.password = @user.password_confirmation = "a" * 5
expect(@user.valid?).to be(false)
end
end
end
| true
|
a81723645733a02a22512d64c57a9be4466b19ab
|
Ruby
|
sodabrew/puppet-dashboard
|
/lib/registry.rb
|
UTF-8
| 1,705
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
class Registry
class << self
delegate :add_callback, :each_callback, :find_first_callback, :to => :instance
end
def self.instance
@instance ||= new
end
def add_callback( feature_name, hook_name, callback_name, value = nil, &block )
disallow_uninstalled_plugins do
if block and value
raise "Cannot pass both a value and a block to add_callback"
elsif @registry[feature_name][hook_name][callback_name]
raise "Cannot redefine callback [#{feature_name.inspect},#{hook_name.inspect},#{callback_name}]"
end
@registry[feature_name][hook_name][callback_name] = value || block
end
end
def each_callback( feature_name, hook_name, &block )
hook = @registry[feature_name][hook_name]
hook.sort.each do |callback_name,callback|
if block.arity == 2
yield( callback_name, callback )
else
yield( callback )
end
end
nil
end
def find_first_callback(feature_name, hook_name)
self.each_callback(feature_name, hook_name) do |thing|
if result = yield(thing)
return result
end
end
nil
end
def initialize
@registry = Hash.new do |registry, feature_name|
registry[feature_name] = Hash.new do |hooks, hook_name|
hooks[hook_name] = Hash.new
end
end
end
private
def installed_plugins
Dir[Rails.root.join('config', 'installed_plugins', '*')].map { |path| File.basename(path) }
end
def disallow_uninstalled_plugins
caller.each do |call_source|
if call_source =~ %r{/vendor/plugins/([^/]+)/}
plugin_name = $1
return unless installed_plugins.include? plugin_name
end
end
yield
end
end
| true
|
dd01c9a34194bf488b60105d010af391e2e11a0a
|
Ruby
|
MarcoBgn/bolt-template
|
/app/models/utility/hist_parameters.rb
|
UTF-8
| 2,257
| 2.90625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
# Helper to facilitate the handling of time period parameters (historical parameters)
class Utility::HistParameters < ApplicationModel
attr_accessor :from, :to, :period
validate :from_before_to?
def initialize(attrs = {})
filtered_attributes = attrs.to_h.symbolize_keys.slice(:from, :to, :period, :time_range)
time_range = filtered_attributes.delete(:time_range)
super(filtered_attributes)
parse_time_range!(time_range) if time_range
end
def to_h
as_json.symbolize_keys
end
def empty?
![from, to, period].any?(&:present?)
end
def full?
![from, to, period].any?(&:blank?)
end
def map
return [yield(from_date, to_date)] unless full? && valid?
parser = Utility::TimeSpan.from_period(period)
group_method = "end_of_#{parser.period}".to_sym
(from_date..to_date).group_by(&group_method).map do |_, dates|
yield(dates.first, dates.last)
end
end
def from_date
Chronic.parse(from)&.to_date
end
def to_date
Chronic.parse(to)&.to_date
end
def interval_end_dates
@interval_end_dates ||= map { |_i_start, i_end| i_end }
end
# Returns the index of the interval enclosing today's date
def today_interval_index
@today_interval_index ||= begin
# time period is strictly in the past
if to_date && to_date < Time.zone.today
nil
# time period is strictly in the future OR
# time period is infinite OR
# time period has to_date in the future but no from_date boundary OR
# time period has from_date in the past but not to_date boundary
elsif (from_date && from_date > Time.zone.today) || !from_date || !to_date
0
# time period encloses today, with from_date and to_date boundaries
else
interval_end_dates.index do |interval_end|
Time.zone.today <= interval_end
end
end
end
end
private
def parse_time_range!(time_range)
return unless to.present?
time_span = Utility::TimeSpan.new(time_range).time_span
self.from = (to_date + time_span).to_s
end
def from_before_to?
return true unless from && to
errors.add(:from, 'date should not be bigger than to date') if from_date > to_date
end
end
| true
|
963fde3d858f9b494e7e302b005ed326a06b1f0b
|
Ruby
|
AJDot/Launch_School_Files
|
/Exercises/Ruby_Basics/Return/tricky_number.rb
|
UTF-8
| 229
| 3.9375
| 4
|
[] |
no_license
|
# Tricky Number
#
# What will the following code print? Why? Don't run it until you've attempted
# to answer.
#
# def tricky_number
# if true
# number = 1
# else
# 2
# end
# end
#
# puts tricky_number
# ANSWER
# 1
| true
|
374504bb985346aa21a37dbea5d029924c86db36
|
Ruby
|
GoldenLion07/parrot-ruby-prework
|
/parrot.rb
|
UTF-8
| 276
| 3.671875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot(phrase="Squawk!")
puts phrase #outputs a new line
return phrase #our return disrupts the flow of our program and instead of outputting => nil in irb, it replaces it with "Squawk!"
end
| true
|
30f1250470dc4eccf9048bd107b192aed0035c7c
|
Ruby
|
jmorris3/ttt-10-current-player-bootcamp-prep-000
|
/lib/current_player.rb
|
UTF-8
| 133
| 3.28125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def current_player(board)
turn_count(board).even? ? "X":"O"
end
def turn_count(board)
board.count {|el| el == "X" || el == "O"}
end
| true
|
4d578c11b47443769c570175e1be2b916489bab6
|
Ruby
|
NeelTandel-BTC/torrent_test
|
/HighTensionMaximumDemandTemporarySupply.rb
|
UTF-8
| 592
| 3.21875
| 3
|
[] |
no_license
|
# calculate charge for High_Tension_Maximum_Demand_Temporary_Supply
class HighTensionMaximumDemandTemporarySupply
attr_accessor :unit
FLAT_RATE = 6.96
DEMAND = 800
FIX_KW = 500
UPTO_DEMAND = 25
ABOVE_DEMAND = 30
MONTH = 28
def initialize(unit)
@unit = unit
end
def cal
final_bill = unit * FLAT_RATE
fixcharge = if FIX_KW <= DEMAND
UPTO_DEMAND * MONTH
else
ABOVE_DEMAND * MONTH
end
final = final_bill + fixcharge
puts "Final bill : #{final_bill} + #{fixcharge} = #{final}"
end
end
| true
|
4a973276241bbaf64635c868058fa79310472eb9
|
Ruby
|
okuramasafumi/ginko
|
/lib/ginko/name_query.rb
|
UTF-8
| 1,422
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
module Ginko
module NameQuery
def search(query, options={})
limit = options[:limit] || 10
if query.nil? || query.empty?
# parse after limiting number of items for performance reason
parse(data.take(limit))
else
result[query] if cached?(query)
parse(update(query)).take(limit)
end
end
private
def filter_with_query(data, query)
data if query.nil? || query.empty?
query = /\A#{query}/
filtered = data.select do |item|
item.fetch('name').match(query) ||
item.fetch('name_h').match(query) ||
item.fetch('name_k').match(query) ||
item.fetch('name_e').match(query)
end
end
def parse(data)
data.map do |item|
item.is_a?(item_klass) ? item : item_klass.new(item)
end
end
def cached?(query)
result[query].nil?
end
def scope(query)
matched_query = result.keys.select do |key|
query.include?(key.to_s)
end.sort.last
return data if matched_query.nil? || matched_query.empty?
@result[matched_query]
end
def update(query)
scoped = scope(query)
result[query] = filter_with_query(scoped, query)
end
def item_klass
raise 'Called abstract method'
end
def result
raise 'Called abstract method'
end
def data
raise 'Called abstract method'
end
end
end
| true
|
954e8dfd3c6eb4aebca72bd09c3a99c7396086a1
|
Ruby
|
smoip/adventure
|
/character.rb
|
UTF-8
| 12,055
| 3.46875
| 3
|
[] |
no_license
|
require "magic"
require "qwertyio"
class Character
include Magic
include QwertyIO
def initialize (inName, npcFlag)
@name = inName
@npc = npcFlag
@maxHP = 10
@currentHP = maxHP
@maxMP = 10
@currentMP = maxMP
@attackPoints = 1
@defensePoints = 1
@agility = 1
@ap_mod = 0
@dp_mod = 0
@ag_mod = 0
@level = 0
@charExp = 0
@exp_value = 1
@inventory = {'potion' => Item.new(0, 0), 'weapon' => Item.new(0, 0), 'armor' => Item.new(0, 0)}
@gold = 0
@spell_list = []
@spell_modifiers = {'attack' => [0, 0], 'defense' => [0, 0], 'agility' => [0, 0]}
# spell mod - reference by mod attr, ary[0] is modifier, ary[1] is turns left (counted by count_player_turn)
# and reset by 'rest'
end
attr_accessor :name, :maxHP, :currentHP, :maxMP, :currentMP, :attackPoints, :defensePoints, :agility, :level, :charExp, :exp_value, :npc, :inventory, :npc, :spell_list, :gold, :spell_modifiers, :ap_mod, :dp_mod, :ag_mod
# same as defining methods to write/return @name, @currentHP, etc.
def alive?
if @currentHP <= 0
false
else
true
end
end
def hp=(amount)
@currentHP += amount
if @currentHP > @maxHP
@currentHP = @maxHP
elsif @currentHP < 0
@currentHP = 0
end
unless alive?
manage_output("#{name} has perished.")
end
end
def mp=(amount)
@currentMP += amount
if @currentMP > @maxMP
@currentMP = @maxMP
elsif @currentMP < 0
@currentMP = 0
end
end
def status_check
status = ["Name: #{name}", "Level: #{level}", "Exp: #{charExp}", "Class: #{self.class}", "Hit Points: #{currentHP}/#{maxHP}", "Magic Points: #{currentMP}/#{maxMP}", "Attack: #{real_attack_points}", "Defense: #{real_defense_points}", "Agility: #{real_agility_points}", "Gold: #{gold}"]
if @spell_list != []
spells = @spell_list
status << "Spells: #{spells}"
end
status
end
def learn_spell(spell)
@spell_list << spell
unless @npc == 1
manage_output("#{@name} has learned the spell #{spell}!")
end
end
def hit_ratio(target)
hit_ratio = 0
if real_agility_points > target.real_agility_points
hit_ratio = 1
elsif real_agility_points <= target.real_agility_points
hit_ratio = target.real_agility_points - real_agility_points
if hit_ratio < 2
hit_ratio = 2
end
end
return hit_ratio
end
def damage_amount(target)
damage = real_attack_points - (target.real_defense_points/2)
if damage <= 0
damage = 1
end
return damage
end
def attack(target)
if target.alive?
manage_output(self.name + ' attacks ' + target.name + '.')
# break this rand into another method
if hit_target?(target)
damage = damage_amount(target)
manage_output(target.name + " takes #{damage} damage!")
target.hp=(-(damage))
unless target.alive?
gain_exp(target.exp_value)
gain_gold(target.gold_value)
end
else
manage_output(self.name + ' misses!')
end
else
manage_output(target.name + ' is already dead.')
end
end
def hit_target?(target)
if rand(hit_ratio(target)) == 0
return true
else
return false
end
end
def gain_exp amount
# adds exp to total
# only prints for player character
unless @npc == 1
manage_output("#{name} gains #{amount} experience.")
end
@charExp += amount
level_check
end
def gain_gold(amount)
unless amount == 0
unless @npc == 1
manage_output("#{name} gains #{amount} gold.")
end
@gold += amount
end
end
def gold_value
value = ((self.level + 1) * (rand(self.exp_value) + 1)) + (rand(4) - 2)
if value < 0
value = 0
end
return value
end
def level_check
if @level < (@charExp/10)
level_up
end
end
def level_up
while level < (@charExp/10)
unless @npc == 1
# don't print npc level up info
manage_output(self.name + ' gains a level!')
end
@level += 1
@charExp -= (@level * 10)
stats_up
end
end
def force_level_up
unless @npc == 1
# don't print npc level up info
manage_output(self.name + ' gains a level!')
end
@level += 1
stats_up
end
def stats_up
@maxHP += 2
@maxMP += 2
@attackPoints += 1
@defensePoints += 1
@agility += 1
@exp_value += 1
new_spells
end
def new_spells
# not everybody learns spells... sad
end
def real_attack_points
ap = @attackPoints + @ap_mod
if ap < 0
ap = 0
end
return ap
end
def real_defense_points
dp = @defensePoints + @dp_mod
if dp < 0
dp = 0
end
return dp
end
def real_agility_points
ag = @agility + @ag_mod
if ag < 0
ag = 0
end
return ag
end
def cast_spell(spell_name, target)
spell_effect = spells[spell_name]
if self.currentMP < spell_effect['mp']
unless @npc == 1
manage_output('Not enough MP.')
end
if @npc == 1
return false
end
else
manage_output("#{name} casts #{spell_name}.")
self.mp=(-(spell_effect['mp']))
if spell_effect['target_hp'] != nil
hp_spell(spell_effect, target)
elsif spell_effect['target_hp'] == nil
temp_spell(spell_effect, target)
end
if @npc == 1
return true
end
end
end
def mod_spell_effect_hp(spell_effect, target)
spell_effect['target_hp'] + (spell_effect['target_hp']/(spell_effect['target_hp'].abs) * (rand(self.level + 1)* (spell_effect['target_hp']/4)))
end
def hp_spell(spell_effect, target)
spell_outcome = mod_spell_effect_hp(spell_effect, target)
effect_string = "#{target.name} "
if spell_outcome > 0
effect_string += 'gains '
elsif spell_outcome < 0
effect_string += 'loses '
end
effect_string += "#{spell_outcome.abs} hit points!"
manage_output(effect_string)
target.hp=(spell_outcome)
unless target.alive?
gain_exp(target.exp_value)
gain_gold(target.gold_value)
end
end
def temp_spell(spell_effect, target)
['attack', 'defense', 'agility'].each do |type|
unless spell_effect[type] == nil
amount = spell_effect[type] + (spell_effect[type]/(spell_effect[type].abs) * (rand(self.level + 1)* (spell_effect[type]/4)))
duration = spell_effect['duration'] + (rand(self.level + 1) * (spell_effect[type]/4))
target.store_temp_mod(type, amount, duration)
end
end
manage_output("#{target.name} is enchanted!")
end
def store_temp_mod(type, amount, duration)
@spell_modifiers[type] = [amount, duration]
# this should be the only place mods get applied
attr_list = {'attack' => 0, 'defense' => 1, 'agility' => 2}
temp_array = []
temp_array[(attr_list[type])] = amount
if type == 'attack'
@ap_mod = temp_array[0]
end
if type == 'defense'
@dp_mod = temp_array[1]
end
if type == 'agility'
@ag_mod = temp_array[2]
end
end
def count_temp_mod
attr_list = {'attack' => @ap_mod, 'defense' => @dp_mod, 'agility' => @ag_mod}
un_apply_flag = false
['attack','defense','agility'].each do |x|
unless @spell_modifiers[x][1] == 0
@spell_modifiers[x][1] -= 1
if @spell_modifiers[x][1] < 0
@spell_modifiers[x][1] = 0
end
if @spell_modifiers[x][1] == 0
remove_temp_mod(x)
un_apply_flag = true
end
end
end
if un_apply_flag == true
manage_output("An enchantment has faded from #{@name}.")
end
end
def remove_temp_mod(type)
if type == 'attack'
@ap_mod = 0
end
if type == 'defense'
@dp_mod = 0
end
if type == 'agility'
@ag_mod = 0
end
end
def use_potion(potion_name)
if (@inventory['potion']).sub_type.to_s == potion_name
manage_output("#{name} uses #{potion_name}.")
potion_effect = potions[potion_name]
self.hp=(potion_effect['hp'])
self.mp=(potion_effect['mp'])
manage_output("#{name} recovers #{potion_effect['hp']} hit points and #{potion_effect['mp']} magic points.")
@inventory['potion'] = Item.new(0)
else
manage_output("#{name} does not have that potion.")
end
end
def receive_item(item)
manage_output("#{@name} has found #{item.name}.")
manage_output("Keep #{item.name} and replace #{(@inventory[item.type]).name}?")
response = manage_input(['yes', 'no'])
if response == 'yes'
old_item = @inventory[item.type]
apply_stats = old_item.report_item_stats
@attackPoints -= apply_stats[0]
@defensePoints -= apply_stats[1]
@inventory[item.type] = item
apply_stats = item.report_item_stats
@attackPoints += apply_stats[0]
@defensePoints += apply_stats[1]
return [true, old_item]
end
if response == 'no'
manage_output("#{@name} leaves the #{item.name}.")
return [false, nil]
end
end
def inventory_check
manage_output("#{@name}'s Inventory: ")
manage_output("Potion: #{@inventory['potion'].name}")
manage_output("Weapon: #{@inventory['weapon'].name}")
manage_output("Armor: #{@inventory['armor'].name}")
end
end
#-----------------------
class Fighter < Character
def initialize inName, npcFlag
super
@maxHP += 5
@currentHP = @maxHP
@maxMP -= 5
@currentMP = @maxMP
@attackPoints += 2
@defensePoints += 2
end
def stats_up
@maxHP += 3
@maxMP += 1
@attackPoints += 2
@defensePoints += 1
@agility += 1
end
def new_spells
if @level == 10
learn_spell('heal')
end
end
end
class Mage < Character
def initialize inName, npcFlag
super
@maxHP -= 2
@currentHP = @maxHP
@maxMP += 8
@currentMP = @maxMP
@spell_list << 'fireball'
@spell_list << 'heal'
end
def stats_up
@maxHP += 1
@maxMP += 4
@attackPoints += 1
@defensePoints += 1
@agility += 1
new_spells
end
def new_spells
if @level == 2
learn_spell('lightning')
end
if @level == 4
learn_spell('cure')
end
if @level == 6
learn_spell('strength')
end
if @level == 8
learn_spell('weakness')
end
end
end
class Thief < Character
def initialize inName, npcFlag
super
@defensePoints += 1
@agility += 2
end
def stats_up
@maxHP += 2
@maxMP += 1
@attackPoints += 1
@defensePoints += 1
@agility += 2
@exp_value += 1
new_spells
end
def new_spells
if @level == 6
learn_spell(heal)
end
end
end
class GreenDragon
def initialize
super('Green Dragon', 1)
@maxHP += 2
@currentHP = @maxHP
@attackPoints += 2
@defensePoints += 2
@currentMP = @maxMP
@agility += 1
@exp_value += 5
@spell_list << 'fire_breath'
end
def stats_up
super
@defensePoints += 2
@maxHP += 2
@currentHP = @maxHP
end
end
class DemiLich < Character
def initialize
super('Demi Lich', 1)
@maxHP += 2
@currentHP = @maxHP
@attackPoints += 1
@defensePoints += 1
@currentMP = @maxMP
@exp_value += 4
@spell_list << 'fireball'
end
def new_spells
if @level == 4
learn_spell('weakness')
end
if @level == 6
learn_spell('lightning')
end
end
end
class LizardMan < Character
def initialize
super('Lizard Man', 1)
@agility += 2
@maxHP += 1
@currentHP = @maxHP
@maxMP -= 10
@attackPoints += 1
@defensePoints += 3
@currentMP = @maxMP
@exp_value += 3
end
def stats_up
super
@agility += 1
@defensePoints += 1
end
end
class Minotaur < Character
def initialize
super('Minotaur', 1)
@agility -= 1
@maxHP += 5
@currentHP = @maxHP
@maxMP -= 10
@attackPoints += 2
@defensePoints += 1
@currentMP = @maxMP
@exp_value += 3
end
def stats_up
super
@maxHP += 1
@currentHP = @maxHP
end
end
class Skeleton < Character
def initialize
super('Skeleton', 1)
@agility += 1
@maxHP += 1
@currentHP = @maxHP
@maxMP -= 10
@attackPoints += 1
@currentMP = @maxMP
@exp_value += 2
end
end
class Serpent < Character
def initialize
super('Serpent', 1)
@agility += 1
@maxHP -= 2
@currentHP = @maxHP
@maxMP -= 10
@currentMP = @maxMP
@attackPoints += 1
@attackPoints -= 1
@exp_value += 2
end
def stats_up
super
@agility += 1
end
end
class GiantRat < Character
def initialize
super('Giant Rat', 1)
@maxHP -= 2
@currentHP = @maxHP
@maxMP -= 10
@currentMP = @maxMP
@exp_value += 1
end
end
class Slime < Character
def initialize
super('Slime', 1)
@agility -= 1
@maxHP -= 6
@currentHP = @maxHP
@maxMP -= 10
@currentMP = @maxMP
end
end
#--------------------
| true
|
1eb2c7c3d24cb1df5672239a3e57a331073e992c
|
Ruby
|
cmaher92/launch_school
|
/exercises/codewars/consonant_value.rb
|
UTF-8
| 698
| 3.765625
| 4
|
[] |
no_license
|
# consonant value
# https://www.codewars.com/kata/59c633e7dcc4053512000073
require 'pry'
# input
# string; lowercase, alphabetic chars only, no spaces
# output
# int; the highest value substring
# rules
# consonants are any letters of the alphabet except 'aeiou'
# split the given str on any vowels
def solve(str)
str.split(/[aeiou]/).map! do |substring|
substring.bytes.map { |value| value - 96 }.reduce(&:+)
end.reject { |value| value == nil }.max
end
puts solve("zodiac") == 26
puts solve("chruschtschov") == 80
puts solve("khrushchev") == 38
puts solve("strength") == 57
puts solve("catchphrase") == 73
puts solve("twelfthstreet") == 103
puts solve("mischtschenkoana") == 80
| true
|
f750d71a3ee995ee8dd3eb30fc1fbfbac984e75b
|
Ruby
|
MeganRenea/school-domain-nyc-clarke-web-082619
|
/lib/school.rb
|
UTF-8
| 467
| 3.703125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require "pry"
class School
attr_reader :roster, :name
def initialize(name)
@name = name
@roster = {}
end
def add_student(student, grade)
roster[grade] ? roster[grade] << student : roster[grade] = [student]
end
def grade(grade)
roster[grade]
end
def sort
roster.reduce({}) do |memo, (grade, students)|
memo[grade] = roster[grade].sort
memo
end
end
end
| true
|
6afe4866766792447156be879d800c8f26477e30
|
Ruby
|
chasepeeler/isis
|
/lib/isis/connections/hipchat-smackr.rb
|
UTF-8
| 2,796
| 2.640625
| 3
|
[] |
no_license
|
# HipChat connection
# Uses Smackr's XMPP connection to HipChat
require 'smackr'
require 'isis/connections/base'
class Isis::Connections::HipChatSmackr < Isis::Connections::Base
attr_accessor :client, :rooms
def initialize(config)
load_config(config)
create_smackr
end
# API
def connect
client.connect!
# @client.auth(config['hipchat']['password'])
# send_jabber_presence
@join_time = Time.now
end
# API
def reconnect
kill_and_clean_up
create_smackr
connect
end
# API
def register_plugins(bot)
@plugins = bot.plugins
end
# API
def yell(message)
rooms.each do |name,room|
room.send_message message
end
end
# API
def join
config['hipchat']['rooms'].each do |room_name|
opts = {
nickname: config['hipchat']['name'],
history: config['hipchat']['history']
}
puts "About to join: #{room_name} #{opts}".green
rooms[room_name] = client.join_room room_name, opts do |msg,room|
message = msg.get_body
speaker = msg.get_from.split('/').last
# always respond to commands prefixed with 'sudo '
sudo = message.match /^sudo (.+)/
message = sudo[1] if sudo
self_speaking = speaker == @config['hipchat']['name']
who =
if self_speaking
speaker.yellow
else
speaker.green
end
who = who.underline if sudo
puts "#{who}: #{message.white}"
# self_speaking = false # TEST
# ignore our own messages
unless self_speaking and not sudo
@plugins.each do |plugin|
# puts "#{plugin.to_s.underline}"
begin
response = plugin.receive_message(message, speaker, room)
unless response.nil?
if response.respond_to?('each')
response.each {|line| room.send_message(line)}
else
room.send_message(response)
end
end
rescue => e
room.send_message "ERROR: Plugin #{plugin.class.name} just crashed"
room.send_message "Message: #{e.message}"
end
end
end
end
end
end
# API
def still_connected?
client.xmpp_connection and client.xmpp_connection.is_connected
end
# ----------------------------------------
# def send_jabber_presence
# @client.send(Jabber::Presence.new.set_type(:available))
# end
def kill_and_clean_up
client.disconnect!
end
def create_smackr
@client = Smackr.new({
server: config['hipchat']['jid'].split('@').last,
username: config['hipchat']['jid'],
password: config['hipchat']['password'],
})
@rooms = {}
end
end
| true
|
718ab63592ff56ebc0383ab5df987e43ada4013c
|
Ruby
|
dmitryS1666/thinknetica_rep
|
/less_7/carriage.rb
|
UTF-8
| 330
| 3
| 3
|
[] |
no_license
|
load 'module/modules.rb'
class Carriage
include CompanyModule
attr_reader :number, :type
def initialize(number)
@number = number
initial_type
end
def cargo?
type == :cargo
end
def passenger?
type == :passenger
end
protected
attr_writer :type
def initial_type
@type = ''
end
end
| true
|
2fb612667511e8c6cc34f8490be59725a13e6d90
|
Ruby
|
aindrayana/codecore-oct-2015
|
/day1/d1-forloop.rb
|
UTF-8
| 102
| 3.28125
| 3
|
[] |
no_license
|
# 7...18 from 7 to 17 not including 18
# 7..18 from 7 to 18
for number in 7..18
puts number
end
| true
|
68124f4d4d27e678231417f5cd8b559ff099c15a
|
Ruby
|
YohannTisserand/student-directory
|
/exercises/1_to_10.rb
|
UTF-8
| 1,575
| 4.03125
| 4
|
[] |
no_license
|
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
students = []
while true do
puts "-- Name please: --"
name = gets.delete("\n")
break if name.empty?
puts "-- Cohort please: --"
cohort = gets.delete("\n")
cohort = "" if cohort.empty?
puts "-- Hobbie please: --"
hobbie = gets.delete("\n")
hobbie = "be evil" if hobbie.empty?
puts "-- Height please: --"
height = gets.delete("\n")
height = "" if height.empty?
students << {name: name, cohort: cohort, hobbie: hobbie, height: height}
puts "Now we have #{students.count} students"
end
students
end
def print_header
puts "The students of Villains Academy"
puts "-------------".center(32)
end
def print(students)
=begin
students.each.with_index(1) do |student, idx|
puts "#{idx}. #{student[:name]} (#{student[:cohort]} cohort)" #if student[:name].length < 12
end
=end
x = 0
puts "-- Enter a cohort, please: --"
month = gets.delete("\n")
while x < students.length do
if month == students[x][:cohort]
i = x + 1
puts "#{i}- #{students[x][:name]} (#{students[x][:cohort]} cohort) | Hobbie: #{students[x][:hobbie]} | Height: #{students[x][:height]}"
end
x += 1
end
end
def print_footer(students)
puts students.length > 1 ? "Overall, we have #{students.count} great students" : "Overall, we have #{students.count} great student"
puts "Empty list" if students.length == 0
end
students = input_students
print_header
print(students)
print_footer(students)
| true
|
72820f7f02c6893727e8ab30e201187a425821fc
|
Ruby
|
AliceOJJm/yandex-direct-api
|
/lib/yandex-direct-api.rb
|
UTF-8
| 2,980
| 2.546875
| 3
|
[] |
no_license
|
require 'net/http'
require 'net/https'
require 'json'
require 'yaml'
require 'uri'
module YandexDirect
class RuntimeError < RuntimeError
end
def self.url
configuration['sandbox'] ? 'https://api-sandbox.direct.yandex.com/json/v5/' : 'https://api.direct.yandex.com/json/v5/'
end
def self.configuration
raise RuntimeError.new("Configure yandex-direct-api for #{@environment || 'current'} environment.") unless @configuration
@configuration
end
def self.parse_json json
begin
return JSON.parse(json)
rescue => e
raise RuntimeError.new "#{e.message} in response."
end
end
def self.load file, env = nil
@environment = env.to_s if env
config = YAML.load_file(file)
@configuration = defined?(@environment) ? config[@environment] : config
end
def self.configure options
@configuration = options
end
def self.request(service, method, params = {}, units = false, config: nil)
configure(config) if config.present?
uri = URI(url + service)
body = {
method: method,
params: params
}
puts "\t\033[32mYandexDirect:\033[0m #{service}.#{method}(#{body[:params]})" if config['verbose'] && !units
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
# http.set_debug_output($stdout)
request = Net::HTTP::Post.new(uri.path)
request['Authorization'] = "Bearer #{config['token']}"
request['Accept-Language'] = config['locale']
request['Client-Login'] = config['login'].downcase.gsub('.', '-')
request.body = JSON.generate(body)
response = http.start do |http|
http.request(request)
end
raise YandexDirect::RuntimeError.new("#{response.code} - #{response.message}") unless response.code.to_i == 200
return response['Units'] if units
json = parse_json(response.body)
messages = []
if json.has_key?('error')
messages.push("#{json['error']['error_code'].to_i} - #{json['error']['error_string']}: #{json['error']['error_detail']}")
else
value = json['result'].present? ? (json['result'].values.first || json['result']) : json
value = value.values if value.kind_of?(Hash)
value.each do |item|
item['Errors'].each do |error|
messages.push("#{error['Code'].to_i} - #{error['Message']}: #{error['Details']}")
end if item.has_key?('Errors')
end if value.present?
end
raise RuntimeError.new(messages.join("\n")) if messages.any?
return json['result']
end
def self.get_units
units = request('dictionaries', 'get', {"DictionaryNames": ["AdCategories"]}, true)
units.split('/')[1].to_i
end
end
require 'services/campaign.rb'
require 'services/add.rb'
require 'services/ad_group.rb'
require 'services/keyword.rb'
require 'services/bid.rb'
require 'services/dictionaries.rb'
require 'services/sitelink.rb'
require 'services/vcard.rb'
require 'live/live.rb'
require 'client.rb'
| true
|
0e3526886eee7e8fe14a35c84ed079b5a0be7a4b
|
Ruby
|
flatiron-lessons/sinatra-basic-routes-lab-web-071717
|
/app.rb
|
UTF-8
| 293
| 2.71875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require_relative 'config/environment'
class App < Sinatra::Base
get '/' do
"This is the homepage!"
end
get '/name' do
"My name is James."
end
get '/hometown' do
"My hometown is Howard Beach."
end
get '/favorite-song' do
"My favorite song is Love Yours by J Cole."
end
end
| true
|
c7760a4f7b20b687bf0b822dbc79dbb46f7f242e
|
Ruby
|
glucero/sysshep
|
/lib/sysshep/xml/generic.rb
|
UTF-8
| 601
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
module SysShep::XML
class Generic
include Enumerable
attr_reader :agent
def initialize(datapoints, options = {})
@agent = options[:agent]
@datapoints = datapoints.each do |datapoint|
datapoint.host ||= options[:host]
datapoint.client ||= options[:client]
end
end
def each(&block)
@datapoints.each &block
end
def to_xml
XML.dump xml
end
def to_pretty_xml
XML.pretty_format xml
end
def to_json
JSON.dump json
end
def to_pretty_json
JSON.pretty_format json
end
end
end
| true
|
fd8cf9a9285b973e2f7e4b7ccfb41cc5acfbe8c0
|
Ruby
|
ichbinorange/AdaCohort14_HW
|
/w2ex_binary_to_decimal.rb
|
UTF-8
| 2,490
| 4.53125
| 5
|
[] |
no_license
|
=begin
Calculate the decimal value for this binary number using the algorithm you devised in class. Return the decimal value.
Note: Do not use Ruby functions. You may use .length method on the array
and retrieve values at a particular index in the array.
Author using the algorithm you devised in class. You may however write your own versions of these methods
Optional
Add a decimal_to_binary method which converts a decimal number received as a parameter
into an array of binary digits. Then write 3 tests for the method.
=end
class Decimal_binary_converter
def is_8bits_binary(user_input)
binary = false
until binary
if (user_input.each_char.to_a.select { |i| i == "0" || i == "1" }).length == 8
eight_bits = user_input.each_char.to_a
binary = true
else
print "Please enter 8 characters filled with only 0’s and 1’s ==> "
user_input = gets.chomp
end
end
return eight_bits
end
def binary_to_decimal(user_input)
num = 0
user_input.each_with_index do |value, index|
num += value.to_i * 2 ** (7 - index)
end
return num
end
def is_numeric(user_input)
numeric = false
until numeric
if (user_input.to_i.to_s == user_input) && (user_input.to_i >=0)
num = user_input
numeric = true
else
print "It's not a whole number, please try again =>"
user_input = gets.chomp
end
end
return num.to_i
end
def decimal_to_binary(user_input)
quotient_i = user_input.divmod(2)[0]
modulus_i = Array(user_input.divmod(2)[1])
until quotient_i == 0
modulus_i.unshift(quotient_i.divmod(2)[1])
quotient_i = quotient_i.divmod(2)[0]
end
bi_num = modulus_i.join
return bi_num
end
end
decimal_binary_converter = Decimal_binary_converter.new
puts %q{
Welcome to my Binary to Decimal Converter!
To convert a binary number to a decimal number,
Please enter 8 characters filled with 0’s and 1’s, e.g. 10001000.
}
print "==> "
user_number = gets.chomp
user_number = decimal_binary_converter.is_8bits_binary(user_number) # return an array
puts decimal_binary_converter.binary_to_decimal(user_number)
# Optional
puts %Q{
\nTo convert a decimal number to a binary number,
Please enter a whole number.}
print "==> "
user_number = gets.chomp
user_number = decimal_binary_converter.is_numeric(user_number) # return a integer
puts decimal_binary_converter.decimal_to_binary(user_number)
| true
|
b8703e37a7f470a96c2e4fdd85f1eaf7a886d672
|
Ruby
|
akuhn/euler
|
/problem_20.rb
|
UTF-8
| 176
| 3
| 3
|
[] |
no_license
|
require_relative 'euler'
# Problem 20
# 21 June 2002
# n! means n (n 1) ... 3 2 1
# Find the sum of the digits in the number 100!
100.factorial.digit_sum.should == 648
| true
|
220a64bdc44d98cba71d7c073e8968a598ea44a3
|
Ruby
|
itggot-emil-willbas/Fesk
|
/slimapp.rb
|
UTF-8
| 4,949
| 2.609375
| 3
|
[] |
no_license
|
require 'rubygems'
require 'sinatra'
require 'slim'
require 'sqlite3'
require 'byebug'
require 'bcrypt'
require_relative 'module.rb'
include Database
enable :sessions
#Varför kan man inte routa till '/mainadmin' om man först reggar, sen loggar in?
get('/') do
slim(:index)
end
get('/logout') do
session.clear
redirect('/')
end
get('/adminregister') do
slim(:adminregister)
end
get('/customerregister') do
slim(:customerregister)
end
get('/mainadmin') do
slim(:mainadmin)
end
get('/maincustomer') do
slim(:maincustomer)
end
get('/inventory/:id/edit_amount') do
fish_id = params[:id]
fishname = get_fishname_from_id(id:fish_id)
if session[:type_of_user] != "admin"
session[:error] = "You are not logged in as admin."
redirect('/error')
end
slim(:edit_fish_amount, locals:{fish_id:fish_id,fishname:fishname})
end
get('/inventory/:id/edit_price') do
fish_id = params[:id]
fishname = get_fishname_from_id(id:fish_id)
if session[:type_of_user] != "admin"
session[:error] = "You are not logged in as admin."
redirect('/error')
end
slim(:edit_fish_price, locals:{fish_id:fish_id,fishname:fishname})
end
get('/error') do
errormsg = session[:error]
type_of_user = session[:type_of_user]
if type_of_user == "admin"
linktxt = "adminregister"
else
if type_of_user == "customer"
linktxt = "customerregister"
else
linktext = "/"
errormg = "Something went terribly bad. You are neither Admin or Customer. Are you a fish?"
end
end
slim(:error, locals:{errormsg:errormsg,linktxt:linktxt})
end
get('/inventory') do
result = show_inventory()
test = "TEst"
slim(:inventory, locals:{result:result, test:test})
end
post('/login') do
if params[:type_of_user] == nil
session[:error] = "Please choose 'Admin' or 'Customer'"
redirect('/error')
end
session[:type_of_user] = params[:type_of_user]
username = params[:username]
password = params[:password]
type_of_user = session[:type_of_user]
password_digest = get_password_digest(username:username,type_of_user:type_of_user)
if password.length > 0 && username.length > 0
if BCrypt::Password.new(password_digest) == password && type_of_user == "admin"
redirect('/mainadmin')
else
if BCrypt::Password.new(password_digest) == password && type_of_user == "customer"
redirect('/maincustomer')
else
redirect('/')
end
end
else
redirect('/')
end
end
post('/adminregister') do
session[:type_of_user] = "admin"
username = params[:username]
secret_word = params[:secret_word]
password = params[:password]
confirm = params[:confirm]
if password.length > 0 && username.length > 0 && secret_word == "fisk"
if password == confirm
password_digest = BCrypt::Password.create(password)
begin
create_admin(username:username,password:password_digest)
rescue SQLite3::ConstraintException
session[:error] = "Username already exists, please choose another"
redirect('/error')
end
else
session[:error] = "Password and confirmation don't match, plz try again"
redirect('/error')
end
redirect('/mainadmin')
else
session[:error] = "Please fill in the form and type the secret word. Hint: f _ _ _"
redirect('/error')
end
end
post('/customerregister') do
session[:type_of_user] = "customer"
username = params[:username]
password = params[:password]
confirm = params[:confirm]
if password.length > 0 && username.length > 0
if password == confirm
password_digest = BCrypt::Password.create(password)
begin
create_customer(username:username,password:password_digest)
rescue SQLite3::ConstraintException
session[:error] = "Username already exists, please choose another"
redirect('/error')
end
else
session[:error] = "Password and confirmation don't match, plz try again"
redirect('/error')
end
redirect('/maincustomer')
else
session[:error] = "Please fill in the form"
redirect('/error')
end
end
post('/inventory/:id/edit_amount') do
fish_amount = params[:number]
fish_id = params[:id] #Tänker jag fel här?
add_fish(fish_amount:fish_amount,id:fish_id)
redirect('/inventory')
end
post('/inventory/:id/edit_price') do
fish_price = params[:number]
fish_id = params[:id] #Tänker jag fel här?
change_price(fish_price:fish_price,id:fish_id)
redirect('/inventory')
end
| true
|
193637028b216e6a25f5d3519459732a73c70e3f
|
Ruby
|
shoynoi/books-app
|
/test/models/user_test.rb
|
UTF-8
| 1,193
| 2.703125
| 3
|
[] |
no_license
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User",
email: "[email protected]",
password: "password",
password_confirmation: "password",
postcode1: "123",
postcode2: "4567")
@bob = users(:bob)
@alice = users(:alice)
end
test "user is valid" do
assert @user.valid?
end
test "郵便番号が正しいフォーマットである" do
invalid_postcodes = [["1234", "567"], ["1234", "5678"], ["a23", "4567"], ["123", "a567"]]
invalid_postcodes.each do |invalid_postcode|
@user.postcode1, @user.postcode2 = invalid_postcode
assert_not @user.valid?
end
end
test "ユーザーは別のユーザーをフォローできる" do
assert_not @bob.following?(@alice)
@bob.follow(@alice)
assert @bob.following?(@alice)
assert @alice.followers.include?(@bob)
end
test "フォロー済みユーザーのフォロー解除ができる" do
@bob.follow(@alice)
assert @bob.following?(@alice)
@bob.unfollow(@alice)
assert_not @bob.following?(@alice)
end
end
| true
|
91984a07911d7a50c28fba2b925fb7e851896499
|
Ruby
|
ToadJamb/ruby_deploy
|
/test/lib/deploy_support.rb
|
UTF-8
| 18,018
| 2.5625
| 3
|
[] |
no_license
|
# This file contains a module which bridges the gap between test code
# and applciation code.
#--
################################################################################
# Copyright (C) 2011 Travis Herrick #
################################################################################
# #
# \v^V,^!v\^/ #
# ~% %~ #
# { _ _ } #
# ( * - ) #
# | / | #
# \ _, / #
# \__.__/ #
# #
################################################################################
# This program is free software: you can redistribute it #
# and/or modify it under the terms of the GNU General Public License #
# as published by the Free Software Foundation, #
# either version 3 of the License, or (at your option) any later version. #
# #
# Commercial licensing may be available for a fee under a different license. #
################################################################################
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; #
# without even the implied warranty of MERCHANTABILITY #
# or FITNESS FOR A PARTICULAR PURPOSE. #
# See the GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
################################################################################
#++
# This module is provided to be used as an include in any necessary class.
#
# This serves as a bridge between test code and application code.
module DeploySupport
# The error format that Trollop uses.
#
# Our error messages should use the same format for consistency.
TROLLOP_MSG = "Error: %s.\nTry --help for help."
# The error format that Trollop uses for argument errors.
#
# Our argument error messages should use the same format for consistency.
TROLLOP_ARG = TROLLOP_MSG % 'argument %s %s'
# The id to use as the changeset ID.
HG_ID = 'c91fb6c87d56'
# These are things that will be used throughout testing in multiple locations.
ITEMS = {
:messages => {
:help_text => %Q{\
Deploy.rb [OPTIONS]
Deploys the code in the current directory to the specified location.
Deploy will look for .exclude in the root folder
to use as an exclude file to send to rsync. Additional exclusions may be
added based on the environment you are deploying to by looking for
.environment.exclude in the root folder.
Notes on differences between local and remote deployments:
1. Local deployments will warn about code not being checked in,
but will not prevent deployments from happening. Remote deployments
will not be allowed with outstanding changes.
2. By default, local deployments are not tagged in source control.
Remote deployments will be. Either (or both) of these may be
turned on/off by using tag-it in the appropriate config file.
tag-it will require that all code is committed before deploying.
NOTE: All options are case sensitive!
options:
--dest, -d <s+>: Specify destinations - multiple destinations may be
specified at once. Each destination corresponds to a
similarly named file in ~/.deploy.
--version, -v: Print version and exit
--help, -h: Show this message
}, # :help_text
:version => 'Deploy %d.%d.%d' % [
Deploy::Version::MAJOR,
Deploy::Version::MINOR,
Deploy::Version::REVISION],
# Trollop messages.
:required_flag => TROLLOP_ARG % ['%s', 'is required'],
:unknown_flag => TROLLOP_MSG % "unknown argument '%s'",
:duplicate_flag => TROLLOP_MSG % "option '%s' specified multiple times",
:missing_option => TROLLOP_MSG % "option '%s' needs a parameter",
:unknown_option => TROLLOP_MSG % "unknown option '%s'",
# Error messages prior to deployment.
:no_config => TROLLOP_MSG % "Config file '%s' not found",
:no_settings => TROLLOP_MSG % "'%s' contains no valid settings",
:na_line => TROLLOP_MSG % "'%s' is an invalid setting in '%s'",
:bad_key => TROLLOP_MSG % "'%s' is an unknown key in '%s'",
:dup_key => TROLLOP_MSG % "'%s' is a duplicate key in '%s'",
:no_server => TROLLOP_MSG % ["A user without a server " +
"has been specified in '%s'"],
:no_user => TROLLOP_MSG % ["A server without a user " +
"has been specified in '%s'"],
:bad_remote => TROLLOP_MSG % ["'%s@%s:%s' specified in %s " +
"is an invalid path " +
"or the user does not have " +
"appropriate privileges"],
:bad_path => TROLLOP_MSG % ["'%s' specified in %s " +
"is an invalid path " +
"or the user does not have " +
"appropriate privileges"],
:no_path => TROLLOP_MSG % "No path was specified in '%s'",
:check_out => TROLLOP_MSG % ["There are pending changes. " +
"The current settings do not allow " +
"uncommitted changes to be " +
"pushed to '%s'"],
:no_repo => TROLLOP_MSG % ["The current working directory does " +
"not appear to be the project root"],
# Error messages during deployment.
:user_group => "user:group could not be determined for %s.",
:chmod_fail => "chmod was unsuccessful on %s.",
:rsync_fail => "RSync command failed for %s.",
:chown_fail => "Resetting owner to %s was unsuccessful for %s.",
# Status messages.
:chmod => "Changing permissions on %s to %d...",
:copying => "Copying files to %s...",
:chown => "Resetting owner to %s on %s...",
:tagging => "Tagging changeset %s...",
:copy_db_yml => "Copying database.yml...",
}, # :messages
:branch => {
:named => 'named_branch',
:default => 'default',
}, # :branch
:dest => {
:base => [
'local_default_one',
'local_default_two',
'remote_default_one',
'remote_default_two'
], # :base
:no_config => ['abcdef', 'ghijkl'],
}, # :dest
:environment => {
:dev => 'development',
:test => 'test',
:prod => 'production',
}, # :env
:extension => {
:bad => '.bad',
}, # :extension
:flag => {
:help => ['--help', '-h'],
:version => ['--version', '-v'],
:dest => ['--dest', '-d']
}, # :flag
:hg_log => [
"changeset: 34:#{HG_ID}",
'branch: v1_dev',
'tag: tip',
'user: Travis Herrick <[email protected]>',
'date: Sun Feb 13 21:50:27 2011 -0500',
'summary: Made some changes.',
], # :hg_log
:function => {
:tag => 'hg_tag',
:hg => 'run_hg',
:db_yml => 'db_yml_contents',
}, # :function
:owner_group => 'owner:group',
:permission => {
:r_xr_xr_x => 555,
:r_x___rwx => 507,
}, # :perm
:path => {
:config => File.expand_path('~/.deploy'),
:db_yml_tmp_folder => File.join('.', 'tmp', 'db', '%s'),
:db_yml_tmp_file => File.join('.', 'tmp', 'db', '%s', 'database.yml'),
}, # :path
:project => {
:good => 'good_project',
:uncommitted => 'uncommitted',
:no_repo => 'no_repo',
:rails => 'rails_project',
}, # :project
:server => {
:allow => 'allow_server',
:deny => 'deny_server',
}, # :server
:tag => {
:ss => 'SuperSaver',
}, # :tag
:tag_date => '2011-01-01 17-09-59',
:user => {
:allow => 'allow_user',
:deny => 'deny_user',
}, # :user
} # ITEMS
# Returns the content of a database.yml file.
#
# Since the parser has been tested outside of the main application,
# we may simply return any version of a full database.yml file.
# ==== Output
# [String] The contents of a full database.yml file.
def db_yml
DbYaml::COMPLEX
end
# Returns a path with a leading '/'.
# ==== Input
# [path : String : ''] The path to append a leading '/' to.
# ==== Output
# [String] <tt>path</tt> with a leading '/'
# or an empty string if <tt>path</tt> was empty.
# ==== Examples
# get_file_path #=> ''
# get_file_path 'blah' #=> '/blah'
# get_file_path '/blah' #=> '/blah'
def get_file_path(path = '')
unless path.strip.empty?
path.strip!
path = '/' + path unless path.match(%r|^/|)
end
return path
end
# Returns the local path in a config file.
# ==== Input
# [path : String : ''] Typically the name of a file,
# but it could be a path itself.
# ==== Output
# [String] A value that is the local path as specified in a config file.
# ==== Examples
# local_path #=> /good/local/path
# local_path 'blah' #=> /good/local/blah/path
# local_path '/blah' #=> /good/local/blah/path
def local_path(path = '')
"/good/local#{get_file_path(path)}/path"
end
# Black magic.
#
# This is used for the following purposes:
# * To return elements from the ITEMS hash.
# * To return messages (from the ITEMS hash),
# possibly with string substitutions.
# ==== Input
# [method : Symbol] The method that was called.
# [*args : Array] Any arguments that were passed in.
# [&block : Block] A block, if specified.
# ==== Output
# [Any] It depends on the method.
def method_missing(method, *args, &block)
# Check if the method is a key in the ITEMS hash.
if ITEMS.has_key? method
# Initialize the variable that will hold the return value.
value = nil
if args.nil? or args.count == 0
# If no arguments have been specified, return the element as is.
value = ITEMS[method]
elsif ITEMS[method][args[0]].is_a?(String) &&
ITEMS[method][args[0]].index('%s')
# The first parameter is the message.
msg = args.shift
if args.count == 0
# If no arguments are left, return the message.
value = ITEMS[method][msg]
else
# Use any remaining arguments to make substitutions.
value = ITEMS[method][msg] % args
end
else # All other methods - which are expected to have one parameter.
# Get the element to return.
item = args[0].to_sym
# Return the indicated element.
value = ITEMS[method][item]
# Dynamically add configuration files.
if value.nil? and [:dest, :function].index(method)
value = item.to_s
end
end
# Strip all trailing line feeds from strings.
value.gsub!(/\n*\z/, '') if value.is_a?(String)
return value
else
super
end
end
# Returns an argument hash by turning the given hash into flags and arguments.
# ==== Input
# [options : Hash : {}] The hash that will be
# turned into command line parameters.
# ==== Output
# [Array] An array that simulates the ARGV array.
def parameters(options = {})
# Place the options hash in a local variable.
argv = []
# Loop through each option, adding a flag and argument for each.
# This will reflect the desired parameters to send to the main class.
options.each do |key, value|
argv << flag(key)[0]
argv << send(key, value)
end
# Return the arguments array.
return argv.flatten
end
# Returns the remote path in a config file.
# ==== Input
# [path : String : ''] Typically the name of a file,
# but it could be a path itself.
# ==== Output
# [String] A value that is the remote path as specified in a config file.
# ==== Examples
# remote_path #=> /good/remote/path
# remote_path 'blah' #=> /good/remote/blah/path
# remote_path '/blah' #=> /good/remote/blah/path
def remote_path(path = '')
"/good/remote#{get_file_path(path)}/path"
end
# Indicates which methods the class will respond to.
# ==== Input
# [method : Symbol] The method to check for.
# [include_private : Boolean] Whether private methods should be checked.
# ==== Output
# [Boolean] Whether the object will respond to the specified method.
def respond_to?(method, include_private = false)
if ITEMS.has_key? method
super
else
return true
end
end
# This method replicates running a command externally.
# This may be either via backticks (shell) or via ssh.
# ==== Input
# [command : String] The command that will be 'run'.
# [options : Hash] The options hash
# (this may only available for ssh commands).
# [project : String] The name of the project for which
# the application is being 'run'.
# ==== Output
# [Boolean] Indicates success.
# [String] Returns output.
# ==== Examples
# run_external('hg_status', {}, 'uncommitted') #=> [true, 'M test/lib/deploy.rb']
def run_external(command, options, project)
case command
# hg status
when 'hg status'
case project
when 'uncommitted' then return true, "M test/lib/deploy.rb"
when 'good_project', 'rails_project' then return true, ''
end
# hg id
when 'hg id' then return true, "#{HG_ID} (v1_dev) tip"
# hg log --rev c91fb6c87d56
when "hg log --rev #{HG_ID}"
out = hg_log
return true, out.join("\n").chomp
# hg branch
when /^hg branch \w+ --force$/
branch = command.gsub(/^hg branch | --force$/, '')
return true, "marked working directory as branch #{branch}"
# hg tag
when /^hg tag "\w+ \d{4}-\d\d-\d\d \d\d-\d\d-\d\d" --force$/
return true, ''
# hg update
when "hg update #{HG_ID} --clean"
return true,
'0 files updated, 0 files merged, 0 files removed, 0 files unresolved'
# stat -c %U:%G
when /^stat -c %U:%G /
path = command.gsub(/.*%G /, '')
case path
when %r|/\w+?_status_fail/path/\w+?$|, %r|/remote_bad_extension|
return false,
"stat: cannot stat `#{path}': Permission denied"
end
return true, owner_group
# sudo chmod 507
when /^sudo chmod 507 /
path = command.match(%r|/.*/path/\w+|).to_s
case path
when %r|/\w+?_chmod_initial_fail/|
output = "chmod: \nchanging permissions of `#{path}'\n" +
": Operation not permitted"
return false, output
end
return true, ''
# sudo chmod 500
when /^sudo chmod \d{3} /
path = command.match(%r|/.*/path/\w+|).to_s
case path
when %r|/\w+?_chmod_final_fail/|
output = "chmod: \nchanging permissions of `#{path}'\n" +
": Operation not permitted"
return false, output
end
return true, ''
# rsync
when /^rsync /
path = command.gsub(/^rsync .+? /, '')
fail = [
"rsync: \nmkdir \"/var/www/deploy\" failed\n: Permission denied (13)",
"rsync error: error in file IO (code 11) at main.c(595) [Receiver=3.0.7]",
"rsync: connection unexpectedly closed (9 bytes received so far) [sender]",
"rsync error: error in rsync protocol data stream (code 12) at io.c(601) [sender=3.0.7]",
]
case path
when %r|rsync_db_fail|
return false, fail.join("\n") unless command.match(/rsync \.\/ /)
when %r|\w+?_rsync_fail/|
return false, fail.join("\n")
end
return true, ''
# ls
when /^ls /
path = command[3..-1]
case path
when %r|\.bad$|, %r|/remote_bad_\w*_?path/|
return false,
"ls: \ncannot access #{path}\n: No such file or directory"
end
return true, "bin\nboot\nmedia"
# sudo chown
when /^sudo chown /
path = command.match(%r|/.*/path/\w+|).to_s
case path
when %r|/\w+?_chown_fail/|
output = "chown: \nchanging ownership of `#{path}'\n" +
": Operation not permitted"
return false, output
end
return true, ''
end
# Raise an error if the command was not handled.
raise ArgumentError.new("'#{command}' is an invalid command " +
"for #{project}.")
end
end
| true
|
3a77016baac4819c33cb8ca762fcc6bf23fc0336
|
Ruby
|
mashiro/saorin
|
/lib/saorin/request.rb
|
UTF-8
| 1,645
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require 'saorin/error'
require 'saorin/dumpable'
require 'saorin/utility'
module Saorin
class Request
include Dumpable
attr_accessor :version, :method, :params, :id
def initialize(method, params, options = {})
@version = options[:version] || Saorin::JSON_RPC_VERSION
@method = method
@params = params
@id = options[:id]
@notify = !options.has_key?(:id)
end
def notify?
@notify
end
def valid?
return false unless @method && @version
return false unless [String].any? { |type| @version.is_a? type }
return false unless [String].any? { |type| @method.is_a? type }
return false unless [Hash, Array, NilClass].any? { |type| @params.is_a? type }
return false unless [String, Numeric, NilClass].any? { |type| @id.is_a? type }
return false unless @version == JSON_RPC_VERSION
return false unless [email protected]_with?('.')
true
end
def validate
raise Saorin::InvalidRequest unless valid?
end
def to_h
h = {}
h['jsonrpc'] = @version
h['method'] = @method
h['params'] = @params if @params && [email protected]?
h['id'] = @id unless notify?
h
end
def self.symbolized_keys(hash)
hash.each do |k, v|
if k.is_a? ::String
hash[k.to_sym] = v
end
end
end
def self.from_hash(hash)
raise Saorin::InvalidRequest unless hash.is_a?(::Hash)
options = hash.dup
method = options.delete('method')
params = options.delete('params')
new method, params, Saorin::Utility.symbolized_keys(options)
end
end
end
| true
|
2727f4b96d7e5abe1f3cb4754d1a450520659abd
|
Ruby
|
floriank/codeclimate
|
/lib/cc/cli/command.rb
|
UTF-8
| 1,536
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require "highline"
require "active_support"
require "active_support/core_ext"
require "rainbow"
module CC
module CLI
class Command
CODECLIMATE_YAML = ".codeclimate.yml".freeze
def initialize(args = [])
@args = args
end
def run
$stderr.puts "unknown command #{self.class.name.split('::').last.underscore}"
end
def self.command_name
name[/[^:]*$/].split(/(?=[A-Z])/).map(&:downcase).join("-")
end
def execute
run
end
def success(message)
terminal.say colorize(message, :green)
end
def say(message)
terminal.say message
end
def warn(message)
terminal.say(colorize("WARNING: #{message}", :yellow))
end
def fatal(message)
$stderr.puts colorize(message, :red)
exit 1
end
def require_codeclimate_yml
unless filesystem.exist?(CODECLIMATE_YAML)
fatal("No '.codeclimate.yml' file found. Run 'codeclimate init' to generate a config file.")
end
end
private
def colorize(string, *args)
rainbow.wrap(string).color(*args)
end
def rainbow
@rainbow ||= Rainbow.new
end
def filesystem
@filesystem ||= CC::Analyzer::Filesystem.new(ENV["FILESYSTEM_DIR"])
end
def terminal
@terminal ||= HighLine.new($stdin, $stdout)
end
def engine_registry
@engine_registry ||= CC::Analyzer::EngineRegistry.new
end
end
end
end
| true
|
75c2ddadd456e51c4e4377526eb3b925fb6a3758
|
Ruby
|
DercilioFontes/jungle-rails
|
/spec/models/user_spec.rb
|
UTF-8
| 4,125
| 2.546875
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe User, type: :model do
describe "Validations" do
it "must not be created with different password and password_corfimation" do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KtKk')
expect(@user.errors.full_messages()).to eq ["Password confirmation doesn't match Password"]
end
it "must be created with same password and password_corfimation" do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.find(@user.id)).not_to be_nil
end
it "must not be created with a email that have already been saved in DB, even case sensitive" do
@user1 = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
@user2 = User.create(first_name: 'Sylvia', last_name: 'Fontes', email: '[email protected]', password: 'PpPp', password_confirmation: 'PpPp')
expect(@user2.errors.full_messages()).to eq ["Email has already been taken"]
end
it "must not be created without first name" do
@user = User.create(first_name: nil, last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(@user.errors.full_messages()).to eq ["First name can't be blank"]
end
it "must not be created without last name" do
@user = User.create(first_name: 'Sylvia', last_name: nil, email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(@user.errors.full_messages()).to eq ["Last name can't be blank"]
end
it "must not be created without email" do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: nil, password: 'KkKk', password_confirmation: 'KkKk')
expect(@user.errors.full_messages()).to eq ["Email can't be blank"]
end
it "must not be created with a password with less than minimum length" do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkK', password_confirmation: 'KkK')
expect(@user.errors.full_messages()).to eq ["Password is too short (minimum is 4 characters)", "Password confirmation is too short (minimum is 4 characters)"]
end
end
describe '.authenticate_with_credentials' do
it 'authenticates a user with correct credentials' do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.authenticate_with_credentials('[email protected]', 'KkKk')).to eq @user
end
it 'not authenticates a user with incorrect credentials' do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.authenticate_with_credentials('[email protected]', 'KkKk')).to_not eq @user
end
it 'authenticates a user with correct credentials and spaces before the email' do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.authenticate_with_credentials(' [email protected]', 'KkKk')).to eq @user
end
it 'authenticates a user with correct credentials and spaces after the email' do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.authenticate_with_credentials('[email protected] ', 'KkKk')).to eq @user
end
it 'authenticates a user with correct credentials and wrong case in the email' do
@user = User.create(first_name: 'Sylvia', last_name: 'Almeida', email: '[email protected]', password: 'KkKk', password_confirmation: 'KkKk')
expect(User.authenticate_with_credentials('[email protected]', 'KkKk')).to eq @user
end
end
end
| true
|
eaab523c2a6a08af2d5e3b3e0abe1f35191b55b3
|
Ruby
|
sxua/dynamics
|
/base/templates/patches.rb
|
UTF-8
| 159
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
class Object
def swizzle(method, &block)
self.class.send(:alias_method, "old_#{method.to_s}".to_sym, method)
self.instance_eval &block
end
end
| true
|
7bac051ff65a2d7d30a4aca2db54d9e8454b3727
|
Ruby
|
KoukiKishida/furima-34299
|
/spec/models/product_spec.rb
|
UTF-8
| 4,749
| 2.671875
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe Product, type: :model do
before do
@product = FactoryBot.build(:product)
end
describe '商品出品機能' do
context '商品出品がうまくいくとき' do
it '画像と商品名、商品説明、カテゴリー、商品状態、配送料負担、発送元の地域、発送までの日数、販売価格が存在すれば登録できる' do
expect(@product).to be_valid
end
it '販売価格9,999,999円であれば登録できる' do
@product.price = 9999999
expect(@product).to be_valid
end
end
context '商品出品がうまくいかないとき' do
it '画像が空では登録できない' do
@product.image = nil
@product.valid?
expect(@product.errors.full_messages).to include "Image can't be blank"
end
it '商品名が空では登録できない' do
@product.product_name = ''
@product.valid?
expect(@product.errors.full_messages).to include "Product name can't be blank"
end
it '商品説明が空では登録できない' do
@product.description = ''
@product.valid?
expect(@product.errors.full_messages).to include "Description can't be blank"
end
it '商品のカテゴリー情報が空では登録できない' do
@product.category_id = ''
@product.valid?
expect(@product.errors.full_messages).to include 'Category is not a number'
end
it '商品の状態についての情報が空では登録できない' do
@product.status_id = ''
@product.valid?
expect(@product.errors.full_messages).to include 'Status is not a number'
end
it '配送料の負担についての情報が空では登録できない' do
@product.burden_id = ''
@product.valid?
expect(@product.errors.full_messages).to include 'Burden is not a number'
end
it '発送までの日数についての情報が空では登録できない' do
@product.day_id = ''
@product.valid?
expect(@product.errors.full_messages).to include 'Day is not a number'
end
it '販売価格についての情報が空では登録できない' do
@product.price = ''
@product.valid?
expect(@product.errors.full_messages).to include "Price can't be blank", 'Price is not a number'
end
it '販売価格は、¥300~¥9,999,999の間のみ保存可能である' do
@product.price = 200
@product.valid?
expect(@product.errors.full_messages).to include 'Price must be greater than or equal to 300'
end
it '販売価格は半角数字のみ保存可能である' do
@product.price = '1000'
@product.valid?
expect(@product.errors.full_messages).to include 'Price is not a number'
end
it 'カテゴリー情報は1(---)では登録できない' do
@product.category_id = 1
@product.valid?
expect(@product.errors.full_messages).to include 'Category must be other than 1'
end
it '商品状態情報は1(---)では登録できない' do
@product.status_id = 1
@product.valid?
expect(@product.errors.full_messages).to include 'Status must be other than 1'
end
it '配送負担情報は1(---)では登録できない' do
@product.burden_id = 1
@product.valid?
expect(@product.errors.full_messages).to include 'Burden must be other than 1'
end
it '発送元の地域は1(---)では登録できない' do
@product.prefectures_id = 1
@product.valid?
expect(@product.errors.full_messages).to include 'Prefectures must be other than 1'
end
it '発送までの日数は1(---)では登録できない' do
@product.day_id = 1
@product.valid?
expect(@product.errors.full_messages).to include 'Day must be other than 1'
end
it '金額は半角英数混合では登録できないこと' do
@product.price = '100000'
@product.valid?
expect(@product.errors.full_messages).to include 'Price is not a number'
end
it '金額は半角英数混合では登録できないこと' do
@product.price = 'aaaaaa'
@product.valid?
expect(@product.errors.full_messages).to include 'Price is not a number'
end
it '販売価格は、¥300~¥9,999,999の間のみ保存可能である' do
@product.price = 10000000
@product.valid?
expect(@product.errors.full_messages).to include 'Price must be less than 10000000'
end
end
end
end
| true
|
a49751451b9563bca5f331b007cf9dd57b871674
|
Ruby
|
mikiok/IronHack-Prework
|
/ShoppingCart.rb
|
UTF-8
| 1,022
| 3.75
| 4
|
[] |
no_license
|
class Item
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
class Houseware < Item
end
class Fruit < Item
end
class ShoppingCart
def initialize
@items = []
@articles = 0
end
def add_item(item)
@items.push(item)
@articles += 1
end
def checkout
total_price = 0.00
@items.each do |item|
total_price += item.price
end
if @articles > 5
discount = total_price/10
total_price -= discount
end
total_price
end
end
joshs_cart = ShoppingCart.new
banana = Fruit.new("Banana", 10)
vaccuum = Houseware.new("Vaccuum", 150)
oj = Item.new("Orange Juice", 10)
rice = Item.new("Rice", 1)
anchovies = Item.new("Anchovies", 2)
joshs_cart.add_item(oj)
joshs_cart.add_item(rice)
joshs_cart.add_item(vaccuum)
joshs_cart.add_item(anchovies)
joshs_cart.add_item(banana)
joshs_cart.add_item(rice)
puts joshs_cart.checkout
| true
|
b1f2fead4478c7bef4d04c4ed402ede943b94169
|
Ruby
|
eriksacre/todolist
|
/app/exhibits/exhibit.rb
|
UTF-8
| 2,873
| 2.6875
| 3
|
[] |
no_license
|
class Exhibit < SimpleDelegator
@@exhibits = []
def initialize(model, context)
@context = context
super(model)
end
def self.exhibits
# @@exhibits
[
IncompleteTaskExhibit,
CompleteTaskExhibit,
TaskListExhibit,
ActivitiesExhibit,
ActivityExhibit,
EnumerableExhibit
]
end
def self.inherited(child)
@@exhibits << child
end
def self.exhibit(object, context=nil)
return object if exhibited_object?(object)
exhibits.inject(object) do |object, exhibit|
exhibit.exhibit_if_applicable(object, context)
end
end
def self.exhibit_if_applicable(object, context)
if applicable_to?(object)
new(object, context)
else
object
end
end
def self.applicable_to?(object)
false
end
def self.exhibited_object?(object)
object.respond_to?(:exhibited?) && object.exhibited?
end
def self.exhibit_query(*method_names)
method_names.each do |name|
define_method(name) do |*args, &block|
exhibit(super(*args, &block))
end
end
end
private_class_method :exhibit_query
def self.object_is_any_of?(object, *classes)
# What with Rails development mode reloading making class matching
# unreliable, plus wanting to avoid adding dependencies to
# external class definitions if we can avoid it, we just match
# against class/module name strings rather than the actual class
# objects.
# Note that '&' is the set intersection operator for Arrays.
(classes.map(&:to_s) & object.class.ancestors.map(&:name)).any?
end
private_class_method :object_is_any_of?
def self.find_definitions(definition_file_paths)
absolute_definition_file_paths = definition_file_paths.map {|path| File.expand_path(path) }
absolute_definition_file_paths.uniq.each do |path|
load("#{path}.rb") if File.exists?("#{path}.rb")
if File.directory? path
Dir[File.join(path, '**', '*.rb')].sort.each do |file|
load file if !file.end_with?("/exhibit.rb")
end
end
end
end
def exhibit(model)
Exhibit.exhibit(model, @context)
end
def render(template)
template.render(:partial => to_partial_path, :object => self)
end
def to_partial_path
if __getobj__.respond_to?(:to_partial_path)
__getobj__.to_partial_path
else
partialize_name(__getobj__.class.name)
end
end
def to_model
__getobj__
end
def class
__getobj__.class
end
def kind_of?(klass)
__getobj__.kind_of?(klass)
end
def instance_of?(klass)
__getobj__.instance_of?(klass)
end
# def is_a?(klass)
# __getobj__.is_a?(klass)
# end
def exhibited?
true
end
private
def partialize_name(name)
"/#{name.underscore.pluralize}/#{name.demodulize.underscore}"
end
end
| true
|
adce6669216a4f1193f1f543e83b5a3aeb30e8bb
|
Ruby
|
chrisdel101/object_oriented_programming
|
/paperboy.rb
|
UTF-8
| 917
| 3.65625
| 4
|
[] |
no_license
|
class Paperboy
attr_reader :earnings
attr_reader :experience
def initialize(name, side)
@name = name
@experience = 0
@side = side
@earnings = 0
end
def quota
(@experience * 0.5) + 50
end
#
def deliver(end_address, start_address)
houses = ((end_address.to_f - start_address + 1) / 2)
if @side == "odd"
houses = houses.ceil
else @side == "even"
houses = houses.floor
end
if houses > quota
money_made = (quota * 0.25) + ((houses - quota) * 0.50)
else
money_made = houses * 0.25
end
if houses < quota
money_made -= 2
end
@earnings += money_made
@experience += houses
return money_made
end
end
def report
return "I'm #{name} and I delivered #{experience} paper and made #{earnings}."
#
#
# def report
# puts "I am #{name} and I have made #{earnings}"
# end
# end
# # end
| true
|
354cae7d03d6e7dff5037fbaf6bc17607522c412
|
Ruby
|
trizen/sidef
|
/scripts/RosettaCode/haversine_formula.sf
|
UTF-8
| 837
| 3.671875
| 4
|
[
"Artistic-2.0"
] |
permissive
|
#!/usr/bin/ruby
#
## http://rosettacode.org/wiki/Haversine_formula
#
class EarthPoint(lat, lon) {
const earth_radius = 6371 # mean earth radius
const radian_ratio = Num.pi/180
# accessors for radians
method latR { self.lat * radian_ratio }
method lonR { self.lon * radian_ratio }
method haversine_dist(EarthPoint p) {
var arc = __CLASS__(
self.lat - p.lat,
self.lon - p.lon,
)
var a = [ pow(sin(arc.latR / 2), 2),
pow(sin(arc.lonR / 2), 2) *
cos(self.latR) * cos(p.latR),
].sum
earth_radius * asin(sqrt(a)) * 2
}
}
var BNA = EarthPoint.new(lat: 36.12, lon: -86.67)
var LAX = EarthPoint.new(lat: 33.94, lon: -118.4)
say BNA.haversine_dist(LAX) # => 2886.444442837983299747157823945...
| true
|
255aa88d64993ff5cf4218ab64a0fdeb42e46360
|
Ruby
|
mrtbld/practice
|
/advent-of-code/2018/day4/part_one.rb
|
UTF-8
| 136
| 2.625
| 3
|
[] |
no_license
|
require_relative 'common.rb'
input = File.readlines('input')
guard_id, minute = find_sleepy_guard(input, &:sum)
puts guard_id * minute
| true
|
52918a460b07ccf6d7da481deca9ce81029d4eec
|
Ruby
|
monochromegane/pendulum
|
/lib/pendulum/command/apply.rb
|
UTF-8
| 848
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
module Pendulum::Command
class Apply
attr_accessor :client, :dry_run, :force
def initialize(client, from, to, dry_run=false, force=false, color=false)
@schedules = matched_schedules(client, from, to, dry_run, force, color)
end
def execute
@schedules.each{|s| s.apply }
end
private
def matched_schedules(client, from, to, dry_run, force, color)
# create or update
schedules = to.map do |schedule|
Schedule.new(
client,
from.find{|f| f.name == schedule.name},
schedule,
dry_run,
force,
color
)
end
# delete
from.reject{|f| to.any?{|t| t.name == f.name}}.each do |schedule|
schedules << Schedule.new(client, schedule, nil, dry_run, force, color)
end
schedules
end
end
end
| true
|
4fc26eee5f67c7603b8b104a5561e008ce62cbd4
|
Ruby
|
tim-group/Blondin
|
/saturation-test/test.rb
|
UTF-8
| 505
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
require "net/http"
THREAD_POOL = []
def for_all_threads(&blk)
100.times { THREAD_POOL << Thread.new(&blk) }
end
def request(path)
http = Net::HTTP.new("localhost", 8082)
http.read_timeout = 500
response = http.get(path)
print '.'
if response.code != '200'
puts "Failed. Response was #{response.code}"
exit 1
end
end
print 'Testing'
for_all_threads { request("/slow") }
for_all_threads { 10.times { request("/fast") } }
THREAD_POOL.each { |thread| thread.join }
puts "Passed"
| true
|
6ff1601782854f0f5a9ff3265bab3156a0212d96
|
Ruby
|
vmar13/ruby-enumerables-generalized-map-and-reduce-lab-nyc-web-021720
|
/lib/my_code.rb
|
UTF-8
| 368
| 3.5
| 4
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def map(array)
new_array = []
counter = 0
while counter < array.length
new_array.push(yield(array[counter]))
counter += 1
end
new_array
end
def reduce(array, starting_value=nil)
if starting_value
sum = starting_value
i = 0
else
sum = array[0]
i = 1
end
while i < array.length
sum = yield(sum, array[i])
i += 1
end
sum
end
| true
|
bfdb9d2b5e6e452bd415d4e3fa87c69cc3220440
|
Ruby
|
panteha/Makersbnb
|
/spec/booking_spec.rb
|
UTF-8
| 1,230
| 2.53125
| 3
|
[] |
no_license
|
require_relative '../app/models/booking.rb'
require_relative '../app/models/pendingbooking.rb'
describe Booking do
it 'makes a new booking in the bookings database table' do
space = double(:space, id: 1, available_from: Date.parse('01-06-2017'), available_to: Date.parse('02-06-2017'), save_parents: true, save_self: true)
expect { Booking.make_bookings(Date.parse('01-06-2017'), Date.parse('02-06-2017'), space, 'bob', 'dave') }.to change{ Booking.count }.by(2)
# space = instance_double(Space, id: 1, name: "House", description: "nice", price: "1", available_from:'01-06-17', available_to:'30-06-17', owner: "colin" )
end
end
describe Pendingbooking do
it 'makes a new booking in the pending bookings database table' do
space = double(:space, id: 1, available_from: Date.parse('01-06-2017'), available_to: Date.parse('02-06-2017'), save_parents: true, save_self: true)
expect { Pendingbooking.make_bookings(Date.parse('01-06-2017'), Date.parse('02-06-2017'), space, 'bob', 'dave') }.to change{ Pendingbooking.count }.by(2)
# space = instance_double(Space, id: 1, name: "House", description: "nice", price: "1", available_from:'01-06-17', available_to:'30-06-17', owner: "colin" )
end
end
| true
|
289029cf700564ef4ebe7a5dff3e74bebb1bc709
|
Ruby
|
ziruinyc/countdown-to-midnight-001-prework-web
|
/countdown.rb
|
UTF-8
| 281
| 3.8125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#write your code here
def countdown(counter)
while counter > 0 do
puts "#{counter} SECOND(S)!"
counter -= 1
end
"HAPPY NEW YEAR!"
end
def countdown_with_sleep(time)
while time > 0 do
puts "#{time} SECOND(S)!"
sleep(10)
time -= 10
end
"HAPPY NEW YEAR!"
end
| true
|
3db32f98990c00d1eb08edb3a6fd17f58a7128e2
|
Ruby
|
sbonds/ruby-learning
|
/head first ruby/11 Documentation/pool puzzle.rb
|
UTF-8
| 430
| 4.21875
| 4
|
[] |
no_license
|
array = [10, 5, 7, 3, 9]
first = array.shift
puts "We pulled #{first} off the start of the array."
last = array.pop
puts "We pulled #{last} off the end of the array."
largest = array.max
puts "The largest remaining number is #{largest}."
=begin
Output goal:
We pulled 10 off the start of the array.
We pulled 9 off the end of the array.
The largest remaining number is 7.
Pool:
clear
lazy
uniq
cycle
reverse
shuffle
=end
| true
|
027e8b643adbbd1257a183417386177705f644fd
|
Ruby
|
HoustonRaboni/first
|
/game1.rb
|
UTF-8
| 1,256
| 4.59375
| 5
|
[] |
no_license
|
# get my number game
# written by me
puts "welcome to \'GET MY NUMBER !\'"
#get the player name and greet him
print "what's your name: "
input = gets
name = input.chomp #is great for cleaning up string return from gets()
puts "welcome #{name}!"
=begin
puts name.inspect
p name
puts 42.methods
puts 42.enum_for
puts "hello".methods
puts 42.class
puts "hello".class
puts true.class
=end
#store a random number for the player to guess
puts "i got a random number between 1 - 100"
puts "can you guess it?"
target = rand(100) + 1
#track how many guesses the player have left
num_guesses = 0
#track whether the player has guessed correctly
guessed_it = false
puts "you 've got #{10 - num_guesses} guesses left'"
puts "make a guess"
guess = gets.to_i
#compare the guess to the target
# print the appropriate message
if guess < target
puts "oops your guess was too low"
elsif guess > target
puts "oops your guess was HIGH"
elsif guess == target
puts "good job #{name}!"
puts "your guessed my number in #{num_guesses} guesses!"
guessed_it = true
end
# if player ran out of turns, tell them what the number is
unless not guessed_it
puts "sorry. you didn't get my number. (it was #{target}.)"
end
| true
|
b8e108daebbe6bcaa9856ece6a5fdd3768654b2f
|
Ruby
|
elijahkim/Metis-Prework
|
/bottles_of_beer_recursive.rb
|
UTF-8
| 242
| 3.640625
| 4
|
[] |
no_license
|
def bottles amt
puts "#{amt} of beer on the wall"
puts "#{amt} of beer!"
puts "take one down, pass it around"
puts "#{amt-1} bottles of beer on the wall!"
puts
if amt>0
bottles (amt-1)
end
end
bottles gets.chomp.to_i
| true
|
e0bd2b4c42705e1719208a9fd1614d1e7e5115f6
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/grains/b807b46a29584a9f9969d7b36d295f70.rb
|
UTF-8
| 328
| 3.453125
| 3
|
[] |
no_license
|
# Clase de granos por cada cuadro en un ajedrez
class Grains
attr_reader :total_cuadros
def initialize
@total_cuadros = 64
end
# Potencia de 2 a la n-1
def square(num_cuadro)
2**(num_cuadro - 1)
end
# Total
def total
@total_cuadros.times do |i|
self.total_granos += square(i)
end
end
end
| true
|
6d03b0d7d7c0d63b5569f68cf3038ebf349ec51b
|
Ruby
|
ma-v/rutabaga_extension
|
/Le_Wagon_Lectures/Week2/Day2/demo_parsing.rb
|
UTF-8
| 331
| 2.546875
| 3
|
[] |
no_license
|
require 'open-uri'
require 'nokogiri'
ingredient = 'lemon'
url = "http://www.letscookfrench.com/recipes/find-recipe.aspx?s=#{ingredient}"
html_file = open(url).read
html_doc = Nokogiri::HTML(html_file)
html_doc.search('.m_titre_resultat a').each do |element|
puts element.text.strip
puts element.attribute('href').value
end
| true
|
27510b8f95e936c87a754b979fd983b51f8fe830
|
Ruby
|
dainiusjocas/labs
|
/IV_semester/ruby/learning_app/spec/models/exam_spec.rb
|
UTF-8
| 3,100
| 2.828125
| 3
|
[
"Beerware"
] |
permissive
|
require File.dirname(__FILE__) + '/../spec_helper'
describe Exam do
fixtures :users
fixtures :words
fixtures :exams
fixtures :scores
describe Exam, " validations/associations" do
it { should validate_presence_of :title }
it { should have_many :tags }
it { should have_many :scores }
it { should belong_to :user }
end
describe Exam, " taking and calculating statistics" do
before do
@predicate = Proc.new {|word, answer| word.value == answer }
end
it "should return score 1 if all answers are correct" do
exams(:one).take(@predicate) {|w| w.value }.should == 1
end
it "should return score 0 if all answers are incorrect" do
exams(:one).take(@predicate) {|w| w.translation }.should == 0
end
it "should return a float number between 0 and 1 with maximum two decimal places as score" do
i = 0
# we should answer 1 word out of 3 by this algorithm
exams(:one).take(@predicate) do |w|
i += 1
if i == 1
w.value
else
w.translation
end
end.should have_valid_format
end
it "should know how many times it was taken" do
scores_size = exams(:one).scores.size
lambda {
exams(:one).take(@predicate) { |w| w.translation }.should == 0
}.should change { exams(:one).scores(true).size }.from(scores_size).to(scores_size + 1)
end
it "should reset its scoring history" do
scores_size = exams(:one).scores.size
lambda {
exams(:one).reset_scores
}.should change { exams(:one).scores(true).size }.from(scores_size).to(0)
end
it "should know its average score rating" do
exams(:one).average_score.should == 0.52
end
it "should have averago score 0 if it hasn't been taken yet" do
exams(:three).average_score.should == 0
end
it "should return its average score as a float number between 0 and 1 and with maximum two decimal places as score" do
2.times { exams(:one).take(@predicate) { |w| w.value }}
exams(:one).take(@predicate) { |w| w.translation }
exams(:one).average_score.should have_valid_format
end
it "should find its last score" do
scores(:average).created_at = Time.new.tomorrow.to_s(:db)
scores(:average).save
exams(:one).last_score.should === scores(:average)
end
describe Exam, " counting inactivity time" do
before do
last_score = Score.new
last_score.stubs(:created_at).returns("2010-04-28 22:25:59")
exams(:one).stubs(:last_score).returns(last_score)
end
it "should know time in hours since last taking" do
exams(:one).hours_from_last_taking_to("2010-04-29 01:25:59").should == 3
end
it "should return 2 if 1.5h have passed" do
exams(:one).hours_from_last_taking_to("2010-04-28 23:56:59").should == 2
end
it "should raise an exception if given date is earlier" do
lambda {
exams(:one).hours_from_last_taking_to("2010-04-28 20:56:59") }.should raise_error
end
end
end
end
| true
|
16e50e0f168fd776854eb492cd13eaf80e24a566
|
Ruby
|
aswilliamson19/Week2_day4_Library-lab
|
/specs/book_spec.rb
|
UTF-8
| 266
| 2.734375
| 3
|
[] |
no_license
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../book')
class BookTest < MiniTest::Test
def setup
@book1 = Book.new('2001: A Space Odyssey')
end
def test_book_name
assert_equal('2001: A Space Odyssey', @book1.name)
end
end
| true
|
87e5c5c98179ba9c6e401ae12aba9e4c34364416
|
Ruby
|
moj-analytical-services/tech-docs-gem
|
/lib/govuk_tech_docs/table_of_contents/heading_tree_builder.rb
|
UTF-8
| 844
| 3.03125
| 3
|
[
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
module GovukTechDocs
module TableOfContents
class HeadingTreeBuilder
def initialize(headings)
@headings = headings
@tree = HeadingTree.new
@pointer = @tree
end
def tree
@headings.each do |heading|
move_to_depth(heading.size)
@pointer.children << HeadingTree.new(parent: @pointer, heading: heading)
end
@tree
end
private
def move_to_depth(depth)
if depth > @pointer.depth
@pointer = @pointer.children.last
if depth > @pointer.depth
@pointer.children << HeadingTree.new(parent: @pointer)
move_to_depth(depth)
end
end
if depth < @pointer.depth
@pointer = @pointer.parent
move_to_depth(depth)
end
end
end
end
end
| true
|
a834142cfb8f29ac1978126204651f99921981c7
|
Ruby
|
fiery-skippers-2014/Kitter
|
/app/helpers/user.rb
|
UTF-8
| 421
| 2.75
| 3
|
[] |
no_license
|
helpers do
def authenticate(user_name)
user = User.find_by_user_name(user_name)
if user != nil
return true
else
return false
end
end
def time_since_tweet(time_stamp)
minutes = ((Time.now - time_stamp)/60).round
if minutes < 1440
time_stamp.strftime("Posted at %I:%M%p")
else
time_stamp.strftime("Posted on %m/%d/%Y at %I:%M%p")
end
end
end
| true
|
ac2ffd58a61d2f3b8f37b2d86d46d8e0a03b7823
|
Ruby
|
DavidAMAnderson/student-directory
|
/directory.rb
|
UTF-8
| 1,757
| 4.3125
| 4
|
[] |
no_license
|
def input_students
puts "Please enter the names of your students"
puts "To finish, just hit return twice"
students = []
name = gets.chomp
while !name.empty? do
students << {name: name, cohort: :november}
puts "Now we have #{students.count} students"
name = gets.chomp
end
students
end
def print_header
puts "The students of Villains Academy"
puts "-------------"
end
def print(students)
students.each do |student|
puts "#{student[:name]} (#{student[:cohort]} cohort)"
end
end
def print_first_letter(students,letter)
students.each_with_index do |student, i|
if student[:name][0].downcase == letter.downcase
puts "Names begining with #{letter} are..."
puts "#{i+1}.#{student[:name]} (#{student[:cohort]} cohort)"
end
end
end
def print_name_length(students,length)
students.each_with_index do |student, i|
if student[:name].length <= length
puts "Names shorter than #{length} characters are..."
puts "#{i+1}.#{student[:name]} (#{student[:cohort]} cohort)"
end
end
end
def interactive_menu
students = []
loop do
# 1. print the menu and ask the user what to do
puts "1. Input the students"
puts "2. Show the students"
puts "9. Exit"
# 2. read the input and save it into a variable
selection = gets.chomp
# 3. do what the user has asked
case selection
when "1"
students = input_students
when "2"
print_header
print(students)
print_footer(students)
when "9"
exit
else puts "I don't know what you mean, try again"
end
end
end
def print_footer(students)
puts "Overall, we have #{students.count} great students"
end
#nothing happens until we call the methods
interactive_menu
| true
|
f912f86a62c7c75731b891ef919b39e2a1d3bf92
|
Ruby
|
ohnickmoy/ruby-enumerables-cartoon-collections-lab-nyc-web-100719
|
/cartoon_collections.rb
|
UTF-8
| 531
| 3.421875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
def roll_call_dwarves(array)
array.each_with_index { |item, index| puts "#{index + 1}. #{item}" }
end
def summon_captain_planet(planeteer)
planeteer.map { |call| call.capitalize + "!" }
end
def long_planeteer_calls(calls)
longFlag = false
calls.map { |x| if x.length > 4 then longFlag = true end }
longFlag
end
def find_the_cheese(strArr)
# the array below is here to help
cheese_types = ["cheddar", "gouda", "camembert"]
strArr.map { |food| if cheese_types.include?(food) then return food end}
return nil
end
| true
|
6589214ff763c8d9d8cd054dd69ebbd4c11a2882
|
Ruby
|
hightower86/tn_lessons
|
/Lesson_09/route.rb
|
UTF-8
| 844
| 3.375
| 3
|
[] |
no_license
|
require_relative 'validation'
require_relative 'modules'
require_relative 'station'
class Route
include InstanceCounter, Validation
attr_reader :route
# attr_accessor :start_station, :end_station
validate :start_station, :presence, Station
validate :end_station, :type, Station
def initialize(start_station, end_station)
# @start_station = start_station
# @end_station = end_station
validate!
@route = [start_station, end_station]
register_instance
end
def title
"#{route.first.title} - #{route.pop.title}"
end
def add_station(station)
@route.insert(-2, station)
end
def del_station(station)
raise "Станции #{station} нет в маршруте!" unless @route.include?(station)
@route.delete(station)
end
def station_list
@route.each { |e| puts e }
end
end
| true
|
bbb3ed453b73ba8511f9bb6cc0c56b9323fe8389
|
Ruby
|
rocky/rbx-trepanning
|
/test/unit/test-app-iseq.rb
|
UTF-8
| 1,667
| 2.71875
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'test/unit'
require 'rubygems'; require 'require_relative'
require_relative '../../app/iseq'
class TestAppISeq < Test::Unit::TestCase
def test_disasm_prefix
meth = Rubinius::VM.backtrace(0, true)[0].method
assert_equal(' -->', Trepan::ISeq.disasm_prefix(0, 0, meth))
assert_equal(' ', Trepan::ISeq.disasm_prefix(0, 1, meth))
meth.set_breakpoint(0, nil)
assert_equal('B-->', Trepan::ISeq.disasm_prefix(0, 0, meth))
assert_equal('B ', Trepan::ISeq.disasm_prefix(0, 1, meth))
end
def test_basic
def single_return
cm = Rubinius::VM.backtrace(0, true)[0].method
last = cm.lines.last
first = 0
0.upto((cm.lines.last+1)/2) do |i|
first = cm.lines[i*2]
break if -1 != first
end
[last, Trepan::ISeq.yield_or_return_between(cm, first, last)]
end
def branching(bool)
cm = Rubinius::VM.backtrace(0, true)[0].method
last = cm.lines.last
first = nil
0.upto((cm.lines.last+1)/2) do |i|
first = cm.lines[i*2]
break if -1 != first
end
if bool
x = 5
else
x = 6
end
Trepan::ISeq.goto_between(cm, first, last)
end
def no_branching
cm = Rubinius::VM.backtrace(0, true)[0].method
last = cm.lines.last
first = 0
0.upto((cm.lines.last+1)/2) do |i|
first = cm.lines[i*2]
break if -1 != first
end
Trepan::ISeq.goto_between(cm, first, last)
end
last, return_ips = single_return
assert_equal([last-1], return_ips)
assert_equal(-2, no_branching)
assert_equal(2, branching(true).size)
end
end
| true
|
92f1d4dfbc8dc03c74d401e266f2fde562bccd9e
|
Ruby
|
masterkain/rmega
|
/lib/rmega/progress.rb
|
UTF-8
| 1,006
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
module Rmega
class Progress
def initialize(params)
@total = params[:total]
@caption = params[:caption]
@bytes = 0
@start_time = Time.now
show
end
def show
percentage = (100.0 * @bytes / @total).round(2)
message = "[#{@caption}] #{humanize(@bytes)} of #{humanize(@total)}"
if ended?
message << ". Completed in #{elapsed_time} sec.\n"
else
message << " (#{percentage}%)"
end
blank_line = ' ' * (message.size + 15)
print "\r#{blank_line}\r#{message}"
end
def elapsed_time
(Time.now - @start_time).round(2)
end
def ended?
@total == @bytes
end
def increment(bytes)
@bytes += bytes
show
end
def humanize(bytes, round = 2)
units = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']
e = (bytes == 0 ? 0 : Math.log(bytes)) / Math.log(1024)
value = bytes.to_f / (1024 ** e.floor)
"#{value.round(round)} #{units[e]}"
end
end
end
| true
|
ee9d0997b4634019423be694b45237f6984640d5
|
Ruby
|
aceimdevelopment/aceim
|
/config/initializers/string.rb
|
UTF-8
| 565
| 3.140625
| 3
|
[] |
no_license
|
#encoding: utf-8
class String
def normalizar
string = self.strip.gsub(" ","")
string = self.strip.gsub("'","")
string = string.gsub("á","a")
string = string.gsub("é","e")
string = string.gsub("í","i")
string = string.gsub("ó","o")
string = string.gsub("ú","u")
string = string.gsub("ñ","n")
string = string.gsub("Á","a")
string = string.gsub("É","e")
string = string.gsub("Í","i")
string = string.gsub("Ó","o")
string = string.gsub("Ú","u")
string = string.gsub("Ń","n")
string
end
end
| true
|
5a39f9538b753a819b6b6f70c3a8c57b24ed0d8b
|
Ruby
|
juanmaberrocal/wkndr-cr
|
/app/helpers/controller_error_response_helper.rb
|
UTF-8
| 690
| 2.734375
| 3
|
[] |
no_license
|
module ControllerErrorResponseHelper
# build all error responses the same way
def build_error_response(messages, status=:unprocessable_entity)
# return json { errors: [messages] }, status: :code
render json: { errors: flatten_messsages(messages) }, status: check_status_code(status)
end
private
# ensure error messages are in a 1D array
def flatten_messsages(messages)
Array(messages).flatten
end
# ensure status passed is an error code
def check_status_code(status)
case status
when :bad_request, :forbidden, :not_found, :method_not_allowed, :unprocessable_entity
status
else
# by default use unprocessable_entity
:unprocessable_entity
end
end
end
| true
|
f8e7ce0294aa1cc65981097c61c41c1a447a5c76
|
Ruby
|
RudeWalrus/git-hub-gist-adder
|
/lib/gistfile.rb
|
UTF-8
| 391
| 3.03125
| 3
|
[] |
no_license
|
class GistFile
def initialize(file_array)
@file_array = file_array
end
def file_name
p @file_array.first
@file_array.first.keys.first
end
def content
@file_array.first['test_file']['content']
end
def ==(other)
if other.class != self.class
false
else
self.file_name == other.file_name && self.content == other.content
end
end
end
| true
|
09569bb203b4e7444cdea91e7b930e7ee46f2796
|
Ruby
|
thomasrogers03/cassandra_model
|
/lib/cassandra_model/v2/read_query.rb
|
UTF-8
| 2,153
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
module CassandraModel
module V2
class ReadQuery
attr_reader :column_names, :hash
def initialize(table, select_columns, restrict_columns, order, limit)
@table_name = table.name
@select_columns = select_columns
@column_names = @select_columns.any? ? @select_columns : table.columns.map(&:name)
@restrict_columns = restrict_columns
@order = order
@limit = limit
@hash = [@table_name, @select_columns, @restrict_columns, @order, @limit].map(&:hash).reduce(&:+)
end
def select_clause
"SELECT #{select_columns_clause} FROM #{@table_name}"
end
def restriction_clause
" WHERE #{restriction}" if @restrict_columns.any?
end
def ordering_clause
" ORDER BY #{@order * ','}" if @order.any?
end
def limit_clause
' LIMIT ?' if @limit
end
def eql?(rhs)
rhs.table_name == table_name &&
rhs.select_columns == select_columns &&
rhs.restrict_columns == restrict_columns &&
rhs.order == order &&
rhs.limit == limit
end
def to_s
"#{select_clause}#{restriction_clause}#{ordering_clause}#{limit_clause}"
end
protected
attr_reader :table_name, :select_columns, :restrict_columns, :order, :limit
private
def restriction
@restrict_columns.map do |column|
column = key_comparer(column) unless column.is_a?(ThomasUtils::KeyComparer)
column_restriction(column)
end * ' AND '
end
def column_restriction(column)
column.key.is_a?(Array) ? range_restriction(column) : single_column_restriction(column)
end
def key_comparer(column)
column.is_a?(Array) ? ThomasUtils::KeyComparer.new(column, 'IN') : column.to_sym.eq
end
def single_column_restriction(column)
"#{column} ?"
end
def range_restriction(column)
"#{column} (#{%w(?) * column.key.count * ','})"
end
def select_columns_clause
@select_columns.any? ? @select_columns * ',' : '*'
end
end
end
end
| true
|
9e19a4f264f8ab6a983c5c3854a1692a4f94ef90
|
Ruby
|
srobert1953/introduction-to-programming
|
/flow_control/conditionals2.rb
|
UTF-8
| 992
| 4.28125
| 4
|
[] |
no_license
|
# cnoditionals2.rb
# more conditionals
# puts "Is it 3 or 25?"
# input = gets.chomp.to_i
# if input == 3
# puts "3? you're the boss!"
# elsif input == 25
# puts "That's right, 25 it is."
# else
# puts "Awhh... you don't listen..."
# puts "Let's try again... 3 or 25?"
# input2 = gets.chomp.to_i
# if input2 == 3
# puts "3? you are the boss!"
# elsif input2 == 25
# puts "That's right, 25 it is."
# else
# puts "You should stop playing now..."
# puts "Because I'd to do this all my life :/"
# end
# end
def three_twentyfive(number)
if number == 3
puts "3? you're the boss!"
elsif number == 25
puts "That's right, 25 it is."
else
puts "Awhh... you don't listen..."
return false
end
end
puts "What number are you, 3 or 25?"
number = gets.chomp.to_i
if three_twentyfive(number)
puts "Thank you for playing"
else
puts "You have only 2 options, please choose wisely... "
number = gets.chomp.to_i
three_twentyfive(number)
end
| true
|
ee0f2690f3f376ce8769073d0055d7b62bee199b
|
Ruby
|
hotsdm/Python_ruby
|
/Container_loop/1.rb
|
UTF-8
| 101
| 2.8125
| 3
|
[] |
no_license
|
members = ['SDM', 'Single']
i = 0
while i < members.length do
puts(members[i])
i = i + 1
end
| true
|
21068183b6cb6ddf396e4eab4f91d93cb1c0a928
|
Ruby
|
vzaffalon/account_movement_challenge
|
/csv_importer.rb
|
UTF-8
| 3,027
| 3.28125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'csv'
require 'redis'
@redis = nil
@accounts_csv = nil
@transactions_csv = nil
@parsed_accounts_csv = nil
@parsed_transactions_csv = nil
class String
def is_number?
true if Integer(self)
rescue StandardError
false
end
end
def receive_args
if ARGV[0].nil? || ARGV[1].nil?
raise StandardError, '-- Error: Você precisa passar dois arquivos como parametro, o primeiro parâmetro deve ser um arquivo de contas e o segundo de transações'
end
end
def create_redis_instance
puts
puts 'Instanciando redis..'
@redis = Redis.new(host: '127.0.0.1', port: 6380) # host e porta do redis no docker
@redis.flushall
end
def open_csv_files
puts
puts 'Abrindo arquivos csv..'
begin
@accounts_csv = File.read(ARGV[0])
@transactions_csv = File.read(ARGV[1])
rescue StandardError => e
raise StandardError, '-- Error: Programa não conseguiu ler os arquivos!'
end
end
def parse_csvs
puts
puts 'Fazendo o parse dos arquivos csv..'
begin
@parsed_accounts_csv = CSV.parse(@accounts_csv, headers: false, skip_blanks: true)
@parsed_transactions_csv = CSV.parse(@transactions_csv, headers: false, skip_blanks: true)
rescue StandardError => e
raise StandardError, '-- Error: Não conseguiu fazer o parse dos arquivos csv!'
end
end
def create_accounts
puts
puts 'Criando contas..'
@parsed_accounts_csv.each do |row|
account_id = row[0]
amount = row[1]
if account_id&.is_number? && amount && amount.is_number?
account_exists = @redis.get(account_id)
if !account_exists
@redis.set(account_id, amount.to_i)
else
raise StandardError, "-- Error: Csv mal formatado! Conta (#{account_id}) duplicada!"
end
else
raise StandardError, '-- Error: Csv mal formatado! Colunas devem ser números inteiros!'
end
end
end
def create_transactions
puts
puts 'Criando transações..'
@parsed_transactions_csv.each do |row|
account_id = row[0]
amount = row[1]
if account_id&.is_number? && amount && amount.is_number?
account_amount = @redis.get(account_id)
if account_amount
amount = amount.to_i
current_amount = @redis.get(account_id).to_i
current_amount += amount
current_amount -= 300 if (current_amount < 0) && (amount < 0)
@redis.set(account_id, current_amount.to_s)
else
raise StandardError, "-- Error: Csv mal formatado! Conta (#{account_id}) não existente!"
end
else
raise StandardError, '-- Error: Csv mal formatado! Colunas devem ser números inteiros!'
end
end
end
def output_result
puts
puts 'Resultado das transações:'
puts
@redis.keys.each do |key, _value|
puts 'Id da conta: ' + key
puts format('Saldo final: R$ %.2f', (@redis.get(key).to_f / 100.0))
puts
end
end
begin
receive_args
create_redis_instance
open_csv_files
parse_csvs
create_accounts
create_transactions
output_result
rescue StandardError => e
puts e
end
| true
|
33f40c3c91b7ac61e28d8765be25b3b114fe5f6d
|
Ruby
|
MBARI-ESP/ESP2Gmisc
|
/ruby/sourceref.rb
|
UTF-8
| 10,861
| 3.046875
| 3
|
[] |
no_license
|
################## sourceref.rb -- [email protected] #####################
# $Source$
# $Id$
#
# The SourceRef class relies on a patched version of ruby/eval.c
# to provide access to the source file and line # where every Method
# or Proc is defined. SourceRef is a container for these and implements
# methods to:
#
# list source code to stdout,
# view source code in an editor,
# edit source code
# reload source code
#
# This file also adds methods to Object and Module to list, view,
# edit, and reload methods and modules as a convenience.
#
# Examples:
# SourceRef.instance_method(:list).source ==> ./sourceref.rb:47
# SourceRef.instance_method(:list).edit ==> opens an editor window
# (SourceRef/:list).edit ==> opens same window
# SourceRef.source[:list].view ==> opens same window r/o
# Date.edit ==> edits all files that define methods in class Date
# Date.source ==> returns hash of Date methods to SourceRefs
# puts Date.source.join ==> display Data methods with SourceRefs
# Date.sources ==> returns the list of files containing Date methods
# Date.reload ==> (re-)loads Date.sources
#
# With a version of irb.rb modified to store the last backtrace,
# the following features are available at the irb prompt:
#
# list|edit|view|reload Module|Method|Integer|Symbol|Exception|String|Thread
#
# Module operates on the list of files that comprise the Module
# Method operates on the text of the Method
# Integer n operates on the most recent backtrace at level n
# Symbol :sym searches backtrace for level corresponding to :sym
# Exception operates on the source where the exception occured
# String fn:nnn operates on file "fn" at line nnn
# no argument is equivalent to backtrace level 0
# Thread operates on that thread's most recent exception
#
############################################################################
class String
def to_srcRef
# parse a source reference from string of form fn:line#
strip!
a = split(':')
return SourceRef.new(self, 0) if a.length < 2
sym=nil
if a.length > 2 and a[-1][0,3] == 'in '
s=a.pop
s=s[4,s.length-5]
s="" unless s
sym=s.intern
end
SourceRef.new(a[0..-2].join(':'), a[-1].to_i, sym)
end
end
class Exception
def to_srcRef(levelOrMethod=0)
# default given any exception the best guess as to its location
SourceRef.from_back_trace(backtrace, levelOrMethod)
end
alias_method :[], :to_srcRef
def rootCause
# define as a NOP so subclasses can override
self
end
end
class SyntaxError < ScriptError
# Decode the Source Ref from a compiler error message
def to_srcRef(level=nil)
return super(level) if level
to_s.split("\s",2)[0].to_srcRef
end
end
class SourceRef #combines source file name and line number
def initialize(file_name, line=nil, symbol=nil)
raise ArgumentError, "missing source file reference" unless @file=file_name
@line = line
@symbol = symbol
end
attr_reader :file, :line, :symbol
def to_s
return file unless line and line>0
return file+':'+line.to_s unless symbol
file+':'+line.to_s+':in `'+symbol.to_s+"'"
end
def to_srcRef
self
end
def list(lineCount=20, lineOffset=0)
# return the next lineCount lines of source text
# or "" if no source is available
text = ""; lineno=0
firstLine=line || 1
begin
File.open(file) {|f|
2.upto(firstLine+lineOffset) { f.readline; lineno+=1 }
1.upto(lineCount) { text << f.readline; lineno+=1 }
}
rescue EOFError # don't sweat EOF unless its before target line #
if lineno < firstLine
raise $!,"Truncated ruby source file: #{self}"
end
rescue Errno::ENOENT
raise $!,"Missing ruby source: #{self}"
end
text.chomp!
end
class <<@@remoteStub = Object.new
def system localCmd
Kernel.system(localCmd)
end
def remap localPath
localPath
end
end
@@remote = @@remoteStub unless defined? @@remote
def self.remote= remoteObject
# configure SourceRef for remote editting
# remoteObject must implement remap to convert pathnames and
# must implement the method :system(string) similar to Kernel::system
@@remote = remoteObject || @@remoteStub
end
def self.remote
@@remote
end
def sys os_cmd
@@remote.system os_cmd
end
private :sys
def edit(options=nil, readonly=false)
# start an editor session on file at line
# If X-windows display available, try nedit client, then nedit directly
hasLine=line && line>1
if disp=ENV["DISPLAY"]
path = @@remote.remap(File.expand_path(file))
if disp.length>1
neditArgs = "-lm Ruby "
neditArgs<< "-read " if readonly
neditArgs<< "-line #{line} " if hasLine
neditArgs<<"#{options} " if options
return self if sys( <<-END
PATH=~/bin:$PATH nohup redit #{neditArgs} "#{path}">/dev/null 2>&1 ||
NeditArgs="#{neditArgs}" Nedit \"#{path}\">/dev/null 2>&1 ||
nedit #{neditArgs} \"#{path}\" &
END
)
end
return self if
sys("TERM=#{ENV["TERM"]} nano -m #{"-v " if readonly}#{
"+#{line} " if hasLine}\"#{path}\"")
end
# if all else fails, fall back on the venerable local 'vi'
system("vi #{"-R " if readonly}#{"-c"+line.to_s+" " if hasLine}\"#{file}\"")
self
end
def view (options=nil)
# start a read-only editor session on file at line
edit(options, true)
end
def reload
# load file referenced by receiver
begin
load file
rescue LoadError
raise $!, "Missing ruby source fle: #{file}"
end
end
def self.find_in_back_trace (trace, symbol)
# return first element in trace containing symbol
# returns nil if no such stack level found
for msg in trace
src = msg.to_srcRef
return src if src.symbol == symbol
end
return nil
end
def self.from_back_trace (trace, level=0)
# return sourceref at level in backtace
# or return level if no such level found
return find_in_back_trace(trace, level) if level.kind_of? Symbol
return unless lvl = trace[level]
lvl.to_srcRef
end
module Code #for objects supporting __file__ & __line__
def source
SourceRef.new(__file__, __line__)
end
alias_method :to_srcRef, :source
# can't use define_method because in ruby 1.6 self would be SourceRef::Code
(OPS = [ :list, :edit, :view, :reload ]).each {|m|
eval "def #{m}(*args); source.#{m}(*args); end"
}
end #module SourceRef::Code
def self.doMethod(m, *args)
src = args.empty? ? $lastErr : args.shift
#convert src to an appropriate SourceRef by whatever means possible
#Modified irb.rb saves last back_trace & exception in IRB.conf
case src
when Module
srcs=(src.sources).each {|srcRef| srcRef.send m, *args}
return srcs
when Integer, Symbol
#assume parameter is a backtrace level or method name
srcFromTrace = $lastErr.to_srcRef src
src = srcFromTrace if srcFromTrace
when Thread
src = $lastErr = src.lastErr
when Exception
$lastErr = src
end
if src.respond_to? :to_srcRef
src.to_srcRef.send m, *args
else
print "No source file corresponds to ",src.inspect,"\n"
end
end
module CommandBundle #add convenient commands for viewing source code
private
Code::OPS.each{|m|define_method(m){|*args|SourceRef.doMethod(m,*args)}}
def backtrace err=Thread.current #default to this thread's most recent err
case err #make whatever we're handed into something that backtraces
when nil
err = $lastErr
when Thread
err = err.lastErr
else
err = Thread[err].lastErr unless err.respond_to? :backtrace
end
if err
puts err.backtrace
$lastErr=err
end
end
end
end #class SourceRef
#mix source code manipulation utilites into the appropriate classes
class Proc; include SourceRef::Code; end
class Method; include SourceRef::Code; end
if defined? UnboundMethod
class UnboundMethod; include SourceRef::Code; end
end
class Object; include SourceRef::CommandBundle; end
class Module
def sourceHash(methodType, methodNameArray)
# private method to build a hash of methodNames to sourceRefs
# exclude methods for which no ruby source is available
h = {}
methodGetter = method(methodType)
methodNameArray.each {|m|
m = m.intern
begin
src = methodGetter[m].source
ln = src.line #this logic is compatible with 1.6 and 1.9 Ruby
h[m] = src if (!ln or ln > 0) and src.file != "(eval)"
rescue TypeError, ArgumentError #on missing source
end
}
h
end
private :sourceHash
def singleton_source(includeAll=false)
# return hash on receiver's singleton methods to corresponding SourceRefs
sourceHash(:method, singleton_methods(includeAll))
end
def instance_source(includeAncestors=false)
# return hash on receiver's instance methods to corresponding SourceRefs
# optionally include accessible methods in ancestor classes
sourceHash(:instance_method,
private_instance_methods(includeAncestors)+
protected_instance_methods(includeAncestors)+
public_instance_methods(includeAncestors))
end
def source(*args)
# return hash on receiver's methods to corresponding SourceRefs
# note that instance_methods will overwrite singletons of the same name
singleton_source(*args).update(instance_source(*args))
end
def % method_name
# return singleton method named method_name in module
# Use / below unless method_name is also an instance method
method method_name
end
def / method_name
# return instance method named method_name in module
begin
return instance_method(method_name)
rescue NameError
end
method method_name
end
def sources(*args)
# return array of unique source file names for all receiver's methods
(singleton_source.values+instance_source(*args).values).collect{|s|
s.file
}.uniq.collect{|fn| SourceRef.new(fn)}
end
def reload(*args)
# load all source files that define receiver's methods
sources.each {|s| s.reload}
end
def edit(*args)
# start editor sessions on all files that define receiver's methods
sources.each{|srcFile| srcFile.edit(*args)}
end
def view(*args)
# start read-only editor sessions on files containing receiver's methods
sources.each{|srcFile| srcFile.view(*args)}
end
def list(*args)
# return first few lines of all files containing self.methods
result=[]
sources.each{|srcFile| result<<srcFile<<"\n"<<srcFile.list(*args)}
result.join "\n"
end
end
| true
|
84dc79c9e0edc4cce1dc188d81152a77bad9e600
|
Ruby
|
neilb14/euler
|
/ruby/36/double-base-palindromes.rb
|
UTF-8
| 284
| 3.546875
| 4
|
[] |
no_license
|
def is_palindrome(num)
digits,length = num.to_s.chars, num.to_s.length
for i in 0..(length/2)
return false unless digits[i] == digits[length-1-i]
end
true
end
sum =0
for n in 0..999_999
next unless is_palindrome(n)
next unless is_palindrome(n.to_s(2))
sum += n
end
puts sum
| true
|
e6261c36aac744cbc890ccfd149273a3ffa27338
|
Ruby
|
rahmanifarid/chess
|
/Chess/pawn.rb
|
UTF-8
| 1,158
| 3.21875
| 3
|
[] |
no_license
|
require_relative 'piece'
class Pawn < Piece
def moves
moves = []
x , y = position
dirs = move_dirs
x1 = position[0] + dirs[0][0]
if board[[x1,y]].is_a?(NullPiece)
moves << [x1, y]
end
if color == :white && position[0] == 1 || color == :black && position[0] == 6
x2 = position[0] + dirs[1][0]
if board[[x2, y]].is_a?(NullPiece)
moves << [x2, y]
end
end
left_diag = [x + dirs[3][0], y + dirs[3][1]]
right_diag = [x + dirs[2][0], y + dirs[2][1]]
if board.valid_pos?(left_diag)
if board[left_diag].symbol == :piece && board[left_diag].color != color
moves << left_diag
end
end
if board.valid_pos?(right_diag)
if board[right_diag].symbol == :piece && board[right_diag].color != color
moves << right_diag
end
end
valid_moves(moves)
end
def move_dirs
dirs = []
if color == :white
dirs = [[1, 0], [2, 0], [1, 1], [1, -1]]
else
dirs = [[-1, 0], [-2, 0], [-1, 1], [-1, -1]]
end
dirs
end
def render
if color == :white
"[\u2659]"
else
"[\u265F]"
end
end
end
| true
|
5f43200e96bfdaf93630dfd463b45c055a0a0435
|
Ruby
|
DerekTownsend/my-collect-prework
|
/lib/my_collect.rb
|
UTF-8
| 114
| 3.140625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def my_collect(array)
i=0
temp=[]
while i<array.length
temp<< yield(array[i])
i+=1
end
temp
end
| true
|
057bedb16d7f4c228de1d47de0c1afe1e5a6cc5e
|
Ruby
|
kahlil29/GEC-Spectrum-Hackathon
|
/feature_extraction.rb
|
UTF-8
| 3,315
| 3.25
| 3
|
[] |
no_license
|
require 'sentimentalizer'
require 'sinatra/activerecord'
require 'sqlite3'
require 'sinatra'
set :database, {adapter: "sqlite3", database: "ReviewsDb"}
class Reviews<ActiveRecord::Base
end
def startSearch
heating_count = 0
camera_count = 0
display_count = 0
memory_count = 0
Sentimentalizer.setup
Reviews.all.each do |user|
review_string = user.review_content
#review_string = "This is a test string with Heating is an issues. The camera on my phone is very good. The phones display also could not be better. The memory however is excellent"
rev = review_string.downcase
x = rev.split(" ")
a = (x.index("heating") || x.index("heat") || x.index("heated") || x.index("overheating"))
#puts a
if a
if(x[a-1] != "not" && x[a-1] != "no" && x[a-1] != "doesn't")
heating_count += 1
end
end
#puts heating_count
#Set up sentimentalizer
rev_analyzed = review_string.downcase #rev_analyzer contains the review string in lowercase
split_string = rev_analyzed.split(".") #Splits the review string ('.' as the splitting parameter)
#camera module
camera_substring = split_string.index{|s| s.include?("camera")}
if camera_substring!=nil
#puts "camera substring is #{camera_substring}"
#puts "The camera substring index is #{split_string[camera_substring]}"
camera_senti_analyzer = Sentimentalizer.analyze(split_string[camera_substring], true)
x = camera_senti_analyzer.split(",\"probability\":") #use split function to split the resulting hash and obtain only probability
x2 = x[1].split(",") #use split function to exclude remaining part
senti_score = (x2[0].to_f)*100 #access probability and convert to float
#puts "Camera senti score is: #{senti_score}"
if senti_score<50
camera_count +=1
end
end
#puts "Camera count is: #{camera_count}"
#display module
display_substring = split_string.index{|s| s.include?("display")}
if display_substring != nil
#puts "display substring is: #{display_substring}"
#puts "display substring index is: #{split_string[display_substring]}"
display_senti_analyzer = Sentimentalizer.analyze(split_string[display_substring], true)
x = display_senti_analyzer.split(",\"probability\":")
x2 = x[1].split(",")
senti_score = (x2[0].to_f)*100
#puts "Display senti score is: #{senti_score}"
if senti_score<50
display_count += 1
end
end
#puts "Display count is: #{display_count}"
#memory module
memory_substring = split_string.index{|s| s.include?("memory")}
if memory_substring!=nil
#puts "Memory substring is: #{memory_substring}"
#puts "Memory substring index is: #{split_string[memory_substring]}"
memory_senti_analyzer = Sentimentalizer.analyze(split_string[memory_substring], true)
x = memory_senti_analyzer.split(",\"probability\":")
x2 = x[1].split(",")
senti_score = (x2[0].to_f)*100
#puts "Memory senti score is #{senti_score}"
if senti_score<50
memory_count += 1
end
end
#puts "Memory count is: #{memory_count}"
end
puts "Heating count is: #{heating_count}"
puts "Camera count is: #{camera_count}"
puts "Display count is: #{display_count}"
puts "Memory count is: #{memory_count}"
return heating_count, camera_count, display_count, memory_count
end
| true
|
4ca0d8e2af44429c4f14ae636529ec214f222285
|
Ruby
|
bblack16/cli_chef
|
/lib/cli_chef/apps/media_info.rb
|
UTF-8
| 2,848
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
require 'cli_chef' unless defined?(CLIChef::VERSION)
require_relative 'media_info/file'
class MediaInfo < CLIChef::Cookbook
self.description = 'MediaInfo is a convenient unified display of the most relevant technical and tag data for video and audio files.'
add_exit_codes(
{ code: 0, description: 'No error' },
{ code: 1, description: 'Failure' }
)
add_default_locations(
'C:/Program Files/MediaInfo/MediaInfo.exe',
'C:/Program Files(x86)/MediaInfo/MediaInfo.exe'
)
add_ingredients(
{ name: :help, description: 'Display the CLI help.', flag: '--help', allowed_values: [nil], aliases: [:h], boolean_argument: true },
{ name: :version, description: 'Display MediaInfo version and exit', flag: '--Version', allowed_values: [nil], aliases: [:v], boolean_argument: true },
{ name: :full, description: 'Full information Display (all internal tags)', flag: '-f', allowed_values: [nil], aliases: [:verbose], boolean_argument: true },
{ name: :output_html, description: 'Full information Display with HTML tags', flag: '--Output=HTML', allowed_values: [nil], aliases: [:html], boolean_argument: true },
{ name: :output_xml, description: 'Full information Display with XML tags', flag: '--Output=XML', allowed_values: [nil], aliases: [:xml], boolean_argument: true },
{ name: :file, description: 'The file to get tags out of', flag: '', allowed_values: [String], aliases: [:input] }
)
def help
run!(help: true).body
end
def version
run!(version: true).body.scan(/(?<= v)\d+\.\d+.*/).first
end
def info(file, full = false)
tracks = run!(file: file, full: full).body.split("\n\n").map do |category|
lines = category.split("\n")
next if lines.empty?
{
type: lines.shift.split(' ').first.downcase.method_case.to_sym
}.merge(lines.hmap { |line| process_line(line) }).keys_to_sym
end.compact
MediaInfo::File.new(tracks.shift.except(:type).merge(path: file)) do |media|
media.tracks = tracks
end
end
protected
IGNORE = [:complete_name]
def process_line(line)
key, value = line.split(':', 2)
key = key.strip.downcase.method_case.to_sym
return nil if IGNORE.include?(key)
[
remap(key),
convert_value(key, value.strip)
]
end
def convert_value(key, value)
case key
when :file_size, :bit_rate, :stream_size, :size
value.parse_file_size
when :duration
value.parse_duration
when :width, :height
value.sub(/\s+/, '').to_i
else
value
end
end
MAPPING = {
unique_id: :id,
stream_size: :size,
file_size: :size,
delay_relative_to_video: :delay,
overall_bit_rate: :bit_rate,
channel_s: :channels,
track_name: :title,
overall_bit_rate_mode: :bit_rate_mode
}
def remap(key)
MAPPING[key] || key
end
end
| true
|
dfe3be801a6dfcac3a6d1d60bf22fc158c4c476d
|
Ruby
|
pedroandrade/downloader
|
/down.rb
|
UTF-8
| 1,899
| 2.96875
| 3
|
[] |
no_license
|
require 'rubygems'
require 'eventmachine'
require 'set'
require 'fiber'
require 'em-http'
class Downloader
def initialize www, workers = 10, &block
@queue = [{:url => www, :type => :head, :other => nil}]
@visited = {}
@traversers = {}
@workers = []
@worknum = workers
instance_eval &block
end
def traverse type, &block
@traversers[type] = block
end
def process_results &processor
@result_processor = processor
end
def claim_result *args
if @result_processor then
@result_processor.call *args
end
end
def run
EM.run do
@worknum.times do |id|
start_worker id
end
end
end
def get_url url
f = Fiber.current
http = EM::HttpRequest.new(url).get
http.errback {f.resume http}
http.callback {f.resume http}
return Fiber.yield
end
private
def start_worker id
Fiber.new do
loop do
if @queue.empty? then
@workers << Fiber.current
if (@workers.size == @worknum) then
puts "finished #{Time.now}"
EM.stop
end
Fiber.yield
else
node = @queue[0]
@queue = @queue.drop 1
visit_node node
wake_workers
end
end
end.resume
end
def visit_node node
type = node[:type]
url = node[:url]
puts "visiting #{url}"
data = get_url url
new_nodes = @traversers[type].call data, node[:other]
new_nodes.select! do |nnode|
@visited[nnode[:type]] ||= Set.new
retval = if (@visited[nnode[:type]].member?(nnode[:url])) then false else true end
@visited[nnode[:type]].add(nnode[:url])
retval
end
@queue += new_nodes
end
def wake_workers
while not(@queue.empty? || @workers.empty?) do
f = @workers[0]
@workers = @workers.drop 1
f.resume
end
end
end
| true
|
7d6535f046a38e3a96fe595b1279f39ed9c93d29
|
Ruby
|
thomaslindback/pepper_ruby
|
/pepper_object_send_3.rb
|
UTF-8
| 592
| 3.828125
| 4
|
[] |
no_license
|
#pepper_send
# Object is called a reciever
# send ,essages to object
class P
attr_accessor :name
def initialize n
@name = n
end
def greeting
"Hello #{@name}"
end
def setter m
self.send("name=", m)
end
end
puts 4+5
puts 4.+ 5
puts 4.send :+,5
puts ""
#p = P.new 'thomas'
#puts p.name
#p.name= 'more'
#puts p.name
#p.name = '007'
#puts p.name
#p.send :name=, "008"
#puts p.name
#puts ""
#puts p.greeting
#p.setter 'paf'
#puts p.greeting
puts ""
a = [3,4,5]
puts a
puts a.class
a.send(:fill, "x")
p a
a.send("fill", "t")
a = [3,4,5]
p a[0], a[-1]
a[6] = 55
p a
| true
|
34347461a8b04dc71cffccacf43500c5319ac037
|
Ruby
|
XuVic/isspay_api
|
/app/supports/array_helper.rb
|
UTF-8
| 126
| 3.046875
| 3
|
[] |
no_license
|
module ArrayHelper
def to_range(array)
min = array[0] || 0
max = array[1] || Float::INFINITY
min..max
end
end
| true
|
4887be0f90f1b7d0c8d636b636cf68323a50d5fa
|
Ruby
|
DeeGee1015/Rumblr
|
/server.rb
|
UTF-8
| 1,733
| 2.515625
| 3
|
[] |
no_license
|
require "sinatra"
require "sinatra/activerecord"
if ENV['RACK_ENV']
ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'])
else
set :database, {adapter: "sqlite3", database: "database.sqlite3"}
end
enable :sessions
class User < ActiveRecord::Base
end
class Post < ActiveRecord::Base
end
get "/" do
erb :home
# puts "running"
end
get "/user/signup" do
@user = User.new
erb :'user/signup'
if session[:user_id]
redirect "/"
else
erb :'user/signup'
end
end
post "/signup" do
@user = User.new(params)
if @user.save
p "#{@user.first_name} was saved to the database"
redirect "/thanks"
end
end
get "/thanks" do
erb :'/user/thanks'
end
get "/user/login" do
if session[:user_id]
redirect "/"
else
erb :'/user/login'
end
end
post "/login" do
user = User.find_by(email: params[:email])
p user.password
p params[:password]
if user.password == params[:password]
session[:user_id] = user.id
redirect "/user/post"
else
redirect "/user/login"
end
end
get '/search' do
erb :'search'
end
post "/login" do
given_password = params['password']
user = User.find_by(email: params['email'])
if user
if user.password == given_password
p "User authenticated successfully!"
session[:user_id] = user.id
else
p "Invalid email or pasword"
end
end
end
get '/user/post' do
@post = Post.all
erb :'/user/post'
end
post '/user/post' do
p params
params.merge!(user_id: session[:user_id])
@post = Post.new(params)
@post.save
redirect '/user/feeds'
end
get "/user/feeds" do
@post = Post.all
erb :'/user/feeds'
end
#Delete request
post '/logout'do
session.clear
p "user logged out successfully"
redirect "/"
end
| true
|
848b554c9f8e3a6df83fcc19a57e3fdf0423b223
|
Ruby
|
JaredRoth/headcount
|
/lib/module_helper.rb
|
UTF-8
| 682
| 3.15625
| 3
|
[] |
no_license
|
require_relative "errors"
module Helper
def error?(condition)
raise UnknownDataError unless condition
end
def truncate(value)
value.to_s[0..4].to_f
end
def sanitize_data(input)
input.to_s.gsub!(/[\s]+/,'')
input = input.to_f if String === input
truncate(input)
end
def sanitize_data_to_na(num)
if sanitize_data(num) == 0 || sanitize_data(num).to_s.upcase.chars[0] == "N"
"N/A"
else
sanitize_data(num)
end
end
def sanitize_grade(num)
{3=>:third_grade,8=>:eighth_grade}.fetch(num,nil)
end
def truncate_percentages(hash)
hash.map do |year,value|
[year, truncate(value.to_f)]
end.to_h
end
end
| true
|
3d24b81373e9926e22311c685f472c76abc1c75f
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/word-count/be3cf32e6a234fb9b69b451d46042a52.rb
|
UTF-8
| 451
| 3.59375
| 4
|
[] |
no_license
|
class Phrase
def initialize phrase
@phrase = phrase
end
def word_count
@word_count || populate_word_count(@phrase) && @word_count
end
private
def add_word word
@word_count[word] += 1
end
def populate_word_count phrase
@word_count = Hash.new(0)
words = extract_word_list phrase
words.each do |word|
add_word word
end
end
def extract_word_list phrase
phrase.downcase.scan(/\w+/)
end
end
| true
|
8b8f2440f7085f2ccbca62441add4d9bc9ed9125
|
Ruby
|
jmondo/bus_tracker
|
/bus.rb
|
UTF-8
| 736
| 2.546875
| 3
|
[] |
no_license
|
require 'sinatra'
require 'json'
require 'httparty'
get '/' do
content_type :json
{potrero: predictions(0), pacific: predictions(1)}.to_json
end
def predictions(index)
prediction_objects = [xml["body"]["predictions"][index]["direction"]].flatten.collect { |h| h["prediction"] }.flatten
minutes = prediction_objects.collect {|p| p["minutes"].to_i }
minutes.sort[0..2].join(',')
end
def xml
with_cache_variable(:@xml) do
HTTParty.get('http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=sf-muni&stops=22%7c4622&stops=22%7c4621&stops=21%7c4994&stops=21%7c7423')
end
end
def with_cache_variable(var_sym)
instance_variable_get(var_sym) || instance_variable_set(var_sym, yield)
end
| true
|
5a2c9e86592466df18aa71a5ebe2399a2b4e844c
|
Ruby
|
vincentwoo/misc
|
/euler_12.rb
|
UTF-8
| 355
| 3.203125
| 3
|
[] |
no_license
|
triangles = Enumerator.new do |yielder|
num = 1
sum = 1
loop do
yielder.yield sum
num += 1
sum += num
end
end
triangles.each do |triangle|
divisors = 0
(1..Math.sqrt(triangle).ceil).each do |factor|
divisors += 2 if triangle % factor == 0
end
# p [triangle, divisors]
if divisors > 500
p triangle
exit
end
end
| true
|
57e0b7f86a295362e407b8796b9c31a0b5e8d169
|
Ruby
|
laranicolas/leetcode
|
/two_sum.rb
|
UTF-8
| 1,408
| 4.09375
| 4
|
[] |
no_license
|
# Given an array of integers, return indices of the two numbers such that they add up to a specific target.
# You may assume that each input would have exactly one solution, and you may not use the same element twice.
# Example:
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# Brute force solution: Time O(n2), Space O(1)
def solution(nums, target)
nums.each.with_index do |n, i|
j = i + 1
while (j <= nums.size-1)
return [i,j] if target == (n + nums[j])
j += 1
end
end
-1
end
# puts solution([2, 7, 11, 15], 9) == [0,1]
# puts solution([2, 7, 11, 15], 50) == -1
# Improve solution. Time O(n), Space O(n)
def solution2(nums, target)
complements = {}
nums.each.with_index do |n, i|
complements[n] = i
end
nums.each_with_index do |n, i|
diff = target - n
return [i, complements[diff]] if complements.include?(diff)
end
-1
end
puts solution2([2, 7, 11, 15], 9) == [0,1]
puts solution2([2, 7, 11, 15], 50) == -1
# Improve solution. Time O(n), Space O(n)
def solution3(nums, target)
complements = {}
nums.each.with_index do |n, i|
diff = target - n
return [complements[diff], i] if complements.include?(diff)
complements[n] = i
end
-1
end
puts solution3([2, 7, 11, 15], 9) == [0,1]
puts solution3([2, 7, 11, 15], 26) == [2,3]
puts solution3([2, 7, 11, 15, 20], 31) == [2,4]
puts solution3([2, 7, 11, 15], 50) == -1
| true
|
9255699a6fbd268c1445c22ba4f09565d47b7384
|
Ruby
|
Inglorion-G/AppAcademy
|
/Week1/W1D5/knight.rb
|
UTF-8
| 2,608
| 3.703125
| 4
|
[] |
no_license
|
class KnightPathFinder
MOVE_POSITIONS = [
[+1,+2],
[-1,-2],
[+1,-2],
[-1,+2],
[+2,+1],
[+2,-1],
[-2,+1],
[-2,-1]
]
attr_accessor :start_pos, :tree
def initialize(start_pos)
@start_pos = start_pos
@tree = create_node(self.start_pos)
build_move_tree
end
def create_node(value)
new_node = TreeNode.new(value)
end
def build_move_tree
q = [self.tree]
coordinates = []
until q.empty?
current_node = q.shift
coordinates << current_node.value
self.class.new_move_positions(current_node.value).each do |pos|
child = create_node(pos)
unless coordinates.include?(pos)
current_node.add_child(child)
q << child
end
end
end
self.tree.value
end
def self.new_move_positions(pos)
x,y = pos
moves = []
MOVE_POSITIONS.each do |position|
moves << [x + position[0], y + position[1]]
end
moves.select{ |move| (0..7).include?(move[0]) && (0..7).include?(move[1]) }
end
def find_path(target)
search_node = self.tree.dfs(target)
search_node.path
end
end
#p KnightPathFinder.new([1,2]).build_move_tree
##########################################################
class TreeNode
attr_accessor :parent, :children, :value
def initialize(value)
@parent = nil
@children = []
@value = value
end
def remove_child(child_node)
if self.children.include?(child_node)
child_node.parent = nil
self.children.delete(child_node)
else
nil
end
end
def add_child(child_node)
if self.children.size == 8
raise "Already has eight children."
end
if child_node.parent
child_node.parent.children.delete(child_node)
end
child_node.parent = self
self.children << child_node
end
def bfs(value)
q = [self]
explored_tiles = []
until q.empty?
current_node = q.shift
explored_tiles << current_node
p current_node.value
return current_node if current_node.value == value
current_node.children.each do |child|
q << child if !explored_tiles.include?(child) && !q.include?(child)
end
end
end
def dfs(value)
temp = nil
return self if self.value == value
return nil if self.children.empty?
self.children.each do |child|
temp = child.dfs(value)
return temp if !temp.nil?
end
nil
end
def path
if parent
parents = self.parent.path
return parents += [self.value]
end
[self.value]
end
end
p KnightPathFinder.new([0,0]).find_path([3,7])
| true
|
97c0eee73a9f5edce16226de7b1f116770478bf0
|
Ruby
|
bragnikita/readmanga-downloader
|
/test/download_task_test.rb
|
UTF-8
| 3,485
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
require 'minitest/autorun'
require 'minitest/unit'
require 'shoulda'
require 'pathname'
require 'fileutils'
require_relative '../lib/readmanga_dldr'
MD = ReadMangaDownloader
class DownloadTasktest < Minitest::Test
context 'After initialization' do
setup do
@root_dir = Dir.mktmpdir 'manga_root'
FileUtils.rm_r(@root_dir.to_s+'/*', {:secure => true, :force => true})
url = 'http://readmanga.me/soredemo_bokura_wa_koi_wo_suru'
@options = {
:target_dir => @root_dir.to_s
}
@task = MD::DownloadTask.new url, @options
end
should 'set root directory for manga' do
expected_root = File.join @root_dir.to_s, 'soredemo_bokura_wa_koi_wo_suru'
assert_equal expected_root, @task.title_root_dir.to_path
assert_equal true, Dir.exist?(@task.title_root_dir)
end
should 'create properly file for manga' do
chapter =MD::ChapterInfo.new 'http://readmanga.me/soredemo_bokura_wa_koi_wo_suru/vol1/3', 1, 3
image_url = 'http://e4.postfact.ru/auto/15/03/20/01.png_res.jpg'
order = 1
file = @task.create_file chapter, image_url, order
assert_equal true, File.exist?(file)
expected_file = File.join @root_dir.to_s, 'soredemo_bokura_wa_koi_wo_suru', 'ch3', '01.png_res.jpg'
assert_equal true, File.identical?(expected_file, file)
end
should 'not create new file if exists' do
chapter =MD::ChapterInfo.new 'http://readmanga.me/soredemo_bokura_wa_koi_wo_suru/vol1/3', 1, 3
image_url = 'http://e4.postfact.ru/auto/15/03/20/01.png_res.jpg'
order = 1
expected_file = File.join @root_dir.to_s, 'soredemo_bokura_wa_koi_wo_suru', 'ch3', '01.png_res.jpg'
FileUtils.mkpath Pathname.new(expected_file).dirname
File.new(expected_file, 'wb').close
file = @task.create_file chapter, image_url, order
assert_equal true, File.exist?(expected_file)
assert_nil file
end
teardown do
if @root_dir && Dir.exist?(@root_dir)
FileUtils.rm_r(@root_dir, {:secure => true, :force => true})
end
end
end
context 'If downloading' do
setup do
@root_dir = Dir.mktmpdir 'manga_root'
FileUtils.rm_r(@root_dir.to_s+'/*', {:secure => true, :force => true})
url = 'http://readmanga.me/soredemo_bokura_wa_koi_wo_suru'
@options = {
:target_dir => @root_dir.to_s
}
@chapter =MD::ChapterInfo.new 'http://readmanga.me/soredemo_bokura_wa_koi_wo_suru/vol1/3', 1, 3
@image_url = 'http://e6.postfact.ru/auto/15/26/64/01.png'
@order = 1
download_handler = OfflineDownloadHandler.new
download_handler.image_file_path = File.join(Pathname.new(__FILE__).dirname, 'resources/01.png')
download_handler.image_file_url = @image_url
@task = MD::DownloadTask.new url, @options, download_handler
end
should 'Download and save file' do
target_file = @task.download_image(@chapter, @order,@image_url)
p target_file
assert_equal true, File.exist?(target_file)
end
teardown do
if @root_dir && Dir.exist?(@root_dir)
FileUtils.rm_r(@root_dir, {:secure => true, :force => true})
end
end
end
end
class OfflineDownloadHandler
attr_accessor :page_content, :image_file_path, :image_file_url
def load_page(url)
Nokogiri::HTML(page_content)
# Nokogiri::HTML(open(url))
end
def load_image(url)
if image_file_url == url
File.new(image_file_path, 'rb')
end
end
end
| true
|
8a7bc515aeb006c696dc4da409356130ec1b8d42
|
Ruby
|
codeAligned/super_happy_interview_time
|
/rb/lib/leetcode/lc_617.rb
|
UTF-8
| 1,630
| 3.71875
| 4
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module LeetCode
# 617. Merge Two Binary Trees
module LC617
TreeNode = Struct.new(:val, :left, :right)
# Description:
# Given two binary trees and imagine that when you put one of them to cover the other,
# some nodes of the two trees are overlapped while the others are not.
#
# You need to merge them into a new binary tree.
# The merge rule is that if two nodes overlap,
# then sum node values up as the new value of the merged node.
# Otherwise, the NOT null node will be used as the node of new tree.
#
# Examples:
# Input:
# left right
# 1 2
# / \ / \
# 3 2 1 3
# / \ \
# 5 4 7
# Output:
# 3
# / \
# 4 5
# / \ \
# 5 4 7
#
# Notes:
# - The merging process must start from the root nodes of both trees.
#
# @param left {TreeNode}
# @param left {TreeNode}
# @return {TreeNode}
def merge_trees(left, right)
return if !left && !right
merged = TreeNode.new(0)
val = 0
left_children = [nil, nil]
right_children = [nil, nil]
if left
val += left.val
left_children = [left.left, left.right]
end
if right
val += right.val
right_children = [right.left, right.right]
end
merged.val = val
merged.left = merge_trees(left_children[0], right_children[0])
merged.right = merge_trees(left_children[1], right_children[1])
merged
end
end
end
| true
|
74114dab8332aa66583d0744d2dd273eaef2f279
|
Ruby
|
KurisuFin/ratebeer
|
/app/models/brewery.rb
|
UTF-8
| 836
| 2.71875
| 3
|
[] |
no_license
|
class Brewery < ActiveRecord::Base
include RatingAverage
has_many :beers, dependent: :destroy
has_many :ratings, through: :beers
validates :name, presence: true
validates :year, numericality: { only_integer: true }
validate :inspect_year
scope :active, -> { where active:true }
scope :retired, -> { where active:[nil, false] }
def inspect_year
if year < 1042 || year > Date.today.year
errors.add(:year, "have to be between 1042-#{Date.today.year}")
end
end
def print_report
puts name
puts " Established at year #{year}"
puts " Number of beers #{beers.count}"
puts " Number of ratings #{ratings.count}"
end
def restart
self.year = 2014
puts "Changed year to #{year}"
end
def self.top(n)
sorted = Brewery.includes(:ratings).all.sort_by{ |b| -(b.average_rating || 0) }
sorted.take(n)
end
end
| true
|
df50a6122b157fddf13d416e890546a4edfa4937
|
Ruby
|
akanksha007/fabelio
|
/app/controllers/users_controller.rb
|
UTF-8
| 833
| 2.59375
| 3
|
[] |
no_license
|
class UsersController < ApplicationController
# to list all the images in asc order of their position
def index
@users = User.all.order(:position)
end
# to pass a user object to view so as help storing it in db
def new
@user = User.new
end
# to save the user input value in database
def create
@user = User.new(user_params)
if @user.save
redirect_to users_path
else
redirect_to new_user_path, alert: "Error creating user."
end
end
# to show one particular image, currently this action is not called in our flow
def show
@users = User.find(params[:id])
end
#rails 4 have a strong parameter concept to prevent mass assignment hence we need
#assign permision to parameters which can be assigned
private
def user_params
params.require(:user).permit(:url, :position)
end
end
| true
|
b3a91054f08d4e303d867608f5f2054a1bfd616f
|
Ruby
|
adamruzicka/taggata
|
/lib/taggata/persistent/directory.rb
|
UTF-8
| 1,817
| 2.609375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
module Taggata
module Persistent
class Directory < Abstract
include ::Taggata::Persistent::WithParent
attr_reader :db, :name, :parent_id, :id
def initialize(db, name, parent_id = nil, id = nil)
@db = db
@name = name
@parent_id = parent_id
@id = id
end
def self.table
:taggata_directories
end
def to_hash
{
:name => name,
:parent_id => parent_id,
:id => id
}
end
def self.new_from_hash(db, hash)
self.new(db,
hash[:name],
hash[:parent_id],
hash[:id])
end
def show(indent = 0)
indent.times { print " " }
puts "+ #{self.name}"
entries.each { |e| e.show(indent + 1) }
end
def directories
@child_directories ||= db.find_child_directories(self)
end
def files
@child_files ||= db.find_child_files(self)
end
def invalidate_cache
@child_directories = @child_files = nil
end
def entries
directories + files
end
# Scan children of this directory
def scan
scanner = ::Taggata::FilesystemScanner.new db
scanner.process(self)
validate
end
def validate
missing = ::Taggata::Persistent::Tag.find_or_create(:name => MISSING_TAG_NAME)
files.reject { |f| ::File.exist? f.path }.each { |f| f.add_tag missing }
directories.each(&:validate)
end
# Get full path of this directory
#
# @result full path of this directory
def path
parents = [self]
parents << parents.last.parent while parents.last.parent
::File.join(parents.reverse.map(&:name))
end
end
end
end
| true
|
57d07245747d2362259b410891272c81f53e32d9
|
Ruby
|
wordkarin/BankAccounts
|
/savings_test.rb
|
UTF-8
| 1,841
| 3.25
| 3
|
[] |
no_license
|
require_relative 'savings_account'
puts "SAVINGS TEST - $10 open amount, withdrawl fail"
sa = Bank::SavingsAccount.new(1212, 2014, 1000)
puts sprintf("New %s opened with balance of $%0.02f, account number: %i.", sa.class.to_s, sa.balance/100.to_f, sa.account_id)
puts "withdraw $1" #expect this to fail, because minimum balance is 1000, and if we did withdraw 100 + the 200 fee for a withdrawl, the balance would be 970 which is less than 1000.
sa.withdraw(100)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "SAVINGS TEST - $200 open amount, withdrawl success"
sa = Bank::SavingsAccount.new(1212, 2014, 20000)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "withdraw $1"
sa.withdraw(100)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "SAVINGS TEST - $100 open amount, add interest"
sa = Bank::SavingsAccount.new(1212, 2014, 10000)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "add interest 0.25"
puts sa.add_interest(0.25)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "SAVINGS TEST - $200 open amount, deposit success"
sa = Bank::SavingsAccount.new(1212, 2014, 20000)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "deposit $1"
sa.deposit(100)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
puts "SAVINGS TEST - $9 open amount, Initialize Fail"
sa = Bank::SavingsAccount.new(1212, 2014, 900)
puts sprintf("Account has balance of $%0.02f, account number: %i.", sa.balance/100.to_f, sa.account_id)
| true
|
5c1adce5daf5c57511de1893c78b5a810cf85206
|
Ruby
|
MiguelSavignano/graphql-ruby
|
/spec/graphql/schema/interface_spec.rb
|
UTF-8
| 2,522
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Schema::Interface do
let(:interface) { Jazz::GloballyIdentifiableType }
describe "type info" do
it "tells its type info" do
assert_equal "GloballyIdentifiable", interface.graphql_name
assert_equal 2, interface.fields.size
end
class NewInterface1 < Jazz::GloballyIdentifiableType
end
class NewInterface2 < Jazz::GloballyIdentifiableType
module Implementation
def new_method
end
end
end
it "can override Implementation" do
new_object_1 = Class.new(GraphQL::Schema::Object) do
implements NewInterface1
end
assert_equal 2, new_object_1.fields.size
assert new_object_1.method_defined?(:id)
new_object_2 = Class.new(GraphQL::Schema::Object) do
implements NewInterface2
end
assert_equal 2, new_object_2.fields.size
# It got the new method
assert new_object_2.method_defined?(:new_method)
# But not the old method
refute new_object_2.method_defined?(:id)
end
end
describe ".to_graphql" do
it "creates an InterfaceType" do
interface_type = interface.to_graphql
assert_equal "GloballyIdentifiable", interface_type.name
field = interface_type.all_fields.first
assert_equal "id", field.name
assert_equal GraphQL::ID_TYPE.to_non_null_type, field.type
assert_equal "A unique identifier for this object", field.description
end
end
describe "in queries" do
it "works" do
query_str = <<-GRAPHQL
{
piano: find(id: "Instrument/Piano") {
id
upcasedId
... on Instrument {
family
}
}
}
GRAPHQL
res = Jazz::Schema.execute(query_str)
expected_piano = {
"id" => "Instrument/Piano",
"upcasedId" => "INSTRUMENT/PIANO",
"family" => "KEYS",
}
assert_equal(expected_piano, res["data"]["piano"])
end
it "applies custom field attributes" do
query_str = <<-GRAPHQL
{
find(id: "Ensemble/Bela Fleck and the Flecktones") {
upcasedId
... on Ensemble {
name
}
}
}
GRAPHQL
res = Jazz::Schema.execute(query_str)
expected_data = {
"upcasedId" => "ENSEMBLE/BELA FLECK AND THE FLECKTONES",
"name" => "Bela Fleck and the Flecktones"
}
assert_equal(expected_data, res["data"]["find"])
end
end
end
| true
|
9e023f401ad983580aba0f3dbc7105163f26a836
|
Ruby
|
wilbertom/aws_provisioner
|
/spec/aws_provisioner/extensions_spec.rb
|
UTF-8
| 392
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
describe "Language extensions" do
describe "Symbol#camelize" do
it "transforms a single word symbol" do
expect(:example.camelize).to eq("Example")
end
it "camel cases two words or more seperated by underscores" do
expect(:another_example.camelize).to eq("AnotherExample")
expect(:another_silly_example.camelize).to eq("AnotherSillyExample")
end
end
end
| true
|
4fda1fc884f7d7648aa25e331562b18571fd5286
|
Ruby
|
msalo3/WordChecker
|
/WordChecker.rb
|
UTF-8
| 1,124
| 4.0625
| 4
|
[] |
no_license
|
def in_words(array,string)
count=0
array.each do |word|
if word==string
count+=1
end
end
if count>0
puts "The word is in that array!"
else
puts "It's not in that array"
end
end
def possible_words(array,string)
value=true
string_holder=""
temp_input=Array.new(string.length)
count=0
string.each_char do |i|
temp_input[count]=i
count+=1
end
array.each do |eachword|
(0..string.length-1).each do |i|
if eachword[i]!=temp_input[i]
value=false
end
end
if value==true
string_holder+= eachword + " "
end
value=true
end
return string_holder
end
contents = File.read('trial.txt')
file_array=contents.downcase.split(" ")
# print file_array
puts "Input please:"
user_in=gets.chomp
puts possible_words(file_array,user_in)
# Below is the program that runs with a prepopulated array of words instead
# of a .txt file like the program above.
# words=["world","worlds","hello","hi","worldlike","womp","worts"]
# in_words(words,"worweld")
#
# puts "Input please:"
# user_in=gets.chomp
# puts possible_words(words,user_in)
| true
|
b682d16b043ef3ae683cd3934249f757ac1411ab
|
Ruby
|
moofmayeda/hacker-news
|
/app/models/link.rb
|
UTF-8
| 507
| 2.5625
| 3
|
[] |
no_license
|
class Link < ActiveRecord::Base
before_save :url_checker
# has_many :comments
has_many :comments, as: :commentable
validates :url, :presence => true
def vote
self.update(votes: self.votes + 1)
end
def score
days_elapsed = (Time.new - self.created_at)/60.0/60/24
self.votes/days_elapsed
end
def self.order_by_score
self.all.sort_by {|link| link.score }.reverse
end
private
def url_checker
self.url.delete!("http://") if self.url.start_with?("http://")
end
end
| true
|
01396e47f0f2743f4fa077e87f2c7da9e9343f2e
|
Ruby
|
sblackstone/project_euler_solutions
|
/434-2.rb
|
UTF-8
| 3,618
| 3.21875
| 3
|
[] |
no_license
|
=begin
00----01----02----03
| A | B | C |
04----05----06----07
| D | E | F |
08----09----10----11
0,0 0,1 0,2 0,3
1,0 1,1 1,2 1,3
2,0 2,1 2,2 2,3
boxr boxc nodes
2 3 (boxr+1)*(boxc+1)
Edges
Each row has boxc edges
Each col has boxr edges
(boxr+1)*boxc + (boxc+1)*boxr
Edges needed to add =
(2 * (boxr+1)*(boxc+1) - 3) - ((boxr+1)*boxc + (boxc+1)*boxr)
(2*3*4 - 3) - (3*3 + 2*4)
24 - 3 = 21 - (9+8) = 4!! =)
=end
require 'pp'
class Node
attr_accessor :adjacent, :pebbles, :nodeid
def initialize
@nodeid = nil
@pebbles = 2
@adjacent = Array.new
end
end
class Framework
attr_accessor :nodes
def initialize(boxr, boxc)
@boxr = boxr
@boxc = boxc
setup_nodes
end
def print_pebbles
0.upto(@boxr) do |r|
0.upto(@boxc) do |c|
print "#{@nodes[r][c].pebbles}"
if c < @boxc and @nodes[r][c].adjacent.include? @nodes[r][c+1]
print " > "
elsif c < @boxc and @nodes[r][c+1].adjacent.include? @nodes[r][c]
print " < "
else
print " "
end
end
puts
0.upto(@boxc) do |c|
if r < @boxr and @nodes[r][c].adjacent.include? @nodes[r+1][c]
print "@ "
elsif r < @boxr and @nodes[r+1][c].adjacent.include? @nodes[r][c]
print "^ "
else
print " "
end
end
puts
end
end
def setup_nodes
@nodes = Array.new
0.upto(@boxr) do |r|
@nodes[r] = Array.new
0.upto(@boxc) do |c|
@nodes[r][c] = Node.new
@nodes[r][c].nodeid = "#{r}:#{c}"
end
end
end
def enlarge_cover(nodea, nodeb)
seen = Hash.new
path = Hash.new
@nodes.flatten.each do |n|
seen[n.nodeid] = false
path[n.nodeid] = -1
end
if nodea.pebbles > 0
nodea.pebbles -= 1
nodea.adjacent.push nodeb
return true
end
if nodeb.pebbles > 0
nodeb.pebbles -= 1
nodeb.adjacent.push nodea
return true
end
found = find_pebble(nodea, seen, path)
if found
rearrange_pebbles(nodea, seen)
return true
end
if !seen[nodeb]
found = find_pebble(nodeb, seen, path)
if found
rearrange_pebbles(nodeb,path)
return true
end
end
return false
end
def find_pebble(v, seen, path)
seen[v.nodeid] = true
path[v.nodeid] = -1
if v.pebbles > 0
return true
end
v.adjacent.each do |adj|
if !seen[adj.nodeid]
path[v.nodeid] = adj
found = find_pebble(adj, seen, path)
return true if found
end
end
return false
end
def rearrange_pebbles(v, path)
while path[v.nodeid] != -1
w = path[v.nodeid]
pp w
if path[w.nodeid].nodeid == -1
w.pebbles -= 1
w.adjacent.push v
else
puts "stuff"
end
v = w
end
end
def insert_edge(r1,c1,r2,c2)
enlarge_cover(@nodes[r1][c1], @nodes[r2][c2])
end
def insert_edges
# ROW EDGES
0.upto(@boxr) do |r|
0.upto(@boxc - 1) do |c|
insert_edge(r,c,r,c+1)
end
end
puts
# COL EDGES
0.upto(@boxc) do |c|
0.upto(@boxr - 1) do |r|
insert_edge(r,c,r+1,c)
end
end
end
end
boxr = 2
boxc = 3
# edges to add = (2 * (boxr+1)*(boxc+1) - 3) - ((boxr+1)*boxc + (boxc+1)*boxr)
f = Framework.new(boxr, boxc)
#f.insert_edge(1,1,2,1)
f.insert_edges
f.insert_edge(0,0,1,1)
f.print_pebbles
| true
|
dba011a6dcdcaeef5accf7220f9df3035180dbec
|
Ruby
|
vitivey/ruby-objects-has-many-through-lab-v-000
|
/lib/patient.rb
|
UTF-8
| 335
| 3.09375
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Patient
def initialize(name)
@name=name
end
def new_appointment(doctor, date)
appointment=Appointment.new(self, doctor, date)
end
def appointments
Appointment.all
end
def doctors
Appointment.all.collect do |appointment|
appointment.doctor
end
end
end
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.