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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
472a13487a3a2a2f04e4d547c8a733fb02168061
|
Ruby
|
Rockster160/Games
|
/split_csv.rb
|
UTF-8
| 752
| 2.78125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby -w
filename = "/Users/rocconicholls/Downloads/total care patient list - Copy of PatientDemo_2Line.csv"
lines_per_file = 100
header_lines = 1
extension = File.extname(filename)
basename = File.basename(filename, extension)
puts "#{extension} - #{basename}"
header = []
File.foreach(filename).with_index do |line, idx|
file_number = idx / lines_per_file
next if file_number > 0
new_file_name = "#{basename}(p#{file_number + 1})#{extension}"
header << line if idx < header_lines
if idx % lines_per_file == 0
File.open(new_file_name, "w+") do |file|
file.write header.join
end
else
File.open(new_file_name, "a") do |file|
file.write line
end
end
rescue => e
puts "Error: #{e.class}"
end
| true
|
b80a42bcdb22dc4a91310125903e99dfbc200fd4
|
Ruby
|
Ricardo-Paul/auto_sales
|
/lib/auto_sales/cli.rb
|
UTF-8
| 1,105
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
class AutoSales::CLI
def call
list_auto
menu
end
def list_auto
@cars = AutoSales::Car.car_info
@cars.each.with_index(1) {|car, i| puts " #{i}. #{car.model}"}
end
def menu
puts" Enter the number of car to have more info / and 'show' to display the list "
input = nil
while input != "exit"
input = gets.strip
if input.to_i > 0
selected_car = @cars[input.to_i - 1]
puts "-----------------------------------------------------------"
puts " MODEL | SALES | ASSEEMBLY (country)"
puts "-----------------------------------------------------------"
puts "#{selected_car.model} - #{selected_car.sales} - #{selected_car.assembly}"
elsif input == "show"
puts "-------------"
puts " MODELS ONLY"
puts "------------"
list_auto
else
puts "Please enter a valid number"
end
end
end
end
| true
|
98f28f8243357b9eead0ee9f98df2372a5d429f2
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/difference-of-squares/290035c1bb0b4d8592ad132c6bc7ca05.rb
|
UTF-8
| 330
| 3.46875
| 3
|
[] |
no_license
|
class Squares
attr_reader :n
def initialize(n)
@n = n
end
def sum_of_squares
f = lambda { |n| n < 2 ? n : f[n-1] + n**2 }
f.call(n)
end
def square_of_sums
f = lambda { |n| n < 2 ? n : f[n-1] + n }
f.call(n)**2
end
def difference
square_of_sums - sum_of_squares
end
end
| true
|
82b4d9219c69d48295950681f0fd4df8af2061b5
|
Ruby
|
Kweiss/Ruby-Code
|
/L2C/ex15.rb
|
UTF-8
| 810
| 4.4375
| 4
|
[] |
no_license
|
#takes teh rguments we pass (file name) and assigns them to the filename string value
filename = ARGV.first
#creates a string value with >> in it
prompt = ">>"
#defines the txt object with the file open command, and uses the filename argument from the first run as the parameters
txt = File.open(filename)
#puts the line and the file name
puts "Here is your file: #{filename}"
#outputs the contents, or morespecifically, what it read from the file
puts txt.read()
txt.close()
#new puts line
puts "I'll also ask you to type it again:"
#print the prompt string
print prompt
#creates a string object and sets the value to the input received from the STDIN
file_again = STDIN.gets.chomp()
#opens the new file
text_again = File.open(file_again)
#outputs the new text
puts text_again.read()
text_again.close()
| true
|
c1e774903900bc9492d140c410e5c2d8790c9831
|
Ruby
|
genehsu/wildmat
|
/spec/wildmat_spec.rb
|
UTF-8
| 3,995
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
require "spec_helper"
require "wildmat"
describe Wildmat do
context 'word characters' do
bad_string = "foo bar baz"
%w[
asdf
_
123
a1
foo_bar_baz
_under
after_
].each do |input|
it "should not change word characters: #{input}" do
Wildmat.regexp_pattern(input).should eq input
end
it "should match itself: #{input} =~ #{input}" do
input.should match Wildmat.to_regexp(input)
end
it "should not match an arbitrary string: #{input} !~ #{bad_string}" do
bad_string.should_not match Wildmat.to_regexp(input)
end
end
end
context 'question mark' do
# Negative cases
negatives = %w[ abc nice caba abcde ]
# Positive cases
[
[ '?abc', %w[ 1abc aabc _abc .abc ] ],
[ 'abc?', %w[ abc1 abcc abc_ abc. ] ],
[ 'a??c', %w[ abzc a12c a_?c a.!c ] ],
].each do |wildmat,inputs|
regexp = Wildmat.to_regexp(wildmat)
it "should match a single character: #{wildmat} =~ #{inputs}" do
inputs.each do |input|
input.should match regexp
end
end
it "should not match the negatives: #{wildmat} !~ #{negatives}" do
negatives.each do |input|
input.should_not match regexp
end
end
end
end
context 'backslash' do
# Negative cases
negatives = %w[ ab abd abcd ]
# Positive cases
[
[ '\a\b\c', %w[ abc ] ],
[ '\a\b\?', %w[ ab? ] ],
[ '\a\b\[', %w[ ab\[ ] ],
].each do |wildmat,inputs|
regexp = Wildmat.to_regexp(wildmat)
it "should match: #{wildmat} =~ #{inputs}" do
inputs.each do |input|
input.should match regexp
end
end
it "should not match: #{wildmat} != #{negatives}" do
negatives.each do |input|
input.should_not match regexp
end
end
end
end
context 'asterisk' do
# Test cases
[
[ 'a*b', %w[ ab aab abb a123b a_:-?=b ], %w[ ba aba ab123 123ab ] ],
[ 'ab*', %w[ ab aba abb ab123 ab_:-?= ], %w[ ba bab 123ab a123b ] ],
[ '*ab', %w[ ab aab bab 123ab _:-?=ab ], %w[ ba aba a123b ab123 ] ],
].each do |wildmat,inputs,negatives|
regexp = Wildmat.to_regexp(wildmat)
it "should match a single character: #{wildmat} =~ #{inputs}" do
inputs.each do |input|
input.should match regexp
end
end
it "should not match the negatives: #{wildmat} != #{negatives}" do
negatives.each do |input|
input.should_not match regexp
end
end
end
end
context 'character class' do
# Test cases
[
[ '[a-z]', %w[ a d z ], %w[ ab 0 - * ] ],
[ '[0-9]', %w[ 0 5 9 ], %w[ a 00 - * ] ],
[ '[a-]', %w[ a - ], %w[ b 0 a- * ] ],
[ '[-a]', %w[ a - ], %w[ b 0 -a * ] ],
[ '[]0-9]', %w[ \] 5 ], %w[ \]0 a - * ] ],
].each do |wildmat,inputs,negatives|
regexp = Wildmat.to_regexp(wildmat)
it "should match: #{wildmat} =~ #{inputs}" do
inputs.each do |input|
input.should match regexp
end
end
it "should not match: #{wildmat} != #{negatives}" do
negatives.each do |input|
input.should_not match regexp
end
end
end
end
context 'negative character class' do
# Test cases
[
[ '[^a-z]', %w[ 0 - * ], %w[ a d z ab ] ],
[ '[^0-9]', %w[ a - * ], %w[ 0 5 9 00 ] ],
[ '[^a-]', %w[ b 0 * ], %w[ a - a- ] ],
[ '[^-a]', %w[ b 0 * ], %w[ a - -a ] ],
[ '[^]0-9]', %w[ a - * ], %w[ \] 5 \]0 ] ],
].each do |wildmat,inputs,negatives|
regexp = Wildmat.to_regexp(wildmat)
it "should match: #{wildmat} =~ #{inputs}" do
inputs.each do |input|
input.should match regexp
end
end
it "should not match: #{wildmat} != #{negatives}" do
negatives.each do |input|
input.should_not match regexp
end
end
end
end
end
| true
|
8568de9555f7c347494d81f977be58992776a2f0
|
Ruby
|
Carmer/bike-share-1
|
/spec/models/station_spec.rb
|
UTF-8
| 3,589
| 2.859375
| 3
|
[] |
no_license
|
require_relative '../spec_helper'
RSpec.describe Station do
describe 'validations' do
it 'validates presence of name' do
station = Station.create(
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: 1
)
expect(station).to_not be_valid
end
it 'validates presence of city' do
station = Station.create(
name: "Blick & Lock",
dock_count: 1,
installation_date: 1
)
expect(station).to_not be_valid
end
it 'validates presence of dock_count' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
installation_date: 1
)
expect(station).to_not be_valid
end
it 'validates presence of installation_date' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1
)
expect(station).to_not be_valid
end
it 'is valid with valid parameters' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: '1/1/2017'
)
expect(station).to be_valid
end
end
describe 'installation_date format' do
describe 'date import' do
it 'imports correctly with single digit date where month and day are the same' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: "1/1/2017"
)
expect(station.installation_date).to eq(Date.parse("Jan 1 2017"))
end
it 'is valid with valid double digit date where month and day are the same' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: "10/10/2017"
)
expect(station.installation_date).to eq(Date.parse("Oct 10 2017"))
end
it 'switches month and day when importing valid date in m/d/Y format' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: "2/4/2017"
)
expect(station.installation_date).to_not eq(Date.parse("Feb 4 2017"))
end
it 'is nil when importing invalid date in m/d/Y format' do
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: "2/15/2017"
)
expect(station.installation_date).to eq(nil)
end
it 'is correct when m/d/Y single digit date is parsed before import' do
formatted = Date.strptime('2/15/2017', '%m/%d/%Y')
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: formatted
)
expect(station.installation_date).to eq(Date.parse("Feb 15 2017"))
end
it 'is correct when m/d/Y double digit date is parsed before import' do
formatted = Date.strptime('11/30/2017', '%m/%d/%Y')
station = Station.create(
name: "Blick & Lock",
city: City.create(name: "New Victoria"),
dock_count: 1,
installation_date: formatted
)
expect(station.installation_date).to eq(Date.parse("Nov 30 2017"))
end
end
end
end
| true
|
2a797a7225338f1b405099739c89cb5c5e08e46a
|
Ruby
|
blakeshall/CfA-Dashboard
|
/post.rb
|
UTF-8
| 1,484
| 2.515625
| 3
|
[] |
no_license
|
require 'net/http'
require 'time'
require 'rubygems'
require 'json'
@host = 'localhost'
@port = '4567'
@post_ws = "/commit"
@payload ={
:before => "before",
:after => "after",
:ref => "ref",
:commits => [{
:id => "commit.id",
:message => "I fixed something",
:timestamp => "#{(Time.now - 800000).xmlschema}",
:url => "commit_url",
:added => "array_of_added_paths",
:removed => "array_of_removed_paths",
:modified => "array_of_modified_paths",
:author => {
:name => "someone",
:email => "commit.author.email"
}
}],
:repository => {
:name => "youcantseeme",
:url => "repo_url",
:pledgie => "repository.pledgie.id",
:description => "repository.description",
:homepage => "repository.homepage",
:watchers => "repository.watchers.size",
:forks => "repository.forks.size",
:private => "repository.private?",
:owner => {
:name => "repository.owner.login",
:email => "repository.owner.email"
}
}
}.to_json
def post
req = Net::HTTP::Post.new(@post_ws, initheader = {'Content-Type' =>'application/json'})
#req.basic_auth @user, @pass
req.body = @payload
response = Net::HTTP.new(@host, @port).start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:
#{response.body}"
end
thepost = post
puts thepost
| true
|
c30a3aa8ac5d194b24f6421997a8f99087997181
|
Ruby
|
elishevaelbaz/activerecord-validations-lab-nyc04-seng-ft-041920
|
/app/models/post.rb
|
UTF-8
| 509
| 2.84375
| 3
|
[] |
no_license
|
class Post < ActiveRecord::Base
validates :title, presence: true
validates :content, length: {minimum: 250}
validates :summary, length: {maximum: 250}
validates :category, inclusion: { in: %w(Fiction Non-Fiction)}
validate :non_clickbait
def non_clickbait
clickbait_arr = [ /Won't Believe/i, /Secret/i, /Top [0-9]*/i, /Guess/i]
if clickbait_arr.none? { |word| word.match self.title}
errors.add(:title, "is not clickbait-y enough")
end
end
end
| true
|
184eab30ac00be7c07d2498cdd299009c2022dd6
|
Ruby
|
jdollete/phase-0-tracks
|
/databases/module_8.5/workout_app.rb
|
UTF-8
| 5,399
| 3.390625
| 3
|
[] |
no_license
|
# An app to record your swole-ness
# Insert New Rows
# Input: String
# Step:
# - Ask user to input workout, weight, and reps Value
# - Input values into Database
# - Until user inputs they are done, loop through the Method
# Output: Updated Database
# Update Rows
# Input: String
# Step:
# - Ask User what they want to Update
# - Ask for new Value
# - Loop until user inputs done
# Output: Updated Database
# Delete Rows
# Input: Integer
# Step:
# - Ask User what they want to delete
# - Delete input from Database
# - Until user inputs done loop again
# Output: Updated Database
# User Interface
# Input: String
# Steps:
# - Welcome User by asking their name
# - Ask user for today's date
# - Ask user what actions they would like to do
# - Keep looping until user is done
# Output: Updated Database
# Require gems
require 'sqlite3'
# require 'faker'
# Create database
db = SQLite3::Database.new("workouts.db")
db.results_as_hash = true
create_table_cmd = <<-SQL
CREATE TABLE IF NOT EXISTS workout_data (
id INTEGER PRIMARY KEY,
date_workout INT,
workout VARCHAR(255),
weight INT,
reps INT
)
SQL
# Method Code ------------------------------------------------------------------
def insert_workout(db, date, user_continue)
while user_continue != 'no'
system ("clear")
puts "---Get Swole App---".center(150)
puts "Please Insert Workout Details"
puts "Workout: "
workout = gets.chomp
puts "Weight (lb): "
weight = gets.to_i
puts "Reps: "
reps = gets.to_i
db.execute("INSERT INTO workout_data (date_workout, workout, weight, reps) VALUES (?, ?, ?, ?)", [date, workout, weight, reps])
puts "Do you have more to add? (yes/no)"
user_continue = gets.chomp.downcase
end
end
#-------------------------------------------------------------------------------
def data_modify(db, user_continue)
while user_continue != 'no'
system ("clear")
puts "---Get Swole App---".center(150)
puts "Here is your current information"
puts '[Line ID -- Workout -- Weight -- Reps]'
db.execute("SELECT * FROM workout_data;").each do |row|
puts "#{row["id"]} - #{row["date_workout"]} - #{row["workout"]} - #{row["weight"]}lbs - #{row["reps"]} reps"
end
puts "Which line would you like to modify?"
modify_line = gets.to_i # Row ID
puts "What Column? [workout/weight/reps]"
modify_column = gets.chomp # Attribute
puts "New Value?"
if modify_column == "weight" || modify_column == "reps" # Value
modify_value = gets.to_i
if modify_column == "weight"
db.execute("UPDATE workout_data SET weight = ? WHERE id = ?", [modify_value, modify_line])
else
db.execute("UPDATE workout_data SET reps = ? WHERE id = ?", [modify_value, modify_line])
end
else
modify_value = gets.chomp
db.execute("UPDATE workout_data SET workout = ? WHERE id = ?", [modify_value, modify_line])
end
puts "Would you like to modify something else? (yes/no)"
user_continue = gets.chomp
end
end
#-------------------------------------------------------------------------------
def data_delete(db, user_continue)
while user_continue != "no"
system ("clear")
puts "---Get Swole App---".center(150)
puts '[Line ID -- Workout -- Weight -- Reps]'
db.execute("SELECT * FROM workout_data;").each do |row|
puts "#{row["id"]} - #{row["date_workout"]} - #{row["workout"]} - #{row["weight"]}lbs - #{row["reps"]} reps"
end
puts "Which Line would you like to delete?"
line_delete = gets.to_i
db.execute("DELETE FROM workout_data WHERE id = ?", [line_delete])
puts "Would you like to delete something else? (yes/no)"
user_continue = gets.chomp
end
end
#-------------------------------------------------------------------------------
def view_data(db)
system ("clear")
puts "---Get Swole App---".center(150)
puts '[Line ID -- Workout -- Weight -- Reps]'
db.execute("SELECT * FROM workout_data;").each do |row|
puts "#{row["id"]} - #{row["date_workout"]} - #{row["workout"]} - #{row["weight"]}lbs - #{row["reps"]} reps"
end
end
# Helper Code ------------------------------------------------------------------
# clear = system ("clear")
# title_app = puts "---Get Swole App---".center(150)
# refresh = clear, title_app # Did not work
user_continue = ""
# User Interface ---------------------------------------------------------------
system ("clear")
puts "---Get Swole App---".center(150)
puts "Input Name:"
user_name = gets.chomp
system ("clear")
puts "---Get Swole App---".center(150)
puts "Welcome #{user_name}, What is today's date? [mmddyyyy]"
date = gets.to_i
db.execute(create_table_cmd)
system ("clear")
puts "---Get Swole App---".center(150)
puts "What would you like to do today?"
puts "[Insert/Modify/Delete/View/Done]"
user_input = gets.chomp.downcase
# Driver Code ------------------------------------------------------------------
while user_input != 'done'
if user_input == 'insert'
insert_workout(db,date, user_continue)
elsif user_input == 'modify'
data_modify(db, user_continue)
elsif user_input == 'delete'
data_delete(db, user_continue)
elsif user_input == 'view'
view_data(db)
else
puts "Invalid Entry"
end
puts "Anything else you want to do? [insert/modify/delete/view/done]"
user_input = gets.chomp.downcase
end
| true
|
680df1b004e1d9406b5589b9fa01321fabfbf54b
|
Ruby
|
samchen2009/dep_tree
|
/dep_tree.rb
|
UTF-8
| 3,080
| 3.0625
| 3
|
[] |
no_license
|
# =========================================
# Script to pass the C header dependancy.
#
# Author: shanchen@marvell.com
# Revision:
# 0.1. 2012-09-04
# ==========================================
class Node
attr_accessor :name,:parent,:childs,:is_leaf
def initialize(name,parent=nil,is_leaf=false)
@name = name
@parent = parent
@childs = []
@is_leaf = is_leaf
end
def my_parents_has?(him)
node = self
while !is_root?(node) and node.name != him.name
node = node.parent
end
if (node.name == him.name)
#puts "find #{him.name} in parents"
end
return node.name == him.name
end
def is_root?(node)
node.parent.nil?
end
def add_child(child)
if !child.is_a?(Node)
child = Node.new(child,self)
return if my_parents_has?(node)
end
@childs << child #if !my_parents_has?(child)
puts "#{self.name} depends on #{child.name}"
end
def find_root()
node = self
while !node.parent.nil?
node = node.parent
end
node
end
def tree_has?(node)
root = find_root
found = root.has_child?(node)
#puts "====> #{node.name} already existed, not go into tree" if found == true
found
end
def has_child?(node)
found = false
self.childs.each do |child|
return true if (child.name == node.name)
return true if child.has_child?(node)
end
false
end
#return the dependancies name
def find_nodes(src_dir="./",full_tree=false)
file = File.open("#{@name}") if !self.is_leaf
file.each_line do |line|
match = /.*#include\s+[<|"](.*?)[\>|"]\s*/.match(line)
if !match.nil? and !match[1].nil?
header = match[1]
name = Dir.glob("#{src_dir}/**/#{header}").first
if name.nil? or name == ""
node = Node.new(header,self,true)
else
node = Node.new(name,self,false)
end
existed = full_tree ? my_parents_has?(node) : tree_has?(node)
if full_tree
add_child(node) if !existed
else
node.is_leaf = existed if !node.is_leaf
add_child(node)
end
end
end
self.childs
end
def build_tree(i,src_dir="./",options)
name = File.basename(self.name)
system("mkdir -p #{i}_#{name}")
return if self.is_leaf
Dir.chdir("#{i}_#{name}") do
childs = self.find_nodes(src_dir,!options.include?("i"))
childs.each do |c|
c.build_tree(i+1,src_dir,options) if !c.nil?
end
end
end
end
def show_tree(path)
puts `tree #{path}`
end
if ($0 == __FILE__)
usage = "usage: ruby dep_tree.rb path/to/your/source/code"
if (!ARGV[0])
puts usage
exit 1
end
options = []
filelist = []
ARGV.each do |arg|
if (arg =~ /^-(\w*)/)
options << arg.gsub(/^-/,'')
else
filelist << arg
end
end
src_dir = Dir.pwd
name = File.absolute_path(filelist.first)
root = Node.new(name)
system('mkdir -p ./tree')
system('rm ./tree/* -rf')
Dir.chdir("./tree") do
root.build_tree(0,src_dir,options)
end
show_tree("./tree")
end
| true
|
c9ee10c1dbac6818338598b556f1d2edbe0fa90f
|
Ruby
|
mabuelkhair/simple-filter
|
/db/seeds.rb
|
UTF-8
| 1,373
| 2.546875
| 3
|
[] |
no_license
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
Product.delete_all
Department.delete_all
Promotion.delete_all
ProductsPromotions.delete_all
d1 = Department.create(name: 'Electronics')
d2 = Department.create(name: 'Sports')
d3 = Department.create(name: 'Toys')
departments = [d1, d2, d3]
names = ['Electronics', 'Sports', 'Toys']
counter = 1
products = []
while counter <= 20
idx = rand(0..2)
price = rand(10.0..500.0).truncate(2)
product = Product.create(name: "#{names[idx]}_#{counter}", department: departments[idx], price: price)
products.append(product)
counter += 1
end
active_promotion = Promotion.create(active: true, code: 'act25', discount: 25.0)
inactive_promotion = Promotion.create(active: false, code: 'pro30', discount: 25.0)
active_promotion.products << products[0]
active_promotion.products << products[10]
active_promotion.products << products[18]
inactive_promotion.products << products[3]
inactive_promotion.products << products[13]
inactive_promotion.products << products[17]
active_promotion.save
inactive_promotion.save
| true
|
911ea3cfd8f502a4e6b4747224d4b70ee40f0ba7
|
Ruby
|
milikkan/intro-to-programming-with-ruby
|
/ch09-exercises/ex10.rb
|
UTF-8
| 168
| 3.578125
| 4
|
[] |
no_license
|
# Can hash values be arrays?
h = {a: [1, 2], b: [3, 4, 5]}
p h
# Can you have an array of hashes? (give examples)
arr = [{a: 1, b: 2}, {name: "bob", age: 24}]
p arr
| true
|
b2c64aab0cedd0553ca4dd171841fef8bbfc7970
|
Ruby
|
Tman22/new_enigma
|
/message.rb
|
UTF-8
| 453
| 3.28125
| 3
|
[] |
no_license
|
require 'pry'
class Message
attr_reader :message
Con = (' '..'z').to_a
def initialize(message)
@message = message
end
def split
@message = @message.chars
end
def assign_to_constant
message = split
message_index = message.map do |letter|
Con.index(letter)
end
message_index
end
def reverse_on_constant(moding_array)
encrypt_array = moding_array.map do |num|
Con.fetch(num)
end
end
end
| true
|
7a4aea8111d9a42c211d599874bdc108cd68aae5
|
Ruby
|
msilen/rbets
|
/lib/gamebookers.rb
|
UTF-8
| 4,654
| 2.71875
| 3
|
[] |
no_license
|
require 'rubygems'
require 'celerity'
require 'gamebookers_helper'
require 'ruby-debug'
Debugger.start
Celerity.index_offset = 0 #настройка Celerity для индексов с 0
class Gamebookers < Celerity::Browser
include GamebookersHelper
def run
establish_connection
get_links_of_sports
iterate_through_valid_sports
print "\e[0m"
end
def establish_connection
@bookmaker=Bookmaker.where(:name => "Gamebookers").first
puts "connecting..."
goto @bookmaker.website
end
#получаем весь список ссылок с видами спорта
def get_links_of_sports
@mainpage_links_of_sports_hrefs= div(:class, "leftNavText").ul(:index=>0).links.map &:href
end
#проходим по ссылке если ставки на этом виде спорта подходят.
def iterate_through_valid_sports
@mainpage_links_of_sports_hrefs.each do |url|
debugger
goto(url)
get_data(url) if page_with_actual_matches?
end
end
#итерируем заглядывая в каждую лигу и тип ставки
def get_data(sport_url)
puts "========================================================"
puts sport_url
goto(sport_url)
select_leagues_and_parse_them
end
def select_leagues_and_parse_them
puts "\e[33mLeagues:\e[0m"
select_list_of_leagues_options=select_list(:id, 'leaguesSelect') #список опций лиг в Select List
leagues_to_scan=reject_redundant_today_options(select_list_of_leagues_options) #список лиг, без событий "сегодня или завтра", т.к они избыточны
leagues_to_scan.each do |league|
@league=league #лига, соревнование
puts "going in: \e[34m" + league +"\e[0m"
goto league_url(league, select_list_of_leagues_options) #идем на страничку текущей итерируемой лиги
parse_page if page_with_actual_matches? && appropriate_bet_type?# обработаем страницу, если подходит по параметрам
back
end
end
def parse_page
odds=elements_by_xpath "//a[@class='bfhref']"# массив коэффициентов
first_x_second(odds) #проверяется является ли ставка 1Х2, и записывает в перем.экземпляра с аналогичным именем
box=[] #сюда временно(построчно) записываются коэф. в порядке их обработки (1й,2й) либо (1й,ничья,2й)
odds.each do |odd|
sides=find_sides(odd)#определим стороны
processed_sides=[] #обработанные стороны-соперники (вырезаны скобки если они есть)
debugger if sides.nil?
sides.flatten.each{|side|processed_sides<<strip_brackets(side)}
@sport=link(:class => "selectedBtn").text.strip.chomp# вид спорта
time=parse_date_string_to_utc(odd.parent.parent.parent.text)#дата события, класс Time
required_size= (@first_x_second) ? 3 : 2 #задаем размер кол-ва ставок на 1 событие (3 ставки для 1х2)
box<<odd.text
if box.size==required_size
coef1=box[0]
coef2=box[required_size-1] #второй коэфициент является либо 2м(если обычная ставка) либо 3м(если 1х2) после ничьи
draw=box[1] if @first_x_second
write_to_db(box, coef1, coef2, processed_sides, time, draw)
draw=nil #сброс значения после записи
box.clear
end
end
end
#запись в бд и вывод на экран отсканированной строки
def write_to_db(box, coef1, coef2, sides, time, draw)
c_1_cf=box[0] #коэффициент первого участника
print "\e[32m"
box.size==3 ? (draw, c_2_cf=box[1], box[2]) : (draw, c_2_cf=nil, box[1]) #задаются значения коэффициентов в зависимости от типа ставки
record=@bookmaker.bets.new(:competition => @league,:sport =>@sport, :competitor_one=>sides[0], :competitor_one_coef => c_1_cf, :draw => draw, :competitor_two => sides[1], :competitor_two_coef => c_2_cf , :event_date =>time)
@red_noprint=!record.valid? #печатать только новые
record.save
puts %Q(#{coef1} #{sides[0]} VS #{sides[1]} #{coef2} #{time} draw:#{draw}\e[0m) unless @red_noprint
print "\e[0m"
end
end
| true
|
92b338c755e2983baa796c5d1f1c395900b15a13
|
Ruby
|
GabbySang/battleattackgame
|
/spec/player_spec.rb
|
UTF-8
| 437
| 2.625
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'player'
describe Player do
subject { described_class.new('Gabby') }
describe '#name' do
it 'returns the player\'s name' do
expect(subject.name).to eq('Gabby')
end
end
describe '#receive_damage' do
it 'reduces a players hp' do
expect(subject.hp).to eq(Player::DEFAULT_HP)
expect { subject.receive_damage }.to change { subject.hp }.by(-10)
end
end
end
| true
|
3478ef545acdaffae9eceac4cb6f414c59f8d0b4
|
Ruby
|
Bohurtadop/CodumAcademy
|
/Kata04/Kata04.rb
|
UTF-8
| 1,634
| 3.8125
| 4
|
[] |
no_license
|
## PARTE 3: DRY FUSION
def calculateDiference(array)
thingWithLessDiference = ""
lessDiference = 100
for i in array
if i[1] < lessDiference
lessDiference = i[1]
thingWithLessDiference = i[0]
end
end
thingWithLessDiference
end
## LEYENDO WEATHER.dat
columnNames = 0
tempDays = []
file = File.open("weather.dat", "r").readlines.each do |linea|
if columnNames < 2
columnNames += 1
else
numberDay = linea[2..3]
maxTemp = linea[6..9].to_f
minTemp = linea[12..15].to_f
tempDays << [numberDay, maxTemp - minTemp]
end
end
#dayWithLessDiference = ""
#lessDiference = 100
#for i in tempDays
# if i[1] < lessDiference
# lessDiference = i[1]
# dayWithLessDiference = i[0]
# end
#end
puts "El día con menor diferencia de temperatura es el día número #{calculateDiference(tempDays)}."
## LEYENDO FOOTBALL.dat
columnNames = 0
teams = []
file = File.open("football.dat", "r").readlines.each do |linea|
if columnNames < 2
columnNames += 1
else
teamName = linea[7..20]
if teamName == "--------------"
break
else
f = linea[43..44].to_i
a = linea[50..51].to_i
if f > a
teams << [teamName, f - a]
else
teams << [teamName, a - f]
end
end
end
end
#teamWithLessDiference = ""
#lessDiference = 100
#for i in teams
# if i[1] < lessDiference
# lessDiference = i[1]
# teamWithLessDiference = i[0]
# end
#end
puts "El equipo con menor diferencia de goles 'para' y 'en contra' es el equipo #{calculateDiference(teams)}."
| true
|
6293656318bd8d914c9ebe568166b7b577f06950
|
Ruby
|
aaj3f/liquery-cli
|
/lib/LiquerY/drink.rb
|
UTF-8
| 5,516
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
class Drink
attr_accessor :idDrink, :strDrink, :all_ingredients, :strIngredient1, :strIngredient2, :strIngredient3, :strIngredient4, :strIngredient5, :strIngredient6, :strIngredient7, :strIngredient8, :strIngredient9, :strMeasure1, :strMeasure2, :strMeasure3, :strMeasure4, :strMeasure5, :strMeasure6, :strMeasure7, :strMeasure8, :strInstructions, :palate
TEST_DRINKS = ["Boulevardier", "Cosmopolitan", "Dirty Martini", "Espresso Martini", "French Negroni", "Gimlet", "Gin Rickey", "Greyhound", "Lemon Drop", "Manhattan", "Martini", "Mojito", "Old Fashioned", "Pisco Sour", "The Last Word"]
DUMMY_DRINK = Drink.new.tap {|d| d.all_ingredients = ["a single bogus and insane ingredient that won't match anything"]}
@@all = []
def self.all
@@all.empty? ? Drink.new_from_hash : @@all
end
def self.new_from_hash(hash = DrinkAPI.new.make_hash)
hash.each do |id, drink_array|
drink = self.new
drink.all_ingredients = []
correct_and_set_data(drink, drink_array)
concat_ingredients(drink)
filter_and_set_by_palate(drink)
@@all << drink unless drink.idDrink == "14133" #To filter out "Cosmopolitan Martini, which for some reason is included in the database twice under different spellings."
end
@@all
end
def self.select_for_test
self.all.select {|d| TEST_DRINKS.include?(d.strDrink)}
end
def print_ingredients
self.all_ingredients.each.with_object("") do |ing, string|
if ing == self.all_ingredients[-1]
string << "and #{ing}."
else
string << "#{ing}, "
end
end
end
def self.search_by_drink_name(name)
name_match = FuzzyMatch.new(Drink.all.map{|d| d.strDrink}).find("#{name}")
if Drink.all.find {|d| d.strDrink == name}
Drink.all.find {|d| d.strDrink == name}
elsif name_match
Drink.all.find {|d| d.strDrink == name_match }
end
end
def self.search_by_alcohol_name(name)
name_match = FuzzyMatch.new(Drink.all.map{|d| d.all_ingredients}.flatten).find("#{name}")
if Drink.all.map {|d| d.all_ingredients}.flatten.include?(name)
Drink.all.select {|d| d.all_ingredients.include?(name)}
elsif name_match
Drink.all.select {|d| d.all_ingredients.include?(name_match)}
end
end
def self.find_ingredients_by_drink_name(name)
drink = self.search_by_drink_name(name)
system "clear"
puts "Drink Ingredients:".light_blue
puts "\n#{drink.strDrink} --".cyan
puts "#{drink.print_ingredients}".cyan
end
def self.find_recipe_by_drink_name(name)
drink = self.search_by_drink_name(name)
system "clear"
puts "Drink Recipe:".light_blue
puts "\n#{drink.strDrink} --".cyan
puts "Ingredients: ".cyan + "#{drink.print_ingredients}".light_blue
puts "#{drink.strInstructions}".cyan
end
def self.search_by_palate(palate)
Drink.all.select {|d| d.palate == palate}
end
private
def self.correct_and_set_data(drink, drink_array)
drink_array.each do |method, arg| ###REMOVE THIS ZERO WHEN YOU PULL FROM API!!!
if !(["strDrink", "strInstructions"].include?(method))
if drink.respond_to?("#{method}") && arg.is_a?(String) && arg.include?("Absolut")
drink.send("#{method}=", "Vodka") #Had to hardcode this in
#because for almost every drink they list a generic liquor
#as an ingredient, except for, frustratingly, certain vodka
#drinks, for which they give a brand name Absolut variety
#that messes up my algorithm
elsif drink.respond_to?("#{method}") && arg.is_a?(String) && (arg.include?("lemon") || arg.include?("Lemon"))
drink.send("#{method}=", "Lemon Juice")
drink.send("strIngredient9=", "Simple Syrup")
elsif drink.respond_to?("#{method}") && arg.is_a?(String) && (arg.include?("Sugar") || arg.include?("Simple"))
drink.send("#{method}=", "Simple Syrup")
elsif drink.respond_to?("#{method}") && arg.is_a?(String) && arg.include?("Lime")
drink.send("#{method}=", "Lime Juice")
elsif drink.respond_to?("#{method}") && arg != " " && arg != ""
drink.send("#{method}=", arg)
end
elsif drink.respond_to?("#{method}") && arg != " " && arg != ""
drink.send("#{method}=", arg)
end
end
end
def self.filter_and_set_by_palate(drink)
if (drink.all_ingredients.map {|d|d.downcase} & ["cream", "milk", "kahlua", "bailey", "bailey\'s irish cream", "creme de cacao", "white creme de menthe", "hot chocolate", "coffee liqueur", "chocolate liqueur", "pina colada mix"]).any?
drink.palate = "creamy"
elsif (drink.all_ingredients.map {|d|d.downcase} & ["lime juice", "lemon juice"]).any? && !(drink.all_ingredients.map {|d|d.downcase}.include?("simple syrup")) || (drink.all_ingredients.map {|d|d.downcase} & ["sour mix", "sweet and sour", "pisco"]).any?
drink.palate = "bright"
elsif (drink.all_ingredients.map {|d|d.downcase} & ["simple syrup", "grenadine", "creme de cassis", "apple juice", "cranberry juice", "pineapple juice", "maraschino cherry", "maraschino liqueur", "grape soda", "kool-aid"]).any?
drink.palate = "sweet"
else
drink.palate = "dry"
end
end
def self.concat_ingredients(drink)
drink.instance_variables.map{|v|v.to_s.tr('@', '')}.select{|v| v.match(/^strIng/)}.each do |v|
unless (drink.send("#{v}") == nil || drink.all_ingredients.include?(drink.send("#{v}")))
drink.all_ingredients << drink.send("#{v}")
end
end
end
end
| true
|
90fbbb88bb26bf7288c401036e26d8a60bb4cced
|
Ruby
|
philmccarthy/backend_mod_1_prework
|
/day_1/lesson_one/ex11.rb
|
UTF-8
| 385
| 4.28125
| 4
|
[] |
no_license
|
print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "What unit of measure was that? "
height_unit = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
print "What unit of measure was that? "
weight_unit = gets.chomp
puts "So, you're #{age} years old, #{height + " " + height_unit} tall and #{weight + " " + weight_unit} heavy."
| true
|
499aba0483aeb780ac4b5d8a990fd47ccfd6d933
|
Ruby
|
1i1it/tea-BE
|
/bl/teas.rb
|
UTF-8
| 1,348
| 2.59375
| 3
|
[] |
no_license
|
CATEGORIES = ["Green", "Red", "White", "Black"]
TEAS = ["Lotus", "Fruit", "Roibus", "Lemon"]
IMAGES = ["http://f.tqn.com/y/britishfood/1/0/f/0/-/-/tealeaves.jpg", "https://auntpattysporch.files.wordpress.com/2015/09/loose-leaf-tea.jpg", "http://pad1.whstatic.com/images/thumb/f/f7/Store-Loose-Leaf-Tea-Step-1.jpg/aid845114-728px-Store-Loose-Leaf-Tea-Step-1.jpg"]
# product page
get "/one_tea" do
tea = Tea.where('_id' => params[:_id]).first
{tea:tea}
end
# homepage
get '/expensive_teas' do
teas = Tea.order_by(:price => 'desc').limit(9).to_a
{teas:teas}
end
#products page that displays a list of teas with filters
get '/show_teas' do
opts = nil
criteria = {}
criteria[:name] = {"$regex" => Regexp.new(params[:name], Regexp::IGNORECASE) } if params[:name].present?
criteria[:caffein_free] = (params[:caffein_free] == 'true') if criteria[:caffein_free]
criteria[:category] = params['category'].capitalize if params['category']
teas = Tea.where(criteria).to_a
{teas:teas}
end
def seed_data()
9.times { category = CATEGORIES.sample
Tea.new({
_id: nice_id,
name: TEAS.sample,
price: rand(30).to_i,
category: category,
caffein_free: true,
description: "Great " + category + " tea",
image: IMAGES.sample}).save
}
end
def remove_fake_teas
Tea.delete_all
end
| true
|
407ded902a44b1f44a6f504225a7504288a773af
|
Ruby
|
hswick/protosemiotics
|
/network.rb
|
UTF-8
| 2,361
| 3
| 3
|
[] |
no_license
|
require './node'
#Gene [act_id, out_id, init_value1, init_value2]
#Id_range is the max number of genes in a chromosome (genome)
class Network
def initialize(num_nodes=0, id_range = 100, num_act_fns=5)
@nodes = {}
for i in 0..num_nodes-1
@nodes[i] = Node.new(i, rand(num_act_fns), rand(id_range), rand_weight, rand_weight)
end
setup_state
end
def setup_state
@edges = []
connect_nodes
@event_queue = []
@logging = false
@log = []
@timesteps = 0
end
def turn_off_logging
@logging = false
end
def rand_weight
n = rand(3)
if n == 0
return 0
elsif n == 1
return 1
else
return nil
end
end
def connect_nodes
@nodes.each do |id, n|
out_id = n.get_out_id
n2 = @nodes[out_id]
if n2 != nil
if n2.not_full_inputs?
if n2.input1_taken?
n2.set_input1 id
@edges << [id, n2.get_id]
else
n2.set_input2 id
@edges << [id, n2.get_id]
end
end
end
end
end
def push_events
@nodes.each do |id, node|
node.push_activation(@event_queue)
end
end
def process_event(packet)
to = packet[0]
from = packet[1]
val = packet[2]
@nodes[to].update_edge_state from, val if @nodes[to]
end
def pop_events
if !@event_queue.empty?
until @event_queue.empty?
process_event(@event_queue.pop)
end
return false
else
return true
end
end
def timestep
push_events
@log << Array.new(@event_queue) if @logging
out = pop_events
@timesteps+=1
out
end
def reset
@nodes.each do |id, n|
n.reset
end
end
def simulate(max_timesteps=100)
i = 0
stopped = false
until i == max_timesteps || stopped
stopped = timestep
i+=1
end
reset
i
end
def dump_log
puts "LOG DUMP"
@log.each_with_index do |row, i|
puts "TIMESTEP: " + i.to_s
print row.to_s + "\n"
end
end
def to_genes
genes = []
n = nodes[0].to_gene.length
for i in 0..n-1
genes << []
end
for i in 0..nodes.length-1
nodes[i].to_gene.each_with_index do |dna, j|
genes[j] << dna
end
end
genes
end
def from_genes(genes)
#Transposition could potentially get optimized by gpu
genes.transpose.each_with_index do |gene, i|
@nodes[i] = Node.new(i, gene[0], gene[1], gene[2], gene[3])
end
setup_state
self
end
def nodes
@nodes
end
def edges
@edges
end
def event_queue
@event_queue
end
end
| true
|
60d070122120fdff581d787857ab00730881137c
|
Ruby
|
homeflow/homeflow_api
|
/lib/homeflow/api/request.rb
|
UTF-8
| 4,036
| 2.578125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Homeflow
module API
YAML::ENGINE.yamler= 'syck' if defined?(YAML::ENGINE)
class Request
include HTTParty
attr_accessor :resource_class, :request_specification
def initialize(request_specification)
@request_specification = request_specification
end
def perform
begin
response = body_of_request(perform_request)
rescue Errno::ECONNREFUSED => e
raise Homeflow::API::Exceptions::APIConnectionError, "Homeflow might be down? Connection error: #{e}"
end
response
end
def perform_request
url = normalised_base_url
query_params = @request_specification.to_params.merge(constant_params)
post_params = (@request_specification.respond_to?(:post_params) ? @request_specification.post_params : {})
if Homeflow::API.config.show_debug && Homeflow::API.configuration.logger
log_line = []
log_line << "Destination - #{url}"
log_line << "Request params:\n#{query_params.to_json}\n"
log_line << "Post params:\n#{post_params.to_json}\n"
log_line << "request_specification:\n#{request_specification.to_json}\n"
log_line << "@request_specification:\n#{@request_specification.to_json}\n"
Homeflow::API.configuration.logger.info(log_line.join("\n"))
end
if request_specification.is_a? Query
return (self.class.get(url, :query => query_params))
elsif request_specification.is_a? ResourceIdentifier
return (self.class.get(url, :query => query_params))
elsif request_specification.is_a? Delete
return (self.class.delete(url, :query => query_params))
elsif request_specification.is_a? Put
return (self.class.put(url, :query => query_params, :body => post_params))
elsif request_specification.is_a? Post
return (self.class.post(url, :query => query_params, :body => post_params))
end
end
def normalised_base_url
source = Homeflow::API.config.source.chomp('/')
if request_specification.is_a? Query
if source_athena && is_resource?('site_content_chunks')
source = source_athena
elsif source_properties && is_resource?('properties')
source = source_properties
elsif source_places && is_place_based_resource?
source = source_places
end
return "#{source}/#{request_specification.resource_class.resource_uri}"
else
if source_places && ["locations", "postcodes", "places", "counties"].map{|i| request_specification.resource_uri.include?(i)}.include?(true)
source = source_places
elsif source_properties && (request_specification.resource_uri.include?('properties'))
source = source_properties
end
return "#{source}/#{request_specification.resource_uri}"
end
end
def _source(source_id)
return nil if Homeflow::API.config.send("source_#{source_id}").blank?
Homeflow::API.config.send("source_#{source_id}").chomp('/')
end
def source_athena
_source('athena')
end
def source_places
_source('places')
end
def source_properties
_source('properties')
end
def is_place_based_resource?
is_resource?('places') || is_resource?('locations') || is_resource?('postcodes') || is_resource?('counties')
end
def is_resource?(resource_id)
request_specification.resource_class.resource_uri == resource_id
end
def body_of_request(request)
if request.respond_to? :body
request.body
else
request
end
end
def constant_params
{
:api_key => Homeflow::API.config.api_key,
:request_key => Homeflow::API.config.request_key
}
end
class << self
def run_for(request_specification)
r = Request.new(request_specification)
r = r.perform
if r.is_a? Hash
Response.new(r)
else
Response.new_from_json(r)
end
end
end
end
end
end
| true
|
1f3af3cacffd8a0348c7bf5b0a68fdb82600489f
|
Ruby
|
Tkam13/atcoder-problems
|
/abc154/c.rb
|
UTF-8
| 108
| 2.703125
| 3
|
[] |
no_license
|
n = gets.to_i
as = gets.chomp.split.map(&:to_i)
if as.size == as.uniq.size
puts "YES"
else
puts "NO"
end
| true
|
7f90a3a1828c67b9a3e51d29e6eb5260c18976b8
|
Ruby
|
adamluzsi/mpatch
|
/examples/hash.rb
|
UTF-8
| 376
| 2.859375
| 3
|
[] |
no_license
|
require "mpatch"
x = {}
(1..10000).each do |i|
x["key#{i}"] = i
end
t=Time.now
x.map_hash{ |k,v| { k.to_sym => v.to_s } }
puts Time.now - t
var= {hello: "world",no: "yes"}
puts var
var= [[:hello, "world"],[:no, "yes"]].map_hash{|k,v| {k => v} }
puts var.inspect
# require 'debugger'
# debugger
var = { hello: "world",no: 'yes' }.include_hash?( no: 'yes' )
puts var
| true
|
53a4b9e46928a32cd572a520f66b6f16e65322f2
|
Ruby
|
brittkistner/codewars
|
/day2/day2.rb
|
UTF-8
| 2,157
| 4.46875
| 4
|
[] |
no_license
|
# Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
def solution(nums)
if nums.class != Array || nums.length ==0
return []
end
nums.sort
end
# Santa's senior gift organizer Elf developed a way to represent up to 26 gifts by assigning a unique alphabetical character to each gift. After each gift was assigned a character, the gift organizer Elf then joined the characters to form the gift ordering code.
# Santa asked his organizer to order the characters in alphabetical order, but the Elf fell asleep from consuming too much hot chocolate and candy canes! Can you help him out?
# Sort the Gift Code
# Write a function called sortGiftCode (sort_gift_code in Ruby) that accepts a string containing up to 26 unique alphabetical characters, and returns a string containing the same characters in alphabetical order.
def sort_gift_code(str)
str.split('').sort.join('')
end
# Write a method sum that accepts an unlimited number of integer arguments, and adds all of them together.
# The method should reject any arguments that are not integers, and sum the remaining integers.
def sum(*integers)
array = []
array.push(*integers)
array.reject! {|num| num.class !=Fixnum}
sum = 0
array.each {|num| sum += num}
sum
end
# Christmas is coming and many people dreamed of having a ride with Santa's sleigh. But, of course, only Santa himself is allowed to use this wonderful transportation. And in order to make sure, that only he can board the sleigh, there's an authentication mechanism.
# Your task is to implement the authenticate() method of the sleigh, which takes the name of the person, who wants to board the sleigh and a secret password. If, and only if, the name equals "Santa Claus" and the password is "Ho Ho Ho!" (yes, even Santa has a secret password with uppercase and lowercase letters and special characters :D), the return value must be true. Otherwise it should return false.
def authenticate(name, password)
if name != "Santa Claus" || password != "Ho Ho Ho!"
return false
end
true
end
| true
|
74ce87510e8533adaf264b7b1a5ca6dbb7e5428d
|
Ruby
|
kaiogoncarvalho/ruby-codesaga
|
/2 - Primeiros passos com Ruby/2 - Trabalhando com coleções/4 - Salvar e carregar arquivos/Desafio/task_list.rb
|
UTF-8
| 2,785
| 3.671875
| 4
|
[] |
no_license
|
def menu()
puts "Bem-vindo ao Task List! Escolha uma opção no menu: \n"
puts '[1] Inserir uma tarefa'
puts '[2] Ver todas as tarefas'
puts '[3] Buscar tarefa'
puts '[4] Marcar tarefa como finalizada'
puts '[5] Sair'
puts
print 'Opção escolhida: '
gets.to_i
end
def show(tarefas)
tarefas.each_with_index do |item, index|
if item
status = item[:status] ? 'Finalizado' : 'Não Finalizado'
puts "##{index + 1} - #{item[:name]} - #{status}"
end
end
end
def search(array, searches)
results = []
searches.each do |item|
results[array.find_index{ |i| i.object_id == item.object_id }] = item
end
results
end
def change_status(tarefa)
tarefa[:status] = true
end
def load_tarefas
tarefas = []
if File.exist?('task.txt')
file = File.read('task.txt')
lines = file.split("\n")
lines.each do |line|
registers = line.split('||')
tarefas[registers[0].to_i] = {name:registers[1], status: (registers[2] == 'true' ? true : false)}
end
end
tarefas
end
tarefas = load_tarefas
while true do
opcao = menu()
case opcao
when 1
print 'Digite sua tarefa: '
tarefa = gets.strip
system('clear')
if /\|\|/.match?(tarefa)
puts "Caracteres não permitidos '||'"
else
tarefas << { name:tarefa, status:false }
puts 'Tarefa cadastrada: ' + tarefa
end
when 2
system('clear')
if tarefas.length == 0
puts 'Não existem tarefas cadastradas'
puts
next
end
puts 'Tarefa(s) Cadastrada(s): '
show(tarefas)
when 3
print 'Digite a busca: '
search = gets.strip
results = search(tarefas, tarefas.find_all {|item| item[:name].casecmp?(search) })
system('clear')
if results.length > 0
puts 'Tarefa(s) encontrada(s): '
show(results)
else
puts 'Não foi encontrado nenhuma tarefa.'
end
when 4
system('clear')
results = search(tarefas, tarefas.find_all {|item| item[:status] == false })
if results.length == 0
puts 'Não existem tarefas não finalizadas'
puts
next
end
puts 'Tarefa(s): '
show(results)
puts
print 'Informe o ID da tarefa: '
id = gets.strip.to_i
tarefa = tarefas[id-1]
system('clear')
if tarefa && id > 0 && tarefa[:status] == false
change_status(tarefa)
puts "Tarefa '#{tarefa[:name]}' foi marcada como finalizada"
else
puts 'Tarefa não encontrada.'
end
when 5
File.open('task.txt', 'w') do |file|
tarefas.each_with_index do |item, index|
file.write("#{index}||#{item[:name]}||#{item[:status]}\n")
end
end
system('clear')
puts 'Tarefas foram salvas'
puts
break
else
system('clear')
puts 'Opção Inválida'
end
puts
end
| true
|
31e4faef6599b1c37c4d9d2fa84d0af67b44fe8a
|
Ruby
|
ares/vzory
|
/pruby/e06/transmitters.rb
|
UTF-8
| 390
| 2.90625
| 3
|
[] |
no_license
|
class StandardTransmitter
def puts(str)
Kernel.puts str
end
end
class DebugTransmitter
def puts(str)
Kernel.puts "size: #{str.size}"
Kernel.puts "message: #{str.inspect}"
end
end
class FileTransmitter
def initialize(f)
@file = f
end
def puts(str)
@file.puts str
rescue => e
Kernel.puts "could not trasmit data"
Kernel.puts e.message
end
end
| true
|
c1667c7ef5b9dbda5dc0c48eb1a06ed0b00771c6
|
Ruby
|
thelazycamel/tinia
|
/lib/tinia/query_builder.rb
|
UTF-8
| 2,115
| 2.8125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Tinia
class QueryBuilder
def initialize(klass, query, opts)
@klass = klass
@query = query
@opts = opts
end
def build
AWSCloudSearch::SearchRequest.new.tap do |req|
bq_terms = ["type:'#{@klass.name}'"]
if @query.present?
if @query =~ /[:\)\(]/
# The query is already an expression, not just a text phrase
bq_terms << @query
else
bq_terms << "'#{@query}'"
end
end
# Every key in the opts hash, with exception of these four below, is considered
# a filter key, that is, the key-value pair will be converted to a term in the
# boolean query (bq) that will be sent to CloudSearch.
# These four are CloudSearch parameters on their own, and so are treated differently.
filters = @opts.reject {|k, v| [:page, :per_page, :order_by, :sort_mode].include?(k)}
filters.each do |field, value|
bq_terms << case value
when Array then array_param(field, value)
when Range then range_param(field, value)
else simple_param(field, value)
end
end
req.bq = to_and_query(bq_terms.reverse) # TODO: remove reverse?
req.size = @opts[:per_page].to_i
req.start = (@opts[:page].to_i - 1) * @opts[:per_page].to_i
if @opts[:order_by].present?
req.rank = @opts[:order_by].to_s
req.rank = ('-' + req.rank) if @opts[:sort_mode] == :desc
end
end
end
def simple_param(key, value)
index_field = @klass.base_class.cloud_search_config.find_index_field(key)
if index_field
index_field.to_param(value)
else
raise Tinia::MissingIndexField.new(key)
end
end
def array_param(key, value)
to_or_query(value.map {|val| simple_param(key, val)})
end
def range_param(key, value)
"#{key}:#{value}"
end
def to_and_query(terms)
"(and #{terms.join(' ')})"
end
def to_or_query(terms)
"(or #{terms.join(' ')})"
end
end
end
| true
|
f60377c4817ee4206edebff51db3825fb43fff9e
|
Ruby
|
pedronotpaydro/params_game_app
|
/app/controllers/api/params_controller.rb
|
UTF-8
| 691
| 2.546875
| 3
|
[] |
no_license
|
class Api::ParamsController < ApplicationController
def name_action
input_value = params["your_name"].upcase
@output_value = "Your name is #{input_value}"
render "name.json.jb"
end
def number_guess_action
winning_number = 33
input_value = params["guess"].to_i
@question = "Guess the number"
if input_value < winning_number
@output_value = "Too low"
elsif input_value > winning_number
@output_value = "Too high"
else
@output_value = "You got it! "
end
render "guess.json.jb"
end
def display_body_action
input_value = params["username"]
output_value = "test #{input_value}"
render "body.json.jb"
end
end
| true
|
e4a42260253fedc91e39d7745f1baef12ee45484
|
Ruby
|
devvmh-forks/sandi_meter
|
/lib/sandi_meter/calculator.rb
|
UTF-8
| 5,221
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
module SandiMeter
class Calculator
def initialize
@data = {classes: [], methods: {}, method_calls: []}
@output = {}
end
def push(data)
data.each_pair do |key, value|
if value.kind_of?(Array)
@data[key] ||= []
@data[key] += value
elsif value.kind_of?(Hash)
@data[key] ||= {}
@data[key].merge!(value)
end
end
end
def calculate!(store_details = false)
@store_details = store_details
check_first_rule
check_second_rule
check_third_rule
check_fourth_rule
@output
end
private
def log_first_rule
@output[:first_rule][:log] ||= {}
@output[:first_rule][:log][:classes] = @data[:classes].inject([]) do |log, klass|
log << [klass.name, klass.size, klass.path] if klass.last_line && !klass.small?
log
end
@output[:first_rule][:log][:misindented_classes] = @data[:classes].select { |c| c.last_line.nil? }.inject([]) do |log, klass|
log << [klass.name, nil, klass.path]
log
end
end
def log_second_rule
@output[:second_rule][:log] ||= {}
@output[:second_rule][:log][:methods] ||= []
@output[:second_rule][:log][:misindented_methods] ||= []
@data[:methods].each_pair do |klass, methods|
methods.select { |m| !m.misindented? && !m.small? }.each do |method|
@output[:second_rule][:log][:methods] << [klass, method.name, method.size, method.path]
end
end
@data[:methods].each_pair do |klass, methods|
methods.each do |method|
next unless method.misindented?
@output[:second_rule][:log][:misindented_methods] << [klass, method.name, method.size, method.path]
end
end
end
def log_third_rule
@output[:third_rule][:log] ||={}
@output[:third_rule][:log][:method_calls] ||= []
# TODO
# add name of method being called
proper_method_calls = @data[:method_calls].inject(0) do |sum, method_call|
@output[:third_rule][:log][:method_calls] << [method_call.number_of_arguments, method_call.path] if method_call.number_of_arguments > 4
end
end
def log_fourth_rule
@output[:fourth_rule][:log] ||={}
@output[:fourth_rule][:log][:controllers] ||= []
controllers.each do |controller|
methods_for(controller).select { |m| m.ivars.length > 1 }.each do |method|
@output[:fourth_rule][:log][:controllers] << [controller.name, method.name, method.ivars.uniq]
end
end
end
def controllers
@data[:classes].select { |c| c.controller? }
end
def methods_for(controller)
@data[:methods].fetch(controller.name) { [] }
end
def check_first_rule
total_classes_amount = @data[:classes].size
small_classes_amount = @data[:classes].select(&:small?).size
misindented_classes_amount = @data[:classes].select { |c| c.last_line.nil? }.size
@output[:first_rule] ||= {}
@output[:first_rule][:small_classes_amount] = small_classes_amount
@output[:first_rule][:total_classes_amount] = total_classes_amount
@output[:first_rule][:misindented_classes_amount] = misindented_classes_amount
log_first_rule if @store_details
end
def check_second_rule
total_methods_amount = 0
small_methods_amount = 0
@data[:methods].each_pair do |klass, methods|
small_methods_amount += methods.select { |m| m.small? }.size
total_methods_amount += methods.size
end
misindented_methods_amount = 0
@data[:methods].each_pair do |klass, methods|
misindented_methods_amount += methods.select { |m| m.last_line.nil? }.size
end
@output[:second_rule] ||= {}
@output[:second_rule][:small_methods_amount] = small_methods_amount
@output[:second_rule][:total_methods_amount] = total_methods_amount
@output[:second_rule][:misindented_methods_amount] = misindented_methods_amount
log_second_rule if @store_details
end
# TODO
# count method definitions argumets too
def check_third_rule
total_method_calls = @data[:method_calls].size
proper_method_calls = @data[:method_calls].inject(0) do |sum, method_call|
sum += 1 unless method_call.number_of_arguments > 4
sum
end
@output[:third_rule] ||= {}
@output[:third_rule][:proper_method_calls] = proper_method_calls
@output[:third_rule][:total_method_calls] = total_method_calls
log_third_rule if @store_details
end
def check_fourth_rule
proper_controllers_amount = 0
total_controllers_amount = 0
@data[:classes].select { |c| c.controller? }.each do |klass|
total_controllers_amount += 1
proper_controllers_amount += 1 unless @data[:methods][klass.name] && @data[:methods][klass.name].select { |m| m.ivars.uniq.size > 1 }.any?
end
@output[:fourth_rule] ||= {}
@output[:fourth_rule][:proper_controllers_amount] = proper_controllers_amount
@output[:fourth_rule][:total_controllers_amount] = total_controllers_amount
log_fourth_rule if @store_details
end
end
end
| true
|
b1e95b0ccccba9576d76774186028f48130c18fa
|
Ruby
|
steve-goldman/wespeak-rails
|
/test/helpers/statement_states_test.rb
|
UTF-8
| 973
| 2.609375
| 3
|
[] |
no_license
|
require 'test_helper'
class StatementStatesTest < ActiveSupport::TestCase
test "[] works" do
assert_equal 1, StatementStates[:alive]
assert_equal 2, StatementStates[:dead]
assert_equal 3, StatementStates[:voting]
assert_equal 4, StatementStates[:accepted]
assert_equal 5, StatementStates[:rejected]
assert_nil StatementStates[:bogus_key]
end
test "key? works" do
assert StatementStates.key?(:alive)
assert StatementStates.key?(:dead)
assert StatementStates.key?(:voting)
assert StatementStates.key?(:accepted)
assert StatementStates.key?(:rejected)
assert_not StatementStates.key?(:bogus_key)
end
test "value? works" do
assert StatementStates.value?(1)
assert StatementStates.value?(2)
assert StatementStates.value?(3)
assert StatementStates.value?(4)
assert StatementStates.value?(5)
assert_not StatementStates.value?(999999)
end
end
| true
|
8492cd9b4bd6b9aa4bf8f38c38f5379e5d1a3a67
|
Ruby
|
joe-hamilton/RB_101
|
/codewars_ls/7.rb
|
UTF-8
| 567
| 4.0625
| 4
|
[] |
no_license
|
# Substring Fun
=begin
problem:
Complete the function that takes an array of words.
You must concatenate the nth letter from each word to construct a new word
which should be returned as a string, where n is the position of the word in
the list.
=end
def nth_char(arr)
arr.map.with_index { |word, idx| word[idx] }.join
end
p nth_char(['yoda', 'best', 'has']) == "yes"
p nth_char([]) == ""
p nth_char(['X-ray']) == "X"
p nth_char(['No','No']) == "No"
p nth_char(['Chad','Morocco','India','Algeria','Botswana','Bahamas','Ecuador','Micronesia']) == "Codewars"
| true
|
ba724f672cb3efbb9a7f63e2bb0a62952ebb20bc
|
Ruby
|
terminalobject/battle
|
/spec/features/attack_spec.rb
|
UTF-8
| 894
| 2.84375
| 3
|
[] |
no_license
|
#spec/features/attack_spec.rb
feature 'attack' do
scenario 'attack Player 2 and get a confirmation' do
sign_in_and_play
click_button('Attack')
expect(page).to have_content('attacked')
end
end
feature 'decrease hp' do
scenario 'hp reduced by 10' do
sign_in_and_play
click_button('Attack')
click_button('Keep playing')
expect(page).to have_content 90
end
end
feature 'switching turns' do
scenario 'turns are switched after attack' do
sign_in_and_play
click_button('Attack')
click_button('Keep playing')
click_button('Attack')
click_button('Keep playing')
expect(page).to have_content('Lily 90/100HP vs. Dexter 90/100HP')
end
end
feature 'losing the game' do
scenario 'one of the players\' health goes to 0 or below' do
sign_in_and_play
both_players_attack_10_times
expect(page).to have_content("loses")
end
end
| true
|
9c4a820092793b741cf9495736e2dde1840717d0
|
Ruby
|
Gonozal/World-Gen
|
/polygon_math.rb
|
UTF-8
| 7,439
| 3
| 3
|
[] |
no_license
|
module WorldGen
class Polygon
# Bounding Box: [Vector[tl_x, tl_y], Vector[br_x, br_y]]: minimum bounding rect
# Vertices: [Vector[x1, y1], Vector[x2, y2], ... , Vector[xn, yn]]: defining points
attr_accessor :vertices, :bounding_box, :game_map, :opacity, :parent
def initialize(params)
params.each do |key, val|
send "#{key}=".to_sym, val if respond_to? "#{key}=".to_sym
end
self.bounding_box = set_bounding_box
self.opacity ||= 1
end
def fill_color
case parent.type
when :mountain then "rgba(139, 69, 19, #{opacity})"
when :lake then "rgba(15, 255, 240, #{opacity})"
when :swamp then "rgba(107, 142, 35, #{opacity})"
when :sea then "rgba(10, 10, 128, #{opacity})"
when :forest then "rgba(34, 139, 34, #{opacity})"
end
end
def stroke_color
case opacity
when 1 then "rgba(0, 0, 0, 0.6)"
else "rgba(0, 0, 0, 0.3)"
end
end
# Offset and scale vertice coordinates for map rendering
def map_vertices(mult = 1)
vertices.map do |v|
((v - game_map.offset) * game_map.zoom * mult).to_a
end
end
def map_offset(delta)
offset(delta).map do |v|
(v - game_map.offset) * game_map.zoom
end
end
# Checks if a point is inside the polygon shape of the terrain, returns true if so
def contains? position
# If POI is given instead of location, get location first
position = position.location if PointOfInterest === position
x = position[0]
y = position[1]
# Use the raycasting technique to determine if point is inside polygon
# We are in 2D, which makes it easier.
# We can also choose the direction of the ray, which makes it almost trivial
# (Choose ray paralell to x-achis
intersections = 0
[vertices, vertices.first].flatten.each_cons(2) do |v1, v2|
# Check if we are inside bounding recangle of 2 vertices
v1x = v1[0]
v1y = v1[1]
v2x = v2[0]
v2y = v2[1]
if (v1y < y and y <= v2y) or (v1y >= y and y > v2y)
# check if we are LEFT of or onthe line from v1 to v2 is at this x coordinate
cp.polygon(*p.map_vertices.map{|v| v.to_a}.flatten)
vx = v2x - v1x
vy = v2y - v1y
if (x <= v1x and x < v2x)
intersections +=1
elsif x >= v1x and x > v2x
next
else
x_line = v1x + vx * (y - v1y) / vy
if vy == 0 or vx == 0 or x < x_line
intersections += 1
end
end
end
end
return intersections.odd?
end
# Calculates the distance from self (polygon) to a vector or POI
def distance position
return -1 if contains? position
# If POI is given instead of location, get location first
position = position.location if PointOfInterest === position
# Set a ridiculous min distance. Any way around this?
min_dist = 999999999
# Iterate over every edge-point (vertex)
vertices.each_cons(2) do |vertices|
c_v = vertices[0]
o_v = vertices[1]
r = ((c_v - o_v) * (position - o_v)) / (position - o_v).magnitude
if r < 0 then dist = (position - o_v).magnitude
elsif r > 1 then dist = (c_v - position).magnitude
else dist = (position - o_v).magnitude ** 2 - r * (c_v - o_v).magnitude ** 2
end
min_dist = [dist, min_dist].min
end
min_dist
end
def set_bounding_box
min_x = min_y = 999999
max_x = max_y = 0
vertices.each do |v|
min_x = [min_x, v[0]].min
min_y = [min_y, v[1]].min
max_x = [max_x, v[0]].max
max_y = [max_y, v[1]].max
end
self.bounding_box = [Vector[min_x, min_y], Vector[max_x, max_y]]
end
def random_point_inside
candidate_x = (bounding_box[0][0]..bounding_box[1][0])
candidate_y = (bounding_box[0][1]..bounding_box[1][1])
return Vector[candidate_x, candidate_y] if contains? Vector[candidate_x, candidate_y]
end
####################################################
#### Offset Polygon ###
#### Functions ###
####################################################
# Get the orientation of a polygon
# Pick "bottom left" corner vertex (and adjacent oes)
# determine orientation matrix of this sub-polygon (which is guaranteed to be convex)
def orientation
p1, p2, p3 = *convex_sub_polygon
det = (p2[0]-p1[0])*(p3[1]-p1[1]) - (p3[0]-p1[0])*(p2[1]-p1[1])
@orientation ||= (det < 0)? 1 : -1
end
# Returns a set of 3 points along a convex subsection of the polygon
def convex_sub_polygon
subsets = []
vertices.each_cons(3) do |p1, p2, p3|
subsets << [p2, [p1, p2, p3]]
end
subsets.sort.first.last
end
# delta: Integer -- Offset amount
def offset(delta, dist = 1.5)
# set delta according to polygon direction, set veriables for first and last p/l
delta = delta * orientation
p_first, p_last = nil; offset_lines = []
l_first, l_last = nil; offset_points = []
refined_points = []
# Offset lines between 2 consecutive vertices out by delta
vertices.each_cons(2) do |p1, p2|
p_first ||= p1; p_last = p2 # save first and last vector for final line
offset_lines << offset_line(p1, p2, delta)
end
offset_lines << offset_line(p_last, p_first, delta)
# Calculate intersections between adjacent lines for new vertices
offset_lines.each_cons(2) do |l1, l2|
l_first ||= l1; l_last = l2 # save first and last vector for final intersection
offset_points << line_intersection(l1, l2)
end
offset_points.insert(0, line_intersection(l_first, l_last))
# Smooth corners of very acute angles
offset_points.each_with_index do |p, key|
v = p - vertices[key]
if v.magnitude > (dist * delta).abs
p2 = vertices[key] + v.normalize * dist * delta.abs
# normal vector for 2 vertices through a point dist*delta away
cutoff_line = [p2, p2 + v.normal_vector]
[-1, 0].each do |i|
if key + i < 0
n = offset_lines.size - 1
elsif key + i >= offset_lines.size
n = 0
else
n = key + i
end
refined_points << line_intersection(cutoff_line, offset_lines[n])
end
else
refined_points << p
end
end
refined_points
end
# calculate line intersections
# most likely used to calculate new points for an offset polygon
def line_intersection(l1, l2)
x1 = l1[0][0]; x2 = l1[1][0]; x3 = l2[0][0]; x4 = l2[1][0]
y1 = l1[0][1]; y2 = l1[1][1]; y3 = l2[0][1]; y4 = l2[1][1]
denominator = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)
return false if denominator == 0
dxy12 = (x1*y2 - y1*x2)
dxy34 = (x3*y4 - y3*x4)
x = (dxy12*(x3-x4) - (x1-x2)*dxy34) / denominator
y = (dxy12*(y3-y4) - (y1-y2)*dxy34) / denominator
WorldGen::Vector[x.round, y.round]
end
def offset_line(p1, p2, delta)
v = p2 - p1
n = v.normal_vector
p_new = p1 + n.normalize * delta
[p_new, p_new + v]
end
end
end
| true
|
e5777d1dfa5a2fe6de879f728803b6e66904de6b
|
Ruby
|
marcosfparreiras/ruby-rack-api
|
/spec/handlers/token_spec.rb
|
UTF-8
| 5,037
| 2.5625
| 3
|
[] |
no_license
|
require_relative '../../src/handlers/token'
describe 'Token' do
let(:token_id) { 'mytokenid' }
let(:user_cpf) { 12341234 }
let(:account_number) { 333 }
let(:account) do
double('account',
number: account_number,
current_balance: 100
)
end
let(:user) do
double('user',
cpf: user_cpf,
account: account
)
end
let(:token) { double('token', id: token_id, user: user) }
subject { Handlers::Token.new(token_id) }
describe '#initialize' do
context 'when token does not exist' do
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(nil)
end
it 'raises 404 not found error' do
expect { Handlers::Token.new(token_id) }.to raise_error(CustomErrors::NotFound)
end
end
end
describe '#withdraw' do
context 'when does not have enought balance' do
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow(Handlers::Token).to receive(:new).and_return(subject)
allow(subject).to receive(:has_enough_balance?).and_return(false)
end
it 'raises 403 forbiden error' do
params = { 'amount' => 200 }
expect { subject.withdraw(params) }.to raise_error(CustomErrors::Forbiden)
end
end
context 'when does have enought balance' do
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow(Handlers::Token).to receive(:new).and_return(subject)
allow(subject).to receive(:has_enough_balance?).and_return(true)
allow(subject).to receive(:update_account_balance)
allow(subject).to receive(:create_operation)
allow(subject).to receive(:token_account).and_return(account)
allow(account).to receive(:values).and_return(key1: 'value1')
end
it 'updates account balance' do
params = { 'amount' => '50' }
expect(subject).to receive(:update_account_balance).with(account, -50)
subject.withdraw(params)
end
it 'creates operation' do
params = { 'amount' => '50' }
expect(subject).to receive(:create_operation).with(-50, 'withdraw')
subject.withdraw(params)
end
end
end
describe '#deposit' do
context 'when account does not exist' do
let(:not_existing_account) { '999' }
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow_any_instance_of(Handlers::Token).to receive(:retrieve_account).and_return(nil)
allow(Handlers::Token).to receive(:new).and_return(subject)
end
it 'raises 403 forbiden error' do
params = { 'amount' => 200, 'account' => not_existing_account }
expect { subject.deposit(params) }.to raise_error(CustomErrors::Forbiden)
end
end
context 'when account exists' do
let(:account_to_deposit) { double('account to deposit') }
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow_any_instance_of(Handlers::Token).to receive(:retrieve_account).and_return(account_to_deposit)
allow(Handlers::Token).to receive(:new).and_return(subject)
allow(subject).to receive(:update_account_balance)
allow(subject).to receive(:create_operation)
allow(subject).to receive(:token_account).and_return(account)
allow(account_to_deposit).to receive(:values).and_return(key1: 'value1')
end
it 'updates account balance' do
params = { 'amount' => '100', 'account' => '88' }
expect(subject).to receive(:update_account_balance).with(account_to_deposit, 100)
subject.deposit(params)
end
it 'creates operation' do
params = { 'amount' => '100', 'account' => '88' }
expect(subject).to receive(:create_operation).with(100, 'deposit')
subject.deposit(params)
end
end
end
describe '#operations' do
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(nil)
end
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow(Handlers::Token).to receive(:new).and_return(subject)
allow(subject).to receive(:account_operations)
end
it 'returns operations filtered by date' do
params = { 'from' => '2017-01-01', 'to' => '2017-01-15', 'type' => 'deposit' }
expect(subject).to receive(:account_operations).with(params['from'], params['to'], params['type'])
subject.operations(params)
end
end
describe '#signout' do
before do
allow_any_instance_of(Handlers::Token).to receive(:retrieve_token).and_return(token)
allow(Handlers::Token).to receive(:new).and_return(subject)
allow(token).to receive(:destroy)
end
it 'deletes token from database' do
expect(token).to receive(:destroy)
subject.signout
end
end
end
| true
|
a55b5bd7b24960b37000e32bd402e846c49fc10f
|
Ruby
|
serendipidoussophia/kwk-l1-ruby-2-meal-choice-lab-kwk-students-l1-min-072318
|
/meal_choice.rb
|
UTF-8
| 435
| 3.8125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def snacks(food="Cheetos")
"Any time, is the right time for #{food}!"
end
def breakfast(food="frosted flakes")
"Morning is the best time for #{food}!"
end
def lunch(food="grilled cheese")
"Noon is the best time for #{food}!"
end
def dinner(food="salmon")
"Evening is the best time for #{food}!"
end
puts breakfast("waffle")
puts lunch("mac and cheese")
puts dinner("hamburger")
puts breakfast
puts lunch
puts dinner
| true
|
d96dcc2ca01fe545661853e27ca925d49c05b287
|
Ruby
|
jorgemtoledo/scriptsRuby
|
/ruby_studies/one/ruby_avancado_2/self.rb
|
UTF-8
| 1,193
| 4.46875
| 4
|
[] |
no_license
|
# Self
# No ruby, self é uma variável especial que aponta para o objeto atual.
# 1- Crie o arquivo self.rb com o seguinte código
# Exemplo 1:
# class Foo
# def bar
# puts self
# end
# end
# foo = Foo.new
# puts foo
# foo.bar
# A variável self aponta para o Objeto onde ela se encontra.
# No caso está apontando para uma instância da classe Foo e, por isso, as instruções puts foo e puts self retornam o mesmo resultado.
# Perceba que a variável self não precisa ser declarada. Ela é disponível em qualquer lugar,
# mas não esqueça que seu valor é referente ao objeto que pertence.
# ========================================================================================
# Exemplo 2:
# Com o self é possível criar métodos de classe, que não precisam de uma instância para serem chamados.
# class Foo
# def self.bar
# puts self
# end
# end
# Foo.bar
# Exemplo 3:
# Você também pode utilizá-lo para se referir a atributos do objeto atual.
class Pen
attr_accessor :color
def pen_color
puts "The color is " + self.color
end
end
pen = Pen.new
pen.color = "blue"
pen.pen_color
# O self.color retorna a cor do objeto pen.
| true
|
78ad1c010f7ee42fb4e00093f89e35295db8b0fb
|
Ruby
|
jacobswartzentruber/project_euler
|
/problem_18.rb
|
UTF-8
| 1,555
| 4.40625
| 4
|
[] |
no_license
|
#By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
#3
#7 4
#2 4 6
#8 5 9 3
#That is, 3 + 7 + 4 + 9 = 23.
#Find the maximum total from top to bottom of the triangle below:
def max_sum_triangle
number = "75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 "
number += "40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 "
number += "38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23"
# Place triangle in an array which is easier to manipulate
@triangle = []
counter = 0
number = number.split(" ")
while number.length > 0
counter += 1
row = []
counter.times { row << number.shift }
@triangle << row
end
# Recursion method that returns the greater sum of the current cell and
# each of the two adjacent cells in the next row
def add_num(row, col)
# If last row, simply return the cell number
return @triangle[row][col].to_i if row == @triangle.length-1
# Find the adjacent two cells in the next row and add current cell's value
a = add_num(row+1,col) + @triangle[row][col].to_i
b = add_num(row+1,col+1) + @triangle[row][col].to_i
# Return the greater of the two sums
return [a,b].max
end
#Start the recursion at cell 0,0
puts add_num(0,0)
end
max_sum_triangle
# Returns 1074
| true
|
3342021438ebe9fd11e7849d672c7b6551b3f745
|
Ruby
|
T-monius/ruby_small_problems
|
/easy_2/tip_calculator.rb
|
UTF-8
| 833
| 4.4375
| 4
|
[] |
no_license
|
# tip_calculator.rb
# Create a simple tip calculator. The program should prompt for a
# bill amount and a tip rate. The program must compute the tip and
# then display both the tip and the total amount of the bill.
# Understanding:
# Inputs 2 strings
# Output 2 Strings with interpolated floats
# Validate Numbers?
# Pseudo Code:
# Get input.to_f/Set = variable 'bill'
# Get input.to_f/Set = variable 'percentage'
# Set variable 'tip' = percentage of bill/ 100
# Set 'total' = 'tip' + 'bill'
puts "Hello User!"
puts "Please, input the dollar amount of your bill: "
bill = gets.chomp.to_f
puts "Please, input the percent of that bill you'd like to tip: "
percentage = gets.chomp.to_f / 100
tip = bill * percentage
total = bill + tip
puts "The tip is $#{format('%0.2f', tip)}."
puts "The total is $#{format('%0.2f', total)}."
| true
|
d7eb36dd9174c4b1ad99beb036fc7b5006f53828
|
Ruby
|
manveru/tick
|
/lib/tick/bin/list.rb
|
UTF-8
| 1,737
| 2.890625
| 3
|
[] |
no_license
|
module Tick::Bin::List
DESCRIPTION = 'List available tickets by custom criteria'
USAGE = <<-DOC
tick list displays available tickets and provides filtering and sorting
SYNOPSIS
tick list [OPTIONS] [Search terms]
DOC
module_function
def parser(bin, opt)
bin.on('-a', '--all',
'Show all tickets'){|v| list_all(bin) }
bin.on('-s', '--status STATUS',
'Show tickets by status'){|v| list_status(bin, v) }
bin.on('-t', '--tags tag1,tag2,...', Array,
'Show tickets with these tags'){|v| list_tags(bin, *v) }
end
def run(bin, options)
list_status(bin, 'open')
end
def list_all(bin)
bin.repo.milestones.each do |milestone|
print_milestone(milestone)
milestone.tickets.each do |ticket|
print_ticket(ticket)
end
end
exit
end
def list_status(bin, status)
bin.repo.milestones.each do |milestone|
print_milestone(milestone)
milestone.tickets.each do |ticket|
next unless ticket.status == status
print_ticket(ticket)
end
end
exit
end
def list_tags(bin, *tags)
bin.repo.milestones.each do |milestone|
print_milestone(milestone)
milestone.tickets.each do |ticket|
next if (ticket.tags & tags).empty?
print_ticket(ticket)
end
end
exit
end
def print_milestone(milestone)
puts "Milestone: #{milestone.tick_name}"
end
def print_ticket(ticket)
puts " Ticket: #{ticket.tick_name}"
ticket.class.members[1..-1].each do |member|
case member
when :tags, 'tags'
puts " #{member}: #{[*ticket[member]].join(', ')}"
else
puts " #{member}: #{ticket[member]}"
end
end
end
end
| true
|
c071b2ec9e44059ce30ce33462258805ebdc8fee
|
Ruby
|
archangel519/Burndown
|
/models/task.rb
|
UTF-8
| 656
| 2.875
| 3
|
[] |
no_license
|
require 'active_record'
class Task < ActiveRecord::Base
belongs_to :story
validates_uniqueness_of :id, :scope => :story_id
validates_uniqueness_of :title, :scope => :story_id
validates_presence_of :story_id, :title, :hours, :status
after_initialize :init
def hours=(value)
value = value.to_f
if value <= 0
value = 0.25 #has to be at least .25 hours
end
#round up to nearest .25
rem = value % 0.25
value = (value - rem) + 0.25 unless rem == 0
value = value.round(2).to_f
write_attribute(:hours, value)
end
private
def init
self.hours ||= 0.25
self.status ||= 1
end
end
| true
|
42c49a39aaa613cc911de0a583394583681baa90
|
Ruby
|
TheRoster/thecollegeroster
|
/app/lib/importer.rb
|
UTF-8
| 546
| 2.734375
| 3
|
[] |
no_license
|
require 'csv'
class Importer
def self.execute
high_school_file_path = "#{Rails.root}/lib/data/high_school.csv"
sport_file_path = "#{Rails.root}/lib/data/sports.csv"
# position_file_path = "#{Rails.root}/lib/data/positions.csv"
importer = Importer.new
message "Importing high schools..."
HighSchoolImporter.new(high_school_file_path).run
message "Importing sports..."
SportsImporter.new(sport_file_path).run
# message "Importing positions..."
# SportsImporter.new(position_file_path).run
end
end
| true
|
c97524bbc870efa4cd5101ebea15febecf2c4bba
|
Ruby
|
silatham99/bash-git-branch
|
/bash_git_branch.rb
|
UTF-8
| 949
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
# bash_git_branch.rb - Script to show the current git branch in the bash PS1
# Rewritten in Ruby by Scott I. Latham (silatham99)
# v1.0.3 - 04/18/2014
BLACK = '\[\033[0;38m\]'
GREEN = '\[\033[0;32m\]'
RED = '\[\033[0;31m\]'
YELLOW = '\[\033[0;33m\]'
DEFAULT_PS1 = "#{YELLOW}"'\w '"#{BLACK}: "
def get_branch(git_query)
words = git_query.split(/\s/)
words.each_index do |index|
branch_next = (words[index-1] == 'On' &&
words[index] == 'branch')
return words[index+1] if branch_next
end
end
def get_commit_color(git_query)
status = false
git_query.lines.each do |line|
status ||= !!line.match(/\Anothing to commit, working directory clean\n\z/)
end
status ? GREEN : RED
end
begin
git_query = %x(git status 2> /dev/null)
raise StandardError.new if git_query.empty?
puts "#{YELLOW}"'\w '"#{get_commit_color(git_query)}(#{get_branch(git_query)}) #{BLACK}: "
rescue
puts DEFAULT_PS1
end
| true
|
48051563eaa0cc590047af31f7424191800f6823
|
Ruby
|
Nova840/phase-0
|
/week-4/variables-methods.rb
|
UTF-8
| 1,162
| 4
| 4
|
[
"MIT"
] |
permissive
|
puts "What is your first name?"
first_name = gets.chomp
puts "What is your middle name?"
middle_name = gets.chomp
puts "What is your last name?"
last_name = gets.chomp
puts "Hello #{first_name} #{middle_name} #{last_name}.\n\n"
puts "What is your favorite number?"
favorite_number = gets.chomp
puts "The number #{favorite_number.to_i + 1} is 1 larger."
=begin
4.3.1 Return a Formatted Address:
https://github.com/Nova840/phase-0/blob/master/week-4/address/my_solution.rb
4.3.2 Defining Math Methods:
https://github.com/Nova840/phase-0/tree/master/week-4/math/my_solution.rb
Reflection:
How do you define a local variable?
name = value
How do you define a method?
def method_name(parameters)
end
What is the difference between a local variable and a method?
A local variables stores a value and a method executes code when called.
How do you run a ruby program from the command line?
ruby [filename].rb
How do you run an RSpec file from the command line?
rspec [filename].rb
What was confusing about this material? What made sense?
I found most of this to be review. I had to look up syntax but other than that it was pretty easy.
=end
| true
|
9408f6260870da32b2f08aa42764d5dfbc895cc5
|
Ruby
|
cnyuanh/tutorials
|
/analysis_of_introgression_with_chromosome_length_alignments/src/get_age_reduction.rb
|
UTF-8
| 2,900
| 3.109375
| 3
|
[] |
no_license
|
# m_matschiner Tue May 29 21:35:40 CEST 2018
# Get the command-line argument.
inmatrix_file_name = ARGV[0]
outmatrix_file_name = ARGV[1]
unless ARGV[2] == nil
exclude_ids = ARGV[2].split(",")
end
# Read the input matrix.
inmatrix_file = File.open(inmatrix_file_name)
inmatrix_lines = inmatrix_file.readlines
inmatrix_ids = inmatrix_lines[0].split
inmatrix_cells = []
inmatrix_vertical_ids = []
inmatrix_lines[1..-1].each do |l|
line_ary = l.split
inmatrix_vertical_ids << line_ary[0]
inmatrix_row = []
line_ary[1..-1].each do |i|
inmatrix_row << i.to_f
end
inmatrix_cells << inmatrix_row
end
# Make sure that the matrix is ordered in the same way horizontally and vertically.
if inmatrix_ids != inmatrix_vertical_ids
puts "ERROR: The matrix is not ordered identically horizontally and vertically!"
exit 1
end
if exclude_ids == nil
species_ids = inmatrix_ids
else
species_ids = []
inmatrix_ids.each {|i| species_ids << i unless exclude_ids.include?(i)}
inmatrix_cells.size.times do |x|
inmatrix_cells[x] = nil if exclude_ids.include?(inmatrix_ids[x])
end
inmatrix_cells.compact!
inmatrix_cells.size.times do |z|
row = inmatrix_cells[z]
row.size.times do |x|
row[x] = nil if exclude_ids.include?(inmatrix_ids[x])
end
row.compact!
end
end
# Prepare the matrix for age reductions.
outmatrix_cells = []
species_ids.size.times do |x|
row_ary = []
species_ids.size.times do |y|
row_ary << 0
end
outmatrix_cells << row_ary
end
# Make the matrix for age reductions.
species_ids.size.times do |a|
species_ids.size.times do |c|
mrca_reduction_pairwise_ac = 0
species_ids.size.times do |b|
mrca_ab_mean_age = inmatrix_cells[a][b]
mrca_ac_mean_age = inmatrix_cells[a][c]
mrca_bc_mean_age = inmatrix_cells[b][c]
if mrca_ab_mean_age < [mrca_ac_mean_age,mrca_bc_mean_age].min
mrca_reduction = [mrca_bc_mean_age-mrca_ac_mean_age,0].max
else
mrca_reduction = 0
end
mrca_reduction_pairwise_ac = mrca_reduction if mrca_reduction > mrca_reduction_pairwise_ac
end
outmatrix_cells[a][c] = mrca_reduction_pairwise_ac.round(5)
end
end
# Determine the cell width.
cell_width = 0
species_ids.each{|i| cell_width = i.size if i.size > cell_width}
outmatrix_cells.each do |row|
row.each{|i| cell_width = i.to_s.size if i.to_s.size > cell_width}
end
cell_width += 2
# Produce a matrix with either the maximum or the sum of mrca reductions for any combination of species A and C.
outstring = "".ljust(cell_width)
species_ids.each {|i| outstring << "#{i.ljust(cell_width)}"}
outstring << "\n"
species_ids.size.times do |x|
outstring << "#{species_ids[x].ljust(cell_width)}".ljust(cell_width)
species_ids.size.times do |y|
outstring << "#{outmatrix_cells[x][y].to_s.ljust(cell_width)}".ljust(cell_width)
end
outstring << "\n"
end
# Write the output matrix.
outmatrix_file = File.open(outmatrix_file_name,"w")
outmatrix_file.write(outstring)
| true
|
c436400a7ed8d10124f5b930db9b68912b36710c
|
Ruby
|
chasenyc/prime_multiplication_tables
|
/spec/lib/prime_spec.rb
|
UTF-8
| 602
| 3.484375
| 3
|
[] |
no_license
|
require_relative '../../lib/prime'
describe Prime do
it "first(amount) returns first n prime numbers in an array" do
expect(Prime.first(2)).to be_a_kind_of(Array)
expect(Prime.first(2)).to eq [2, 3]
expect(Prime.first(8)).to eq [2, 3, 5, 7, 11, 13, 17, 19]
expect(Prime.first(-1)).to eq []
end
it "is_prime? checks whether given number is a prime" do
expect(Prime.is_prime?(1)).to eq false
expect(Prime.is_prime?(2)).to eq true
expect(Prime.is_prime?(991)).to eq true
expect(Prime.is_prime?(12)).to eq false
expect(Prime.is_prime?(0)).to eq false
end
end
| true
|
652e88e6a37f19aecda8fd30b4d83dd96eec8aea
|
Ruby
|
janenyasoro/begin_ruby
|
/nested_classes.rb
|
UTF-8
| 247
| 3.03125
| 3
|
[] |
no_license
|
class Drawing
def self.give_me_a_circle
Circle.new
end
class Line
end
class Circle
def what_am_i
"This is a circle"
end
end
end
a = Drawing.give_me_a_circle
puts a.what_am_i
a = Drawing::Circle.new
puts a.what_am_i
a = Circle.new
puts a.what_am_i
| true
|
be92dc406c06c0d94007a34878c9a9a0e6a27dbe
|
Ruby
|
Achury/rei
|
/integrador/app/models/api/authentication.rb
|
UTF-8
| 400
| 2.515625
| 3
|
[] |
no_license
|
class Api::Authentication < Api::Base
def self.valid_password?(username, password)
return false if username.blank? or password.blank?
request = get("/ulises/schedule", :query => { :username => username, :password => password })
puts request
return request.parsed_response.is_a?(Array) # If it's valid, the API call will return an array. Otherwise, will return a hash.
end
end
| true
|
1c9b945f3894abbe764e4aa7d965734488965d92
|
Ruby
|
duckyrettes/learn_ruby
|
/03_simon_says/simon_says.rb
|
UTF-8
| 672
| 3.9375
| 4
|
[] |
no_license
|
def echo(phrase)
return phrase
end
def shout(phrase)
return phrase.upcase
end
def repeat(phrase, num=2)
str = ""
result = while num > 0 do
str += phrase + " "
num -= 1
end
str.strip!
return str
end
def start_of_word(word, num=1)
return word[0..num-1]
end
def first_word(phrase)
return phrase.split[0]
end
def titleize(phrase)
phrase_words = phrase.capitalize
if phrase.include? " "
phrase_words = phrase_words.split
phrase_words.each do |word, index|
if (word != "and" && word != "the" && word != "over")
word.capitalize!
end
end
phrase_words = phrase_words.join(" ")
end
return phrase_words
end
| true
|
fb204e60ea8a6d3ae8a5544c180ec032e267a4f4
|
Ruby
|
braegel/AmateurfunkPruefungsfragen
|
/extractor.rb
|
UTF-8
| 510
| 2.90625
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
filename="TechnischeKenntnisseA.txt"
data = File.read(filename)
while data =~ /\n/
data = data.gsub(/\n/,"")
end
qna_pattern = Regexp.new("([A-Z]{2}[0-9]{3,4}.+?)(A .+?)B ",Regexp::MULTILINE)
file_out = File.open("#{filename}.tab.txt", 'w')
counter = 0
while data =~ qna_pattern
counter += 1
question = $1
answer = $2
# puts "Q(#{counter}): #{question}"
# puts "A: #{answer}"
file_out.write("#{question}\t#{answer}\n")
data = data.sub(qna_pattern ,"")
end
file_out.close
| true
|
acfdd4483b20b4b48779f41379caf1f39ae3e090
|
Ruby
|
SandUniHH/PBI-Blatt04
|
/Aufgabe4.3/stack-skeleton.rb
|
UTF-8
| 1,258
| 3.71875
| 4
|
[] |
no_license
|
#!/usr/bin/ruby
#
# Dieses ist unsere Ruby - Implementierung für einen Stack
# Zum Glück sind viele Stack-Funktionalitäten schon mit in die Ruby-Array Klasse
# eingebaut. Daher ist es nicht viel Arbeit, diese Implementierung zu
# vervollständigen.
class Stack
# initialize() initalisiert ein Objekt einer Klasse und wird bei Ruby bei
# jedem new()-Aufruf mit aufgerufen.
# Das heißt, wenn man s = Stack.new() eintippt, wird ein neues Array erstellt
# und in s.data gespeichert.
def initialize ()
@data = Array.new()
end
# Diese Methode soll das Element x auf dem Stack legen.
def push(x)
end
# Diese Methode soll das Element oberste Element vom Stack holen und
# zurückgeben.
def pop
# Wenn der Stack leer ist, und trotzdem pop aufgerufen wird ist das ein
# Fehler des Programmierers. Dies teilen wir ihm mit, indem wir eine
# Ausnahme auslösen.
if self.empty? == true
raise "stack is empty!"
end
end
# Diese Methode soll das oberste Element zurückgeben, ohne es vom Stack zu
# holen.
def top
# auch hier sollte eine Exception geworfen werden, wenn der Stack leer ist.
end
# Diese Methode soll true liefern, falls der Stack leer ist, ansonsten false.
def empty?
end
end
| true
|
7893e332120e53e334b6b5bb424fd3f307109874
|
Ruby
|
kylelaughlin/w02-d01-classes
|
/lib/guitar_player.rb
|
UTF-8
| 615
| 3.1875
| 3
|
[] |
no_license
|
require 'pry'
require_relative 'guitar.rb'
class GuitarPlayer
attr_accessor :name, :age, :sweet_riffs_played
def initialize(name:, age:)
@name = name
@age = age
@sweet_riffs_played = 0
@guitar = nil
end
def guitar
@guitar
end
def guitar=(guitar)
@guitar = guitar
end
def pick_a_guitar=(new_guitar)
if !new_guitar.player.nil?
old_player = new_guitar.player
old_player.guitar = nil
end
@guitar = new_guitar
new_guitar.player = self
end
def play_sweet_riff
@sweet_riffs_played += 1
self.guitar.sweet_riffs_executed += 1
end
end
| true
|
fbd9ddc172da3d0575d078719ef8f38eef920694
|
Ruby
|
junwen29/amazingcoders-rails
|
/app/services/wish_service.rb
|
UTF-8
| 2,318
| 2.734375
| 3
|
[] |
no_license
|
class WishService
module ClassMethods
def wish(venue_id, user_id)
unless Venue.exists?(venue_id)
raise ActiveRecord::RecordNotFound
end
wish = Wish.where(venue_id:venue_id, user_id: user_id).first
if wish ## if you have already done wish, you can't.
return wish
end
return Wish.create!(venue_id:venue_id, user_id:user_id)
end
def unwish(venue_id, user_id)
wish = Wish.where(venue_id:venue_id, user_id:user_id)
if wish.size == 0
raise ActiveRecord::RecordNotFound
else
if wish.destroy_all
return true
else
raise ActiveRecord::ActiveRecordError
end
end
end
# sets venue.is_wishlist for list of venues
def set_is_wishlist(venues, user_id)
return venues if user_id.nil?
if venues.respond_to?(:each)
venue_ids = Wish.where(user_id: user_id).pluck(:venue_id)
venues.each do |v|
v.is_wishlist = venue_ids.include?(v.id)
end
else
venues.is_wishlist = is_wish?(venues.id, user_id)
end
venues
end
# to check if a user did wish or not
def is_wish?(venue_id, user_id)
Wish.exists?(venue_id:venue_id, user_id: user_id)
end
# Get num of users who wish list a venue
def num_wishlist_venue (venue_id)
num = Wish.where(:venue_id => venue_id)
num.count
end
# Total num of users who wish list the venues associated with a deal
def num_wishlist_deal(deal_id, push_date = nil)
venue_id = DealVenue.where(:deal_id => deal_id).pluck(:venue_id)
if push_date == nil
Wish.where(venue_id: venue_id).select(:user_id).distinct.count
else
Wish.where(venue_id: venue_id).where('created_at <= ?',push_date).select(:user_id).distinct.count
end
end
# Get array of user id who wishlist the venues associated with a deal
def get_user_id(deal_id, push_date = nil)
venue_id = DealVenue.where(:deal_id => deal_id).pluck(:venue_id)
if push_date == nil
Wish.where(venue_id: venue_id).select(:user_id).distinct
else
Wish.where(venue_id: venue_id).where('created_at <= ?',push_date).select(:user_id).distinct
end
end
end
class << self
include ClassMethods
end
end
| true
|
dc531b30cb238bfad1f0db7f87eb3b598bd29145
|
Ruby
|
patricia13/blog
|
/blog/app/models/article.rb
|
UTF-8
| 251
| 2.53125
| 3
|
[] |
no_license
|
association to achieve this. Modify the Article model, app/models/article.rb, as follows:
class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end
| true
|
970490b4d43976e0b53bd7752961dfa93c48db11
|
Ruby
|
whimet/RobotSimulator
|
/lib/robot_simulator/table.rb
|
UTF-8
| 255
| 3.203125
| 3
|
[] |
no_license
|
class Table
def initialize(width, height)
raise 'invalid width' if width <= 0
raise 'invalid height' if height <= 0
@width = width
@height = height
end
def contains(coordinate)
coordinate.within(0, 0, @width, @height)
end
end
| true
|
40767515b92680247eaf142bf27421c4a81ddca2
|
Ruby
|
hemashree/data_structure
|
/compute_sum.rb
|
UTF-8
| 154
| 3.578125
| 4
|
[] |
no_license
|
class A
def sum(n)
result = 0
i = 1
while( i <= n)
result += i
i += 1
end
return result
end
end
a = A.new
p a.sum(10)
| true
|
92223db2594e52bb8cde56f531b47c3084c671f3
|
Ruby
|
sameerank/Ruby-exercises
|
/poker/rspec_demo/bobs_bad_code/tree_written_october_2015.rb
|
UTF-8
| 140
| 2.546875
| 3
|
[] |
no_license
|
# The person who wrote this file doesn't know that tree_written_august_2013.rb exists
class Tree
def grow
"getting WIDER"
end
end
| true
|
1ce55a80cc848e01d3bf87a62a918b108d416f1e
|
Ruby
|
mray6288/the-bachelor-todo-prework
|
/lib/bachelor.rb
|
UTF-8
| 1,353
| 3.5625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def get_first_name_of_season_winner(data, season)
winner = ''
data[season].each do |contestant|
if contestant['status'] == 'Winner'
winner = contestant['name'].split[0]
break
end
end
winner
end
def get_contestant_name(data, occupation)
name = ''
data.each do |season, contestants|
contestants.each do |contestant|
if contestant['occupation'] == occupation
name = contestant['name']
break
end
end
end
name
end
def count_contestants_by_hometown(data, hometown)
count = 0
data.each do |season, contestants|
contestants.each do |contestant|
if contestant['hometown'] == hometown
count += 1
end
end
end
count
end
def get_occupation(data, hometown)
occupation = nil
data.each do |season, contestants|
contestants.each do |contestant|
if contestant['hometown'] == hometown
occupation = contestant['occupation']
break
end
end
end
occupation
end
def get_average_age_for_season(data, season)
average_age = 0.0
count = data[season].length
data[season].each {|contestant| average_age += contestant['age'].to_f}
(average_age/count).round
end
| true
|
bb37f5ccb19c47f15ae82cd3254a13c0692cf7ac
|
Ruby
|
GrayMyers/the-last-airbender
|
/app/poros/character.rb
|
UTF-8
| 290
| 2.796875
| 3
|
[] |
no_license
|
class Character
attr_reader :affiliation, :enemies, :allies, :name, :image_url
def initialize(data)
@name = data[:name]
@image_url = data[:photoUrl] ? data[:photoUrl] : ""
@affiliation = data[:affiliation]
@enemies = data[:enemies]
@allies = data[:allies]
end
end
| true
|
5e7dc7be71cd1873a8e4d6b34428a0a41b895e5e
|
Ruby
|
SimonBo/ruby
|
/caesar.rb
|
UTF-8
| 1,398
| 3.765625
| 4
|
[] |
no_license
|
def caesar_cipher(message, shift)
letter_hash={}
letter_hash_capital={}
final_string=""
nr=1
('a'..'z').to_a.each do |letter|
letter_hash[letter]= nr
nr+=1
end
nr_for_capital=1
('A'..'Z').to_a.each do |letter|
letter_hash_capital[letter]= nr_for_capital
nr_for_capital+=1
end
message.split("").each do |letter|
if letter.match(/\W/)
final_string << letter
elsif letter_hash_capital.has_key?(letter)
final_key= letter_hash_capital[letter]+shift
# puts final_key
if final_key>26
final_key=final_key % 26
if final_key==0
final_key=letter_hash_capital[letter]
end
end
# puts letter_hash_capital.key(final_key)
final_string << letter_hash_capital.key(final_key).to_s
else
# puts letter
final_key= letter_hash[letter]+shift
# puts final_key
if final_key>26
final_key=final_key % 26
if final_key==0
final_key=letter_hash[letter]
end
end
# puts letter_hash.key(final_key)
final_string << letter_hash.key(final_key).to_s
# final_string << letter_hash[(letter_hash[letter]+shift)].to_s
end
end
puts final_string
end
caesar_cipher("huj",2)
caesar_cipher("What a string!", 5)
caesar_cipher("huj",200)
# > caesar_cipher("What a string!", 5)
# => "Bmfy f xywnsl!"
| true
|
9d51cbb8739e83031f81c4fd21d4fae68d6aa31e
|
Ruby
|
marcelomanhabosco/SentimentalAnalysis
|
/db/seeds.rb
|
UTF-8
| 6,969
| 2.53125
| 3
|
[] |
no_license
|
# encoding: UTF-8
caminho = "#{Rails.root}/db/seed_data/"
# StopWords
File.open(caminho + 'stopwords.txt').each_with_index do |linha, index|
puts "Importando StopWords #{index} - #{linha}"
StopWord.create!(:stop_word => linha.chomp)
end
# Dicionário Internetês
File.open(caminho + 'internetslangwords.txt').each_with_index do |linha, index|
slang_word, correct_word = linha.chomp.split(" | ")
puts "Importando Internetes #{index} - #{slang_word}"
InternetSlangWord.create!(:slang_word => slang_word, :correct_word => correct_word)
end
# Classes Gramaticais
WordClass.create!(:id => 1, :name=>"Verbo")
WordClass.create!(:id => 2, :name=>"Adjetivo")
WordClass.create!(:id => 3, :name=>"Advérbio")
WordClass.create!(:id => 4, :name=>"Substantivo")
# Thesaurus em Português
File.open(caminho + 'base_tep2.txt').each_with_index do |linha, index|
synset_id, word_class_id, words, synset_ant = linha.chomp.split(" ")
synset_ant = nil if synset_ant == ""
puts "Importando Synset #{synset_id}"
synset = Synset.create!(:id => synset_id, :word_class_id => word_class_id, :synset_ant => synset_ant)
words.split(",").each do |w|
synset.synset_words.create(:word => w)
end
end
# Dicionario Afetivo
File.open(caminho + 'affective_words.txt').each_with_index do |linha, index|
word, pos, neg = linha.chomp.split(" | ")
puts "Importando Palavra Afetiva - #{word}"
AffectiveWord.create!(:word => word, :pos => pos, :neg => neg)
end
# Relações de Antonímia e Sinonímia
File.open(caminho + 'triplos.txt').each_with_index do |linha, index|
word_class_id, word, relation, related_word = linha.chomp.split(" ")
puts "Importando Relacão #{index} - #{word} ~ #{relation} ~ #{related_word}"
WordRelation.create!(:word_class_id => word_class_id, :word => word, :relation => relation, :related_word => related_word)
end
# Entidades e Opiniões
Entity.create!(:id => 1, :name => "2012")
Entity.create!(:id => 2, :name => "300")
Entity.create!(:id => 3, :name => "A Origem (Inception)")
Entity.create!(:id => 4, :name => "Avatar")
Entity.create!(:id => 5, :name => "Crepusculo")
Entity.create!(:id => 6, :name => "Crepusculo Lua Nova")
Entity.create!(:id => 7, :name => "Guerra ao Terror")
Entity.create!(:id => 8, :name => "Harry Potter")
Entity.create!(:id => 9, :name => "Paranormal")
Entity.create!(:id => 10, :name => "Premonição")
File.open(caminho + '/opinioes/2012-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - 2012 #{index}"
Opinion.create!(:entity_id => 1, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/2012-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - 2012 #{index}"
Opinion.create!(:entity_id => 1, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/300-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - 300 #{index}"
Opinion.create!(:entity_id => 2, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/300-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - 300 #{index}"
Opinion.create!(:entity_id => 2, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/A_Origem-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - A Origem #{index}"
Opinion.create!(:entity_id => 3, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/A_Origem-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - A Origem #{index}"
Opinion.create!(:entity_id => 3, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Avatar-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Avatar #{index}"
Opinion.create!(:entity_id => 4, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Avatar-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Avatar #{index}"
Opinion.create!(:entity_id => 4, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Crepusculo-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Crepusculo #{index}"
Opinion.create!(:entity_id => 5, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Crepusculo-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Crepusculo #{index}"
Opinion.create!(:entity_id => 5, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Crepusculo_Lua_Nova-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Crepusculo Lua Nova #{index}"
Opinion.create!(:entity_id => 6, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Crepusculo_Lua_Nova-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Crepusculo Lua Nova #{index}"
Opinion.create!(:entity_id => 6, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Guerra-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Guerra ao Terror #{index}"
Opinion.create!(:entity_id => 7, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Guerra-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Guerra ao Terror #{index}"
Opinion.create!(:entity_id => 7, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Harry-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Harry Potter #{index}"
Opinion.create!(:entity_id => 8, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Harry-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Harry Potter #{index}"
Opinion.create!(:entity_id => 8, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Paranormal-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Paranormal #{index}"
Opinion.create!(:entity_id => 9, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Paranormal-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Paranormal #{index}"
Opinion.create!(:entity_id => 9, :human_score => "Negativo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Premonicao-positivas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Premonicao #{index}"
Opinion.create!(:entity_id => 10, :human_score => "Positivo", :opinion_text => linha)
end
File.open(caminho + '/opinioes/Premonicao-negativas.txt').each_with_index do |linha, index|
puts "Importando Opiniao - Premonicao #{index}"
Opinion.create!(:entity_id => 10, :human_score => "Negativo", :opinion_text => linha)
end
| true
|
2c08cc14ae81b3c8f8dfeee8c48fd7cd5f3cae6e
|
Ruby
|
plagelao/PlageServer
|
/server/application.rb
|
UTF-8
| 1,071
| 2.953125
| 3
|
[] |
no_license
|
class ApplicationFactory
APPLICATIONS = {:tutorial => "<html><head></head>\n<body>\n<h3>\nWelcome to the tutorial\n</h3>\n<p>To add a web page put it in the same directory where the server is running</p></body></html>"}
def create(application_name)
return RootApplication.new if application_name == '/'
app = (application_name.slice(1..-1).to_sym)
return UserApplication.new(application_name, APPLICATIONS[app]) if APPLICATIONS.include?(app)
NotFoundApplication.new application_name
end
end
class RootApplication
def response
"HTTP/1.1 200 OK\r\n\r\n<html><head></head>\n<body>\n<h3>\nWelcome to PlageServer. Visit /tutorial for more information\n</h3>\n</body></html>"
end
def uri
'/'
end
end
class UserApplication
def initialize(uri, html)
@uri = uri
@html = html
end
def response
"HTTP/1.1 200 OK\r\n\r\n#{@html}"
end
def uri
@uri
end
end
class NotFoundApplication
def initialize(uri)
@uri = uri
end
def response
"HTTP/1.1 404 Not Found\r\n\r\n"
end
def uri
@uri
end
end
| true
|
4b9840609c090132b8c27a710fcad7d2cc9ba250
|
Ruby
|
asim/logslam
|
/lib/logslam/auth.rb
|
UTF-8
| 757
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
require 'net/http'
require 'digest/sha1'
require 'base64'
module AUTH
def self.authenticated?(username, password)
url = URI.parse('http://example.com/some_auth_url')
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url.path)
request.set_form_data({
'username' => username,
'passwordHash' => hash_password(password),
'application' => 10
})
response = http.request(request)
if response.is_a?(Net::HTTPSuccess)
true if response.body.include?("authenticated=true")
else
false
end
rescue
false
end
protected
private
def self.hash_password(password)
Base64.encode64(Digest::SHA1.digest("#{password}{theSaltyGoodness}")).chomp
end
end
| true
|
2d4381a690c3439f140af659763f28e5ceae9111
|
Ruby
|
merwan/Pongosu.old
|
/lib/pongosu/ball.rb
|
UTF-8
| 468
| 3.21875
| 3
|
[] |
no_license
|
class Ball
attr_accessor :x, :y, :height
def initialize(window)
@height = 5
@image = Gosu::Image.new(window, "images/ball.png", true)
@x = 100.0
@y = 100.0
@vel_x = -2
@vel_y = -2
end
def draw
@image.draw(@x, @y, 1)
end
def move
@x += @vel_x
@y += @vel_y
end
def bounce_x
@vel_x = -@vel_x
end
def bounce_y
@vel_y = -@vel_y
end
end
| true
|
850fc747ad5a95a8e1fd5441d46d698d959483ee
|
Ruby
|
safiire/cryptopals
|
/lib/cryptopals/cyclic_xor.rb
|
UTF-8
| 971
| 3
| 3
|
[] |
no_license
|
# frozen_string_literal: true
module Cryptopals
class CyclicXor
Result = Struct.new(:plaintext, :key)
def self.crack(ciphertext, max_keysize: 40)
new.crack(ciphertext, max_keysize)
end
def crack(ciphertext, max_keysize)
key_size = CyclicXorKeysize.call(ciphertext, max_keysize: max_keysize).first
key = transpose_to_columns(ciphertext, key_size).map do |single_byte_xor|
SingleByteXor.crack(single_byte_xor).key.chr
end.join
Result.new(ciphertext.cyclic_xor(key), key)
end
private
def transpose_to_columns(ciphertext, key_size)
[].tap do |columns|
ciphertext.bytes.each_slice(key_size) do |block|
padded_block(block, key_size).each_with_index do |byte, col|
columns[col] ||= ''
columns[col] += byte.chr
end
end
end
end
def padded_block(block, key_size)
block + [0] * (key_size - block.size)
end
end
end
| true
|
246fb9bbd71f2218e0f84adc9825d61826868d45
|
Ruby
|
kailanak1/ruby-oo-complex-objects-school-domain-seattle-web-012720
|
/lib/school.rb
|
UTF-8
| 846
| 3.921875
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# code here!
require 'pry'
class School
attr_accessor = :roster, :name
def initialize(name)
@name = name
@roster = {}
end
def name
@name
end
def roster
@roster
end
def add_student(name, grade)
#if the grade exists, add student
#if the grade does not exist, add the grade and student
if @roster[grade]
@roster[grade].push(name)
else
@roster[grade] = [name]
end
end
def grade(grade)
@roster[grade]
end
def sort
#sort each student in each grade
#map returns an array
#binding.pry
@roster.each do |g, s|
#binding.pry
s = s.sort!
end
#binding.pry
@roster
end
end
| true
|
a4a7e09d95a159d2f7b34307d4acfdf850623770
|
Ruby
|
cklim83/launch_school
|
/02_rb101_rb109_small_problems/04_easy_4/10_signed_number_to_string.rb
|
UTF-8
| 2,379
| 4.53125
| 5
|
[] |
no_license
|
=begin
Convert a Signed Number to a String!
In the previous exercise, you developed a method that converts non-negative
numbers to strings. In this exercise, you're going to extend that method by
adding the ability to represent negative numbers as well.
Write a method that takes an integer, and converts it to a string representation.
You may not use any of the standard conversion methods available in Ruby,
such as Integer#to_s, String(), Kernel#format, etc. You may, however, use
integer_to_string from the previous exercise.
Examples
signed_integer_to_string(4321) == '+4321'
signed_integer_to_string(-123) == '-123'
signed_integer_to_string(0) == '0'
=end
=begin
Algorithm
- Check if number is <0, if yes call integer_to_string with -input, then
prepend the '-' sign, other just call integer_to_string
=end
DIGITS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def integer_to_string(number)
result = ''
loop do
number, remainder = number.divmod(10)
result.prepend(DIGITS[remainder])
break if number == 0
end
result
end
def signed_integer_to_string(number)
if number < 0
integer_to_string(-number).prepend('-')
elsif number > 0
integer_to_string(number).prepend('+')
else
'0'
end
end
p signed_integer_to_string(4321) == '+4321'
p signed_integer_to_string(-123) == '-123'
p signed_integer_to_string(0) == '0'
=begin
Solution
def signed_integer_to_string(number)
case number <=> 0
when -1 then "-#{integer_to_string(-number)}"
when +1 then "+#{integer_to_string(number)}"
else integer_to_string(number)
end
end
Discussion
This solution is very similar to the string_to_signed_integer method we wrote
2 exercises ago. It simply checks the sign of the number, and passes control
to integer_to_string for the heavy lifting.
The expression number <=> 0 may look a bit odd; this is ruby's "spaceship"
operator. It compares the left side against the right side, then returns +1
if the left side is greater than the right, -1 if the left side is smaller
than the right, and 0 if the values are the same. This is often useful when
you need to know whether a number is positive, negative, or zero.
Further Exploration
Refactor our solution to reduce the 3 integer_to_string calls to just one.
TO REVIEW:
- Use of comparison operator (spaceship <=>) in case statement in suggested
solution
=end
| true
|
69201db0f16db4eac47cea2f025ad3351c3ff37b
|
Ruby
|
UweKrause/haw-pm1-a4
|
/person_comparable.rb
|
UTF-8
| 2,745
| 3.984375
| 4
|
[] |
no_license
|
require 'set'
#beschreibt eine Klasse Person, die Briefe von anderen Personen erhalten kann und Briefe an andere Personen senden
#inkludiert Comparable
#Das Inkludieren des Moduls 'Comparable' ist insofern sinnvoll, da dieses weitere Vergleichsoperatoren,
#wie z.B: <,>,= auf Basis des Spaceship_Operators definiert.
#Somit kann eine eigene Klasse , die Comparable inkludiert,diese auch nutzen.
#Author:: Lucas Anders, Uwe Krause
class Person
include Comparable
#accessors ermöglichen, dass die Objekte der Klasse Brief auf den Postein-/ausgang zugreifen können
attr_accessor :posteingang, :postausgang
attr_reader :name, :strasse, :plz, :ort
def initialize(name, strasse, plz, ort)
@name = name
@strasse = strasse
@plz = plz
@ort = ort
@posteingang = Set.new()
@postausgang = Set.new()
end
#gibt alle Briefe im Posteingang auf der Konsole aus
def lesen
@posteingang.each{|x| puts x + "\n"}
end
#gibt alle Briefe im Postausgang auf der Konsole aus
def gesendete_lesen
@postausgang.each{|x| puts x}
end
#gibt die aktuellen Werte der Attribute in einem Array zurück
#wird für die Vergleichsmethoden benötigt
def zustand
return [@name, @strasse, @plz, @ort]
end
def ==(other)
if other.nil?
return false
end
return self.zustand()==other.zustand()
end
def eql?(other)
return false if other.nil?
return true if
self.equal?(other)
return false if
self.class != other.class
return self.==(other)
end
def hash
return self.zustand.hash
end
#vergleicht beide Objekte hinsichtlich der natürlichen Ordnung der Attribute Name, Strasse, PLZ und Ort
#benoetigt, um Comparable zu benutzen
#@param variante gibt an, nach welchem Kriterium geordnet werden soll
def <=>(other,variante = 1)
# return nil unless self.class == other.class
case variante
#alphabetisch
when 1
return spaceship_alphabetisch(other)
#umgekehrt alphabetisch
when 2
return (spaceship_alphabetisch(other) * (-1))
end
end
#definiert den Spaceship-Operator nach alphabetischer Ordnung
def spaceship_alphabetisch(other)
return nil unless self.class == other.class
if (@name <=> other.name) == 0
if (@strasse <=> other.strasse) == 0
if (@plz <=> other.plz) == 0
return @ort <=> other.ort
end
return @plz <=> other.plz
end
return @strasse <=> other.strasse
end
return @name <=> other.name
end
#gibt die Person in einem lesbaren String zurück
def to_s
return "\t #{@name} \n \t #{@strasse} \n \t #{@plz} \n \t #{@ort}"
end
end
| true
|
d0281b4a94d5e7b9db87f6a8280a640d887f16f9
|
Ruby
|
sectrimte/wuxia
|
/envoi_mail.rb
|
UTF-8
| 798
| 2.65625
| 3
|
[] |
no_license
|
require 'gmail'
class MailAttached
def initialize( subject, filename, msg="envoye par ruby")
puts 'creating mailAttached'
@subject = subject
@msg = msg
@filename = filename
@gmail = Gmail.connect('sectrimte', 'password')
end
def sendMail(dest_mail)
filename = @filename
subject = @subject
msg = @msg
email = @gmail.compose do
to dest_mail
subject subject
body msg
add_file filename
end
email.deliver! # or: gmail.deliver(email)
puts "#{filename} sent to #{dest_mail}"
end
def logout
if @gmail.logged_in?
@gmail.logout
end
end
end
#send_mail = MailAttached.new("CDb21c12", "book-21-chapter-12.epub")
#send_mail.sendMail("davyphu@gmail.com")
#send_mail.sendMail("kedeomas@gmail.com")
#send_mail.logout
| true
|
da903faee1b136fea5f2fc4a604b1bc47db00186
|
Ruby
|
jeanetterosario88/ruby-puppy-onl01-seng-pt-032320
|
/lib/dog.rb
|
UTF-8
| 264
| 3.640625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Dog
attr_reader :name
@@all = []
def initialize (name)
@name = name
save
end
def save
@@all << self
end
def self.all
@@all
end
def self.print_all
self.all.each do |dog|
puts dog.name
end
end
def self.clear_all
@@all.clear
end
end
| true
|
0bbd22925541822138ad7305cc2296b8cf9d35aa
|
Ruby
|
kage1029/atcoder
|
/atcoder154C.rb
|
UTF-8
| 127
| 3.15625
| 3
|
[] |
no_license
|
n = gets.chomp.to_i
array = gets.split(" ").map(&:to_i)
if array.size == array.uniq.size
puts "YES"
else
puts "NO"
end
| true
|
402ad18104568f9eb59c6d8dbb503f774e78d2d4
|
Ruby
|
michaeltanner/vhdl_parser
|
/lib/vhdl_parse_ret.rb
|
UTF-8
| 1,551
| 2.765625
| 3
|
[] |
no_license
|
require "vhdl_parser"
filename = ARGV[0]
entity = VHDL_Parser.parse_file(filename)
#TODO: Handle generics
#TODO: parse command-line arguments in a real way (e.g., -h, -o asdf.as, etc.)
output_type = ARGV[1]
case output_type
when "signals"
entity.ports.each_with_index do |port, index|
print "signal s_" + port.name + " : " + port.type + port.size + ";"
if index != entity.ports.length - 1
print "\n"
end
end
when "component"
puts "component " + entity.name + " is"
puts " port("
entity.ports.each_with_index do |port, index|
print " " + port.name + " : " + port.direction + " " + port.type + port.size
if index != entity.ports.length - 1
print ",\n"
end
end
print "\n );\nend component;"
when "instantiation"
#TODO: auto-increment this number
puts "inst_" + entity.name + "_0 : " + entity.name
puts " port map("
entity.ports.each_with_index do |port, index|
print " " + port.name + " => s_" + port.name
if index != entity.ports.length - 1
print ",\n"
end
end
print "\n );"
when "instantiation_short"
#TODO: auto-increment this number
puts "inst_" + entity.name + "_0 : entity work." + entity.name
puts " port map("
entity.ports.each_with_index do |port, index|
print " " + port.name + " => s_" + port.name
if index != entity.ports.length - 1
print ",\n"
end
end
print "\n );"
else
puts "Not a valid output type"
end
| true
|
645fbf30442df98a6cf22630350bedcc7bf0fb15
|
Ruby
|
emersonp/epicodus
|
/ruby/oo/todo/lib/task.rb
|
UTF-8
| 478
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
class Task
def initialize(description)
@description = description
@complete = false
@priority = 3
end
def description
@description
end
def complete?
@complete
end
def complete_toggle
if @complete
@complete = false
else
@complete = true
end
end
def set_priority(value)
@priority = value
end
def priority
@priority
end
end
| true
|
14c3debe4c40b410c8bbb37992e93df5fbfa1e97
|
Ruby
|
runpaint/numb
|
/lib/numb/størmer.rb
|
UTF-8
| 108
| 2.65625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# coding: utf-8
class Integer
def størmer?
((self ** 2) + 1).prime_factors.max >= 2 * self
end
end
| true
|
c2c4a35a226e9f9984f92e8a23352101570cdcf9
|
Ruby
|
zigvu/chia
|
/ruby/classes/PatchTracker.rb
|
UTF-8
| 4,790
| 2.703125
| 3
|
[] |
no_license
|
require 'json'
require 'fileutils'
class PatchTracker
attr_reader :allPatches
def initialize(configReader, patchFolder, annotationFolder)
@patchFolder = patchFolder
@annotationFolder = annotationFolder
@vt_caffeBatchSize = configReader.vt_caffeBatchSize
# key: frameNumber, value: JSON from file
@allPatches = {}
read_all_annotations
end
def read_all_annotations
tempPatches = {}
Dir["#{@annotationFolder}/*.json"].each do |fname|
j = JSON.parse(IO.read(fname))
tempPatches.merge!({ Integer(j['frame_number']) => j })
end
# put in order of frame number
sortedKeys = tempPatches.keys.sort
sortedKeys.each do |sortedKey|
@allPatches.merge!({sortedKey => tempPatches[sortedKey]})
end
return true
end
# adds patch number to each patch to keep track in leveldb
def add_patch_number_for_leveldb
leveldbCounter = 0
@allPatches.each do |frameNumber, fileJSON|
fileJSON['scales'].each do |scale|
scale['patches'].each do |patch|
patch.merge!({leveldb_counter: leveldbCounter})
leveldbCounter = leveldbCounter + 1
end
end
end
end
def add_leveldb_results(resultFileName)
allScores = {}
File.open(resultFileName, 'r').each_line do |line|
cleanLine = line.chomp.delete(' ').split(',')
next if cleanLine[1] == nil
# index 0 is the leveldb_counter
leveldbCounter = Integer(cleanLine[0])
# subsequent indices are class probs
scores = {}
for i in 1..(cleanLine.count - 1)
scores.merge!({(i - 1) => Float(cleanLine[i])})
end
allScores.merge!({leveldbCounter => scores})
end
@allPatches.each do |frameNumber, fileJSON|
fileJSON['scales'].each do |scale|
scale['patches'].each do |patch|
leveldbCounter = Integer(patch['leveldb_counter'])
patch.merge!({scores: allScores[leveldbCounter]})
end
end
end
end
def write_leveldb_labels(outputFileName)
file = File.open(outputFileName, 'w')
leveldbLabels = {}
# first, read all counter/filename combo
@allPatches.each do |frameNumber, fileJSON|
fileJSON['scales'].each do |scale|
scale['patches'].each do |patch|
patchFilename = patch['patch_filename']
leveldbCounter = Integer(patch['leveldb_counter'])
leveldbLabels.merge!({ leveldbCounter => patchFilename })
end
end
end
leveldbArr = leveldbLabels.sort_by { |labelCounter, patchName| labelCounter }
sanityCheckCounter = 0
leveldbArr.each do |labeldbItem|
if labeldbItem[0] != sanityCheckCounter
puts "labeldbItem[0]: #{labeldbItem[0]}; sanityCheckCounter: #{sanityCheckCounter}"
raise RuntimeError, "PatchTracker: Error writing leveldb labels - label counter not contiguous"
end
sanityCheckCounter = sanityCheckCounter + 1
end
leveldbArr.each do |labeldbItem|
# pretend all patches are in the first class
file.puts "#{labeldbItem[1]} 0"
end
file.close
end
def get_caffe_min_iterations
patchCount = 0
@allPatches.each do |frameNumber, fileJSON|
fileJSON['scales'].each do |scale|
scale['patches'].each do |patch|
patchCount = patchCount + 1
end
end
end
return (patchCount * 1.0 / @vt_caffeBatchSize).ceil
end
def update_all_annotations
@allPatches.each do |frameNumber, fileJSON|
outputFileName = "#{@annotationFolder}/#{fileJSON['annotation_filename']}"
FileUtils.rm(outputFileName)
write_annotation(outputFileName, fileJSON)
end
end
def write_annotation(outputFileName, hash)
File.open(outputFileName, 'w') do |file|
file.puts JSON.pretty_generate(hash)
end
end
def dump_csv(outputFileName)
file = File.open(outputFileName, 'w')
topLine = "frame_number,frame_filename,annotation_filename,scale,patch_filename," +
"patch_dim_x,patch_dim_y,patch_dim_width,patch_dim_height"
scrs = allPatches.first[1]["scales"][0]["patches"][0]["scores"]
scrsKeyArr = []
scrs.each do |k,v|; scrsKeyArr << k; end
scrsKeyArr.each do |sck|
topLine = "#{topLine},scores_cls_#{sck}"
end
file.puts topLine
@allPatches.each do |frame_number, fileJSON|
frame_filename = fileJSON["frame_filename"]
annotation_filename = fileJSON["annotation_filename"]
fileJSON['scales'].each do |scale|
scaleNum = Float(scale["scale"])
scale['patches'].each do |patch|
patch_filename = patch["patch_filename"]
patch_dim_x = patch["patch"]["x"]
patch_dim_y = patch["patch"]["y"]
patch_dim_width = patch["patch"]["width"]
patch_dim_height = patch["patch"]["height"]
line = "#{frame_number},#{frame_filename},#{annotation_filename},#{scaleNum},#{patch_filename}," +
"#{patch_dim_x},#{patch_dim_y},#{patch_dim_width},#{patch_dim_height}"
scrsKeyArr.each do |sck|
line = "#{line},#{patch['scores'][sck]}"
end
file.puts line
end
end
end
file.close
end
end
| true
|
dc3ac267deb2774eef4311b28be8f05474f9a6aa
|
Ruby
|
drod1000/job-tracker
|
/spec/models/company_spec.rb
|
UTF-8
| 1,605
| 2.515625
| 3
|
[] |
no_license
|
require 'rails_helper'
describe Company do
describe "validations" do
context "invalid attributes" do
it "is invalid without a name" do
company = Company.new()
expect(company).to be_invalid
end
it "has a unique name" do
Company.create(name: "Dropbox")
company = Company.new(name: "Dropbox")
expect(company).to be_invalid
end
end
context "valid attributes" do
it "is valid with a name" do
company = Company.new(name: "Dropbox")
expect(company).to be_valid
end
end
end
describe "relationships" do
it "has many jobs" do
company = Company.new(name: "Dropbox")
expect(company).to respond_to(:jobs)
end
it "has many contacts" do
company = create(:company)
expect(company).to respond_to(:contacts)
end
it "associated jobs are destroyed" do
company = create(:company)
job = create(:job, company: company)
expect {company.destroy}.to change {Job.count}.by(-1)
end
it "associated contacts are destroye" do
company = create(:company)
contact = create(:contact, company: company)
expect {company.destroy}.to change {Contact.count}.by(-1)
end
end
describe "instance methods" do
it "returns average interest level" do
company = create(:company)
create_list(:job, 3, level_of_interest: 50)
create(:job, level_of_interest: 25, company: company)
create_list(:job, 2, level_of_interest: 10, company: company)
expect(company.average_interest).to eq 15
end
end
end
| true
|
0207f630d88c80e2d01b5372305d7a4d316a7dcb
|
Ruby
|
DFE-Digital/apply-for-teacher-training
|
/app/components/provider_interface/user_personal_details_component.rb
|
UTF-8
| 698
| 2.53125
| 3
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
module ProviderInterface
class UserPersonalDetailsComponent < SummaryListComponent
def initialize(user:, change_path: nil)
@user = user
@change_path = change_path
end
def rows
%i[first_name last_name email_address].map do |field|
row_for_field(field)
end
end
private
attr_accessor :user, :change_path
def row_for_field(field)
field_label = field.to_s.humanize
row = {
key: field_label,
value: user.send(field),
}
return row if change_path.blank?
row.merge(
action: {
href: change_path,
visually_hidden_text: field_label,
},
)
end
end
end
| true
|
e01303bf9bd3eb68fd6d6bb9bcde427e1834dab3
|
Ruby
|
DevLuDaley/ruby_cli_gem_project
|
/lib/RubyCliGemProject/player.rb
|
UTF-8
| 2,152
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
class RubyCliGemProject::Player
#https://stackoverflow.com/questions/3772864/how-do-i-remove-leading-whitespace-chars-from-ruby-heredoc
attr_accessor :name, :number, :position,
:player_height, :player_age,
:player_weight, :player_college,
:player_salary, :player_url, :attributes, :player_object,
:player_headshot_small, :player_headshot_big,
:free_throw_percentage, :games_played, :field_goal_percentage,
:three_point_field_goal_percentage, :minutes_per_game,
:rebounds_per_game, :assists_per_game,
:blocks_per_game,:Steals_per_game,
:turnovers_per_game, :points_per_game,
:tag_field_goal_percentage, :tag_three_point_field_goals_made_attempted_per_game,
:tag_three_point_field_goal_percentage,
:tag_free_throws_made_attempted_per_game,
:tag_free_throw_percentage, :tag_rebounds_per_game,
:tag_assists_per_game, :tag_blocks_per_game,
:tag_Steals_per_game, :tag_personal_fouls_per_game,
:tag_turn_overs_per_game, :tag_points_per_game,
:tag_games_played, :tag_minutes_per_game, :tag_field_goals_made_attempted_per_game
@@all = []
# :personal fouls_per_game,
# :Minutes Per Game,:Field Goals Made-Attempted Per Game,
# :3-Point Field Goals Made-Attempted Per Game,
# :Free Throws Made-Attempted Per Game,
def initialize #(name) #= "NEEDS_A_NAME", position, number = "numeral")
@@all << self
@name = name
@number = number
@position = position
#@points_per_game = points_per_game
#@games_played = games_played
#@@nyk_players = nyk_players
end
#should return all players
def self.all
@@all
end
#should clear all players from the @@all []
def self.clear
all.clear
end
#should return message to test that .class methods.
def self.today
"yeah buddy!"
end
end
| true
|
164460d66966bc25c1058fb10b5b1cdf23e1bf0c
|
Ruby
|
metermaid/algorithms
|
/heaps/kth_largest.rb
|
UTF-8
| 519
| 4.375
| 4
|
[] |
no_license
|
# Finding the kth largest element using a min-heap
# We start counting at one right hahahaha
def kth_largest(arr, k)
return nil if k > arr.length
heaped, remaining = arr[0..k-1], arr[k..-1]
heap = Heap.new(heaped)
remaining.each do |n|
if n > heap.top
heap.pop!
heap.push(n)
end
end
heap.top
end
p kth_largest([3,4,7,5,1,36,65,23], 3) # 23
p kth_largest([], 3) # nil
p kth_largest([2,12,2,12,2,12,2,12,12], 5) # 12
p kth_largest(["cab", "bca", "kes", "acb"], 4) # "acb"
| true
|
e6501d579c67bfa4c8129faf1f0cd15129fc9bb9
|
Ruby
|
leanlabs/fitgem_oauth2
|
/lib/fitgem_oauth2/body_measurements.rb
|
UTF-8
| 2,150
| 2.578125
| 3
|
[] |
no_license
|
module FitgemOauth2
class Client
fat_periods = %w("1d" "7d" "1w" "1m")
weight_periods = %("1d" "7d" "30d" "1w" "1m")
body_goals = %("fat" "weight")
# ======================================
# Boday Fat API
# ======================================
def fat_on_date(date)
get_call("/1/user/#{@user_id}/body/log/fat/date/#{format_date(date)}.json")
end
def fat_for_period(base_date, period)
if fat_period?(period)
get_call("1/user/#{@user_id}/body/log/fat/date/#{format_date(start_date)}/#{period}.json")
else
raise FitgemOauth2::InvalidArgumentError, "period should be one of #{fat_periods}"
end
end
def fat_for_range(start_date, end_date)
get_call("1/user/#{@user_id}/body/log/fat/date/#{format_date(start_date)}/#{format_date(end_date)}.json")
end
# ======================================
# Body Goals API
# ======================================
def body_goal(type)
if type && body_goals.include?(type)
get_call("1/user/#{@user_id}/body/log/#{type}/goal.json")
else
raise FitgemOauth2::InvalidArgumentError, "goal type should be one of #{body_goals}"
end
end
# ======================================
# Body Weight API
# ======================================
def weight_on_date(date)
get_call("/1/user/#{@user_id}/body/log/weight/date/#{format_date(date)}.json")
end
def weight_for_period(base_date, period)
if weight_period?(period)
get_call("1/user/#{@user_id}/body/log/weight/date/#{format_date(start_date)}/#{period}.json")
else
raise FitgemOauth2::InvalidArgumentError, "period should be one of #{weight_periods}"
end
end
def weight_for_range(start_date, end_date)
get_call("1/user/#{@user_id}/body/log/weight/date/#{format_date(start_date)}/#{format_date(end_date)}.json")
end
private
def fat_period?(period)
return period && fat_periods.include?(period)
end
def weight_period?(period)
return period && weight_periods.include?(period)
end
end
end
| true
|
62569034760925d0375239af18e0a5c0b7b755b3
|
Ruby
|
RedTeamCOSC470/Stargazer
|
/test/unit/schedule_test.rb
|
UTF-8
| 4,006
| 2.8125
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: schedules
#
# id :integer(38) not null, primary key
# start_time :datetime
# exposure :integer(38)
# number_of_pictures :integer(38)
# created_at :datetime
# updated_at :datetime
# user_id :integer(38)
# area_width :integer(38)
# area_height :integer(38)
# zoom :integer(38)
# iso :integer(38)
# shutter :string(255)
# duration :integer(38)
# right_ascension :datetime
# declination :integer(38)
# object_name :string(255)
#
##########################################################################################
# File: schedule_test.rb
# Project: Stargazer
# Author: Red Team
# Desc: Unit test for the "schedule" model.
##########################################################################################
require 'test_helper'
class ScheduleTest < ActiveSupport::TestCase
def setup
# create a schedule with necessary, correct input values for the following tests
@schedule = Schedule.new
@schedule.start_time = "2014-05-06 04:36:00"
@schedule.right_ascension = Time.now
@schedule.declination = 34.04
@schedule.exposure = 12
@schedule.shutter = "1/1000"
@schedule.iso = 400
@schedule.zoom = 1
@schedule.duration_text = "4 hrs"
@schedule.number_of_pictures = nil
end
def teardown
@schedule = nil
end
# Tests for schedule values:
def test_schedule_time_cannot_be_before_current_time
@schedule.start_time = "2004-05-06 04:36:00"
assert !@schedule.save, "Worked? Saved a schedule to position itself in the past."
end
# Tests for right ascension coordinate values:
def test_user_must_enter_value_for_right_ascension
@schedule.right_ascension = nil
assert !@schedule.save, "Worked? Saved a nil value for right ascension."
end
# Tests for declination coordinate values:
def test_declination_coordinate_must_be_a_number
@schedule.declination = "abc"
assert !@schedule.save, "Worked? Saved a non-number declination value."
end
def test_no_negative_declination_coordinate_can_be_entered
# enter a negative number
@schedule.declination = -12
assert !@schedule.save, "Worked? Saved a negative declination value."
# enter a positive number
@schedule.declination = 12.02
assert @schedule.save
end
def test_user_must_enter_value_for_declination
@schedule.declination = nil
assert !@schedule.save, "Worked? Saved a nil value for declination."
end
# Tests for exposure_rating values:
def test_exposure_rating_cannot_be_past_set_limits
@schedule.exposure = 14
assert @schedule.save, "Saved!"
end
def test_exposure_should_be_an_integer
# try to enter a non-integer value
@schedule.exposure = "f"
assert !@schedule.save, "Worked? Saved a string."
@schedule.exposure = 2.01
assert !@schedule.save, "Worked? Saved a float."
# should be able to save when an integer is entered
@schedule.exposure = 2
assert @schedule.save
end
def test_user_must_enter_value_for_exposure
@schedule.exposure = nil
assert !@schedule.save, "Worked? Saved a nil value for exposure."
end
# Tests for number_of_pictures values:
def test_number_of_pictures_should_be_an_integer
# make sure duration_text is null
@schedule.duration_text = nil
# try to enter a non-integer
@schedule.number_of_pictures = "f"
assert !@schedule.save, "Worked? Saved a string."
@schedule.number_of_pictures = 2.01
assert !@schedule.save, "Worked? Saved a float."
# should be able to save when an integer is entered
@schedule.number_of_pictures = 2
assert @schedule.save
end
def test_user_cannot_enter_two_different_duration_types
@schedule.number_of_pictures = 2
@schedule.duration_text = "4 hrs"
assert !@schedule.save, "Worked? Saved a two types of durations."
end
end
| true
|
1ff5f0df3ea3663e286d0509d4b8d347064e6a06
|
Ruby
|
ryan-brock/CoffeeAndCode
|
/puzzlers/kata02/ntbrock/karate_chop.rb
|
UTF-8
| 2,753
| 3.34375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# http://codekata.com/kata/kata02-karate-chop/
# https://test-unit.github.io/
require "rubygems"
gem "test-unit"
require "test/unit"
require "test/unit/ui/console/testrunner"
# POSH - Plain Old Semantic HTML
def chop(needle, haystackRaw)
chop_recurse(needle, haystackRaw.sort, 0, haystackRaw.length-1, 0)
end
def chop_recurse(needle, haystackRaw, start, stop, depth)
# D-Fence
if depth > 5 then
raise "Exceeded Depth"
elsif start == stop then
return start
elsif haystackRaw == nil || haystackRaw.length <= 0 then
return -1
else
if ( start == nil ) then
start = 0
end
if ( stop == nil ) then
stop = haystackRaw.length-1
end
## Upper level ensures sorted
haystack = haystackRaw[start..stop]
puts "-[ Depth: #{depth} ]--[ Start: #{start} Stop: #{stop} ]-------------------"
puts "haystack length: #{haystack.length} looking for needle: #{needle} haystack: #{haystack}"
midpoint = haystack.length / 2
midpointValue = haystack[midpoint]
# Value at mid-point
puts "midpoint #{midpoint} value: #{midpointValue}"
if midpointValue == needle then
puts "Exact match at midpoint #{midpoint} start: #{start}"
return start + midpoint
elsif midpointValue > needle then
# recurse left
puts "recurse left #{start} to #{stop - midpoint}"
chop_recurse(needle, haystack, start, stop - midpoint, depth+1)
else
# recurse right
puts "recurse right #{start+midpoint} to #{stop}"
chop_recurse(needle, haystack, start + midpoint, stop, depth+1)
end
end
end
class MyTest < Test::Unit::TestCase
def test_chop()
assert true
assert_equal(-1, chop(3, []))
# assert_equal(-1, chop(3, [1]))
assert_equal(0, chop(1, [1]))
#
assert_equal(0, chop(1, [1, 3, 5]))
assert_equal(1, chop(3, [1, 3, 5]))
assert_equal(2, chop(5, [1, 3, 5]))
# assert_equal(-1, chop(0, [1, 3, 5]))
# assert_equal(-1, chop(2, [1, 3, 5]))
# assert_equal(-1, chop(4, [1, 3, 5]))
# assert_equal(-1, chop(6, [1, 3, 5]))
#
assert_equal(0, chop(1, [1, 3, 5, 7]))
assert_equal(1, chop(3, [1, 3, 5, 7]))
assert_equal(2, chop(5, [1, 3, 5, 7]))
assert_equal(3, chop(7, [1, 3, 5, 7]))
# assert_equal(-1, chop(0, [1, 3, 5, 7]))
# assert_equal(-1, chop(2, [1, 3, 5, 7]))
# assert_equal(-1, chop(4, [1, 3, 5, 7]))
# assert_equal(-1, chop(6, [1, 3, 5, 7]))
# assert_equal(-1, chop(8, [1, 3, 5, 7]))
end
end
# https://stackoverflow.com/questions/6515333/how-do-i-execute-a-single-test-using-ruby-test-unit/6515354
puts "hjiiii ya"
tests = Test::Unit::TestSuite.new("Karate Chop Tests")
tests << MyTest.new('test_chop')#calls myTest#test_chop
Test::Unit::UI::Console::TestRunner.run(tests)
| true
|
1aadf9772c886d527b10e8353a1cdc46a642f3b5
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/etl/769b60286fd14090bed0224958dc6f3c.rb
|
UTF-8
| 232
| 2.796875
| 3
|
[] |
no_license
|
class ETL
class << self
def transform(scores)
scores.each_with_object({}) do |(key,value), split_scores|
value.each do |word|
split_scores[word.downcase] = key
end
end
end
end
end
| true
|
6f8280a2a709eb8d01c8c47e8873e821930dd672
|
Ruby
|
jaharaclark/railsy-engine
|
/spec/requests/api/v1/merchants_request_spec.rb
|
UTF-8
| 3,252
| 2.65625
| 3
|
[] |
no_license
|
require 'rails_helper'
RSpec.describe 'Merchants API' do
before :each do
@merchant = create(:merchant)
@item_1 = create(:item, merchant: @merchant)
@item_2 = create(:item, merchant: @merchant)
end
#Get All Merchants
it 'happy: gets all merchants, a maximum of 20 at a time' do
create_list(:merchant, 20)
get '/api/v1/merchants'
expect(response).to be_successful
merchants = JSON.parse(response.body, symbolize_names: true)[:data]
expect(merchants.count).to eq(20)
merchants.each do |merchant|
expect(merchant[:attributes]).to have_key(:name)
expect(merchant[:attributes][:name]).to be_a(String)
end
end
it 'happy: gets all merchants, 50 per page' do
create_list(:merchant, 50)
get '/api/v1/merchants?per_page=50&page=1'
expect(response).to be_successful
merchants = JSON.parse(response.body, symbolize_names: true)[:data]
expect(merchants.count).to eq(50)
end
it 'sad: fetching page 1 if page is 0 or lower' do
create_list(:merchant, 20)
get '/api/v1/merchants?per_page=20&page=-2'
expect(response).to be_successful
merchants = JSON.parse(response.body, symbolize_names: true)[:data]
expect(merchants.count).to eq(20)
get '/api/v1/merchants?per_page=20&page=0'
expect(response).to be_successful
merchants = JSON.parse(response.body, symbolize_names: true)[:data]
expect(merchants.count).to eq(20)
end
#Get One Merchant
it 'happy: can get one merchant by its id' do
id = create(:merchant).id
get "/api/v1/merchants/#{id}"
merchant = JSON.parse(response.body, symbolize_names: true)[:data]
expect(response).to be_successful
expect(merchant).to have_key(:id)
expect(merchant[:id].to_i).to be_an(Integer)
expect(merchant[:attributes]).to have_key(:name)
expect(merchant[:attributes][:name]).to be_a(String)
end
it 'sad: bad merchant integer id returns 404' do
get "/api/v1/merchants/863516878328343843"
expect(response).not_to be_successful
expect(response.status).to eq(404)
end
#Get A Merchant's Items
it 'can get a merchants items' do
get "/api/v1/merchants/#{@merchant.id}/items"
expect(response).to be_successful
items = JSON.parse(response.body, symbolize_names: true)[:data]
expect(items.count).to eq(2)
items.each do |item|
expect(item).to have_key(:id)
expect(item[:id].to_i).to be_an(Integer)
expect(item[:attributes]).to have_key(:name)
expect(item[:attributes][:name]).to be_a(String)
expect(item[:attributes]).to have_key(:description)
expect(item[:attributes][:description]).to be_a(String)
expect(item[:attributes]).to have_key(:unit_price)
expect(item[:attributes][:unit_price]).to be_a(Float)
expect(item[:attributes]).to have_key(:merchant_id)
expect(item[:attributes][:merchant_id]).to be_an(Integer)
end
end
it 'sad: bad merchant integer id returns 404 and no items' do
get "/api/v1/merchants/8293478202384935/items"
items = JSON.parse(response.body, symbolize_names: true)[:data]
expect(response).not_to be_successful
expect(response.status).to eq(404)
expect(items).to eq(nil)
end
end
| true
|
d64eb477a1803470567587c2e5109ac0b8f0caf1
|
Ruby
|
CarlosMontilla/codeeval
|
/easy/theMajorElement/theMajorElement
|
UTF-8
| 555
| 3.5625
| 4
|
[] |
no_license
|
#!/usr/bin/ruby
# It finds the major element that repeats more than a half of the list
# It does not work with list with negative numbers
def solveProblem lst
big = -1
numbers = {}
half = lst.length / 2
lst.each do |i|
if numbers.has_key?(i) then
numbers[i] += 1
else
numbers[i] = 1
end
if numbers[i] > half then return i end
end
return big
end
File.open(ARGV[0],'r').read.split("\n").each do |line|
res = solveProblem (line.split(",").map {|i| i.to_i })
if res == -1 then puts "None" else puts res end
end
| true
|
362601af620cafa84c54784696f2c74a38f499ed
|
Ruby
|
venkatev/chronus_app
|
/app/models/user.rb
|
UTF-8
| 1,277
| 2.71875
| 3
|
[] |
no_license
|
require 'digest/sha1'
class User < ActiveRecord::Base
include Authentication
include Authentication::ByPassword
include Authentication::ByCookieToken
#-----------------------------------------------------------------------------
# ATTRIBUTES AND RELATIONSHIPS
#-----------------------------------------------------------------------------
attr_accessible :email, :name, :password, :password_confirmation
#-----------------------------------------------------------------------------
# VALIDATIONS
#-----------------------------------------------------------------------------
validates_format_of :name, :with => Authentication.name_regex, :message => Authentication.bad_name_message, :allow_nil => true
validates_length_of :name, :maximum => 100
validates_presence_of :email
validates_length_of :email, :within => 6..100
validates_uniqueness_of :email, :case_sensitive => false
validates_format_of :email, :with => Authentication.email_regex, :message => Authentication.bad_email_message
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(email, password)
u = User.find_by_email(email) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
end
| true
|
8dc8f9695aa1c3f69d4e9fe539b79ad143923468
|
Ruby
|
jonmorehouse/pmd
|
/lib/pmd/pause.rb
|
UTF-8
| 367
| 2.546875
| 3
|
[] |
no_license
|
module PMD
class Pause
def initialize
end
def self.is_paused
if File.exists? Config.pause_path
return true
end
return false
end
def execute!
if not File.exists? Config.pause_path
FileUtils.touch Config.pause_path
else
FileUtils.rm Config.pause_path
end
end
end
end
| true
|
ef1995538838798a999fc263809e851b2ec0f28f
|
Ruby
|
venelrene/learn_ruby_the_hard_way
|
/ex5.rb
|
UTF-8
| 750
| 4.09375
| 4
|
[] |
no_license
|
name = "Zed A. Shaw"
age = 35 # not a lie 2009
height = 74 # inches
weight = 180
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
centimeter = 2.54
kilogram = 2.205
puts "Let's talk about #{name}."
puts "He's #{height} inches tall."
# added the formula to get centimeters
puts "Which is #{height + centimeter} centimeters tall"
puts "He's #{weight} pounds heavy."
puts "Actually that's not too heavy."
# added the formula to get kilogram
puts "If you think about how much it is in kilogram (#{weight / kilogram})"
puts "He's got #{eyes} eyes and #{hair} hair."
puts "His teeth are usually #{teeth} depending on the coffee."
# this line is tricky, try to get it exactly right
puts "If I add #{age}, #{height}, and #{weight} I get #{age + height + weight}."
| true
|
643e36b836d8949740d8a5bd2c4f8fe8153967ae
|
Ruby
|
rahulrajdevaraj/artoo-crazyflie
|
/lib/artoo/adaptors/crazyflie.rb
|
UTF-8
| 1,308
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'artoo/adaptors/adaptor'
module Artoo
module Adaptors
# Connect to a crazyflie quadcopter
# @see crazyflie documentation for more information
class Crazyflie < Adaptor
attr_reader :crazyflie, :commander
# Creates a connection with crazyflie
# @return [Boolean]
def connect
require 'crubyflie' unless defined?(::Crubyflie)
@crazyflie = ::Crubyflie::Crazyflie.new('/tmp/test')
source = additional_params[:source] || ""
if source.empty?
flies = @crazyflie.scan_interface
if flies.empty?
raise "No crazyflies!"
end
source = flies.first
end
@crazyflie.open_link(source)
@commander = ::Crubyflie::Commander.new(@crazyflie)
super
end
# Closes connection with device
# @return [Boolean]
def disconnect
@crazyflie.close_link
super
end
# device info interface
def firmware_name
"Crazyflie"
end
def version
Crubyflie::VERSION
end
# Uses method missing to call device actions
# @see device documentation
def method_missing(method_name, *arguments, &block)
@crazyflie.send(method_name, *arguments, &block)
end
end
end
end
| true
|
cdc5d4afc8d8c36503b213b832908aee1ceb9f68
|
Ruby
|
dashalary/oo-tic-tac-toe-bootcamp-prep-000
|
/lib/tic_tac_toe.rb
|
UTF-8
| 1,763
| 4.25
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class TicTacToe
def initialize(board = nil)
@board = board || Array.new(9, " ")
end
def current_player
turn_count % 2 == 0 ? "X" : "O"
end
def turn_count
@board.count{|token| token == "X" || token == "O"}
end
def display_board
puts " #{@board[0]} | #{@board[1]} | #{@board[2]} "
puts "-----------"
puts " #{@board[3]} | #{@board[4]} | #{@board[5]} "
puts "-----------"
puts " #{@board[6]} | #{@board[7]} | #{@board[8]} "
end
WIN_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 4, 8],
[2, 4, 6],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]
]
def input_to_index(user_input)
user_input.to_i - 1
end
def move(index, character = "X")
@board[index] = character
end
def position_taken?(index)
if @board[index] == nil || @board[index] == "" || @board[index] == " "
return false
else
return true
end
end
def valid_move?(index)
index.between?(0,8) && !position_taken?(index)
end
def turn
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(index)
move(index, current_player)
display_board
else
turn
end
end
def won?
WIN_COMBINATIONS.detect do |combo|
@board[combo[0]] == @board[combo[1]] &&
@board[combo[1]] == @board[combo[2]] &&
position_taken?(combo[0])
end
end
def full?
if @board.include?(" ")
return false
else
true
end
end
def draw?
if full? && !won?
return true
else
return false
end
end
def over?
if won? || full? || draw?
return true
end
end
def winner
combo = won?
if combo
return @board[combo[0]]
end
end
def play
until over?
turn
end
if won?
puts "Congratulations #{winner}!"
elsif draw?
puts "Cat's Game!"
end
end
end
| true
|
282ca677cf8a5c2e081ae2db7580017956cfe087
|
Ruby
|
robobee/rademade_fixtures
|
/lib/rademade_fixtures/active_record.rb
|
UTF-8
| 1,977
| 2.71875
| 3
|
[] |
no_license
|
module RademadeFixtures
class ActiveRecord
attr_accessor :persisted
attr_accessor :attributes
attr_accessor :table_name
def initialize(config = {})
@connection = config[:connection] || Connection.instance
@attributes = config[:attributes] || self.class.attributes
@table_name = config[:table_name] || self.class.table_name
@proxy = Hash.new
@persisted = false
end
def get(attribute)
unless attributes.include?(attribute)
raise ArgumentError
end
@proxy[attribute]
end
def set(attribute, value)
unless attributes.include?(attribute)
raise ArgumentError
end
@proxy[attribute] = value
end
def save
persisted ? update : create
end
def self.attributes
raise NotImplementedError
end
def self.table_name
raise NotImplementedError
end
def self.find(id)
sql = "SELECT * FROM #{table_name} WHERE id = $1"
result = Connection.instance.exec_params(sql, [id])
return nil if result.cmd_tuples == 0
object = self.new
object.persisted = true
self.attributes.each do |attribute|
object.set(attribute, result[0][attribute.to_s])
end
object
end
private
def create
columns = attributes.map(&:to_s).join(", ")
placeholders = (1..attributes.count).map { |i| "$#{i}" }.join(", ")
params = attributes.map { |a| @proxy[a] }
sql = "INSERT INTO #{table_name} (#{columns}) VALUES (#{placeholders})"
@connection.exec_params(sql, params)
end
def update
columns = attributes.map(&:to_s)
placeholders = (1..attributes.count).map { |i| "$#{i}" }
zipped = columns.zip(placeholders).map { |pair| pair.join(" = ") }.join(", ")
params = attributes.map { |a| @proxy[a] }
sql = "UPDATE #{table_name} SET #{zipped} WHERE id = #{@proxy[:id]}"
@connection.exec_params(sql, params)
end
end
end
| true
|
af74c9c82dcae870fc8f0470ce2786bcb78789e6
|
Ruby
|
simoniong/patterns
|
/tests/user_test.rb
|
UTF-8
| 1,067
| 2.6875
| 3
|
[] |
no_license
|
require File.dirname(__FILE__) + '/test_helper'
require "not_active_record"
require "models/user"
class UserTest < Test::Unit::TestCase
def test_initialize_with_attributes
user = User.new(id: 1, name: "Marc")
assert_equal 1, user.id
assert_equal "Marc", user.name
end
def test_find
user = User.find(1)
assert_equal 1, user.id
end
def test_all
user = User.all.first
assert_equal 1, user.id
end
def test_map_values_to_columns
values = [1, "Marc"]
columns = [:id, :name]
expected_attributes = {id: 1, name: 'Marc'}
# attributes = {}
# columns.each_with_index do |column, i|
# attributes[column] = values[i]
# end
attributes = User.map_values_to_columns(values)
assert_equal expected_attributes, attributes
end
def test_columns
assert_equal [:id, :name], User.columns
end
def test_table_name
assert_equal "users", User.table_name
end
def test_valid
user = User.new
assert ! user.valid?
assert_equal ["can't be blank"], user.errors[:name]
end
end
| true
|
ff7e06d6dfd62d8365d76bc42a64e3753d2996cf
|
Ruby
|
alanwillms/defender
|
/spec/actor/monster_spec.rb
|
UTF-8
| 5,970
| 2.625
| 3
|
[] |
no_license
|
describe Monster do
let :image do
image = instance_double("Image")
allow(image).to receive(:resized_width).and_return(32)
allow(image).to receive(:resized_height).and_return(32)
image
end
let :map do
Game.current_window.current_screen.map
end
let :monster do
map.monsters.first
end
let :target do
double('Building')
end
before :each do
allow(MapHelper).to receive(:tile_size).and_return(32)
allow(MapHelper).to receive(:screen_padding).and_return(0)
tileset = []
(Monster::SPRITE_FRAMES_COUNT * 4).times { tileset << image }
allow(SpriteHelper).to receive(:tiles).and_return(tileset)
end
context "#warp" do
it "changes monster row, column, x and y" do
monster.warp(Cell.new(map, 1, 1))
expect(monster.x).to eq(32)
expect(monster.y).to eq(32)
expect(monster.current_row).to eq(1)
expect(monster.current_column).to eq(1)
end
end
context "#attack!" do
context "target has more health points than damage suffered" do
it "reduces target health_points" do
allow(target).to receive(:health_points).and_return(30)
expect(target).to receive(:health_points=).with(30 - Game.config[:monsters][:weak_1][:damage])
monster.attack! target
end
end
context "target has more health points than damage suffered" do
it "zero target health_points" do
allow(target).to receive(:health_points).and_return(1)
expect(target).to receive(:health_points=).with(0)
monster.attack! target
end
end
end
context "#find_target" do
before :each do
# Remove all walls
buildings = map.instance_variable_get(:@buildings_map)
map.instance_variable_set(:@maze, nil)
map.buildings.each do |building|
if building.type == :wall
buildings[building.cell.row][building.cell.column] = nil
end
end
monster.warp(Cell.new(map, 1, 1))
end
it "sets target x and y positions" do
monster.warp(Cell.new(map, 0, 0))
monster.find_target
expect(monster.target_x).to be(MapHelper.tile_size)
expect(monster.target_y).to be(0)
end
it "turn up if y decreased" do
monster.instance_variable_set(:@target_x, monster.x)
monster.instance_variable_set(:@target_y, monster.y - 1)
monster.send(:set_face)
expect(monster.facing).to be(Monster::SPRITE_UP_POSITION)
end
it "turn down if y increased" do
monster.instance_variable_set(:@target_x, monster.x)
monster.instance_variable_set(:@target_y, monster.y + 1)
monster.send(:set_face)
expect(monster.facing).to be(Monster::SPRITE_DOWN_POSITION)
end
it "turn left if x decreased" do
monster.instance_variable_set(:@target_x, monster.x - 1)
monster.instance_variable_set(:@target_y, monster.y)
monster.send(:set_face)
expect(monster.facing).to be(Monster::SPRITE_LEFT_POSITION)
end
it "turn right if x increased" do
monster.instance_variable_set(:@target_x, monster.x + 1)
monster.instance_variable_set(:@target_y, monster.y)
monster.send(:set_face)
expect(monster.facing).to be(Monster::SPRITE_RIGHT_POSITION)
end
end
context "move" do
context "horizontally" do
it "decrease x if target at the left" do
monster.warp(Cell.new(map, 0, 1))
monster.instance_variable_set(:@target_x, 0)
monster.instance_variable_set(:@target_y, 0)
previous_x = monster.x
monster.move
expect(monster.x).to be(previous_x - monster.speed)
end
it "increase x if target at the right" do
monster.warp(Cell.new(map, 0, 0))
monster.instance_variable_set(:@target_x, MapHelper.tile_size)
monster.instance_variable_set(:@target_y, 0)
previous_x = monster.x
monster.move
expect(monster.x).to be(previous_x + monster.speed)
end
it "changes current column if arrived at target" do
monster.warp(Cell.new(map, 0, 0))
monster.instance_variable_set(:@target_x, MapHelper.tile_size)
monster.instance_variable_set(:@target_y, 0)
monster.speed = MapHelper.tile_size
monster.move
expect(monster.current_column).to be(1)
end
end
context "vertically" do
it "decrease y if target at the top" do
monster.warp(Cell.new(map, 1, 0))
monster.instance_variable_set(:@target_x, 0)
monster.instance_variable_set(:@target_y, 0)
previous_y = monster.y
monster.move
expect(monster.y).to be(previous_y - monster.speed)
end
it "increase y if target at the bottom" do
monster.warp(Cell.new(map, 0, 0))
monster.instance_variable_set(:@target_x, 0)
monster.instance_variable_set(:@target_y, MapHelper.tile_size)
previous_y = monster.y
monster.move
expect(monster.y).to be(previous_y + monster.speed)
end
it "changes current row if arrived at target" do
monster.warp(Cell.new(map, 0, 0))
monster.instance_variable_set(:@target_x, 0)
monster.instance_variable_set(:@target_y, MapHelper.tile_size)
monster.speed = MapHelper.tile_size
monster.move
expect(monster.current_row).to be(1)
end
end
end
context "#draw" do
it "renders the image" do
expect(image).to receive(:draw_rot_resized)
monster.draw
end
it "renders a health bar" do
health_bar = double('health_bar')
allow(HealthBar).to receive(:new).and_return(health_bar)
expect(image).to receive(:draw_rot_resized)
expect(health_bar).to receive(:draw)
monster.draw
end
end
context "#center" do
it "returns center x,y of the center" do
allow(MapHelper).to receive(:tile_size).and_return(32)
monster.warp(Cell.new(map, 0, 0))
expect(monster.center).to eq([16, 16])
end
end
end
| true
|
c1e4961f9cd85768a7f94f0d342e2c4b1f6538a2
|
Ruby
|
nog/atcoder
|
/contests/abc258/g/main.rb
|
UTF-8
| 295
| 3.03125
| 3
|
[] |
no_license
|
N = gets.to_i
A = Array.new N
N.times do |i|
A[i] = gets.to_i(2)
end
result = 0
(N-2).times do |i|
ai = A[i]
(i+1).upto(N-2) do |j|
next if ai[j] == 0
aj = A[j]
warn "i:#{i} j:#{j} str:#{(ai & aj).to_s(2)}"
result += (ai & aj).to_s(2).count('1')
end
end
puts result / 2
| true
|
b5e59027e88699fb0b91ea9a3d7b9135e179bd2a
|
Ruby
|
ebababi/modalbox_helper
|
/lib/modalbox_helper.rb
|
UTF-8
| 1,776
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
# = Modalbox Helper
module ModalboxHelper
#
# Returns a link of the given +name+ that will trigger the ModalBox JavaScript
# library's function show using the onclick handler and return false after the
# fact.
#
# The first argument +name+ is used as the link text.
#
# The next arguments are optional and may include the content context, a hash
# of options and a hash of html_options.
#
# The +content+ argument can be omitted in favor of a block, which evaluates
# to a string when the template is rendered.
#
# The +options+ will accept a hash of attributes passed as options to the show
# function. Some examples are :title => “Preferences“, :width => 600 etc. You
# may also pass an :escape boolean option to HTML escape the content. By
# default this is false.
#
# The +html_options+ will accept a hash of html attributes for the link tag.
# Some examples are :class => “nav_button“, :id => “articles_nav_button“ etc.
#
# Note: if you choose to specify the content in a block, but would like to
# pass html_options, set the +options+ parameter to nil.
#
# ==== Examples
# This creates a modal dialog for the content of a url:
# <%= link_to_modal 'Preferences', edit_user_registration_path %>
def link_to_modal(name, *args, &block)
if block_given?
options = args.first
html_options = args.second || {}
content = capture(&block)
else
content = args[0]
options = args[1]
html_options = args[2] || {}
end
data = options.delete(:escape) ? "data:#{html_escape(content)}" : content
html_options['href'] = data || '#'
html_options['data-modal'] = options.try(:to_json) || 'true'
content_tag(:a, name, html_options)
end
end
| true
|
45e22b9d4f423770b5cfdb131d94ba62c4c22e55
|
Ruby
|
machvee/craps-strategy-simulator
|
/lib/craps/strategies/bet_presser.rb
|
UTF-8
| 3,551
| 3.109375
| 3
|
[] |
no_license
|
class BetPresser
#
# bring bet to exact amount in sequence until
# press_amounts array is exhausted, and maintain the last
# amount until the bet is lost. Or, press bet by
# press_unit if not nil. PARLAY in sequence or press_unit means
# full press of winnings to scale. begin processing sequence at
# start_pressing_at_win and stop after stop_win
#
#
attr_reader :player
attr_reader :maker
attr_reader :press_amounts
attr_reader :press_unit
attr_accessor :start_amount
attr_reader :start_win_count
attr_accessor :start_pressing_at_win
attr_accessor :amount_to_bet
attr_accessor :stop_win
FOREVER=-1
PARLAY=-1
def initialize(player, maker, craps_bet)
@player = player
@maker = maker
@press_unit = nil
@press_amounts = []
@craps_bet = craps_bet
@start_amount = nil
@amount_to_bet = nil
@start_pressing_at_win = 1 # default is press immediately after first win
@stop_win = FOREVER # default is not never stop pressing once its started
reset
end
def set_start_amount(amount)
@start_amount = amount
@amount_to_bet = start_amount
end
def sequence(amounts)
@press_amounts = amounts
end
def incremental(amount)
@press_unit = amount
end
def next_bet_amount
raise "You haven't set a starting amount to bet on #{@craps_bet}" if amount_to_bet.nil?
return amount_to_bet unless has_press_sequence? # bet amount doesn't change after win
num_wins = current_bet_wins - start_win_count
#
# don't change the bet if we're outside the win/press window
#
if num_wins < start_pressing_at_win || (stop_win != FOREVER && num_wins >= stop_win)
return amount_to_bet
end
#
# based on current win sequence and programmed press amount,
# return the new/current bet amount
#
new_bet_amount =
if press_unit.present?
press_to_amt =
if press_unit == PARLAY
# until we can figure the amount just won,
# just double existing bet amount
amount_to_bet * 2
else
current_pressable_wins = (num_wins - start_pressing_at_win) + 1
start_amount + (press_unit * current_pressable_wins)
end
maker.stats.press(press_to_amt)
press_to_amt
else
if num_wins > press_amounts.length
press_amounts[-1]
else
#
# offset into the press_sequence to find the current betting level
#
press_amounts[num_wins-start_pressing_at_win].tap do |press_to_amt|
maker.stats.press(press_to_amt)
end
end
end
@amount_to_bet = new_bet_amount
amount_to_bet
end
def reset
@start_win_count = current_bet_wins
@amount_to_bet = @start_amount
end
def to_s
amt = "bet $#{@amount_to_bet} "
when_press = if start_pressing_at_win > 1
", after %d %s," % [start_pressing_at_win, "win".pluralize(start_pressing_at_win)]
else
''
end
the_press = if press_unit.present?
"then#{when_press} press by #{press_unit}"
elsif press_amounts.present?
"then#{when_press} press to #{press_amounts}"
else
'with no press'
end
amt + the_press
end
private
def current_bet_wins
player_bet_win_stat.total
end
def player_bet_win_stat
@_pbws ||= player.bet_stats.stat_by_name(@craps_bet.stat_name)
end
def has_press_sequence?
press_unit.present? || press_amounts.length > 0
end
end
| true
|
2717fdc5ae446383e8e3cf5571ad5a403ef4b734
|
Ruby
|
GenSplice-Research-Development/version
|
/Chemical Structure of DNA/char.rb
|
UTF-8
| 2,382
| 3.421875
| 3
|
[] |
no_license
|
#A tribute to Erwin Chargaff
def Chargaff(*b,a)
nib = *b.map{|d|d.upcase}.sort
percent = a.abs
return "Only integers are permitted" unless percent.class == Integer or percent.class == Float
return "Only one or two bases are allowed" if nib.count > 2
if nib.count == 1
return "argument error" if nib[0].length > 1 or nib[0].length < 1
return "base error" unless nib[0] == ?C or nib[0] == ?T or nib[0] == ?A or nib[0] == ?G or nib[0].class == String
case nib[0]
when "A"
totalpercent = percent * 2
gcpercent1 = 100 - totalpercent
gcpercent2 = gcpercent1/2.0
bases = {:A => percent,:T => percent,:G => gcpercent2,:C => gcpercent2}
puts bases
when "T"
totalpercent = percent * 2
gcpercent1 = 100 - totalpercent
gcpercent2 = gcpercent1/2.0
bases = {:T => percent,:A => percent,:G => gcpercent2,:C => gcpercent2}
puts bases
when "G"
totalpercent = percent * 2
gcpercent1 = 100 - totalpercent
gcpercent2 = gcpercent1/2.0
bases = {:G => percent,:C => percent,:T => gcpercent2,:A => gcpercent2}
puts bases
when "C"
totalpercent = percent * 2
gcpercent1 = 100 - totalpercent
gcpercent2 = gcpercent1/2.0
bases = {:C => percent,:G => percent,:T => gcpercent2,:A => gcpercent2}
puts bases
else
puts "error"
end
elsif nib.count == 2
return "argument error" if nib[0].length > 1 or nib[0].length < 1 or nib[1].length > 1 or nib[1].length < 1
return "base error" unless nib[0] == ?C or nib[0] == ?T or nib[0] == ?A or nib[0] == ?G or nib[0].class == String
return "base error" unless nib[1] == ?C or nib[1] == ?T or nib[1] == ?A or nib[1] == ?G or nib[1].class == String
return "Only G and C or T and A are allowed" unless nib == %w(C G) or nib == %w(A T)
case nib
when %w(A T)
totalpercent = percent / 2
gcpercent1 = 100 - percent
gcpercent2 = gcpercent1/2.0
base = {:A => totalpercent,:T => totalpercent,:G => gcpercent2,:C => gcpercent2}
puts base
when %w(C G)
totalpercent = percent / 2
gcpercent1 = 100 - percent
gcpercent2 = gcpercent1/2.0
base = {:C => totalpercent,:G => totalpercent, :T => gcpercent2,:A => gcpercent2}
puts base
else
puts "error"
end
end
rescue NoMethodError
puts "base error"
end
| true
|
a9c9e2d4113eeb5d6e904658454a7262a2e6da99
|
Ruby
|
mannyhappenings/interview
|
/hackerrank/calculate-gcd/calculate_gcd.rb
|
UTF-8
| 562
| 3.453125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
puts 'Running in ruby'
def min(first, second)
first < second ? first : second
end
def max(first, second)
first > second ? first : second
end
def gcd(first, second)
first, second = min(first, second), max(first, second)
first, second = second % first, first until (second % first).zero?
first
end
def gcd_multiple(*numbers)
numbers.reduce { |first, second| gcd(first, second) }
end
(0...gets.to_i).each do |_|
numbers = gets.split.map(&:to_i)
puts "gcd(#{numbers.join(', ')}) = #{gcd_multiple(*numbers)}"
end
| true
|
7d2134dc56a39472cdc1394c3cd6c8fe90df16e1
|
Ruby
|
twerth/acts_as_boolean
|
/lib/acts_as_boolean.rb
|
UTF-8
| 5,321
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
require 'active_record/version'
module ActsAsBoolean
module ClassMethods
# Treats a column as a boolean, whether it's a tinyint, integer, float,
# string, etc. No matter how the true and false are stored in the database.
#
# This is useful when you don't have control over how booleans are
# stored by different applications. For example: Microsoft Access stores
# booleans as 0 and -1. Normally -1 in a MySQL database, would be
# converted, by Rails/ActiveRecord, into a false, rather than true as it
# should be.
#
# You can use either foo or foo? methods and they return the same result.
#
# The following are false (lower or any case), all else are true:
# false, nil, 0, 0.0, '', '0', '0.0', 'f', 'false', 'n', 'no', 'negative',
# [], {}
# You can add to these, for individual columns, using the false_is_also
# parameter. Note: if you use the set_false_as parameter, it will
# automatically be added to the list of falses for this column.
#
# You can specify a specific way a boolean should be stored when
# assigned with set_false_as and set_true_as parameters. This will not
# change how the value is evaluated on read. In other words, if you save
# a false as a 'nope', a value of '0' or 'f' in the database will still be
# read as a false. It only affects how it is stored.
#
# The values set with set_true_as and set_false_as have to be appropriate
# for the field type. You, obviously, can't store 'foo' in an integer field.
# Also note that boolean type fields can't have set_false_as or
# set_true_as set, because booleans are stored differently in different
# databases (for example: 't' and 'f' in sqlite and 0 and 1 in others).
# However, acts_as_boolean is still useful for booleans, to correctly
# convert something like a -1 to true.
#
# Parameters:
#
# * set_false_as - What false value to store in the column on assignment.
# By default any value will be stored, and converted to
# true or false when you read the value.
# * set_true_as - What true value to store in the column on assignment.
# By default any value will be stored, and converted to
# true or false when you read the value.
# * false_is_also - Additional values to be treated as false, a value or
# an array is fine
#
# Examples of use:
# class Person < ActiveRecord::Base
# acts_as_boolean :alive, :employee
# acts_as_boolean :vendor, client, :set_true_as => -1
# acts_as_boolean :foo, :false_is_also => ['nine', 'nada', 9999]
# acts_as_boolean :bar, :set_false_as => 'no', :set_true_as => 'yes', :false_is_also => 'nyet'
#
# #...
# end
def acts_as_boolean(*args)
options = args.extract_options!
false_is_also = options[:false_is_also]
set_false_as, set_true_as = options[:set_false_as], options[:set_true_as]
if false_is_also or set_false_as
if false_is_also and set_false_as
false_is_also = [*set_false_as] | [*false_is_also] # Combine them as an array
elsif set_false_as
false_is_also = set_false_as # Use just the one value, else just false_is_also
end
end_true_call = ", #{false_is_also.inspect}"
else
end_true_call = ""
end
# Create setters
set_false = set_false_as ? set_false_as.inspect : 'new_value'
set_true = set_true_as ? set_true_as.inspect : 'new_value'
args.each do |arg|
# For Rails 2.1 and higher, tell dirty module that we are changing the value
if (ActiveRecord::VERSION::MAJOR == 2 and ActiveRecord::VERSION::MINOR >= 1) or
(ActiveRecord::VERSION::MAJOR > 2)
dirty_code = "#{arg}_will_change!"
end
kode = %Q(
def #{arg}=(new_value)
#{dirty_code}
if is_true?( new_value #{end_true_call})
self[:#{arg}] = #{set_true}
else
self[:#{arg}] = #{set_false}
end
end
)
class_eval kode
end
# Create getters
args.each do |arg|
kode = %Q(
def #{arg}?
is_true?( #{arg}_before_type_cast #{end_true_call})
end
alias :#{arg} :#{arg}?
)
class_eval kode
end
end
end # ClassMethods
module InstanceMethods
protected
def is_true?(value, false_is_also = nil)
if false_is_also and (false_is_also == value or Array(false_is_also).include?(value)) # For performance
false
else
if value.kind_of?(String) # Split into 2 arrays for performance reasons
!STRING_FALSES.include?(value.downcase)
else
!FALSES.include?(value)
end
end
end
private
STRING_FALSES = [ '', '0', '0.0', 'f', 'false', 'n', 'no', 'negative' ]
FALSES = [ false, nil, 0, 0.0, [], {} ]
end # InstanceMethods
end # ActsAsBoolean
class ActiveRecord::Base
include ActsAsBoolean::InstanceMethods
end
ActiveRecord::Base.extend ActsAsBoolean::ClassMethods
| true
|
67821d18d7b5d079474006b28977f776de80f3ac
|
Ruby
|
kkburr/homework_assignments
|
/Warmups/11/spec/lib/Crypt_spec.rb
|
UTF-8
| 1,649
| 3.015625
| 3
|
[] |
no_license
|
require 'rspec'
require './lib/crypt.rb'
describe Crypt do
subject {Crypt}
# context '#encrypt' do
# it 'should return "DBC" for .encrypt("CAB", 1)' do
# expect(subject.encrypt('CAB', 1)).to eq('DBC')
# end
# end
#
# context '#decrypt' do
# it 'should return "CAB" for .decrypt("DBC", 1)' do
# expect(subject.decrypt('DBC', 1)).to eq('CAB')
# end
# end
#
#end
describe "#encrypt(plain_text, key)" do
it "encrypts cab with a key of 1: dbc" do
expect(subject.encrypt("cab", 1)).to eq("dbc")
end
it "encrypts cab with a key of 2: ecd" do
expect(subject.encrypt("cab", 2)).to eq("ecd")
end
it "encrypts caz with a key of 2: eca" do
expect(subject.encrypt("caz", 2)).to eq("eca")
end
context "when not provided a key" do
it "chooses a key randomly" do
encrypted_string = subject.encrypt("string")
expect(subject.decrypt(encrypted_string)).to include("string")
end
end
end
describe "#decrypt(cryptotext, key)" do
it "decrypts dbc with a key of 1: cab" do
expect(subject.decrypt("dbc", 1)).to eq("cab")
end
it "decrypts ecd with a key of 2: cab" do
expect(subject.decrypt("ecd", 2)).to eq("cab")
end
context "when not provided a key" do
it "decrypts all possible values" do
expect(subject.decrypt("ecd")).to include("cab")
end
it "decrypts the encrypted string" do
my_string = "this is the string"
encrypted_string = subject.encrypt(my_string, subject.random_key)
expect(subject.decrypt(encrypted_string)).to include(my_string)
end
end
end
end
| true
|
ff178a21a64117055d2fa4dbaac514cad64cad33
|
Ruby
|
edward-mn/learn-ruby
|
/OneBit/method_missing.rb
|
UTF-8
| 263
| 3.953125
| 4
|
[
"MIT"
] |
permissive
|
class Fish
#método missing
def method_missing(method_name)
puts "Fish don't have #{method_name.capitalize} behavior"
end
def swim
puts 'Fish is swimming'
end
end
my_fish = Fish.new
my_fish.swim
my_fish.walk #Aqui o método missing é acionado
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.