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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
cfc907a3a0660af4351197ee25a26c6753dfd699 | Ruby | fizzik/orion | /app/models/product.rb | UTF-8 | 1,275 | 2.5625 | 3 | [] | no_license | class Product < ActiveRecord::Base
attr_accessible :description, :image_url, :price, :title
validates :title, :description, :image_url, presence: true
validates :title, uniqueness: true
validates :title, length: {maximum: 100}
validates :description, uniqueness: true
validates :image_url, allow_blank: true, format: {
with: %r{\.(gif|jpg|png)$}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
validates :price, numericality: {greater_than_or_equal_to: 0.01}
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
def self.to_csv(options = {})
CSV.generate(options) do |csv|
csv << column_names
all.each do |product|
csv << product.attributes.values_at(*column_names)
end
end
end
end
| true |
e0b75393e3d5fe328fdbe05d6f523681370da703 | Ruby | dementova/store | /app/lib/discount_factory/color.rb | UTF-8 | 421 | 2.765625 | 3 | [] | no_license | module DiscountFactory
class Color
attr_reader :discount
def initialize products
@products = products
end
def define
exist? ? Discount::CONFIG['discount_amount']['color'] : 0
end
private
def exist?
amount_products >= Discount::CONFIG['amount_products']['by_color']
end
def amount_products
@amount_products ||= @products.count{|p| p.color == Discount::CONFIG['color'] }
end
end
end | true |
97d9416fc0b3276e38b7a1108e30a216269be3c6 | Ruby | zed-0xff/zpng | /lib/zpng/adam7_decoder.rb | UTF-8 | 2,556 | 3.09375 | 3 | [
"MIT"
] | permissive | module ZPNG
class Adam7Decoder
attr_accessor :bpp
attr_reader :scanlines_count
# http://en.wikipedia.org/wiki/Adam7_algorithm#Passes
def initialize width, height, bpp
@bpp = bpp
raise "Invalid BPP #{@bpp.inspect}" if @bpp.to_i == 0
@widths = [
[(width/8.0).ceil] * (height/8.0).ceil, # pass1
[((width-4)/8.0).ceil] * (height/8.0).ceil, # pass2
[(width/4.0).ceil] * ((height-4)/8.0).ceil, # pass3
[((width-2)/4.0).ceil] * (height/4.0).ceil, # pass4
[(width/2.0).ceil] * ((height-2)/4.0).ceil, # pass5
[((width-1)/2.0).ceil] * (height/2.0).ceil, # pass6
[width] * ((height-1)/2.0).ceil # pass7
].map{ |x| x == [0] ? [] : x }
@scanlines_count = 0
# two leading zeroes added specially for convert_coords() code readability
@pass_starts = [0,0] + @widths.map(&:size).map{ |x| @scanlines_count+=x }
@widths.flatten! # yahoo! :))
end
# scanline width in pixels
def scanline_width idx
@widths[idx]
end
# scanline size in bytes, INCLUDING leading filter byte
def scanline_size idx
(scanline_width(idx) * bpp / 8.0).ceil + 1
end
# scanline offset in imagedata
def scanline_offset idx
#TODO: optimize
(0...idx).map{ |x| scanline_size(x) }.inject(&:+) || 0
end
# convert "flat" coords in scanline number & pos in scanline
def convert_coords x,y
# optimizing this into one switch/case statement gives
# about 1-2% speed increase (ruby 1.9.3p286)
if y%2 == 1
# 7th pass: last height/2 full scanlines
[x, y/2 + @pass_starts[7]]
elsif x%2 == 1 && y%2 == 0
# 6th pass
[x/2, y/2 + @pass_starts[6]]
elsif x%8 == 0 && y%8 == 0
# 1st pass, starts at 0
[x/8, y/8]
elsif x%8 == 4 && y%8 == 0
# 2nd pass
[x/8, y/8 + @pass_starts[2]]
elsif x%4 == 0 && y%8 == 4
# 3rd pass
[x/4, y/8 + @pass_starts[3]]
elsif x%4 == 2 && y%4 == 0
# 4th pass
[x/4, y/4 + @pass_starts[4]]
elsif x%2 == 0 && y%4 == 2
# 5th pass
[x/2, y/4 + @pass_starts[5]]
else
raise "invalid coords"
end
end
# is the specified scanline is a first scanline in the pass?
# When the image is interlaced, each pass of the interlace pattern is
# treated as an independent image for filtering purposes
def pass_start? idx
@pass_starts.include?(idx)
end
end
end
| true |
d1b9bc3797af581409355636414d980e1bfcd91c | Ruby | steve-hawkins/uplifting_quote | /spec/uplifting_quote_spec.rb | UTF-8 | 1,008 | 2.84375 | 3 | [
"MIT"
] | permissive | require "spec_helper"
RSpec.describe UpliftingQuote do
it "has a version number" do
expect(UpliftingQuote::VERSION).not_to be nil
end
describe ".add" do
it "should add two numbers" do
expect(UpliftingQuote.add(0, 0)).to eq(0)
expect(UpliftingQuote.add(1, 3)).to eq(4)
expect(UpliftingQuote.add(1.1, 3.8)).to eq(4.9)
end
it "should error if not a fixnum" do
expect{UpliftingQuote.add(1, "a")}.
to raise_error("1 and/or a is not a number, try again...")
end
end
describe ".reverse" do
it "should reverse a string" do
expect(UpliftingQuote.reverse("")).to eq("")
expect(UpliftingQuote.reverse("london")).to eq("nodnol")
end
it "should error if not a string" do
expect{UpliftingQuote.reverse(15)}.
to raise_error("15 is not a string, try again...")
end
end
describe ".get_quote" do
it "should return an uplifting quote" do
expect(UpliftingQuote.get_quote).not_to be nil
end
end
end
| true |
1b08ce50f0115ad2d51a7fcbd85dbbc69f8f87c6 | Ruby | xWilsonle/RubyCounting | /count.rb | UTF-8 | 958 | 3.96875 | 4 | [] | no_license |
#Gets the name for the user
def getName
puts "What is your name?"
$inputName = gets
end
#Gets the number for the user
def getNumber
puts("What is your number?")
begin
$inputNumber = Integer(gets.chomp)
rescue
puts("Please enter a valid number")
retry
end
end
#gets the increment
def getIncrement
puts("What is your increment?")
begin
$inputIncrement = Integer(gets.chomp)
rescue
puts("Please input a valid number")
retry
end
if $inputIncrement > $inputNumber || $inputIncrement == 0
puts("Your increment cannot be bigger than your number")
getIncrement
end
end
#prints out the results of the inputs
def printResult
puts("Hello " + $inputName)
printNumberSequence
end
#prints out the number sequence
def printNumberSequence
i = 0
loop do
print(i)
print(" ")
i+= $inputIncrement
if i > $inputNumber
break
end
end
end
def getInputs
getName
getNumber
getIncrement
end
#The Main Code
getInputs
printResult
| true |
9025e1774624782dd4f0773f194fc263d062421f | Ruby | yoricksijsling/voter | /app/models/poll.rb | UTF-8 | 745 | 2.71875 | 3 | [] | no_license | class Poll
include MongoMapper::Document
key :title
key :description
many :options
many :participants
def get_participant(code)
self.participants.select{ |p| p.code == code }.first
end
def options_csv # yeah yeah not really csv i know
self.options.map{|o| o.title }.join ','
end
def options_csv=(titles)
throw :burp if self.options.any?
titles.split(',').each do |title|
self.options << Option.new(:title => title)
end
end
def participant_count
self.participants.count
end
def participant_count=(count)
throw :burp if self.participants.any?
(0..(count.to_i-1)).map do |i|
self.participants << Participant.new(:code => rand(1000000).to_s)
end
end
end | true |
d21c41fd055d55aa52c61441dc796b5728e4b800 | Ruby | yuemori/active_any | /lib/active_any/relation/order_clause.rb | UTF-8 | 1,175 | 2.875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module ActiveAny
class Relation
class OrderClause
def self.empty
new
end
OrderValue = Struct.new(:key, :sort_type)
attr_reader :order_values
def initialize(values = [], reverse = false)
@reverse = reverse
@order_values = convert_order_values(values)
end
def reverse?
@reverse
end
def reverse!
@reverse = true
self
end
def +(other)
OrderClause.new(
order_values + other.order_values,
reverse? || other.reverse?
)
end
alias merge +
def ==(other)
reverse? == other.reverse? && order_values == other.order_values
end
def empty?
order_values.empty?
end
private
def convert_order_values(values)
values.map do |arg|
case arg
when ::Hash then OrderValue.new(arg.keys.first, arg.values.first)
when ::Symbol, ::String then OrderValue.new(arg, :asc)
when OrderValue then arg
else
raise ArgumentError
end
end
end
end
end
end
| true |
21465b37f99167e3482fc60ae5f93eab696b4254 | Ruby | jhellerstein/crocus | /test/tc_elements.rb | UTF-8 | 1,533 | 2.71875 | 3 | [] | no_license | require './test_common.rb'
require '../lib/crocus/minibloom'
class TestElements < Test::Unit::TestCase
def test_pull_element
e = Crocus::PullElement.new(:p, 0, (1..1000000000))
i = e.to_enum do |out, inp|
out.yield inp if inp.class <= Numeric and inp%2 == 0
end
assert_equal([2,4,6], i.take(3))
end
def test_push_element
results = []
p = Crocus::PushElement.new(:r,0) do |inp|
if inp[0].class <= Numeric and inp[0]%2 == 0
results << [inp[0]*2]
else
results << [-1]
end
end
p.insert([2])
p.flush
assert_equal([4], results.pop)
p.insert([1])
p.flush
assert_equal([-1], results.pop)
p.insert([:a])
p.flush
assert_equal([-1], results.pop)
p.insert(nil)
p.flush
assert_equal(nil, results.pop)
end
def test_push_pair
results = []
p = Crocus::PushElement.new(:p,0)
q = Crocus::PushElement.new(:q,0) do |inp|
if inp[0].class <= Numeric and inp[0]%2 == 0
results << [inp[0]*2]
else
results << [-1]
end
end
p.wire_to(q)
p.insert([2])
p.flush; q.flush
assert_equal([4], results.pop)
end
def test_pull_itemset
it = Crocus::ItemSet.new(:r,2,[0])
(0..1000).each do |i|
it << [i,i+1]
end
e = Crocus::PullElement.new(:p, 0, it)
i = e.to_enum do |out, inp|
out.yield inp if inp.class <= Array and inp[0].class <= Numeric and inp[0]%2 == 0
end
assert_equal([[0,1],[2,3],[4,5]], i.take(3))
end
end
| true |
664b3568b9bb6fd7e6b7d12f15cc788ee176f8f6 | Ruby | williamtome/ruby-course | /estruturas_de_controle/iteracao/foreach.rb | UTF-8 | 199 | 3.609375 | 4 | [] | no_license | lista = [1,2,3,4,5]
lista.each do |item|
puts "Número: #{item}"
end
palavra = "Onomatopéia"
puts "total de letras: #{palavra.size}"
palavra.each_char do |letra|
puts "Letra: #{letra}"
end | true |
676320d373a0a4874767a26a41ae1eeb2faacdb5 | Ruby | pixapi/headcount | /test/headcount_analyst_test.rb | UTF-8 | 5,119 | 2.609375 | 3 | [] | no_license | require_relative 'test_helper'
require './lib/headcount_analyst'
require './lib/district_repository'
class HeadcountAnalystTest < Minitest::Test
def test_it_has_a_class
dr = DistrictRepository.new
ha = HeadcountAnalyst.new(dr)
assert_instance_of HeadcountAnalyst, ha
end
def test_it_gets_participation_variation_district_vs_state
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"}})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.766, ha.kindergarten_participation_rate_variation('ACADEMY 20', :against => 'COLORADO')
end
def test_it_gets_participation_variation_district_vs_state_ignoring_corrupted_data
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"}})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.0, ha.kindergarten_participation_rate_variation('WEST YUMA COUNTY RJ-1', :against => 'COLORADO')
end
def test_it_gets_participation_variation_district_vs_district
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"}})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.446, ha.kindergarten_participation_rate_variation('ACADEMY 20', :against => 'YUMA SCHOOL DISTRICT 1')
end
def test_calculate_average
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"}})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.7088181818181819, ha.calculate_average("ADAMS COUNTY 14")
end
def test_it_gets_participation_variation_district_vs_district
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv"}})
ha = HeadcountAnalyst.new(dr)
result = {2004 => 1.257, 2005 => 0.96, 2006 => 1.05, 2007 => 0.992, 2008 => 0.717, 2009 => 0.652,
2010 => 0.681, 2011 => 0.727, 2012 => 0.688, 2013 => 0.694, 2014 => 0.661 }
result.each do |year, rate|
assert_in_delta rate, ha.kindergarten_participation_rate_variation_trend('ACADEMY 20', :against => 'Colorado')[year], 0.005
end
end
def test_it_compares_variations_of_kindergarten_participation_with_high_school_graduation
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}})
ha = HeadcountAnalyst.new(dr)
assert_equal 0.800, ha.kindergarten_participation_against_high_school_graduation('STEAMBOAT SPRINGS RE-2')
assert_equal 0.548, ha.kindergarten_participation_against_high_school_graduation('MONTROSE COUNTY RE-1J')
end
def test_it_compares_variations_of_kindergarten_participation_with_high_school_graduation
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}})
ha = HeadcountAnalyst.new(dr)
assert ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'ACADEMY 20')
end
def test_it_refutes_when_compares_variation_kindergarten_participation_with_high_school_graduation_out_of_range
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}})
ha = HeadcountAnalyst.new(dr)
refute ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'MONTROSE COUNTY RE-1J')
refute ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'SIERRA GRANDE R-30')
assert ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'PARK (ESTES PARK) R-3')
end
def test_it_compares_variations_of_kindergarten_participation_with_high_school_graduation_statewide
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}})
ha = HeadcountAnalyst.new(dr)
refute ha.kindergarten_participation_correlates_with_high_school_graduation(for: 'STATEWIDE')
end
def test_it_compares_variations_of_kindergarten_participation_with_high_school_graduation_multiple_districts
dr = DistrictRepository.new
dr.load_data({
:enrollment => {
:kindergarten => "./data/Kindergartners in full-day program.csv",
:high_school_graduation => "./data/High school graduation rates.csv"
}})
ha = HeadcountAnalyst.new(dr)
assert ha.kindergarten_participation_correlates_with_high_school_graduation(:across => ["ACADEMY 20", 'PARK (ESTES PARK) R-3', 'YUMA SCHOOL DISTRICT 1'])
end
end
| true |
c30ddbe7b4fa088f42b51f55904bdb1b61d4a608 | Ruby | mlyubarskyy/leetcode | /206_reverse_linked_list.rb | UTF-8 | 520 | 3.625 | 4 | [] | no_license | # Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @return {ListNode}
def reverse_list(head)
return head if !head || !head.next
node = reverse_list(head.next)
head.next.next = head
head.next = nil
node
end
def reverse_list(head)
prev = nil
node = head
while node
tmp = node.next
node.next = prev
prev = node
node = tmp
end
prev
end
| true |
155034648e2684621e22a77516f4e8af02fddb14 | Ruby | ualbertalib/serials-admin | /data_scripts/spec/bad_issn_spec.rb | UTF-8 | 553 | 2.515625 | 3 | [] | no_license | require_relative("spec_helper")
RSpec.configure do |c|
c.include TestData
end
describe BadIssn do
let(:bad_issn){ BadIssn.new(StringIO.new(bad_issn_data)) }
# BadIssn takes reads the badissn data, takes in a titleID and returns whether the issn is bad or not.
context "when provided with a titleID" do
it "returns if the record's issn is in the list" do
expect(bad_issn=="6059055").to be_true
end
it "returns false if the record's issn is not in the list" do
expect(bad_issn=="5555555").to be_false
end
end
end
| true |
e9b3c28af1653c2bb3b517a37010a3882219cffb | Ruby | TertiumQuid/Cthulhu-Quest | /app/models/armament.rb | UTF-8 | 1,084 | 2.5625 | 3 | [] | no_license | class Armament < ActiveRecord::Base
ORIGIN = ['purchase','gift','reward']
belongs_to :weapon
belongs_to :investigator
scope :weapons, includes(:weapon)
before_validation :set_weapon_name, :on => :create
after_create :arm_investigator
attr_accessor :origin
validates :investigator_id, :numericality => true
validates :weapon_id, :numericality => true, :uniqueness => {:scope => :investigator_id}
validates :weapon_name, :presence => true
validates :origin, :allow_blank => true, :inclusion => { :in => ORIGIN }
validate :origin_valid, :on => :create
private
def origin_valid
return if origin.blank? || !purchase?
errors[:investigator_id] << "lacking funds" unless valid_purchase?
end
def purchase?
origin == 'purchase'
end
def valid_purchase?
weapon && investigator && investigator.funds >= weapon.price
end
def set_weapon_name
self.weapon_name = weapon.name if weapon
end
def arm_investigator
investigator.update_attribute(:armed_id, id) if investigator.armed_id.nil?
end
end | true |
d39ce3aa749afe4bfecc9d22351596e821e6e0fc | Ruby | cthomaspdx/fat-linode | /libraries/linode_api.rb | UTF-8 | 1,722 | 2.84375 | 3 | [] | no_license | module FatLinode
class LinodeApi
attr_accessor :api_key, :node_name, :public_ip
def initialize(args)
@api_key = args[:api_key]
@node_name = args[:node_name]
@public_ip = args[:public_ip]
end
def private_ips
all_ips.collect {|ip| ip.ipaddress if private?(ip)}.compact
end
def private_ip
node_ips.detect{|ip| private?(ip)}
end
def node_private_ip
if private_ip
private_ip.ipaddress
else
warn "no private_ip issued on this linode"
end
end
def node_public_ip
node_ips.detect{|ip| private?(ip) == false}.ipaddress
end
def node_gateway
array = node_public_ip.split(".")
array[-1] = "1"
array.join(".")
end
def node_ips
if detect_linode_by_label
find_ips(:LinodeId => detect_linode_by_label.linodeid)
elsif detect_lionde_by_public_ip
find_ips(:LinodeId => detect_lionde_by_public_ip.linodeid)
else
warn "Cannot detect the linode you are deploying"
end
end
private
def conn
@conn ||= Linode.new(:api_key => api_key)
end
def linode
begin
conn.linode
rescue
raise "Could not connect to linode's api!"
end
end
def find_ips(linodeid)
linode.ip.list(linodeid)
end
def all_ips
linode.ip.list
end
def private?(ip_instance)
ip_instance.ispublic.zero?
end
def detect_linode_by_label
@detected ||= linode.list.detect{|l| l.label == node_name} if node_name
end
def detect_lionde_by_public_ip
@detected ||= linode.ip.list.detect{|ip| ip.ipaddress == public_ip} if public_ip
end
end
end
| true |
da077dbb4d7bae19eea387d79884bd58f6668ce2 | Ruby | andrewetobin/home-consultant | /app/services/appointment_collector.rb | UTF-8 | 1,559 | 2.671875 | 3 | [] | no_license | class AppointmentCollector
def initialize(appointment_info, auth_token, email)
@appointment_info = appointment_info
@auth_token = auth_token
@email = email
response
end
def build_body
{
HTTP_AUTH_TOKEN: @auth_token,
email: @email,
address: @appointment_info[:consultation][:address],
about_this_home: @appointment_info[:consultation][:about_this_home],
client_enthusiasm: @appointment_info[:consultation][:client_enthusiasm],
commission: @appointment_info[:consultation][:commission],
about_the_seller: @appointment_info[:consultation][:about_the_seller],
credit_card: @appointment_info[:consultation][:credit_card],
exp_date: @appointment_info[:consultation][:exp_date],
price: @appointment_info[:consultation][:price]
}
end
def send_data
TreloraApiInterface.new.post(:update, build_body)
end
def response
@response ||= JSON.parse(send_data.body, symbolize_names: true)
end
def about_this_home
@response[:listing_consultation][:consultation][:about_this_home]
end
def client_enthusiasm
@response[:listing_consultation][:consultation][:client_enthusiasm]
end
def commission
@response[:listing_consultation][:consultation][:commission]
end
def about_the_seller
@response[:listing_consultation][:consultation][:about_the_seller]
end
def credit_card
@response[:listing_consultation][:consultation][:credit_card]
end
def exp_date
@response[:listing_consultation][:consultation][:exp_date]
end
end
| true |
4e1365b9aae51e6d7fe0a0eb764786d82ecc6fc4 | Ruby | bradgreen3/apicurious | /app/models/github_starred_repo.rb | UTF-8 | 519 | 3.015625 | 3 | [] | no_license | class GithubStarredRepo
attr_reader :full_name, :updated_at, :language
def initialize(raw_repo={})
@full_name = raw_repo[:full_name]
@updated_at = clean_date(raw_repo[:updated_at])
@language = raw_repo[:language]
end
def self.for_user(token)
starred_repos = GithubService.new(token).starred_repos
starred_repos.map do |raw_repo|
GithubStarredRepo.new(raw_repo)
end
end
def clean_date(raw_date)
d = DateTime.parse(raw_date)
d.strftime('%B %e, %Y at %H:%M')
end
end
| true |
522daa4689eb1f6deb9aa92074cd295ad98a5af7 | Ruby | bestmike007/log4rails | /lib/log4r/MDC.rb | UTF-8 | 1,462 | 2.515625 | 3 | [
"BSD-2-Clause"
] | permissive | # :include: rdoc/MDC
#
# == Other Info
#
# Version:: $Id$
# Author:: Colby Gutierrez-Kraybill <colby(at)astro.berkeley.edu>
require 'monitor'
module Log4r
MDCNAME = "log4rMDC"
MDCNAMEMAXDEPTH = "log4rMDCMAXDEPTH"
$globalMDCLock = Monitor.new
# See log4r/MDC.rb
class MDC < Monitor
private_class_method :new
class << self
def check_thread_instance
# need to interlock here, so that if
# another thread is entering this section
# of code before the main thread does,
# then the main thread copy of the MDC
# is setup before then attempting to clone
# it off
if ( Thread.current[MDCNAME] == nil ) then
$globalMDCLock.synchronize do
Thread.main[MDCNAME] ||= Hash.new
clone_from_main if Thread.current != Thread.main
end
end
end
def clone_from_main
Thread.current[MDCNAME] = Thread.main[MDCNAME].clone
end
private :clone_from_main
def get(a_key)
check_thread_instance()
Thread.current[MDCNAME][a_key];
end
def get_context
check_thread_instance()
return Thread.current[MDCNAME].clone
end
def put(a_key, a_value)
check_thread_instance()
Thread.current[MDCNAME][a_key] = a_value
end
def remove(a_key)
check_thread_instance()
Thread.current[MDCNAME].delete(a_key)
end
end
end
end
| true |
bd6a0c70cb6f69b566c0866a633f8a8395723e84 | Ruby | cvolpe12/ruby-objects-belong-to-lab-nyc-web-career-010719 | /lib/post.rb | UTF-8 | 152 | 2.765625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require 'pry'
class Post
attr_accessor :title, :author
@@posts = []
def initialize
@@posts << self
end
def all
@@posts
end
end
| true |
5e710ac33900fc42a32e7cf1e71a66f2a28f7f57 | Ruby | rainforestapp/get_env | /spec/get_env_spec.rb | UTF-8 | 1,601 | 2.640625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
RSpec.describe GetEnv do
before(:all) do
ENV['SOME_STRING'] = 'foo'
ENV['SOME_INT'] = '1'
ENV['SOME_FLOAT'] = '1.23'
ENV['SOME_TRUE'] = 'true'
ENV['SOME_FALSE'] = 'false'
end
it "has a version number" do
expect(GetEnv::VERSION).not_to be nil
end
describe '#[]' do
it 'handles nil' do
expect(GetEnv[nil]).to eq(nil)
end
it 'handles missing value' do
expect(GetEnv['klfadjslfkadjsflkadjs']).to eq(nil)
end
it 'returns strings' do
expect(GetEnv['SOME_STRING']).to eq('foo')
end
it 'casts ints' do
expect(GetEnv['SOME_INT']).to eq(1)
end
it 'casts floats' do
expect(GetEnv['SOME_FLOAT']).to eq(1.23)
end
it 'casts bools' do
expect(GetEnv['SOME_TRUE']).to be(true)
expect(GetEnv['SOME_FALSE']).to be(false)
end
end
describe '#fetch' do
it 'casts types' do
expect(GetEnv.fetch('SOME_FLOAT')).to eq(1.23)
end
it 'returns the value when found' do
expect(GetEnv.fetch('SOME_FLOAT', 3.21)).to eq(1.23)
end
it 'returns the defaults when not found' do
expect(GetEnv.fetch('SOME_NON_EXISTANT_FLOAT', 3.21)).to eq(3.21)
end
it 'raises an exception if not found and no default is specified' do
expect do
GetEnv.fetch('SOME_NON_EXISTANT_FLOAT')
end.to raise_error KeyError, /key not found: "SOME_NON_EXISTANT_FLOAT"/
end
it 'accepts a block for the default value' do
v = GetEnv.fetch('SOME_NON_EXISTANT_FLOAT') { 3.21 }
expect(v).to eq(3.21)
end
end
end
| true |
f2b0232e522d9f76e5d9ce647847861d94b3e3dd | Ruby | RubyCamp/rc2021sp_g6 | /Generic Mario/scenes/ending/director.rb | UTF-8 | 857 | 2.5625 | 3 | [] | no_license | module Ending
class Director
def initialize
#文字のフォント、サイズ
@font = Font.new(70, "丸 ゴシック")
@font2 = Font.new(40, "MS ゴシック")
@image = Image.load('images/墓.png')
end
def reload
end
def play
#画像の描画
Window.bgcolor = C_BLACK
Window.draw_scale(500, 320, @image, 6, 6)
@image.set_color_key(C_WHITE)
#文字の描画
Window.draw_font(300, 150, "GAME OVER", @font ,color: C_RED)
Window.draw_font(350, 460, "RESTRAT : R_key", @font2 ,color: C_RED)
Scene.add(Game::Director.new, :game) #初期位置の初期化
Scene.move_to(:opening) if Input.key_push?(K_R)
end
end
end | true |
0e790dfb83b25dc31a7a8b9b7e6e5cb4c6fb9df3 | Ruby | markpackham/codeclan_week04_big_project | /models/customer_lesson.rb | UTF-8 | 2,686 | 2.90625 | 3 | [] | no_license | require_relative("../db/sql_runner")
class Customer_Lesson
attr_accessor(:customer_id, :lesson_id)
attr_reader(:id)
def initialize(options)
@id = options["id"].to_i if options["id"]
@customer_id = options["customer_id"].to_i
@lesson_id = options["lesson_id"].to_i
end
def save()
sql = "INSERT INTO customers_lessons
(
customer_id,
lesson_id
)
VALUES
(
$1, $2
)
RETURNING id"
values = [@customer_id, @lesson_id]
result = SqlRunner.run(sql, values)
id = result.first["id"]
@id = id
end
def update()
sql = "UPDATE customers_lessons SET
(
customer_id,
lesson_id
)
=
(
$1, $2
)
WHERE id = $3;"
values = [@customer_id, @lesson_id, @id]
SqlRunner.run(sql, values)
end
def self.delete_all
sql = "DELETE FROM customers_lessons;"
SqlRunner.run(sql)
end
def self.delete(id)
sql = "DELETE FROM customers_lessons
WHERE id = $1"
values = [id]
SqlRunner.run(sql, values)
end
def self.all()
sql = "SELECT * FROM customers_lessons;"
results = SqlRunner.run(sql)
return results.map { |hash| Customer_Lesson.new(hash) }
end
def self.all_tables()
sql = "SELECT *
FROM lessons
INNER JOIN customers_lessons
ON lessons.id = customers_lessons.lesson_id
INNER JOIN customers
ON customers.id = customers_lessons.customer_id;"
results = SqlRunner.run(sql)
return results.map { |hash| Customer_Lesson.new(hash) }
end
def self.find(id)
sql = "SELECT * FROM customers_lessons
WHERE id = $1;"
values = [id]
results = SqlRunner.run(sql, values)
return Customer_Lesson.new(results.first)
end
def customer()
sql = "SELECT * FROM customers
WHERE id = $1;"
values = [@customer_id]
results = SqlRunner.run(sql, values)
return Customer.new(results.first)
end
def lesson()
sql = "SELECT * FROM lessons
WHERE id = $1;"
values = [@lesson_id]
results = SqlRunner.run(sql, values)
return Lesson.new(results.first)
end
def self.lesson_numbers()
sql = "SELECT COUNT(customers_lessons.customer_id), customers_lessons.lesson_id
FROM customers_lessons
GROUP BY customers_lessons.lesson_id
ORDER BY COUNT(customers_lessons.customer_id) DESC;"
results = SqlRunner.run(sql)
return results.map { |hash| Customer_Lesson.new(hash) }
end
def charge_customer(customer, lesson)
customer.funds = customer.funds - lesson.price
end
def self.map_items(customer_lesson_data)
return customer_lesson_data.map { |customer_lesson| Customer_Lesson.new(customer_lesson) }
end
end
| true |
57747aa4a3e6dd038da183d2e3e4d9dd35e9fbc3 | Ruby | gonyolac/ls_ruby_course | /ruby_more_topics/weekly_challenges/protein_translation.rb | UTF-8 | 1,791 | 3.71875 | 4 | [] | no_license | class Translation
# no need for initialize?; no indication of instance object; class method
#track states of a Translation? (no need!)
@codon_codes = {
"Methionine": ['AUG'],
"Phenylalanine": ['UUU', 'UUC'],
"Leucine": ['UUA', 'UUG'],
"Serine": ['UCU', 'UCC', 'UCA', 'UCG'],
"Tyrosine": ['UAU', 'UAC'],
"Cysteine": ['UGU', 'UGC'],
"Tryptophan": ['UGG'],
"STOP": ['UAA', 'UAG', 'UGA']
}
def self.of_codon(codon)
filtered_codes = @codon_codes.select {|k,v| v.include?(codon)}
raise InvalidCodonError if filtered_codes.empty?
valid_protein = (filtered_codes.keys[0]).to_s
end
# Translation.of_codon('AUG') DONE
# => 'Methionine' DONE
# essentially, display the protein (key) where the inputted codon is present; DONE
# scan the values in the hash then display corresponding key with the match DONE
# need to find out: how to use key method to find occurence/match within the array
def self.of_rna(rna_strand)
# display array with protein values, translated from rna_strand
proteins = [] # final display array
codons = [] # works!
rna_index = 0
while rna_index < rna_strand.size
codons << rna_strand.slice(rna_index..rna_index+2)
rna_index += 3
end
codons.each do |codon|
string_codon = codon.to_s
break if self.of_codon(string_codon) == "STOP"
proteins << self.of_codon(string_codon)
end
# code prior to refactor
#protein_counter = 0
#while protein_counter < codons.size
# need_to_translate = codons[protein_counter].to_s
# break if self.of_codon(need_to_translate) == "STOP"
# proteins << self.of_codon(need_to_translate)
# protein_counter += 1
#end
proteins
end
end
class InvalidCodonError < Exception
end
| true |
6c9c0a42ec121a9d3485821563741ef3ec047b49 | Ruby | amenning/Design_Patterns_GOF_In_Ruby | /Structural_Patterns/class_structural/proxy/example.rb | UTF-8 | 377 | 2.5625 | 3 | [] | no_license | require_relative 'real_image.rb'
require_relative 'proxy_image.rb'
puts 'Open pretend document with real image'
immediate_image = RealImage.new('Real')
puts 'Scroll down page so image is on page'
immediate_image.display
puts "\n" + 'Open pretend document with proxy image'
proxy_image = ProxyImage.new('Proxy')
puts 'Scroll down page so image is on page'
proxy_image.display
| true |
34a7027ef37086fcc91809b56b1de73ab64058a1 | Ruby | snreid/uc-tracker | /app/models/usda/api.rb | UTF-8 | 827 | 2.53125 | 3 | [] | no_license | module USDA
require 'uri'
require 'net/http'
require 'json'
class API
attr_accessor :base_uri
API_KEY = { api_key: Rails.application.secrets.usda_api_key }
def initialize(base_uri = "http://api.nal.usda.gov/ndb/")
@base_uri = base_uri
end
def response(endpoint, params = {})
uri = build_uri(endpoint, params)
response = Net::HTTP.get(uri)
JSON.parse(response)
end
def build_uri(endpoint, params)
params.merge!(API_KEY)
uri = URI(@base_uri + endpoint)
uri.query = URI.encode_www_form(params)
uri
end
def json_response(endpoint, params={})
response( endpoint, params.merge!({format: "json"}) )
end
def xml_response(endpoint, params={})
response( endpoint, params.merge!({format: "xml"}) )
end
end
end | true |
6e1202486c3f61b2eaca7998688659d7c4b3415a | Ruby | peterylai/project_euler | /p026.rb | UTF-8 | 357 | 3.734375 | 4 | [] | no_license | require 'prime'
def recurring_cycle_length(num)
return 0 if num % 2 == 0 || num % 5 == 0
repetend_length = 1
while (((10**repetend_length) - 1) % num) != 0
repetend_length += 1
end
repetend_length
end
max = 0
Prime.each(1000) do |prime|
max = recurring_cycle_length(max) > recurring_cycle_length(prime) ? max : prime
end
puts max
| true |
eeab91ccfc6e0b5c866e4a811f26938a0429dd57 | Ruby | omustafa1994/starwars-api | /spec/fixerio_spec.rb | UTF-8 | 984 | 2.640625 | 3 | [] | no_license | require 'spec_helper'
describe 'starwars api' do
before(:all) do
@starwars_people = ParseJson.new(HTTParty::get("https://swapi.co/api/people/1").body).json_data
@starwars_planet = ParseJson.new(HTTParty::get("https://swapi.co/api/planets/1").body).json_data
end
it 'should be a hash' do
expect(@starwars_people).to be_kind_of(Hash)
end
it "should contain name Luke Skywalker" do
expect(@starwars_people["name"]).to eq "Luke Skywalker"
end
it "should contain hair color of blond" do
expect(@starwars_people["hair_color"]).to eq "blond"
end
it "should contain skin color of fair" do
expect(@starwars_people["skin_color"]).to eq "fair"
end
it "should contain eye color of blue" do
expect(@starwars_people["eye_color"]).to eq "blue"
end
it "should contain gender of male" do
expect(@starwars_people["gender"]).to eq "male"
end
it "should contain name Tatooine" do
expect(@starwars_planet["name"]).to eq "Tatooine"
end
end
| true |
00613edf6e5a1890ed5e1debf22dcbdecfb6d525 | Ruby | binzume/ruby-irc-bot | /irc.rb | UTF-8 | 4,134 | 2.703125 | 3 | [] | no_license | require 'time'
require 'net/irc'
require 'kconv'
require 'digest/md5'
def irc_connect servers, bot
servers.map{|server|
s = IrcServer.new(server)
client = s.connect
client.add_bot(bot) if bot
t = Thread.new do
client.start
puts "IRC client finished."
end
s
}
end
class IrcServer
attr_accessor :config, :id
attr_reader :client
def initialize config, id = nil
@config = config
@id = id || Digest::MD5.hexdigest(config['server'] + ":" + config['nick'])
end
def connected
@client && @client.connected
end
def connect
host = @config["server"].split(':')[0]
port = (@config['server'].split(':')[1]||6667).to_i
@client = IrcClient.new(host, port, {
:nick => @config['nick'],
:user => @config['user'],
:real => @config['name'],
:pass => @config['pass'],
:use_ssl => @config['use_ssl'],
})
@config["channels"].each{|ch|
@client.add_channel(ch)
}
@client
end
def disconnect
if @client && @client.connected
@client.finish
@client = nil
end
end
end
class IrcChannel < Channel
include Net::IRC::Constants
attr_reader :client
def initialize(name, client)
@type = 'IRC'
@name = name
@client = client
@connected = true
@members = Set.new
end
def send msg
@client.post(NOTICE, @name, msg) if @connected
end
def leave
@client.post(PART, @name)
@connected = false
end
def request_names
@client.post(NAMES, @name)
end
end
class IrcClient < Net::IRC::Client
attr :connected
attr_reader :channels
def initialize(*args)
super
@connected = false
@channels = {}
@auto_join = true
end
# BUG: only use last one.
def add_bot b
@bot = b
end
def add_channel name
@channels[name] = IrcChannel.new(name, self)
@channels[name].connected = false
end
def on_message(m)
@bot.on_irc_message(m) if @bot
#p m
if m.command == JOIN && m.prefix == @prefix
ch = channel(m[0])
ch.connected = true
@bot.on_join(ch) if @bot
end
if m.command == JOIN && m.prefix != @prefix
ch = channel(m[0])
ch.members.add(m.prefix.nick)
@bot.on_join_user(ch, m.prefix.nick) if @bot
end
if m.command == PART && m.prefix == @prefix
ch = channel(m[0])
ch.connected = false
@bot.on_leave(ch) if @bot
end
if m.command == PART && m.prefix != @prefix
ch = channel(m[0])
ch.members.delete(m.prefix.nick)
@bot.on_part_user(ch, m.prefix.nick) if @bot
end
if m.command == KICK
ch = channel(m[0])
ch.connected = false
@bot.on_leave(ch) if @bot
end
if m.command == INVITE
post JOIN, m[1] if @auto_join
end
if m.command == RPL_NAMREPLY
ch = channel(m[2])
m.params[3].split(/\s/).each{|n|
ch.members << n.gsub(/[+@:]/,"")
}
end
end
def channel name
ch = @channels[name] || IrcChannel.new(name,self)
@channels[name] = ch
ch
end
def on_rpl_welcome(m)
super
@channels.each_value {|ch|
post JOIN, ch.name
}
@bot.on_start unless @connected
@connected = true
end
def on_privmsg(m)
ch = @channels[m[0]] || IrcChannel.new(m[0],self)
# m = [channel, message]
@bot.on_message(ch, m[1].toutf8, m.prefix)
end
def send_notice(msg)
post(NOTICE, @channels[0], msg)
end
def on_connected
if @opts.use_ssl
puts "Using SSL"
require 'openssl'
ssl_context = OpenSSL::SSL::SSLContext.new
# ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
@socket = OpenSSL::SSL::SSLSocket.new(@socket, ssl_context)
@socket.sync = true
@socket.connect
end
super
end
def finish
begin
post(QUIT) if @connected
rescue Exception => e
warn e
warn e.backtrace.join("\r\t")
end
@connected = false
@channels.each_value {|ch|
@bot.on_leave(ch) if @bot
}
super
end
def post(command, *params)
super
end
end
| true |
d3f0b8cbe7cc1565bf51f6a51c644831ffffae9c | Ruby | jk1dd/homework | /pseudocode_extended.rb | UTF-8 | 1,947 | 3.8125 | 4 | [] | no_license | =begin
I have a text document and want to know
“What are the three most common words in the text?”
1. You know the problem is solved when you are able to inspect the list
of the 3 most frequent workds
2. To interface, you want to input the text document, and have those three
words (at least) spit out
3. The first trivial case is prompting for the text document
4.
Input text document
Split and sort words and make them uniform (all downcase)
If words are the same
put into collection
Count collection elements, sort by this
Output words with count
Extension: Let’s exclude the following:
I, you, he, she, it, we, they, they, a, an.
------
I have a file with 100 numbers. I want to create two new files:
one with all the odds and one with all the evens.
1. The problem is solved when I have two files, one with evens and one with
odds, and all numbers accounted for
2. I want to input the list of numbers, and have two files outputted
that I can inspect separately
3. The first trivial case is prompting for the file.
4.
Input the list of numbers
Iterate through the list to find if even
If even, put in new list
create file with this list, name it to show what is in it
Else if odd, put in new list
create file with this list, name it to show what is in it
Extension: Don’t allow duplicates in the output
I have a file with 100 latitude/longitude pairs.
Find the point that’s closest to the north pole.
1. I know the problem is solved if I can input a file with lat/long pairs
and display the one closest to the north pole.
2. I want a way to input the numbers and have it display back to me the
closest point
3. The first trivial case would be prompting for the file
4.
Input the list of latitude and longitudes
For each set of coordinates
subtract pair from north pole's coordinates
Display the coordinates showing the smallest difference
Extension: Find the one closest to the magnetic north pole.
=end
| true |
9e16ec24c65aaad9693d74600a4d502c5f8897c6 | Ruby | AlisonZXQ/leetcode | /Algorithms/001. Two Sum/Solution.rb | UTF-8 | 369 | 3.25 | 3 | [] | no_license | # @param {Integer[]} nums
# @param {Integer} target
# @return {Integer[]}
def two_sum(nums, target)
map={}
index=0
nums.each{|num| map[(target-num)]=index;index+=1}
puts map
for i in 0..nums.size
print i,nums[i],map[nums[i]]
if map[nums[i]] && i!=map[nums[i]]
return [i,map[nums[i]]]
end
end
return []
end | true |
d979d2bc6697887eff6562a5ae74328773877250 | Ruby | dmyers3/launch_school_101 | /lesson_3/easy1.rb | UTF-8 | 1,079 | 3.875 | 4 | [] | no_license | # Question 3
advice = "Few things in life are as important as house training your pet dinosaur"
advice.gsub!('important', 'urgent')
puts advice
# Question 5
puts (10..100).include?(42)
# Question 6
famous_words = "seven years ago..."
famous_words.insert(0, 'Four score and ')
puts famous_words
famous_words = "seven years ago..."
famous_words = "Four score and ".concat(famous_words)
puts famous_words
# Question 7
def add_eight(number)
number + 8
end
number = 2
how_deep = "number"
5.times { how_deep.gsub!("number", "add_eight(number)") }
p how_deep
p eval(how_deep)
# Question 8
flintstones = ["Fred", "Wilma", ["Barney", "Betty"], ["BamBam", "Pebbles"]]
flintstones.flatten!
p flintstones
# Question 9
flintstones = { "Fred" => 0, "Wilma" => 1, "Barney" => 2, "Betty" => 3, "BamBam" => 4, "Pebbles" => 5 }
barney = flintstones.to_a[2]
p barney
# Question 10
flintstones_hash = Hash.new
flintstones = ["Fred", "Barney", "Wilma", "Betty", "Pebbles", "BamBam"]
flintstones.each_with_index do | value, index |
flintstones_hash[value] = index
end
p flintstones_hash | true |
b30bf9727b2a56edb73bb37c0f97db9fdf48b45e | Ruby | mithunder916/hartl_sample_app | /ruby/string_shuffle.rb | UTF-8 | 203 | 3.21875 | 3 | [] | no_license | def string_shuffle(s)
s.split('').shuffle.join
end
p string_shuffle('foobar')
p string_shuffle('myxomatosis')
class String
def shuffle
self.split('').shuffle.join
end
end
p "goobar".shuffle
| true |
68a2fe9895ee02cd20dc2b3b88612a5c2a99b6c2 | Ruby | mxhold/vimperor | /spec/lib/type_coersion_spec.rb | UTF-8 | 3,813 | 2.9375 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
require_relative '../../lib/type_coersion'
describe ArrayExtensions::DeepToH do
describe '#deep_to_h' do
it 'converts deeply nested array into hash' do
module TestModule
using ArrayExtensions::DeepToH
def self.actual_hash
[[:a, [[:b, [[:c, :d]]]]]].deep_to_h
end
end
expected_hash = { a: { b: { c: :d } } }
expect(TestModule.actual_hash).to eql expected_hash
end
end
end
describe TypeCoersion do
describe '.coercer_for' do
it 'returns a coercer class for the given type' do
module TypeCoersion
class FooCoercer
end
end
expect(described_class.coercer_for(:foo)).to eql TypeCoersion::FooCoercer
end
end
end
describe TypeCoersion::HashCoercer do
describe '#coerce' do
it 'converts the values of a hash based on the provided config' do
config = {
bool: :boolean,
str: :string,
int: :integer,
deep: {
nested: {
hash: :boolean,
}
},
empty: :string,
}
hash = {
bool: 'true',
str: 123,
int: '123',
deep: {
nested: {
hash: 'false',
}
},
empty: '',
}
expected_hash = {
bool: true,
str: '123',
int: 123,
deep: {
nested: {
hash: false,
}
},
empty: nil,
}
coercer = described_class.new(config: config)
expect(coercer.coerce(hash)).to eql expected_hash
end
end
end
describe TypeCoersion::IntegerCoercer do
describe '.coerce' do
context 'non-nil value' do
it 'converts the value to an integer' do
expect(described_class.coerce('1')).to eql 1
end
end
context 'nil' do
it 'returns nil, not zero' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
describe TypeCoersion::StringCoercer do
describe '.coerce' do
context 'non-nil string' do
it 'returns the original string' do
expect(described_class.coerce('foo')).to eql 'foo'
end
end
context 'integer' do
it 'returns the integer converted to a string' do
expect(described_class.coerce(1)).to eql '1'
end
end
context 'empty string' do
it 'returns nil' do
expect(described_class.coerce('')).to eql nil
end
end
context 'nil' do
it 'returns nil' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
describe TypeCoersion::BooleanCoercer do
describe '.coerce' do
context 'true string' do
it 'returns true' do
expect(described_class.coerce('true')).to eql true
end
end
context '1 string' do
it 'returns true' do
expect(described_class.coerce('1')).to eql true
end
end
context '1 integer' do
it 'returns true' do
expect(described_class.coerce(1)).to eql true
end
end
context 'true' do
it 'returns true' do
expect(described_class.coerce(true)).to eql true
end
end
context 'false string' do
it 'returns false' do
expect(described_class.coerce('false')).to eql false
end
end
context '0 string' do
it 'returns false' do
expect(described_class.coerce('0')).to eql false
end
end
context '0 integer' do
it 'returns false' do
expect(described_class.coerce(0)).to eql false
end
end
context 'false' do
it 'returns false' do
expect(described_class.coerce(false)).to eql false
end
end
context 'nil' do
it 'returns nil' do
expect(described_class.coerce(nil)).to eql nil
end
end
end
end
| true |
f972f88dc2bf00080969135f1d2554f5f1efb1ae | Ruby | ChienliMa/schools | /lib/schools/schools.rb | UTF-8 | 2,442 | 2.921875 | 3 | [] | no_license | require "nokogiri"
require 'open-uri'
require "socket"
class Schools
attr_accessor :type
attr_accessor :max_page_num
Type = { elementary:"mainxx", middle:"maincz", high:"main" }
def initialize( school_type )
@type = school_type
# get max page num
url ="http://xuexiao.eol.cn/iframe/#{Type[school_type]}.php?page=1"
html = request( url )
html.force_encoding('utf-8')
page = Nokogiri::HTML( html )
@max_page_num = page.search("center").text[-8..-1].match('\d{2,}').to_s.to_i
end
def request( url )
"""
Sent HTTP request to baidu and grab the respond html.
"""
# force encoding
url = URI::encode(url)
uri = url.match(/cn.*?\z/).to_s[2..-1]
host = url.match(/.*?eol.cn/).to_s[7..-1]
http_request = "GET #{uri} HTTP/1.1\r\n"+
"Content-Type: text/html; charset=utf-8\r\n"+
"Host:#{host}\r\n"+
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"+
"Connection:keep-alive\r\n"+
"User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:33.0) Gecko/20100101 Firefox/33.0\r\n\r\n"
socket = TCPSocket.open( host, 80)
socket.puts( http_request)
html = ""
while line = socket.gets
html += line
# automatically end
break if html.include?('</HTML>') || html.include?('</html>')
end
socket.close
return html
end
def urls_in_page( page_i )
url ="http://xuexiao.eol.cn/iframe/#{Type[@type]}.php?page=#{page_i}"
html = request( url )
page = Nokogiri::HTML( html )
urls = []
( page.search('h1') + page.search('h5') ).each do |heading|
# why nokogiti will erase ''index.shtml here
urls << heading.search('a').attribute('href').value + 'index.shtml'
end
return urls
end
def get_info( url )
html = request( url )
page = Nokogiri::HTML( html )
school = {}
school[:name] = page.search('title').text.split('-')[0]
table = page.search("table[@class='line_22']")
table.search('td').each do |line0|
line = line0.text
if line[0,2] == "校址"
school[:address] = line[3..-1]
elsif line[0,2] == "地区"
school[:region] = line[3..-1]
elsif line[0,2] == "网址"
school[:website] = line0.search('a').first.attribute('href').value
elsif line[0,2] == "电话"
school[:phone] = line[3..-1]
end
end
school[:type] = @type
return school
end
end | true |
a8684f7219199b4618e40625436fb140ee8344e4 | Ruby | HyeokJungKim/OO-mini-project-nyc-web-031218 | /app/models/Recipe.rb | UTF-8 | 752 | 3.171875 | 3 | [] | no_license | class Recipe
@@all = []
attr_accessor :users, :ingredients, :name
def initialize(name)
@name = name
@@all << self
@ingredients = []
end
def self.most_popular
arr = RecipeCard.all.map do |rc|
rc.recipe
end
hash = Hash.new(0)
arr.each do |recipe|
hash[recipe] +=1
end
arr.max_by do |recipe|
hash[recipe]
end
end
def add_ingredients(arr)
arr.each do |ingredient|
self.ingredients << ingredient
RecipeIngredient.new(ingredient, self)
end
end
def allergens
ing = Allergen.all.map do |allergen|
allergen.ingredient
end
self.ingredients.select do |ingredient|
ing.include?(ingredient)
end
end
def self.all
@@all
end
end
| true |
5018cfd890d3b484de9032b3f7744a7449fcd9a0 | Ruby | danjglick/launch-academy-challenges | /perimeter-method/code.rb | UTF-8 | 70 | 2.59375 | 3 | [] | no_license | def perimeter(width, height = width)
(width * 2) + (height * 2)
end
| true |
e5a608d039fcbd1f905d845995299cd7b30caf34 | Ruby | bbchui/practice_problems | /ruby_problems/tech_coding2.rb | UTF-8 | 1,155 | 4.28125 | 4 | [] | no_license | # We also want to allow parentheses in our input. Given an expression string using the "+", "-", "(", and ")" operators like "5+(16-2)", write a function to parse the string and evaluate the result.
# Sample input:
# expression1 = "5+16-((9-6)-(4-2))"
# expression2 = "22+(2-4)"
# Sample output:
# evaluate(expression1) => 20
# evaluate(expression2) => 20
expression1 = "5+16-((9-6)-(4-2))"
# [5, 16-((9-6)-(4-2))]
# [5, 16, ((9-6), (4-2))]
expression2 = "22+(2-4) + (3 - 1 + (2+3))"
def calculator(str)
str = str.split('+')
str = str.map do |el, i| # n
el.split('-').map {|num| num.to_i}.reduce(:-) # m * m
# str[i] = el.split('-')
end
str.reduce(:+)
end
def calc(str)
count = 0
paren = []
i = 0
while i < str.length
if str[i] == "("
count += 1
paren.push(i)
i += 1
elsif str[i] == ")"
count -= 1
sum = calculator(str[paren.last + 1...i])
str = str[0...paren.last] + sum.to_s + str[i + 1..-1]
i = paren.last + 1
paren.pop
else
i += 1
end
end
calculator(str)
end
p calc(expression1)
p calc(expression2)
# p calculator(expression)
| true |
bf78f7870007494f5d9bae1f6079ee32ffc2e365 | Ruby | sirscriptalot/mugatu | /lib/mugatu/attribute_type.rb | UTF-8 | 499 | 2.609375 | 3 | [
"MIT"
] | permissive | module Mugatu
module AttributeType
def set_cast_with(sym)
@cast_with = sym
end
def get_cast_with
@cast_with
end
def cast(value)
if value.respond_to?(get_cast_with)
value.send(get_cast_with)
else
raise_cast_error(value)
end
end
def raise_cast_error(value)
raise TypeError, "cannot cast #{value} into #{name} (TypeError)"
end
end
end
Dir[File.dirname(__FILE__) + '/types/**/*.rb'].each {|file| require file }
| true |
45a3e18d9a911fafc412a533a5a5c731a22cc381 | Ruby | Karis-T/RB139 | /exercises_more_topics/medium_1.rb | UTF-8 | 2,579 | 3.90625 | 4 | [] | no_license | #1
class Device
def initialize
@recordings = []
end
def listen
record(yield) if block_given?
end
def record(recording)
@recordings << recording
end
def play
puts @recordings.last
end
end
listener = Device.new
listener.listen { "Hello World!" }
listener.listen
listener.play # Outputs "Hello World!"
#3
def gather(items)
puts "Let's start gathering food."
yield(items) if block_given?
puts "Nice selection of food we have gathered!"
end
items = ['apples', 'corn', 'cabbage', 'wheat']
gather(items) {|items| puts "#{items.join(', ')}"}
#4
def solve(array)
yield(array)
end
array = %w(raven finch hawk eagle)
p solve(array) {|_, _, *raptors| raptors}
#5
items = ['apples', 'corn', 'cabbage', 'wheat']
def gather(items)
puts "Let's start gathering food."
yield(items)
puts "We've finished gathering!"
end
gather(items) do |*args , wheat|
puts *args.join(", ")
puts wheat
end
gather(items) do | apples, *args , wheat |
puts apples
puts args.join(", ")
puts wheat
end
gather(items) do |apples , *args |
puts apples
puts args.join(", ")
end
gather(items) do |apples, corn, cabbage, wheat|
puts "#{apples}, #{corn}, #{cabbage}, and #{wheat}"
end
#6
def convert_to_base_8(n)
n.to_s(8).to_i
end
base8_proc = method(:convert_to_base_8).to_proc
p [8, 10, 12, 14, 16, 33].map(&base8_proc) # => [10, 12, 14, 16, 20, 41]
# def convert_to_base_8(n)
# n.to_s(8).to_i
# end
# # ->
# Proc.new { |n| n.to_s(8).to_i }
# #when we use & to convert our Proc to a block, it expands out to...
# # ->
# [8, 10, 12, 14, 16, 33].map { |n| n.to_s(8).to_i }
#7
def bubble_sort!(arr)
loop do
sorted = 0
(arr.length-1).times do |i|
if block_given?
next sorted += 1 if yield(arr[i], arr[i+1])
else
next sorted += 1 if arr[i] < arr[i+1]
end
arr[i], arr[i+1] = arr[i+1], arr[i]
end
break if sorted == arr.length-1
end
arr
end
array = [5, 3]
bubble_sort!(array)
p array == [3, 5]
array = [5, 3, 7]
bubble_sort!(array) { |first, second| first >= second }
p array == [7, 5, 3]
array = [6, 2, 7, 1, 4]
bubble_sort!(array)
p array == [1, 2, 4, 6, 7]
array = [6, 12, 27, 22, 14]
bubble_sort!(array) { |first, second| (first % 7) <= (second % 7) }
p array == [14, 22, 12, 6, 27]
array = %w(sue Pete alice Tyler rachel Kim bonnie)
bubble_sort!(array)
p array == %w(Kim Pete Tyler alice bonnie rachel sue)
array = %w(sue Pete alice Tyler rachel Kim bonnie)
bubble_sort!(array) { |first, second| first.downcase <= second.downcase }
p array == %w(alice bonnie Kim Pete rachel sue Tyler)
| true |
2496aebf1f016cd7426e2ef5174173d2482da88b | Ruby | rien/minitest-utils | /test/minitest/utils/let_test.rb | UTF-8 | 883 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
class LetTest < Minitest::Test
i_suck_and_my_tests_are_order_dependent!
$count = 0
let(:count) { $count += 1 }
test 'defines memoized reader (first test)' do
assert_equal 0, $count
5.times { assert_equal 1, count }
end
test 'defines memoized reader (second test)' do
assert_equal 1, $count
5.times { assert_equal 2, count }
end
test 'cannot override existing method' do
exception, * = assert_raises {
self.class.let(:count) { true }
}, ArgumentError
assert_equal 'Cannot define let(:count); method already defined by LetTest.', exception.message
end
test 'cannot start with test' do
exception, * = assert_raises {
self.class.let(:test_number) { true }
}, ArgumentError
assert_equal 'Cannot define let(:test_number); method cannot begin with \'test\'.', exception.message
end
end
| true |
00c80251bad6aaa72cd1cd903435eb121d173e0b | Ruby | hnmn/termux-rootfs | /termux-rootfs/data/data/com.termux/files/usr/lib/ruby/gems/2.4.0/gems/celluloid-io-0.16.2/lib/celluloid/io/stream.rb | UTF-8 | 9,715 | 2.953125 | 3 | [
"MIT",
"Ruby"
] | permissive | # Partially adapted from Ruby's OpenSSL::Buffering
# Originally from the 'OpenSSL for Ruby 2' project
# Copyright (C) 2001 GOTOU YUUZOU <gotoyuzo@notwork.org>
# All rights reserved.
#
# This program is licenced under the same licence as Ruby.
module Celluloid
module IO
# Base class of all streams in Celluloid::IO
class Stream
include Enumerable
# The "sync mode" of the stream
#
# See IO#sync for full details.
attr_accessor :sync
def initialize
@eof = false
@sync = true
@read_buffer = ''.force_encoding(Encoding::ASCII_8BIT)
@write_buffer = ''.force_encoding(Encoding::ASCII_8BIT)
@read_latch = Latch.new
@write_latch = Latch.new
end
# Wait until the current object is readable
def wait_readable; Celluloid::IO.wait_readable(self); end
# Wait until the current object is writable
def wait_writable; Celluloid::IO.wait_writable(self); end
# System read via the nonblocking subsystem
def sysread(length = nil, buffer = nil)
buffer ||= ''.force_encoding(Encoding::ASCII_8BIT)
@read_latch.synchronize do
begin
read_nonblock(length, buffer)
rescue ::IO::WaitReadable
wait_readable
retry
end
end
buffer
end
# System write via the nonblocking subsystem
def syswrite(string)
length = string.length
total_written = 0
remaining = string
@write_latch.synchronize do
while total_written < length
begin
written = write_nonblock(remaining)
rescue ::IO::WaitWritable
wait_writable
retry
rescue EOFError
return total_written
rescue Errno::EAGAIN
wait_writable
retry
end
total_written += written
# FIXME: mutating the original buffer here. Seems bad.
remaining.slice!(0, written) if written < remaining.length
end
end
total_written
end
# Reads +size+ bytes from the stream. If +buf+ is provided it must
# reference a string which will receive the data.
#
# See IO#read for full details.
def read(size=nil, buf=nil)
if size == 0
if buf
buf.clear
return buf
else
return ""
end
end
until @eof
break if size && size <= @read_buffer.size
fill_rbuff
break unless size
end
ret = consume_rbuff(size) || ""
if buf
buf.replace(ret)
ret = buf
end
(size && ret.empty?) ? nil : ret
end
# Reads at most +maxlen+ bytes from the stream. If +buf+ is provided it
# must reference a string which will receive the data.
#
# See IO#readpartial for full details.
def readpartial(maxlen, buf=nil)
if maxlen == 0
if buf
buf.clear
return buf
else
return ""
end
end
if @read_buffer.empty?
begin
return sysread(maxlen, buf)
rescue Errno::EAGAIN
retry
end
end
ret = consume_rbuff(maxlen)
if buf
buf.replace(ret)
ret = buf
end
raise EOFError if ret.empty?
ret
end
# Reads the next "line+ from the stream. Lines are separated by +eol+. If
# +limit+ is provided the result will not be longer than the given number of
# bytes.
#
# +eol+ may be a String or Regexp.
#
# Unlike IO#gets the line read will not be assigned to +$_+.
#
# Unlike IO#gets the separator must be provided if a limit is provided.
def gets(eol=$/, limit=nil)
idx = @read_buffer.index(eol)
until @eof
break if idx
fill_rbuff
idx = @read_buffer.index(eol)
end
if eol.is_a?(Regexp)
size = idx ? idx+$&.size : nil
else
size = idx ? idx+eol.size : nil
end
if limit and limit >= 0
size = [size, limit].min
end
consume_rbuff(size)
end
# Executes the block for every line in the stream where lines are separated
# by +eol+.
#
# See also #gets
def each(eol=$/)
while line = self.gets(eol)
yield line
end
end
alias each_line each
# Reads lines from the stream which are separated by +eol+.
#
# See also #gets
def readlines(eol=$/)
ary = []
while line = self.gets(eol)
ary << line
end
ary
end
# Reads a line from the stream which is separated by +eol+.
#
# Raises EOFError if at end of file.
def readline(eol=$/)
raise EOFError if eof?
gets(eol)
end
# Reads one character from the stream. Returns nil if called at end of
# file.
def getc
read(1)
end
# Calls the given block once for each byte in the stream.
def each_byte # :yields: byte
while c = getc
yield(c.ord)
end
end
# Reads a one-character string from the stream. Raises an EOFError at end
# of file.
def readchar
raise EOFError if eof?
getc
end
# Pushes character +c+ back onto the stream such that a subsequent buffered
# character read will return it.
#
# Unlike IO#getc multiple bytes may be pushed back onto the stream.
#
# Has no effect on unbuffered reads (such as #sysread).
def ungetc(c)
@read_buffer[0,0] = c.chr
end
# Returns true if the stream is at file which means there is no more data to
# be read.
def eof?
fill_rbuff if !@eof && @read_buffer.empty?
@eof && @read_buffer.empty?
end
alias eof eof?
# Writes +s+ to the stream. If the argument is not a string it will be
# converted using String#to_s. Returns the number of bytes written.
def write(s)
do_write(s)
s.bytesize
end
# Writes +s+ to the stream. +s+ will be converted to a String using
# String#to_s.
def << (s)
do_write(s)
self
end
# Writes +args+ to the stream along with a record separator.
#
# See IO#puts for full details.
def puts(*args)
s = ""
if args.empty?
s << "\n"
end
args.each do |arg|
s << arg.to_s
if $/ && /\n\z/ !~ s
s << "\n"
end
end
do_write(s)
nil
end
# Writes +args+ to the stream.
#
# See IO#print for full details.
def print(*args)
s = ""
args.each { |arg| s << arg.to_s }
do_write(s)
nil
end
# Formats and writes to the stream converting parameters under control of
# the format string.
#
# See Kernel#sprintf for format string details.
def printf(s, *args)
do_write(s % args)
nil
end
# Flushes buffered data to the stream.
def flush
osync = @sync
@sync = true
do_write ""
return self
ensure
@sync = osync
end
# Closes the stream and flushes any unwritten data.
def close
flush rescue nil
sysclose
end
#######
private
#######
# Fills the buffer from the underlying stream
def fill_rbuff
begin
@read_buffer << sysread(BLOCK_SIZE)
rescue Errno::EAGAIN
retry
rescue EOFError
@eof = true
end
end
# Consumes +size+ bytes from the buffer
def consume_rbuff(size=nil)
if @read_buffer.empty?
nil
else
size = @read_buffer.size unless size
ret = @read_buffer[0, size]
@read_buffer[0, size] = ""
ret
end
end
# Writes +s+ to the buffer. When the buffer is full or #sync is true the
# buffer is flushed to the underlying stream.
def do_write(s)
@write_buffer << s
@write_buffer.force_encoding(Encoding::BINARY)
if @sync or @write_buffer.size > BLOCK_SIZE or idx = @write_buffer.rindex($/)
remain = idx ? idx + $/.size : @write_buffer.length
nwritten = 0
while remain > 0
str = @write_buffer[nwritten,remain]
begin
nwrote = syswrite(str)
rescue Errno::EAGAIN
retry
end
remain -= nwrote
nwritten += nwrote
end
@write_buffer[0,nwritten] = ""
end
end
# Perform an operation exclusively, uncontested by other tasks
class Latch
def initialize
@owner = nil
@waiters = 0
@condition = Celluloid::Condition.new
end
# Synchronize an operation across all tasks in the current actor
def synchronize
actor = Thread.current[:celluloid_actor]
return yield unless actor
if @owner || @waiters > 0
@waiters += 1
@condition.wait
@waiters -= 1
end
@owner = Task.current
begin
ret = yield
ensure
@owner = nil
@condition.signal if @waiters > 0
end
ret
end
end
end
end
end
| true |
d58313d185774aebaf27d386460523f87f0a6b41 | Ruby | e-barr/notBuggySkipe_back-end | /app/models/contact.rb | UTF-8 | 929 | 2.578125 | 3 | [] | no_license | class Contact < ApplicationRecord
belongs_to :user_1, class_name: :User, foreign_key: :user_1_id
belongs_to :user_2, class_name: :User, foreign_key: :user_2_id
validates :user_1_id, presence: true
validates :user_2_id, presence: true
def self.make_new_contact(user_1_id, user_2_id)
if user_1_id == user_2_id
return
else
found_contact = User.find(user_1_id)
found_contact2 = User.find(user_2_id)
if found_contact && found_contact2
Contact.create(user_1_id: user_1_id, user_2_id: user_2_id)
Contact.create(user_1_id: user_2_id, user_2_id: user_1_id)
end
end
end
def self.delete_contact(id)
found_contact = Contact.all.find { |contact| contact.id == id }
second_contact = Contact.all.find { |contact| contact.user_1 == found_contact.user_2 && contact.user_2 == found_contact.user_1 }
found_contact.destroy
second_contact.destroy
end
end
| true |
4ad21d016aea18e0f722c9c7f33f06f2dab7220a | Ruby | travis4all/node-backplane | /features/support/defaults.rb | UTF-8 | 702 | 2.65625 | 3 | [
"MIT"
] | permissive | class Defaults
def initialize(config)
@config = config
@valid_info = @config['valid_info']
@count = 1
end
def get_count()
return @count
end
def inc_count()
@count += 1
end
def get_valid_bus()
@config['base_url'] + '/' + @config['backplane']['version'] + '/bus/' + @valid_info['bus']
end
def get_invalid_bus()
@config['base_url'] + '/' + @config['backplane']['version'] + '/bus/' + 'invalid_bus'
end
def get_valid_channel(channel)
get_valid_bus + '/channel/' + channel
end
def get_valid_token()
@config['valid_info']['key']
end
def get_auth_header(key)
'Basic ' + Base64.encode64(@valid_info['bus'] + ':' + key)
end
end | true |
6695ae8e208b278f99dcde8c886c0a4fd9bb4a26 | Ruby | ClearFit/marketo-api-ruby | /lib/marketo_api/lead.rb | UTF-8 | 6,691 | 2.75 | 3 | [
"MIT"
] | permissive | require 'forwardable'
# An object representing a Marketo Lead record.
class MarketoAPI::Lead
extend Forwardable
include Enumerable
NAMED_KEYS = { #:nodoc:
id: :IDNUM,
cookie: :COOKIE,
email: :EMAIL,
lead_owner_email: :LEADOWNEREMAIL,
salesforce_account_id: :SFDCACCOUNTID,
salesforce_contact_id: :SFDCCONTACTID,
salesforce_lead_id: :SFDCLEADID,
salesforce_lead_owner_id: :SFDCLEADOWNERID,
salesforce_opportunity_id: :SFDCOPPTYID
}.freeze
KEY_TYPES = MarketoAPI.freeze(*NAMED_KEYS.values) #:nodoc:
private_constant :KEY_TYPES
# The Marketo ID. This value cannot be set by consumers.
attr_reader :id
# The Marketo tracking cookie. Optional.
attr_accessor :cookie
# The attributes for the Lead.
attr_reader :attributes
# The types for the Lead attributes.
attr_reader :types
# The proxy object for this class.
attr_reader :proxy
def_delegators :@attributes, :[], :each, :each_pair, :each_key,
:each_value, :keys, :values
##
# :method: [](hash)
# :call-seq:
# lead[attribute_key]
#
# Looks up the provided attribute.
##
# :method: each
# :call-seq:
# each { |key, value| block }
#
# Iterates over the attributes.
##
# :method: each_pair
# :call-seq:
# each_pair { |key, value| block }
#
# Iterates over the attributes.
##
# :method: each_key
# :call-seq:
# each_key { |key| block }
#
# Iterates over the attribute keys.
##
# :method: each_value
# :call-seq:
# each_value { |value| block }
#
# Iterates over the attribute values.
##
# :method: keys
# :call-seq:
# keys() -> array
#
# Returns the attribute keys.
##
# :method: values
# :call-seq:
# values() -> array
#
# Returns the attribute values.
def initialize(options = {})
@id = options[:id]
@attributes = {}
@types = {}
@foreign = {}
self[:Email] = options[:email]
self.proxy = options[:proxy]
yield self if block_given?
end
##
# :method: []=(hash, value)
# :call-seq:
# lead[key] = value -> value
#
# Looks up the provided attribute.
def []=(key, value)
@attributes[key] = value
@types[key] ||= infer_value_type(value)
end
# :attr_writer:
# :call-seq:
# lead.proxy = proxy -> proxy
#
# Assign a proxy object. Once set, the proxy cannot be unset, but it can be
# changed.
def proxy=(value)
@proxy = case value
when nil
defined?(@proxy) && @proxy
when MarketoAPI::Leads
value
when MarketoAPI::ClientProxy
value.instance_variable_get(:@client).leads
when MarketoAPI::Client
value.leads
else
raise ArgumentError, "Invalid proxy type"
end
end
# :call-seq:
# lead.foreign -> nil
# lead.foreign(type, id) -> { type: type, id: id }
# lead.foreign -> { type: type, id: id }
#
# Sets or returns the foreign system type and person ID.
def foreign(type = nil, id = nil)
@foreign = { type: type.to_sym, id: id } if type and id
@foreign
end
# :attr_reader: email
def email
self[:Email]
end
# :attr_writer: email
def email=(value)
self[:Email] = value
end
# Performs a Lead sync and returns the new Lead object, or +nil+ if the
# sync failed.
#
# Raises an ArgumentError if a proxy has not been configured with
# Lead#proxy=.
def sync
raise ArgumentError, "No proxy configured" unless proxy
proxy.sync(self)
end
# Performs a Lead sync and updates this Lead object in-place, or +nil+ if
# the sync failed.
#
# Raises an ArgumentError if a proxy has not been configured with
# Lead#proxy=.
def sync!
if lead = sync
@id = lead.id
@cookie = lead.cookie
@foreign = lead.foreign
@proxy = lead.proxy
removed = self.keys - lead.keys
lead.each_pair { |k, v|
@attributes[k] = v
@types[k] = lead.types[k]
}
removed.each { |k|
@attributes.delete(k)
@types.delete(k)
}
self
end
end
# Returns a lead key structure suitable for use with
# MarketoAPI::Leads#get.
def params_for_get
self.class.key(:IDNUM, id)
end
# Returns the parameters required for use with MarketoAPI::Leads#sync.
def params_for_sync
{
returnLead: true,
marketoCookie: cookie,
leadRecord: {
Email: email,
Id: id,
ForeignSysPersonId: foreign[:id],
ForeignSysType: foreign[:type],
leadAttributeList: {
attribute: attributes.map { |key, value|
{
attrName: key.to_s,
attrType: types[key],
attrValue: value
}
}
}
}.delete_if(&MarketoAPI::MINIMIZE_HASH)
}.delete_if(&MarketoAPI::MINIMIZE_HASH)
end
class << self
# Creates a new Lead from a SOAP response hash (from Leads#get,
# Leads#get_multiple, Leads#sync, or Leads#sync_multiple).
def from_soap_hash(hash) #:nodoc:
lead = new(id: hash[:id].to_i, email: hash[:email]) do |lr|
if type = hash[:foreign_sys_type]
lr.foreign(type, hash[:foreign_sys_person_id])
end
hash[:lead_attribute_list][:attribute].each do |attribute|
name = attribute[:attr_name].to_sym
lr.attributes[name] = attribute[:attr_value]
lr.types[name] = attribute[:attr_type]
end
end
yield lead if block_given?
lead
end
# Creates a new Lead key hash suitable for use in a number of Marketo
# API calls.
def key(key, value)
{
leadKey: {
keyType: key_type(key),
keyValue: value
}
}
end
private
def key_type(key)
key = key.to_sym
res = if KEY_TYPES.include? key
key
else
NAMED_KEYS[key]
end
raise ArgumentError, "Invalid key #{key}" unless res
res
end
end
def ==(other)
id == other.id && cookie == other.cookie && foreign == other.foreign &&
attributes == other.attributes && types == other.types
end
def inspect
"#<#{self.class} id=#{id} cookie=#{cookie} foreign=#{foreign.inspect} attributes=#{attributes.inspect} types=#{types.inspect}>"
end
private
def infer_value_type(value)
case value
when Integer
'integer'
when Time, DateTime
'datetime'
else
'string'
end
end
end
| true |
508921af042a0222319fa2a86295881f2ff46146 | Ruby | wgltony/ReactRealTimeNewsScrapingandRecommendationSystem-GraphiteSystemMonitor | /tap-news/elasticsearch_server/logstash-5.4.0/logstash-core/lib/logstash/timestamp.rb | UTF-8 | 478 | 2.546875 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | # encoding: utf-8
require "logstash/namespace"
module LogStash
class TimestampParserError < StandardError; end
class Timestamp
include Comparable
# TODO (colin) implement in Java
def <=>(other)
self.time <=> other.time
end
# TODO (colin) implement in Java
def +(other)
self.time + other
end
# TODO (colin) implement in Java
def -(value)
self.time - (value.is_a?(Timestamp) ? value.time : value)
end
end
end
| true |
ddfc91760bdb022e2bdcf3bd20561863e20137ea | Ruby | marcelgalang/my-select-001-prework-web | /lib/my_select.rb | UTF-8 | 174 | 3.203125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def my_select(collection)
i = 0
result = []
while i < collection.length
if (yield(collection[i]))
result << collection[i]
end
i+=1
end
result
end | true |
c15fc898db44fef608c6a9ad9dc4bdfe076d8981 | Ruby | arnewauters/RubyRabbits | /rabbit.rb | UTF-8 | 682 | 3.4375 | 3 | [] | no_license | require_relative 'animal'
require 'win32console'
require 'colored'
class Rabbit < Animal
def initialize()
@breedingAge = 1 + rand(1)
@maximumAge = 8 + rand(4)
@breedingProbability = 0.7
@maxLitterSize = 6
super
end
def checkFood
end
def breed(maximum)
if (maximum == 0 || @age < @breedingAge)
return nil
end
breedingFactor = rand(100)
if(breedingFactor <= (@breedingProbability * 100))
litter = 2 + rand(@maxLitterSize)
litter = maximum if (litter > maximum)
return Array.new(litter, Rabbit.new());
else
return nil
end
end
def to_s
return "R"
# if (age < 1)
# x.yellow
# else
# x.green
# end
end
end | true |
0d3f188b76eee88d0c1892bcce0d51127d4fba7b | Ruby | cgservices/officer | /lib/officer/lock_store.rb | UTF-8 | 5,674 | 2.6875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module Officer
class LockQueue < Array
def to_host_a
map {|conn| conn.to_host_s}
end
end
class Lock
attr_reader :name
attr_reader :size
attr_reader :queue
attr_reader :lock_ids
def initialize name, size = 1
@name = name
@size = size.to_i
@lock_ids = (0..@size-1).to_a
@queue = LockQueue.new
end
end
class LockStore
include Singleton
def initialize
@locks = {} # name => Lock
@connections = {} # Connection => Set(name, ...)
@locked_connections = {} # {lock_id => Connection}
@acquire_counter = 0
@mutex = Mutex.new
end
def log_state
l = Officer::Log
l.info '-----'
l.info 'LOCK STORE:'
l.info ''
l.info "locks:"
@locks.each do |name, lock|
l.info "#{name}: connections=[#{lock.queue.to_host_a.join(', ')}]"
end
l.info ''
l.info "Connections:"
@connections.each do |connection, names|
l.info "#{connection.to_host_s}: names=[#{names.to_a.join(', ')}]"
end
l.info ''
l.info "Acquire Rate: #{@acquire_counter.to_f / 5}/s"
@acquire_counter = 0
l.info '-----'
end
def acquire name, connection, options={}
name, size = split_name(name)
if options[:queue_max]
lock = @locks[name]
if lock && !lock.queue.include?(connection) && lock.queue.length >= options[:queue_max]
connection.queue_maxed name, :queue => lock.queue.to_host_a
return
end
end
@acquire_counter += 1
lock = @locks[name] ||= Lock.new(name, size)
if lock.queue[0..lock.size-1].include?(connection)
return connection.already_acquired(name)
end
if lock.queue.count < lock.size
lock.queue << connection
lock_id = lock_connection(connection, lock)
(@connections[connection] ||= Set.new) << name
connection.acquired name, lock_id
else
lock.queue << connection
(@connections[connection] ||= Set.new) << name
connection.queued(name, options)
end
end
def release name, connection, options={}
name, size = split_name(name)
if options[:callback].nil?
options[:callback] = true
end
lock = @locks[name]
names = @connections[connection]
# Client should only be able to release a lock that
# exists and that it has previously queued.
if lock.nil? || names.nil? || !names.include?(name)
connection.release_failed(name) if options[:callback]
return
end
# If connecton has the lock, release it and let the next
# connection know that it has acquired the lock.
if index = lock.queue.index(connection)
if index < lock.size
lock.queue.delete_at(index)
release_connection(connection, lock)
connection.released name if options[:callback]
if next_connection = lock.queue[lock.size-1]
lock_id = lock_connection(next_connection, lock)
next_connection.acquired name, lock_id
end
@locks.delete name if lock.queue.count == 0
# If the connection is queued and doesn't have the lock,
# dequeue it and leave the other connections alone.
else
lock.queue.delete connection
connection.released name
end
names.delete name
end
end
def reset connection
# names = @connections[connection] || []
names = @connections[connection] || Set.new
names.each do |name|
release name, connection, :callback => false
end
@connections.delete connection
connection.reset_succeeded
end
def timeout name, connection
name, size = split_name(name)
lock = @locks[name]
names = @connections[connection]
return if lock.queue.first == connection # Don't timeout- already have the lock.
lock.queue.delete connection
names.delete name
connection.timed_out name, :queue => lock.queue.to_host_a
end
def locks connection
locks = {}
@locks.each do |name, lock|
locks[name] = lock.queue.to_host_a
end
connection.locks locks
end
def connections connection
connections = {}
@connections.each do |conn, names|
connections[conn.to_host_s] = names.to_a
end
connection.connections connections
end
def my_locks connection
my_locks = @connections[connection] ? @connections[connection].to_a : []
connection.my_locks my_locks
end
def close_idle_connections(max_idle)
@connections.each do |conn, names|
if conn.last_cmd_at < Time.now.utc - max_idle
Officer::Log.error "Closing due to max idle time: #{conn.to_host_s}"
conn.close_connection
end
end
end
protected
def split_name(name)
if name.include?("|")
name_array = name.split("|")
size = (name_array.last.to_i > 0 && name_array.size > 1) ? name_array.last.to_i : 1
else
size = 1
end
[name, size]
end
def lock_connection(connection, lock)
@mutex.synchronize do
@locked_connections[lock.lock_ids.first] = connection
lock_id = lock.lock_ids.shift
lock.lock_ids.push(lock_id)
lock_id
end
end
def release_connection(connection, lock)
@mutex.synchronize do
if lock_id = @locked_connections.key(connection)
lock.lock_ids.delete(lock_id)
lock.lock_ids.insert(0, lock_id)
lock_id
end
end
end
end
end
| true |
d7636f51dcdbf83014d8ab016b8a59f6c61230a4 | Ruby | Hiten-waroo/LS_CORE | /R101_lesson_3/practice_problems_medium_2_q3.rb | UTF-8 | 1,626 | 4.09375 | 4 | [] | no_license | def tricky_method(a_string_param, an_array_param)
a_string_param += "rutabaga" #this is not mutable
an_array_param << "rutabaga" #this is mutable
end
my_string = "pumpkins"
my_array = ["pumpkins"]
tricky_method(my_string, my_array)
puts "My string looks like this now: #{my_string}" #this remains "pumpkins" as method += is not mutable
puts "My array looks like this now: #{my_array}" #rutabaga is added to the array as << is mutable
def tricky_method_two(a_string_param, an_array_param)
a_string_param << 'rutabaga' # this is mutable method so will update the string varible
an_array_param = ['pumpkins', 'rutabaga'] # this sets parameter array
end
my_string = "pumpkins"
my_array = ["pumpkins"]
tricky_method_two(my_string, my_array)
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
#Questiion 5 LS solution
def not_so_tricky_method(a_string_param, an_array_param)
a_string_param += "rutabaga"
an_array_param += ["rutabaga"]
return a_string_param, an_array_param # return the two parameter varibles
end
my_string = "pumpkins"
my_array = ["pumpkins"]
my_string, my_array = not_so_tricky_method(my_string, my_array) # set the varibles to the methods parameter varible return
puts "My string looks like this now: #{my_string}"
puts "My array looks like this now: #{my_array}"
# Question 6 How could the following method be simplified without changing its return value?
def color_valid(color)
if color == "blue" || color == "green"
true
else
false
end
end
# my solution
def color_valid(color)
color == "blue" || color == "green"
end
| true |
1f15e6375d351e09f8c2d44998a5fdf9b166effa | Ruby | axiomiety/exercism-io | /ruby/robot_name.rb | UTF-8 | 540 | 3.3125 | 3 | [] | no_license | require 'set'
class Robot
attr_reader :name
@@names = Set.new
@@alpha_uppercase = ('A'..'Z').to_a
@@digits = (0..9).map{|i| i.to_s}
def self.generate_unique_name
# [A-Z]*2 + [0-9]*3
uid = ''
loop do
2.times { uid << @@alpha_uppercase.sample }
3.times { uid << @@digits.sample }
break unless @@names.member? uid
uid = ''
end
@@names.add uid
uid
end
def initialize
@name = Robot.generate_unique_name
end
def reset
@name = Robot.generate_unique_name
end
end
| true |
4f4e90a4ea336aca7a1a38477db8a34d40218535 | Ruby | lhoff0/public_library | /pblibrary.rb | UTF-8 | 1,962 | 4.15625 | 4 | [] | no_license | # pblibrary.rb
# define class Library
# Report all books it contains
class Library
def initialize (library_title)
@library_title = library_title
@shelves=[]
end
def add_shelf(shelf)
@shelves << shelf
end
def delete_shelf(shelf)
@shelves.delete(shelf)
end
def books
puts @library_title + ' library'
puts '----------------'
@shelves.each do |shelf|
shelf.books_on_shelf.each do |book|
puts book.title
end
end
end
end
# define class Shelf
# Report total number of shelves and books
# Each shelf should know the book it contains
class Shelf
attr_accessor :shelf_label, :books_on_shelf
def initialize (shelf_label,library)
@shelf_label = shelf_label
puts @shelf_label + ' shelf'
@books_on_shelf=[]
library.add_shelf(self)
end
def enshelf(book) #book object added to array
@books_on_shelf << book
puts book.title + ' has been added to the ' + @shelf_label + ' shelf'
end
def unshelf(book) #book object deleted from array
@books_on_shelf.delete(book)
puts book.title + ' has been removed from the ' + @shelf_label + ' shelf'
end
end
# define class Book
# use "enshelf" and "unshelf" methods
class Book
attr_accessor :title
def initialize(title)
@title = title
puts @title + ' is your book'
end
def enshelf(shelf) #put on shelf
shelf.enshelf(self)
end
def unshelf(shelf) #take off shelf
shelf.unshelf(self)
end
end
hudson = Library.new("Hudson")
fiction = Shelf.new("fiction", hudson) #initialize
nonfiction = Shelf.new("nonfiction", hudson)
red_wall = Book.new("Red Wall")
oz = Book.new("OZ")
puts red_wall.title
puts fiction.shelf_label
puts fiction.books_on_shelf
red_wall.enshelf(fiction)
oz.enshelf(fiction)
hudson.books
puts '----------------'
#fiction.books_on_shelf.each do |book|
#puts book.title
#end
#puts '----------------'
red_wall.unshelf(fiction)
#fiction.books_on_shelf.each do |book|
#puts book.title
#end
hudson.books
| true |
cbd5a32f60eafa323d44c08af54b4820097e34db | Ruby | macjapm/projecteuler | /p11.rb | UTF-8 | 1,070 | 3.28125 | 3 | [] | no_license | #Author : Mackenzie Park-McInnes
#Title : P11
#Purpose : Solve 'projecteuler.net' archived problem 11
def v(x, y, arr)
prd = 1
if y > 16 == false
for rep in 1..4
prd *= (arr[x + (y*19)]).to_i
y += 1
end
end
return prd
end
def h(x, y, arr)
prd = 1
if x > 16 == false
for rep in 1..4
prd *= (arr[x + (y*19)]).to_i
x += 1
end
end
return prd
end
def ld(x, y, arr)
prd = 1
if x > 16 || y > 16 == false
for i in 1..4
prd *= (arr[x + (y*19)]).to_i
x += 1
y += 1
end
end
return prd
end
def rd(x, y, arr)
prd = 1
if x > 19 || y > 19 == false
for i in 1..4
prd *= (arr[x + (y*19)]).to_i
x -= 1
y += 1
end
end
return prd
end
def prd(i, j, arr, l)
p = (h(i, j, arr))
l = p > l ? p : l
p = v(i, j, arr)
l = p > l ? p : l
p = ld(i, j, arr)
l = p > l ? p : l
p = rd(i, j, arr)
l = p > l ? p : l
return l
end
lrg = 0
fd = File.open("p11.txt")
data = ""
fd.each do |line|
data.concat(line)
end
data.sub("\n","")
elem = data.scan(/[\d]{2}/)
for i in 0..19
for j in 0..19
lrg = prd(i, j, elem, lrg)
end
end
puts lrg
| true |
1b4800d9f4cdb12f039fe64413dc94121705c9bc | Ruby | stok0102/word_count | /lib/word_count.rb | UTF-8 | 228 | 3.421875 | 3 | [
"MIT"
] | permissive | require('pry')
class String
def word_count (user_input)
result = 0
input_array = user_input.split(" ")
input_array.each do |match|
if self == match
result += 1
end
end
result
end
end
| true |
4dbaf27d8e5afaae53b40ec97c081e7c38c201ca | Ruby | katharinap/my_recipes | /test/models/recipe_test.rb | UTF-8 | 3,137 | 2.53125 | 3 | [] | no_license | # == Schema Information
#
# Table name: recipes
#
# id :integer not null, primary key
# name :string
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# picture :string
# active_time :integer
# total_time :integer
# prep_time :integer
# cook_time :integer
# notes :text
# directions :text
# ingredients :text
# references :text
#
# Indexes
#
# index_recipes_on_active_time (active_time)
# index_recipes_on_cook_time (cook_time)
# index_recipes_on_prep_time (prep_time)
# index_recipes_on_total_time (total_time)
# index_recipes_on_user_id (user_id)
#
require File.expand_path("../../test_helper", __FILE__)
class RecipeTest < ActiveSupport::TestCase
should belong_to :user
context 'validations' do
should validate_presence_of :name
should validate_uniqueness_of :name
should "be valid" do
assert create(:kale_chips).valid?
end
end
context '.user_name' do
setup do
@user = build(:user, name: 'test_name', email: 'test@email.com')
@recipe = build(:recipe, user: @user)
end
should "return 'unknown' if there is no user" do
recipe = Recipe.new
assert_equal 'unknown', recipe.user_name, "user_name should be 'unknown' if there is no user"
end
should "return user's name" do
assert_equal @user.name, @recipe.user_name, "user_name should be user's name"
end
should "return user's email if there is no name" do
@recipe.user.name = nil
assert_equal @user.email, @recipe.user_name, "user_name should be user's email"
end
end
context 'by name scope' do
should "sort by name" do
recipe1 = create(:kale_chips)
recipe2 = create(:ice_cream)
recipes = Recipe.by_name
assert_equal 2, recipes.count
assert_equal [recipe2, recipe1].collect(&:name), recipes.collect(&:name)
end
end
context '.steps' do
setup do
@recipe = Recipe.new(directions: "Sprinkle salt and pepper\n\tDrizzle oil\n\n Bake in oven at 450c ")
end
should "return an array of single steps without leading or trailing whitespace" do
assert_equal ['Sprinkle salt and pepper', 'Drizzle oil', 'Bake in oven at 450c'], @recipe.steps
end
end
context '#search' do
setup do
tag = create(:tag, name: 'quick')
@recipe1 = create(:recipe, name: 'Quinoa Bowl', ingredients: "1 cup quinoa\n1 cup brown lentils\ntahini\bunch of greens", tags: [tag])
@recipe2 = create(:recipe, name: 'Ice Cream', ingredients: "1 can coconut milk\n2 tb corn starch\n1/2 cup agave nectar\nvanilla extract")
@recipe3 = create(:recipe, name: 'Cold Brewed Iced Coffee', ingredients: 'coffee', tags: [tag])
end
should "search the name" do
assert_equal [@recipe3, @recipe2], Recipe.search('ice').sort_by(&:name)
end
should "search the ingredients" do
assert_equal [@recipe1], Recipe.search('lentils')
end
should 'search the tags' do
assert_equal [@recipe3, @recipe1], Recipe.search('quick').sort_by(&:name)
end
end
end
| true |
5765648b2d2d2fae9cea5832e5895de462dfc28d | Ruby | jungchae/ruby-pwa | /bin/weights.rb | UTF-8 | 1,983 | 2.65625 | 3 | [] | no_license | #!/usr/bin/env ruby
# Author:: Mike Williams
#
# Dumps event weights to screen
#
require 'optparse'
require 'pwa/dataset'
require 'utils'
require 'plot/utils'
require 'plot/iteration'
#
# parse command line
#
#options = {:type => :acc}
options = {}
cmdline = OptionParser.new
cmdline.banner = 'Usage: plot.rb [...options...] file.xml'
cmdline.on('-h','--help','Prints help to screen'){puts cmdline; exit}
cmdline.on('-c','--ctrl FILE',String,'Fit control file'){|opt| options[:c]=opt}
cmdline.on('-d DATASET',String,'Dataset (defaults to 1st found)'){|opt|
options[:d] = opt
}
cmdline.on('-i #',String,'Plot specific iteration (default is best)'){|opt|
options[:i] = opt.to_i
}
cmdline.on('-t','--type (acc,raw)',String,'type (acc,raw)'){|opt|
options[:type] = :acc if opt == "acc"
options[:type] = :raw if opt == "raw"
}
xml_file = cmdline.parse(ARGV)[0]
#
# get weights
#
Plot::Iteration.set(xml_file)
Plot::Iteration.sort!
iter = Plot::Iteration.best
iter = Iteration[options[:i]] unless(options[:i].nil?)
$bin_ranges = iter.bin_ranges
PWA::ParIDs.set(iter.names2ids)
load options[:c]
PWA::Dataset.each{|dataset|
next unless(dataset.type == :evt)
next if(!options[:d].nil? and dataset.name != options[:d])
dataset.read_in_amps(PWA::ParIDs.max_id,options[:type])
if options[:type] == :acc
cuts = dataset.get_cuts(options[:type])
elsif options[:type] == :raw
cuts = []
100000.times{|i|; cuts[i] = 1.0 }
end
num_events = dataset.get_num_events(options[:type],cuts)
dataset.set_for_intensities(iter.pars,'.')
intensities = []
event = 0
sum = 0
cuts.each_index{|ev_index|
if(cuts[ev_index] > 0)
int = dataset.intensity(event)
intensities.push int
sum += int
event += 1
else
intensities.push 0
end
}
dataset.read_in_norm(options[:type])
y = dataset.calc_yield(iter.pars,'.',options[:type])
# scale = y/sum
# intensities.each{|int| puts int*scale}
intensities.each{|int| puts int}
break
}
| true |
4ccdcb39fd99eafe08520fe3e43c486eefa9a510 | Ruby | tapfit/tapfit | /lib/crawler_validation/process_class.rb | UTF-8 | 5,643 | 2.515625 | 3 | [] | no_license | require_relative 'process_base'
require './lib/workout_key'
class ProcessClass < ProcessBase
def initialize(opts={})
if !opts.nil?
@valid_keys = opts.keys
@valid_keys = @valid_keys.collect{|i| i.to_s}
@place_id = opts[:place_id]
@name = opts[:name]
@tags = opts[:tags]
@source_description = opts[:source_description]
@source = opts[:source]
@source_id = opts[:source_id]
@start_time = opts[:start_time]
@end_time = opts[:end_time]
@price = opts[:price]
@instructor = opts[:instructor]
@can_buy = opts[:can_buy]
@class_id = opts[:class_id]
@is_day_pass = opts[:is_day_pass]
@is_cancelled = opts[:is_cancelled]
end
end
def save_to_database(source_name)
if validate_crawler_values?(source_name)
puts "failed to validate class"
else
place = Place.find(@place_id)
instructor_id = nil
if !@instructor.nil?
full_name = @instructor.split(" ")
first_name = full_name[0] if full_name.length > 0
last_name = full_name[1] if full_name.length > 1
if "#{first_name} #{last_name}" == "Cancelled Today"
puts "Workout cancelled today"
return
end
instructor = place.instructors.where(:first_name => first_name, :last_name => last_name).first
instructor = Instructor.create(:first_name => first_name, :last_name => last_name) if instructor.nil?
instructor_id = instructor.id
end
if place.can_buy
@can_buy = true
else
@can_buy = false
end
workout_key = WorkoutKey.get_workout_key(@place_id, @name)
if place.dropin_price.nil?
old_workout = Workout.where(:workout_key => workout_key).where("price IS NOT NULL").order("start_time DESC").first
if !old_workout.nil?
@price = old_workout.original_price
if @price.nil?
@price = old_workout.price
end
end
else
@price = place.dropin_price
end
original_price = @price
if !place.place_contract.nil?
if place.place_contract.price.nil?
if !place.place_contract.discount.nil? && !@price.nil?
begin
@price = ((1 - place.place_contract.discount) * @price).round
rescue
puts "discount: #{place.place_contract.discount}, price: #{@price}"
end
end
else
@price = place.place_contract.price
end
old_workout = Workout.where(:workout_key => workout_key).where("price IS NOT NULL").order("start_time DESC").first
if !old_workout.nil?
original_price = old_workout.original_price
end
end
if @source_description.nil?
old_workout = Workout.where(:workout_key => workout_key).where("source_description IS NOT NULL").first
if !old_workout.nil?
@source_description = old_workout.source_description
end
end
starts = self.change_date_to_utc(@start_time, place.address.timezone)
ends = self.change_date_to_utc(@end_time, place.address.timezone)
workout = Workout.where(:workout_key => workout_key).where(:start_time => starts).first
if !workout.nil?
puts "Workout already exists"
if !@is_cancelled.nil? && @is_cancelled
puts "Updating workout to is_cancelled"
if place.id != 1931 && place.id != 2308
workout.update_attributes(:is_cancelled => true)
end
end
update_lowest_price(place.id)
return
end
puts "is_cancelled: #{@is_cancelled}"
if @is_cancelled.nil?
@is_cancelled = false
end
crawler_info = nil
if !@class_id.nil?
crawler_info = { :class_id => @class_id }
end
if @is_day_pass.nil?
@is_day_pass = false
end
if place.id == 1931 || place.id == 2308
@is_cancelled = false
end
pass_detail = place.pass_details.first
pass_detail_id = nil
if !pass_detail.nil?
pass_detail_id = pass_detail.id
end
workout = Workout.new(:name => @name, :place_id => @place_id, :source_description => @source_description, :start_time => starts.utc, :end_time => ends.utc, :price => @price, :instructor_id => instructor_id, :source => @source, :workout_key => workout_key, :is_bookable => @is_bookable, :can_buy => true, :is_day_pass => @is_day_pass, :original_price => original_price, :is_cancelled => @is_cancelled, :pass_detail_id => pass_detail_id, :crawler_info => crawler_info)
workout.is_day_pass = @is_day_pass
if !workout.valid?
puts "errors: #{workout.errors}"
end
if workout.save
puts "saved to database #{workout.name}, place_id: #{workout.place_id}"
update_lowest_price(workout.place_id)
return workout.id
else
puts "failed to save #{workout.errors}"
return nil
end
end
end
def change_date_to_utc(time, timezone)
Time.zone = timezone
newTime = Time.zone.now.beginning_of_day.change(:year => time.year, :month => time.month, :day => time.day, :hour => time.hour, :min => time.strftime("%M").to_i )
Time.zone = "UTC"
return newTime
end
def update_lowest_price(place_id)
place = Place.find(place_id)
lowest_price_workout = place.todays_workouts.order("price ASC").first
if !lowest_price_workout.nil?
place.lowest_price = lowest_price_workout.price
place.lowest_original_price = lowest_price_workout.original_price
place.save
end
end
end
| true |
772a7739f3f10400fe69acfeba317dc320dab3c3 | Ruby | AlexBaranosky/GongOMatic | /src/audio_player.rb | UTF-8 | 434 | 2.984375 | 3 | [] | no_license | require File.dirname(__FILE__) + '/../src/speaker'
require 'win32/sound'
include Win32
class AudioPlayer
GONG_WAV = File.dirname(__FILE__) + '/../resources/blong2.wav'
def play(routine_parts)
routine_parts.each do |p|
Speaker.new.speak(p.message) if p.has_message?
wait_then_ring_gong(p.duration)
end
end
private
def wait_then_ring_gong(seconds)
sleep(seconds)
Sound.play(GONG_WAV)
end
end | true |
f8c80f4488a543841867e15f8bf5890893adf118 | Ruby | Claiborne/media-qa | /codefoo_2013/if_statement.rb | UTF-8 | 465 | 4.21875 | 4 | [] | no_license | number = 1
# contrived example
if number == 1
puts 'number is 1'
elsif number == 2
puts 'number is 2'
else
puts 'number is nethier 1 nor 2'
end
# this does the same thing as above
puts 'number is 1' if number == 1
puts 'number is 2' if number == 2
puts 'number is nethier 1 nor 2' if number != 1 && number != 2
# more useful
def increment_whole_number(number)
raise ArgumentError if number.class != Fixnum
number + 1
end
puts increment_whole_number 1 | true |
30fd41722eb734a064659ec2a1380c4adc34917e | Ruby | kepishelf/ruby | /coursera_test.rb | UTF-8 | 18,223 | 3.40625 | 3 | [] | no_license | # ruby playground / sandbox = d:\sandbox\ruby\coursera_test.rb
# see notes from coursera : d:\sandbox\ruby\ruby-reference.txt
a = 6
# ----------------------------------------------------------
# IF ELSE, CASE, UNTIL
# ----------------------------------------------------------
puts 'more stuff after this'
if a==3
puts 3
elseif a==4
puts 4
else
puts "I dont know how much a is = to"
end
puts "a = to : #{a}"
unless a == 6
puts "a is not 6 "
end
# LOOPS - while and until loop
while a < 9
puts a
a += 1
end
until a > 11
puts a
a += 1
end
resa = 2
resa *= 6
puts resa
# ----------------------------------------------------------
# MODIFIER
# ----------------------------------------------------------
a=5; b=0
puts "execute in one line : " if a == 5 and b == 0
resa = 2
# multiplel resa * 2 while the result (resa) is less than 100 2, 4, 8, 16, 32, 64, x 128
resa *= 2 while resa < 9
puts resa
# TRUE / FALSE
c = nil
puts "true" if "false"
puts "false" if false
puts "false" if c == nil
# TRIPLE EQUALS -- does this regular expression (/sera/) MATCH the "coursera" string
if /sera/ === "coursera"
puts "Triple Equals"
end
# ----------------------------------------------------------
# CASE
# ----------------------------------------------------------
puts ' -------------- testing CASE'
age = 53
case
when age > 21
puts "legal"
when 1 === 0
puts "illogical"
else
puts "default case"
end
name = 'Fisher'
case name
when /fish/i then puts "reg exp matched the name : #{name} "
when 'Smith' then puts "the name var matched. value = #{name}"
end
# ----------------------------------------------------------
# FOR - each, times
# ----------------------------------------------------------
for i in 200..202
puts i
end
puts " after for i = #{i}"
# each
ary = [1,2,3,4,5]
ary.each do |i|
puts i
end
# ----------------------------------------------------------
# METHODS
# ----------------------------------------------------------
def simple()
puts "this is method simple"
end
puts simple()
#- what is restuned : the last executed line in the method
def multiply( a, b )
a * b
end
puts multiply(3,18)
def divide_by?(number)
# number has a method "zero"
return false if number.zero?
# else return true
true
end
puts divide_by? 0
# default arguments
def add_numbers(a = 2)
a + 7
end
puts add_numbers()
def max(p1, *unknown_numbers, p3)
unknown_numbers.max
end
puts max("jeff", 2,5,2,7,19,20, "")
# ----------------------------------------------------------
# BLOCKS
# ----------------------------------------------------------
3.times do |index|
if index > 0
puts index
end
end
# or via single line
3.times { |index| puts index if index > 0 }
# Methods and passing blocks : implicit, epxlicit
def testmethod
return "no passed block of code" unless block_given?
yield
yield
end
puts testmethod()
puts testmethod() {puts 'hello world'}
# EXplicit : pushed as last parameter and use a "call" parameter
def test_explicit(&block_of_code)
return "no block passed" if block_of_code.nil?
block_of_code.call
end
puts test_explicit()
puts test_explicit() { puts "New text passed to method" }
# ----------------------------------------------------------
# FILES
# ----------------------------------------------------------
# read and display entire file
open('watcher.cfg') { |f| puts f.read }
filename = 'testa.txt'
# check that file exists
begin
File.foreach( filename ) do |line|
puts "--------- #{line}"
puts line.chomp # remote newline char from end of string
arr = line.split
puts arr
end
rescue Exception => e
puts "error missing file : #{e.message}"
end
if File.exist? filename
puts "file found"
else
puts "file NOT found"
end
puts "End of file Exist / Read"
# WRITING to files
newfile = "jeffoutput.txt"
File.open(newfile, "w") do |filehandle|
puts "Writing to #{newfile}"
filehandle.puts "line#1"
filehandle.puts "line#2"
filehandle.puts "line#3"
end
puts ENV["NWUSERNAME"] = "GAVEL"
puts ENV["NWUSERNAME"]
# ----------------------------------------------------------
# STRINGS / SYMPOLS
# ----------------------------------------------------------
puts "jeff \nWarvel \n"
a=24;b=6
puts "#{a} times #{b} = #{ a * b } "
myname = "Jeff Warvel"
myname[3,2] = 'xxxxx'
puts myname
:ThisIsaSymbol
cur_weather = %Q{It's a hot day outside
Grab your umbrellas…}
puts cur_weather
cur_weather.lines do |line|
line.sub! 'hot', 'rainy' # substitute 'hot' with 'rainy'
puts "#{line.strip}"
end
# ----------------------------------------------------------
# ARRAYS
# ----------------------------------------------------------
arr_words = %w{ jeff warvel was here }
puts arr_words
puts arr_words.first
puts arr_words[-2,1] # start at end, go back to and use 1
puts arr_words[1..2]
puts arr_words.join(';') # convert space to semicolon
# appending : push or <<
# Remove : pop or shift
# Set : [] =
# Sample : randomly pull out elements
# Sorting : sort!, reverse!
# You want a stack (LIFO)? Sure
stack = []; stack << "one"; stack.push ("two")
puts stack
puts stack.pop # => two
puts "after pop #{stack}"
# You need a queue (FIFO)? We have those too...
queue = []; queue.push "one"; queue.push "two" ; queue.push "thre"
puts queue.shift # removes the first item in
puts queue
a = [5,3,4,2].sort!.reverse!
p a # => [5,4,3,2] (actually modifies the array)
p a.sample(2) # => 2 random elements
a = [5,3,4,2].sort!.reverse!
a = [5,3,4,2]
a[6] = 33
p a # will add 2 nils to auto expand array => [5, 4, 3, 2, nil, nil, 33]
# array Methods - common
arr1 = [2,3,4,5,22]
arr1.each { |value| print " next #{value} " }
puts ""
sel_arr = arr1.select { |num| num > 3}
puts sel_arr
puts map_arr = arr1.map{ |x| x-200}
# ----------------------------------------------------------
# RANGES
# ----------------------------------------------------------
arange = 1..6
puts (1..10) === 9.375 # true
puts arange.to_a.sample(2) # convert to array and get a sample (random of 2 elements of array)
# ----------------------------------------------------------
# HASHES
# ----------------------------------------------------------
puts "--------------- HASHES --------------------------"
hashmap = { "key1" => "value of key", "size" => 22 }
hashmap["jeff"] = "warvel"
hashmap.each_pair do | key, value|
puts "Key: #{key} = #{value}"
end
puts "nil" if hashmap["missing"] == nil
# init a hash to values of zero, then count words and put sums into this Hash
word_frequency = Hash.new(0)
sentence = "Chicka chicka boom boom"
sentence.split.each do |word|
word_frequency[word.downcase] += 1
puts "counting #{word}, currval = #{word_frequency[word.downcase]}"
end
puts word_frequency # => {"chicka" => 2, "boom" => 2}
# Named parameter "like" behavior...
# method, with a default "hash" argument setting foreground, and backgroup
def adjust_colors (props = {foreground: "red", background: "white"})
puts "Foreground: #{props[:foreground]}" if props[:foreground]
puts "Background: #{props[:background]}" if props[:background]
end
adjust_colors # => foreground: red
# => background: white
# now set forground using a symbol (2 ways)
# 3 ways to set the value... note the ({} )are optional
adjust_colors ({ :foreground => "green" }) # => foreground: green
adjust_colors background: "yella" # => background: yella
adjust_colors :background => "magenta" # => background: magenta
# block and hash Confusion
a_hash = { :one => "one" }
puts a_hash # => {:one=>"one"}
# If you try to print out a hash - you get a SyntaxError
# RUBY GETS CONFUSED AND THINKS {} IS A BLOCK!!!
# puts { :one => "one" }
# To get around this - you can use parens around the Hash
puts ({ :one => "one" })
# ----------------------------------------------------------
# CLASSES
# ----------------------------------------------------------
puts "--------------- CLASSES --------------------------"
class Person
def initialize (name, age) # "CONSTRUCTOR"
@name = name
@age = age
end
def get_info
@additional_info = "Interesting"
"Name: #{@name}, age: #{@age}"
end
end
# Create an object of Person class and assign to "person1" var
person1 = Person.new("Joe", 14)
# show the "instance" variables available to to object from the Class "Person"
p person1.instance_variables # [:@name, :@age]
# This adds an another Instance varaible @additional_info
puts person1.get_info # => Name: Joe, age: 14
p person1.instance_variables # [:@name, :@age, :@additional_info]
# Access to Instance Variables - must define GETTER, SETTER methods
# getter, setter methods
class Person2
def initialize (name, age) # "CONSTRUCTOR"
@name = name
@age = age
end
def get_info ()
@additional_info = "Interesting"
"Name: #{@name}, age: #{@age}"
end
def name()
@name
end
def name=(set_name)
@name = set_name
end
end
puts "- Creating Jeff Person Object / Instance"
person2 = Person2.new("jeff", 53)
puts person2.name
#puts person2
person2.name = "Warvel"
puts "using Set then new Name instance var = #{person2.name}"
# Getter, Setter - more Convenient using : attr_accessor (both, attr_reader, attr_writer
class PersonNew
attr_accessor :name, :age
end
puts "- Using attr_accessor"
person3 = PersonNew.new
person3.name = "jeffry"
puts person3.name
person3.age = "this is not a number"; puts person3.age
# to control the Intance Vars in the Object
# Use a CONSTRUCTOR
# Using "self" - when inside method, refers to the object
# when outside the Instance method, self refers to the class itself
puts "- Using self within a init method of a class"
class PersonD
attr_reader :age # create the getter methods for age
attr_accessor :name # creates getter, setter for name
def initialize (name, ageVar) # CONSTRUCTOR
@name = name
self.age = ageVar # call the age= method . "self" is required here. (when inside the method)
# if only had "age = ageVar" would only set local var, not the Instance var
# self.age is actuall the Method that gets called here
# amd that method is below.
#puts "--- setting age: #{age }" # put calls the age reader method (this is for debug only)
end
def age= (new_age)
@age = new_age unless ( new_age > 120 or new_age < 0 )
end
end
person1 = PersonD.new("Jeff Warvel", 53)
puts "Created Instance object : Name is #{person1.name} Age is #{person1.age}" # => My age is 13
newage = 1
puts "Attempting to set Age to: #{newage}"
person1.age = newage # Try to change the age
puts "Resulting person object.age: #{person1.age}"
puts "- Using the double pipes"
class PersonE
attr_reader :age # create the getter methods for age
attr_accessor :name # creates getter, setter for name
def initialize (name, ageVar) # CONSTRUCTOR
@name = name
self.age = ageVar # call the age= method . "self" is required here. (when inside the method)
end
# age setter method
def age= (new_age)
@age ||="n/a" # Default - use age if set, else use "n/a"
@age = new_age unless ( new_age > 120 or new_age < 0 ) # put bounds on the age setting
end
end
person1 = PersonE.new("Jeff Warvel",133)
puts "Resulting person object.age: #{person1.age}"
# --------------------------------------------------------
puts "- CLASS METHODS AND VARIABLES - "
# 3 ways to define the class level methods , variables
class MathFunctions
def self.double(var) # 1. Using self - Class Method
times_called; var * 2;
end
class << self # 2. Using << self - Class Variable
def times_called
@@times_called ||= 0; @@times_called += 1
end
end
end
def MathFunctions.triple(var) # 3. Outside of class
times_called; var * 3
end
# No instance created for any of these
puts MathFunctions.double 5 # => 10
puts MathFunctions.triple(3) # => 9
puts MathFunctions.times_called # => 3
# ----------------------------------------------------------
# CLASSES
# ----------------------------------------------------------
puts "- CLASS INHERITANCE - "
class Dog
def to_s
"Dog"
end
def bark
"barks loudly"
end
end
class SmallDog < Dog
def bark # Override
"barks quietly"
end
end
dog = Dog.new # (btw, new is a class method)
small_dog = SmallDog.new
puts "#{dog}1 #{dog.bark}" # => Dog1 barks loudly
puts "#{small_dog}2 #{small_dog.bark}" # => Dog2 barks quietly
# MIXIN example
puts "- MIXIN / Include - "
module SayMyName
attr_accessor :name
def print_name
puts "Name: #{@name}"
end
end
class Person
include SayMyName
end
class Company
include SayMyName
end
person = Person.new
person.name = "Joe"
person.print_name # => Name: Joe
company = Company.new
company.name = "Google & Microsoft LLC"
company.print_name # => Name: Google & Microsoft LLC
puts "--------------- SCOPE --------------------------"
puts "- Scope inside outside a class "
v1 = "outside"
class MyClass
def my_method
# p v1 EXCEPTION THROWN - no such variable exists
v1 = "inside"
p v1
p local_variables
#
puts "what is self inside a class "
p self
end
end
p v1 # => outside
obj = MyClass.new
obj.my_method # => inside
# => [:v1]
puts "variables outside class ---"
p local_variables # => [:v1, :obj]
p self # => main
puts "- Using Constants - start with Upper"
module MyModule
MyConstant = 'Outer Constant'
class MyClass
puts MyConstant # => Outer Constant
MyConstant = 'Inner Constant'
puts MyConstant # => Inner Constant
end
puts MyConstant # => Outer Constant
end
jeff = MyModule::MyClass.new
puts "- Block scope "
class BankAccount
attr_accessor :id, :amount
def initialize(id, amount)
@id = id
@amount = amount
end
end
acct1 = BankAccount.new(123, 200)
acct2 = BankAccount.new(321, 100)
acct3 = BankAccount.new(421, -100)
accts = [acct1, acct2, acct3]
total_sum = 0 # avail outside and inside block scope
accts.each_with_index do |eachAcct, index ; newvar | # set newvar to have scope only in the block
total_sum += eachAcct.amount # total_sum gets inherited to inside this scope
newvar = 1
puts " index: #{index} - newvar #{newvar} "
end
#puts newvar # => is not in this scope, only local to block
puts total_sum # => 200
# Blocks - Local Scope Example
arr = [5, 4, 1]
cur_number = 10
arr.each do |cur_number|
some_var = 10 # NOT available outside the block
print cur_number.to_s + " " # => 5 4 1
end
puts # print a blank line
puts cur_number # => 10
adjustment = 5
arr.each do |cur_number;adjustment|
adjustment = 10
print "#{cur_number + adjustment} " # => 15 14 11
end
puts
puts adjustment # => 5 (Not affected by the block)
puts "--------------- ACCESS CONTROL --------------------------"
puts "- Method 'access' is public (default), protected or private"
class MyAlgorithm
private
def test1 # first method is private
"Private"
end
def priv1
"also private"
end
# any additional methods are private , until hit another access control keyword
protected
def test2 # method test2 is protected
"Protected"
end
public
def public_again
"Public"
end
end
# option 2, define methods, then after that set the Acess Control :methodname
class Another
def test1
"Private, as declated later on"
end
private :test1
end
# Understanding Private access
puts "- Understanding Private access"
class Person
def initialize(age)
self.age = age # LEGAL - EXCEPTION - the exception is the "Setter" for a private method
# and can only do this using "self" in the initialize method for this class
puts my_age
# puts self.my_age # ILLEGAL - even Contructor cannot access the private "my_age" method
# CANNOT USE self or any other receiver
end
private
def my_age
@age
end
def age=(age)
@age = age # Exception to private is the "setter" for age
end
end
Person.new(25) # => 25
puts "--------------- UNIT TESTS --------------------------"
puts "- Uses Test::Unit and additional file : Class_test"
#--- this is the Class code
class Calculator
attr_reader :name
def initialize(name)
@name = name
end
def add(one, two)
one - two
end
def subtract(one, two)
one + two
end
def divide(one, two)
one / two
end
end
#--- file to run unit tests on above class
# ////////////////////////////////////////////////////////////////////
require 'test/unit' # fixing error with testing - had to update the "test-unit" ruby package : gem install test-unit
require_relative 'calculator'
# This is a class that "extend"s the Calculator class above. can name this anything
# but the : Test::Unit is what links it to the unit test lib/control (???)
#class CalculatorTest < Minitest::Test
class CalculatorTest < Test::Unit::TestCase
# this create an instance of the Calculator class and we give it any name
# this is the prep / setup() for unit test
def setup
@calc = Calculator.new('test')
end
# unit test for all methods
def test_add
assert_equal 5, @calc.add(2,3) # assert that adding 2 and 3 = 5
end
def test_minus
assert_equal -12, @calc.subtract(23,35)
end
def test_divide
assert_equal -8, @calc.divide(16,-2)
end
# special assertion that check for zero in denom - requires latest "test-unit"
# assert_raise : specifies the Exception error you would expect
# this code will actually run the divde by Zero and prove that we see / catch the expected error
def test_divide_by_zero
assert_raise ZeroDivisionError do
@calc.divide(1, 0)
end
end
def teardown
@calc
end
end
# ////////////////////////////////////////////////////////////////////
puts "--------------- RSPEC --------------------------"
puts " - EXAMPLE in subdir : rspec-example - "
puts " see: calculator.rb, and calculator_spec.rb "
puts " testing the Calculator() class "
puts " - rspec Matchers - "
| true |
7c3660f38389a83156f6c3755e8b3c1ce48e2286 | Ruby | Sayanc93/HashtagBattle | /app/services/twitter_streaming_service.rb | UTF-8 | 912 | 2.625 | 3 | [] | no_license | class TwitterStreamingService
attr_reader :client, :user
def initialize user = nil
@user = user
@client = TweetStream::Client.new(oauth_token_secret: user.secret,
oauth_token: user.token)
end
# Tracks tweets in a stream, stream exits when user's connected attribute is toggled.
def track hashtag
client.track(hashtag.name) do |tweet, client|
client.stop if !user.reload.connected
hashtag = user.hashtags.find_by(name: hashtag.name)
hashtag.count = hashtag.count + 1
hashtag.save!
broadcast_counter_data hashtag
end
end
# Broadcasts the counter to the relevant user with tag information.
def broadcast_counter_data hashtag
ActionCable.server.broadcast("hashtag_counter_#{user.id}",
hashtag: hashtag.name,
counter: hashtag.count)
end
end
| true |
a458a7d95b90625c9651ce6b0d926a385dbabf7e | Ruby | Kacper3331/fight_club | /app/models/result.rb | UTF-8 | 1,813 | 2.90625 | 3 | [] | no_license | class Result < ActiveRecord::Base
def self.create_result(first_fighter_id, second_fighter_id)
first_fighter_skill = select_skill(first_fighter_id)
second_fighter_skill = select_skill(second_fighter_id)
first_fighter_exp_points = fighter_info(first_fighter_id).exp_points.to_i
second_fighter_exp_points = fighter_info(second_fighter_id).exp_points.to_i
first_fighter_attack = fighter_attack(first_fighter_skill.level, first_fighter_exp_points)
second_fighter_attack = fighter_attack(second_fighter_skill.level, second_fighter_exp_points)
if first_fighter_attack > second_fighter_attack
add_data(first_fighter_id, second_fighter_id, first_fighter_skill, second_fighter_skill, first_fighter_attack, second_fighter_attack)
else
add_data(second_fighter_id, first_fighter_id, second_fighter_skill, first_fighter_skill, second_fighter_attack, first_fighter_attack)
end
end
def self.add_data(winner_id, loser_id, winner_skill, loser_skill, winner_attack, loser_attack)
result = Result.new
result.winner_id = winner_id
result.loser_id = loser_id
result.winner_skill_id = winner_skill.id
result.loser_skill_id = loser_skill.id
result.winner_attack = winner_attack
result.loser_attack = loser_attack
result.save
Fighter.add_exp_points(fighter_info(winner_id), 10)
Fighter.add_exp_points(fighter_info(loser_id), 5)
end
def self.select_skill(fighter_id)
Fight.select_skill(fighter_id)
end
def self.fighter_info(fighter_id)
Fight.fighter_info(fighter_id)
end
def self.fighter_attack(skill_level, exp_points)
Fight.calculate_attack(skill_level, exp_points)
end
def self.winner_fighter(fighter_id)
Fight.fighter_info(fighter_id).firstname + ' ' + Fight.fighter_info(fighter_id).lastname
end
end
| true |
3263723ae224100964b6cdf833b07ec46174d754 | Ruby | Lecogoni/THP-W2-D2 | /exo_03.rb | UTF-8 | 125 | 3.59375 | 4 | [] | no_license | # 2.3. Un programme qui calcule des âges
puts "Ton âge ?"
input = gets.chomp.to_i
puts "Tu avais #{input - 4} ans en 2017" | true |
508d2d4f50044dd989c525ff69a5f54bb1782d05 | Ruby | mercedesb/fun_friendly_cs_ruby | /app/models/inheritance/geranium.rb | UTF-8 | 402 | 2.625 | 3 | [] | no_license | # frozen_string_literal: true
class Inheritance::Geranium < Inheritance::Plant
def initialize
@name = 'Geranium'
@sun = true
@wet = false
@light_needs = '4 - 6 hours of direct sunlight per day.'
@soil_needs = 'Plant in a pot with soil-less potting mixture and good drainage.'
@water_needs = 'Water thoroughly and allow to soil to completely dry between waterings.'
end
end
| true |
a2911ef2516111c3b10d77745f0028643390feb3 | Ruby | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/ruby/raindrops/21283d4391e3498f86c6749baba92311.rb | UTF-8 | 298 | 3.046875 | 3 | [] | no_license | class Raindrops
def self.convert(number)
return_string = String.new
return_string += "Pling" if number % 3 == 0
return_string += "Plang" if number % 5 == 0
return_string += "Plong" if number % 7 == 0
return_string = number.to_s if return_string.empty?
return_string
end
end
| true |
5b12e6005d8490f11fafd07717e64cbe8894ba4f | Ruby | vconcepcion/level_up_exercises | /supportive/supportive.rb | UTF-8 | 3,889 | 2.921875 | 3 | [
"MIT"
] | permissive | # In case you missed them, here are the extensions: http://guides.rubyonrails.org/active_support_core_extensions.html
require 'active_support/all'
class BlagPost
attr_accessor :author, :comments, :categories, :body, :publish_date
Author = Struct.new(:name, :url)
DISALLOWED_CATEGORIES = [:selfposts, :gossip, :bildungsromane]
def initialize(args)
args = args.inject({}) do |hash, (key, value)|
hash[key.to_sym] = value
hash
end
if args[:author] != '' && args[:author_url] != ''
@author = Author.new(args[:author], args[:author_url])
end
if args[:categories]
@categories = args[:categories].reject do |category|
DISALLOWED_CATEGORIES.include? category
end
else
@categories = []
end
@comments = args[:comments] || []
@body = args[:body].gsub(/\s{2,}|\n/, ' ').gsub(/^\s+/, '')
@publish_date = (args[:publish_date] && Date.parse(args[:publish_date])) || Date.today
end
def to_s
[ category_list, byline, abstract, commenters ].join("\n")
end
private
def byline
if author.nil?
""
else
"By #{author.name}, at #{author.url}"
end
end
def category_list
return "" if categories.empty?
if categories.length == 1
label = "Category"
else
label = "Categories"
end
if categories.length > 1
last_category = categories.pop
suffix = " and #{as_title(last_category)}"
else
suffix = ""
end
label + ": " + categories.map { |cat| as_title(cat) }.join(", ") + suffix
end
def as_title(string)
string = String(string)
words = string.gsub('_', ' ').split(' ')
words.map!(&:capitalize)
words.join(' ')
end
def commenters
return '' unless comments_allowed?
return '' unless comments.length > 0
ordinal = case comments.length % 10
when 1 then "st"
when 2 then "nd"
when 3 then "rd"
else "th"
end
"You will be the #{comments.length}#{ordinal} commenter"
end
def comments_allowed?
publish_date + (365 * 3) > Date.today
end
def abstract
if body.length < 200
body
else
body[0..200] + "..."
end
end
end
blag = BlagPost.new("author" => "Foo Bar",
"author_url" => "http://www.google.com",
"categories" => [:theory_of_computation, :languages, :gossip],
"comments" => [ [], [], [] ], # because comments are meaningless, get it?
"publish_date" => "2013-02-10",
"body" => <<-ARTICLE
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus.
Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit.
Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam
tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula
ultricies a non tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut
gravida lorem. Ut turpis felis, pulvinar a semper sed, adipiscing id dolor. Pellentesque auctor
nisi id magna consequat sagittis. Curabitur dapibus enim sit amet elit pharetra tincidunt feugiat
nisl imperdiet. Ut convallis libero in urna ultrices accumsan. Donec sed odio eros. Donec viverra
mi quis quam pulvinar at malesuada arcu rhoncus. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. In rutrum accumsan ultricies. Mauris vitae nisi at sem
facilisis semper ac in est.
ARTICLE
)
puts blag.to_s
| true |
e54893b5b2c786a289df92e92d303610bdf3393b | Ruby | eabrash/Scrabble | /lib/Scrabble_scoring.rb | UTF-8 | 1,952 | 3.609375 | 4 | [] | no_license | require_relative "../Scrabble_module"
class Scrabble::Scoring
LETTER_VALUES = {"A"=> 1, "E"=> 1, "I"=> 1, "O"=> 1, "U"=> 1, "L"=> 1, "N"=> 1, "R"=> 1, "S"=> 1, "T"=> 1,
"D"=> 2, "G"=> 2,
"B"=> 3, "C"=> 3, "M"=> 3, "P"=> 3,
"F"=> 4, "H"=> 4, "V"=> 4, "W"=> 4, "Y"=> 4,
"K"=> 5,
"J"=> 8, "X"=> 8,
"Q"=> 10, "Z"=> 10
}
def self.score(word)
score = 0
word.upcase!
word.each_char do |letter|
score += LETTER_VALUES[letter]
end
# 50 point bonus for using all 7 tiles
if word.length == 7
score += 50
end
return score
end
def self.highest_score_from(array_of_words)
array_of_scores = []
array_of_words.each do |word|
array_of_scores << self.score(word)
end
#Combine the array_of_words and array_of_scores into a 2D array where the word and its score are stored in the same element of the primary array => [[word, score], [word2, score2]]
array_of_word_scores = array_of_words.zip(array_of_scores)
max_score = array_of_scores.max
#There are no tie scores
if array_of_scores.grep(max_score).size == 1
#Find the in index of the max_score in the array_of_scores, then go to the same index in the array_of_word and return the associated word
return array_of_words[array_of_scores.index(max_score)]
#There is more than one word with the same high score
else
#Isolate the highest scoring words
array_of_max_scoring_words_and_scores = array_of_word_scores.select{|x| x[1]==max_score}
end
#Find and compare the length of high score words
winner = array_of_max_scoring_words_and_scores[0]
array_of_max_scoring_words_and_scores.each do |x|
#If the word length is 7, the word wins
if x[0].length == 7
return x[0]
#If the word is shorter than the first word with a high score, it becomes the winning word
elsif x[0].length < winner[0].length
winner = x
end
end
return winner[0]
end
end
| true |
4f137fb43a36401b23e4adc79d52ed90fff06cea | Ruby | um-eng-web/grupo3 | /bookie.rb | UTF-8 | 119 | 2.796875 | 3 | [] | no_license | require_relative 'person.rb'
class Bookie < Person
def initialize(nome,pass, mail)
super(nome,pass,mail)
end
end | true |
58e5ed2032d250881e622a151280dcb800ee318c | Ruby | andrechalom/outarms | /outarms-core.rb | UTF-8 | 4,930 | 3.1875 | 3 | [] | no_license | # Class inspired by Chingu::BasicGameObject https://github.com/ippa/chingu/blob/master/lib/chingu/basic_game_object.rb
# These classes however don't require a graphic interface
class GameObject
# Para entender essa linha: http://openmymind.net/2010/6/25/Learning-Ruby-class-self/
class << self; attr_accessor :instances; end
attr_reader :x, :y, :hp, :armor, :range, :level, :speed
def initialize(options = {})
$world.add_game_object(self)
@options = options
@x = options[:x] || 0
@y = options[:y] || 0
@hp = options[:hp] || 0
@armor = options[:armor] || 0
@range = options[:range] || 30
@level = options[:level] || 1
@speed = options[:speed] || 0
# Quanto o objeto jah eh criado com level alto, chame a funcao upgrade
# para subir os stats
ups = @level - 1
ups.times{upgrade; @level-= 1}
# Quando GUI está ligada, cria a imagem
setup_image(options)
# Adiciona essa instancia na lista das instancias de classe
self.class.instances ||= Array.new
self.class.instances << self
end
def damage(ammount)
ammount -= @armor
ammount = 0.1 if ammount < 0.1
@hp -= ammount
end
def setup_image(options = {}); end # PLACEHOLDER for GUI
def dist(object)
dx = @x-object.x
dy = @y-object.y
Math.hypot(dx, dy)
end
def self.all
instances ? instances.dup : []
end
def self.each; all.each { |object| yield object }; end
def report
puts "I am a level #{level} #{self} on #{x}, #{y}. HP: #{hp}"
end
def destroy
$world.delete_game_object(self)
self.class.instances.delete(self)
end
# placeholders for methods
def update; end
def upgrade
@level += 1
end
def upcost; puts "Trying to upgrade a base GameObject!"; end
def up_if_possible
if $world.coins > upcost
$world.add_coins(-upcost)
upgrade
end
end
end
class Timer
class << self; attr_accessor :instances; end
def self.all; instances ? instances.dup : []; end
def self.each; all.each { |object| yield object }; end
attr_reader :interval, :current, :action
def initialize(owner, interval, action)
@owner = owner
@interval = interval
@action = action
@current = interval
self.class.instances ||= Array.new
self.class.instances << self
end
def update
return if @interval == 0; #not even ticking...
@current -= 1
if @current == 0
@current = @interval
@owner.send @action
end
end
end
class GameWorld
attr_reader :coins, :kills, :game_objects
def initialize
@game_objects = []
@coins = 0; @kills = 0
end
def add_game_object(object)
@game_objects.push(object)
end
def delete_game_object(object)
@game_objects.delete(object)
end
def destroy_all
@game_objects.dup.each{|x| x.destroy }
end
def update
Timer.each{|x| x.update}
@game_objects.each{|x| x.update}
end
def report
puts "Kills: #{kills}, coins #{coins}\nObject list:"
@game_objects.each{|x| x.report}
end
def killed; @kills +=1; end
def add_coins(ammount); @coins += ammount; end
end
class Creep < GameObject
attr_reader :visible
def initialize(options = {})
super(options)
@visible = true
end
def nearest_core
cores = Core.all
return [cores[0], dist(cores[0])] if cores.size == 1
n = cores[0]; d = dist(n) #UNTESTED!!
cores.each{|x|
if dist(x) < d
n = x
d = dist(n)
end
}
return [n, d]
end
def update
super
if @hp < 0 #Destroyed
$world.killed
$world.add_coins(@speed+3*@armor)
destroy
end
core, dist = nearest_core
if dist < speed # Reached
core.damage(hp)
destroy
else # Moving
@x += (core.x - @x)/dist*@speed
@y += (core.y - @y)/dist*@speed
end
end
end
class Spawner < GameObject
def initialize(options = {})
super(options)
Timer.new(self, 70, :spawn) # Creates a timer to spawn every 70 ticks
Timer.new(self, 50*70, :upgrade) # Creates a timer to upgrade spawning every 50 spawns
end
def spawn
Creep.new({x: @x+14, y: @y+23, speed: 2*@level, hp: 1*@level, level:@level})
end
def upgrade
@level += 1
end
def update
super
end
end
class Tower < GameObject
def initialize(options = {});
@maxtimer = options[:timer] || 30
@shoottimer = @maxtimer
@damage = options[:damage] || 3
super(options);
# @range = options[:range] || 30 <- done on super
end
def upcost
@level*@level*90
end
def upgrade
@level +=1
@range += 10
@maxtimer /= 1.1
@damage += 3
end
def update
super
if @shoottimer > 0
@shoottimer -= 1
else
Creep.each { |creep|
if dist(creep) < @range && creep.visible
#FIRE!!
@shoottimer = @maxtimer
creep.damage(@damage)
break;
end
}
end
end
end
class Core < GameObject
def self.alive
Core.each{|x| return false if x.hp < 0}
return true
end
end
def format(secs)
string = ""
hours = secs / (60*60)
secs -= hours*60*60
string += "#{hours} hours, " if hours > 0
minutes = secs / 60
secs -= minutes*60
string += "#{minutes} minutes, " if minutes > 0
string += "#{secs} seconds"
string
end
| true |
a32d3b79e0bae01ec130de2e581d2eff72eb83bf | Ruby | horangijk/dumbo-web-100818 | /10-intro-testing/app/animal.rb | UTF-8 | 182 | 2.609375 | 3 | [] | no_license | class Animal
def zoos_escaped_from
escapes = Escape.all.select do |escape|
escape.animal == self
end
escapes.map do |escape|
escape.zoo
end
end
end | true |
7a44067a3306968337f569ca4355d024f2afadb8 | Ruby | rymanalo/convert_to_phone_number | /convert_to_phone_number.rb | UTF-8 | 393 | 3.578125 | 4 | [] | no_license | def convert_to_phone_number(num)
str = ""
num2 = num.to_s.reverse.split("")
str << num2.shift
str << num2.shift
str << num2.shift
str << num2.shift
str << "-" + num2.shift
str << num2.shift
str << num2.shift + " "
str << ")" + num2.shift
str << num2.shift
str << num2.shift + "( "
str << num2.shift + "+"
str.reverse
end
puts convert_to_phone_number(11231231234) | true |
f6bf7d96922cfb31a7e2619b0f8929158dd9033e | Ruby | oseivale/roll-of-the-die | /roll_die_ten_times.rb | UTF-8 | 198 | 2.71875 | 3 | [] | no_license | # PRINTING THE RESULTS OF RANDOMLY ROLLED DIE
counter = 0
until counter == 10
puts "The result of your roll is #{Random.rand(1..7)}" # --> This generates a number between 0 and 6
counter += 1
end
| true |
6b858568e45c49d836042e8bc864ab157913481c | Ruby | rofreg/reservations | /app/models/cart_item.rb | UTF-8 | 623 | 3.109375 | 3 | [] | no_license | class CartItem
attr_reader :equipment_model, :quantity
def initialize(equipment_model)
@equipment_model = equipment_model
@quantity = 1
end
def increment_quantity
@quantity += 1
end
def decrement_quantity
if @quantity > 0
@quantity -= 1
end
end
def details
detail = {
:equipment_model => @equipment_model,
:quantity => @quantity
}
end
def name
@equipment_model.name
end
def available?(range_of_dates)
range_of_dates.each do |day|
return false if equipment_model.available_count(day) < quantity
end
true
end
end
| true |
59309e48a0abdf9ada7514b09186d1dd988efea5 | Ruby | hussainpithawala/parking-lot-problem-ruby | /lib/command/create.rb | UTF-8 | 483 | 2.75 | 3 | [] | no_license | require_relative 'base_command'
module Command
class Create < BaseCommand
attr_reader :capacity, :msg
def initialize(context)
super(context)
context_is_not_nil?
if context.capacity < 1
raise "capacity cannot be less than 1"
end
super(context)
@capacity = context.capacity
end
def execute
context.parking_lot = ParkingLot.new(capacity)
return "Created parking lot with #{capacity} slots"
end
end
end | true |
f259d7b45f74ed39b946639450d408ebbfab05d9 | Ruby | chses9440611/Ruby_the_hard_way_ex | /ex2.rb | UTF-8 | 97 | 2.71875 | 3 | [] | no_license | #The comment character in Ruby is '#''
puts "I could have code like this."
puts "This will run."
| true |
82da31f1d6c6065db818aa0fac44682cbcf4fdde | Ruby | awanderson8/Poco-A-Poco | /Alphabetize-Words.rb | UTF-8 | 241 | 3.734375 | 4 | [] | no_license | puts "Type out 1 word per line. When you are finished, press \'enter\'."
words = []
input = gets.chomp
while input != ""
input = gets.chomp
words.push input
end
puts "Here are your words in alphabetical order."
puts words.sort
| true |
4e056609e664f730699adc541c763adb9cf8ead5 | Ruby | get4137/ruby_ruby | /while.rb | UTF-8 | 1,022 | 3.5625 | 4 | [] | no_license | # frozen_string_literal: true
# answer = 'Y'
# while answer == 'Y'
# puts 'Хотите продолжить? (Y/N) '
# answer = gets.strip.capitalize
# end
# hh = {}
# while true
# print 'enter name (Enter to stop): '
# name = gets.strip.capitalize
# if name == ''
# break
# end
# print 'enter phone number: '
# number = gets.strip
# hh[name] = number
# end
# puts hh
# hh = {
# 'dog' => 'собака',
# 'cat' => 'кошка',
# 'girl' => 'девушка'
# }
# loop do
# print 'enter the word: '
# eng = gets.strip
# if eng == ''
# exit
# end
# puts hh[eng]
# end
# def run_5_times
# x = 0
# while x < 5
# yield x, 55
# x += 1
# end
# end
# run_5_times {|i, v| puts "Something, index #{i}, value: #{v}"}
# input = File.open('test.txt', 'r')
# while (line = input.gets)
# puts line
# end
# input.close
# input = File.open('test.txt', 'r')
# while (line = input.gets)
# line.strip!
# if line.size == 6
# puts line
# end
# end
# input.close
| true |
1709f972f4eb1513d6240de32387cae1baac69b9 | Ruby | roniRamon/aA-homeworks | /W2D5/lru_cache.rb | UTF-8 | 503 | 3.5 | 4 | [] | no_license | class LRUCache
attr_reader :arr, :size
def initialize(size)
@arr = Array.new()
@size = size
end
def add(element)
#befor add element see if exist
#if yes delete it an move to end
if @arr.include?(element)
@arr.delete_at(@arr.index(element))
end
#check if arr size == 4
keep_size
@arr << element
end
def count
@arr.length
end
def show
@arr
end
private
def keep_size
if count == @size
@arr.shift
end
end
end
| true |
c0a2d9d85053bc0c896f6cea0197d1aa5a81a4f6 | Ruby | garuma/sorbetor | /test/sorbetor/string_container_test.rb | UTF-8 | 2,099 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | # typed: true
require "test_helper"
class Sorbetor::StringContainerTest < Minitest::Test
def test_string_comes_back_the_same
text = "Hello World!"
assert_equal Sorbetor::Text::StringContainer.from_s(text).to_s, text
end
def test_can_concat_two_strings
text1 = "Hello "
text2 = "World!"
container = Sorbetor::Text::StringContainer.from_s(text1)
container = container.append(text2)
assert_equal text1 + text2, container.to_s
end
def test_can_remove_string
text1 = "Hello World!"
text2 = " World!"
container = Sorbetor::Text::StringContainer.from_s(text1)
container = container.remove((0..4))
assert_equal text2, container.to_s
end
def test_can_append_entire_text
text = "Hello World!"
container = Sorbetor::Text::StringContainer.empty
text.each_char { |c| container = container.append(c) }
assert_equal text, container.to_s
end
def test_can_insert_text
text = "Hello World!"
container = Sorbetor::Text::StringContainer.from_s(text)
1.upto(4).each do
container = container.insert(5, "o")
end
assert_equal "Hellooooo World!", container.to_s
end
def test_can_replace_beginning
text = "Hello World!"
container = Sorbetor::Text::StringContainer.from_s(text).replace((0..4), "Bye")
assert_equal text.sub("Hello", "Bye"), container.to_s
end
def test_can_replace_end
text = "Hello World!"
container = Sorbetor::Text::StringContainer.from_s(text).replace((6..10), "Me")
assert_equal text.sub("World", "Me"), container.to_s
end
def test_can_iterate_over_each_chars
text = "Hello World!"
result = String.new(capacity: text.length)
container = Sorbetor::Text::StringContainer.from_s(text)
container.all_chars.each do |c|
result.concat(c)
end
assert_equal text, result
end
def test_can_access_individual_characters
text = "Hello World!"
container = Sorbetor::Text::StringContainer.from_s(text)
assert_equal "H", container[0]
assert_equal "W", container[6]
assert_equal "Hello", container[(0...5)]
end
end
| true |
a7d9d020857b2b2910c0e8b4ed0a0e56f5be36e4 | Ruby | timreganporter/JMS-302 | /exercises/quiz-midterm-prep/grade_calculator.rb | UTF-8 | 1,110 | 4.4375 | 4 | [] | no_license | # This could have even more comments. However, this code is quite readable without
# even the existing comments. It's overcommented for my tasts, but
# you should get in the habit of commenting your code. It'll help you and your reader.
# Prompt the user for a grade, get the grade and return it
def get_grade
puts "Enter a grade or type 'done'."
grade = gets.chomp
grade # not needed since the assignment above returns the value of grade
end
# Calculate the grades, given an array of grades
def calculate_average(grades)
total = 0 # running total
grades.each do |grade|
total += grade.to_i # total = total + grade
end
total/grades.size
end
# Ge5 the user's name
puts "Please enter your name:"
name = gets.chomp
# Get all grades
grades = [] # array to hold grades
while true
grade = get_grade
# stop if they user enters 'done'
if (grade.downcase == 'done')
break
end
# otherwise add the grade to the array
grades.push grade
end
# Calculate the average
average = calculate_average grades
# Print the answer as instructed
puts "#{ name.upcase }: #{average}" | true |
417608a1f557938d7c58fbb843486dc1e626afbb | Ruby | madnificent/has_barcode | /lib/has_barcode.rb | UTF-8 | 680 | 2.796875 | 3 | [
"MIT"
] | permissive | module HasBarcode
def self.included(mod)
mod.extend(ClassMethods)
end
module ClassMethods
def has_barcode
require 'barby'
require 'barby/outputter/rmagick_outputter'
extend HasBarcode::SingletonMethods
include HasBarcode::InstanceMethods
end
end
module SingletonMethods
# Finds an object, when the barcode is given.
# barcode must be an object that returns a number when to_i calling to_i on it
def find_by_barcode( barcode )
find( barcode.to_i / 1000 )
end
end
module InstanceMethods
# The magical method
def barcode
Barby::Code128C.new( (self.id * 1000).to_s )
end
end
end
| true |
43dd5db4e06c07ea7603a54ecfe85f7d58c69649 | Ruby | nttl22/ruby | /app/controllers/user_controller.rb | UTF-8 | 927 | 2.5625 | 3 | [] | no_license | class UserController < ApplicationController
def new
end
def login
end
def login_handle
user = User.find_by email: params[:user][:email].downcase
if user && user.authenticate(params[:user][:password])
session[:email] = user.email
flash[:success] = "Đăng nhập thành công!"
redirect_to :root
else
flash[:danger] = "Email hoặc mật khẩu không đúng!"
render :login
end
end
def create
@user = User.new user_params
if @user.save
flash[:success] = "Đăng ký thành công!"
redirect_to login_path
else
flash[:warning] = "Đăng ký thất bại!"
render :new
end
end
private
def user_params
params.require(:user).permit :firstName, :lastName, :email, :password, :password_confirmation
end
end
| true |
8baf771c7faf3b765be4cfaa15204b89c2da68a6 | Ruby | RianaFerreira/routeplanner | /main.rb | UTF-8 | 3,109 | 3.34375 | 3 | [] | no_license | require 'sinatra'
# require 'pry'
# require 'sinatra/reloader'
# stations per line
subway = {
"N Line" => ["Times Square","34th","28th on the N","Union Square","8th on the N"],
"L Line" => ["8th","6th","Union Square","3rd","1st"],
"6 Line" => ["Grand Central","33rd","28th","23rd","Union Square","Astor Place"]
}
# display the home page of the MTA application
get '/' do
@subway = subway
@route = []
erb :form
end
# the form submits the start and end values in a hash
post '/route' do
@subway = subway
# get the route value stored for the start key
@start = params[:start]
# get the route value stored for the end key
@end = params[:end]
# determine the stations on the route
# split the start value into line and station stored in an array
journey_start = @start.split(',')
journey_end = @end.split(',')
start_line = journey_start[0]
start_station = journey_start[1]
end_line = journey_end[0]
end_station = journey_end[1]
# determine the number of stops based on the route array
# return to the root path and display the journey stops
@route = route_info(start_line, start_station, end_line, end_station, subway)
erb :form
end
def route_info(start_line, start_station, end_line, end_station, subway)
# use to store the route stops
route = []
# find the intersecting station where the users should change lines
interchange = (@subway[start_line] & @subway[end_line]).first
# check where the route starts on the line because if it's stored in an array it's read from pos 0 up
start_index = subway[start_line].index(start_station)
end_index = subway[end_line].index(end_station)
start_interchange_index = subway[start_line].index(interchange)
end_interchange_index = subway[end_line].index(interchange)
unless start_station == end_station
# if the journey starts and ends on the same line
if start_line == end_line
# determine direction of journey on the line
if start_index > end_index
#starting from the end of the line
route = subway[start_line].slice(end_index..start_index).reverse
else
# starting from the begining of the line
# extract the route and return it
route = subway[start_line].slice(start_index..end_index)
end
else
# if the journey starts and ends on different lines
# determine the direction of journey to the interchange
if start_index < start_interchange_index
route = route + subway[start_line].slice(start_index..start_interchange_index)
else
route = route + subway[start_line].slice(start_interchange_index..start_index).reverse
end
#determine the direction of the journey from the interchange
if end_interchange_index < end_index
route = route + subway[end_line].slice(end_interchange_index..end_index)
#raise subway[end_line].slice(end_index..end_interchange_index).inspect
else
#raise 'err'
route = route + subway[end_line].slice(end_index..end_interchange_index).reverse
end
end
end
route
end | true |
e7d8e2aef32819cfc37e09d1136b4d844929d22f | Ruby | krasho/blog | /app/services/post_service.rb | UTF-8 | 219 | 2.5625 | 3 | [] | no_license | class PostService
attr_reader :service
def new
@service = Post.new
end
def all
@service = Post.order("publish_date DESC").all
end
def find (id)
@service = Post.find id
end
end
| true |
9166b31cc8e70b400145180a8555f10201eba2af | Ruby | camcarter131/aA-Homeworks | /W2D4/octopus.rb | UTF-8 | 1,590 | 4 | 4 | [] | no_license |
fishes = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh']
def sluggish(arr)
sorted = false
while !sorted
sorted = true
(0...arr.length-1).each do |i|
if arr[i].length > arr[i+1].length
arr[i], arr[i+1] = arr[i+1], arr[i]
sorted = false
end
end
end
arr[-1]
end
def dominant(arr, &prc)
return arr if arr.length <= 1
mid = arr.length / 2
merge(
dominant(arr.take(mid), &prc),
dominant(arr.drop(mid), &prc),
&prc
)
end
def merge(left, right, &prc)
merged = []
prc = Proc.new { |num1, num2| num1.length <=> num2.length } unless block_given?
until left.empty? || right.empty?
case prc.call(left.first, right.first)
when -1
merged << left.shift
when 0
merged << left.shift
when 1
merged << right.shift
end
end
merged + left + right
end
def clever(arr)
longest = arr.first
arr.each do |fish|
longest = fish if fish.length > longest.length
end
longest
end
tiles_array = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up" ]
def slow_dance(dir, tiles)
tiles.each_with_index do |direction, i|
return i if dir == direction
end
end
# putting the tiles into a hash
tiles_hash = {}
tiles_array.each_with_index do |dir, i|
tiles_hash[dir] = i
end
def fast_dance(dir, tiles)
tiles[dir]
end
p fast_dance("up", tiles_hash)
p fast_dance("right-down", tiles_hash)
| true |
b3b0b7f6b840d13fe2cd9b7ebb5d0c3101e82e17 | Ruby | darkmyst/project-euler | /002/project-002.rb | UTF-8 | 153 | 3.171875 | 3 | [] | no_license | total = 0
last = 1
current = 1
while current <= 4000000
total += current if current % 2 == 0
last, current = current, current + last
end
puts total
| true |
414b9d07871a395e52b2d4664c44290c1fcaebc7 | Ruby | rahmaniansyah/elxgo-ruby-intermediet | /week-4/homework/models/order.rb | UTF-8 | 279 | 2.765625 | 3 | [] | no_license | require '../db/mysql_connector.rb'
class Order
attr_accessor :reference_no , :customer_name , :date, :items
def initialize(param)
@reference_no = param[:reference_no ]
@customer_name = param[:customer_name ]
@date = param[:date]
end
end | true |
5d561d82c4fed6e02c6bc544416c1dbc2421221e | Ruby | brantwellman/Turing-task-manager | /test/models/task_manager_test.rb | UTF-8 | 3,019 | 2.875 | 3 | [] | no_license | require_relative '../test_helper'
class TaskManagerTest < Minitest::Test
# def create_tasks(num)
# num.times do |n|
# TaskManager.create({:title => "a title#{n+1}", :description => "a description#{n+1}"})
# end
# end
def test_task_can_be_created
TaskManager.create({ title: "Do it!",
description: "This must be done."})
task = TaskManager.find(1)
assert_equal "Do it!", task.title
assert_equal "This must be done.", task.description
assert_equal 1, task.id
end
def test_it_can_find_all_tasks
TaskManager.create({ title: "Do it!",
description: "This must be done."})
TaskManager.create({ title: "Drink!",
description: "This is optional."})
TaskManager.create({ title: "Eat!",
description: "When you are hungry"})
tasks = TaskManager.all
task1 = tasks[0]
task2 = tasks[1]
task3 = tasks[2]
assert_equal 3, tasks.count
assert_equal "Do it!", task1.title
assert_equal "Drink!", task2.title
assert_equal "When you are hungry", task3.description
assert_equal 1, task1.id
end
def test_it_finds_an_existing_task
TaskManager.create({ title: "Do it!",
description: "This must be done."})
TaskManager.create({ title: "Drink!",
description: "This is optional."})
TaskManager.create({ title: "Eat!",
description: "When you are hungry"})
task1 = TaskManager.find(2)
task2 = TaskManager.find(3)
assert_equal "Drink!", task1.title
assert_equal "When you are hungry", task2.description
end
def test_it_updates_an_existing_task_and_doesnt_modify_other_tasks
TaskManager.create({ title: "Drink!",
description: "This is optional."})
TaskManager.create({ title: "Eat!",
description: "When you are hungry"})
TaskManager.update(1, { title: "Consume",
description: "Everyone must do it"})
task1 = TaskManager.find(1)
task2 = TaskManager.find(2)
assert_equal "Consume", task1.title
assert_equal "Everyone must do it", task1.description
assert_equal "Eat!", task2.title
end
def test_it_destroys_an_existing_task_without_destroying_other_tasks
TaskManager.create({ title: "Do it!",
description: "This must be done."})
TaskManager.create({ title: "Drink!",
description: "This is optional."})
TaskManager.create({ title: "Eat!",
description: "When you are hungry"})
tasks1 = TaskManager.all
TaskManager.delete(1)
tasks2 = TaskManager.all
task2 = TaskManager.find(3)
task3 = TaskManager.find(2)
assert_equal 3, tasks1.count
assert_equal 2, tasks2.count
assert_equal "Eat!", task2.title
assert_equal "Drink!", task3.title
assert tasks2.none? { |task| task.title == "Do it!" }
end
end
| true |
a480cc175e6805ad530e61c694b4b80cb17bf105 | Ruby | AndreaGarofoli/CosmicParser | /cosmp.rb | UTF-8 | 838 | 2.75 | 3 | [] | no_license | # Parsa un file .vcf e genera un file di testo con: cromosoma, posizione e
# il rapporto del n° di riscontri di mutazioni di questo tipo su tutte
# le mutazioni studiate
class VCFp
attr_reader :m
attr_writer :m
def rimc(i)
c=0
m=open(i).readlines.map{ |i| i.chomp.to_s}
m.size.times{ |x|
if m[x][0]=="#" then m[x]=NIL
else
m[x]=m[x].split("\t")
c=c+m[x][7].partition('CNT=').last.to_i
end
}
m=m.compact
m.delete_if {|x| x == nil}
m.size.times{ |x|
m[x][2]=m[x][5]=m[x][6]=m[x][3]=m[x][4]=""
m[x][7]="#{m[x][7].partition('CNT=').last.to_i}/#{c}"
m[x]=m[x].join("\t")
}
File.open("out.txt", "w") {|f| f.write(m.join("\n"))}
end
end
a=VCFp.new
a.rimc("cosm.vcf")
| true |
55695a8095ddc1ddb111ffa617ec16e2a64c0984 | Ruby | sqwiggle/switchboard | /lib/switchboard/router.rb | UTF-8 | 774 | 2.78125 | 3 | [
"MIT"
] | permissive | module Switchboard
class Router
include Singleton
attr_accessor :default_adapter
def self.default_adapter=(val)
self.instance.default_adapter = val
end
def self.routes
self.instance.routes
end
def self.route(key, &block)
routes << Route.new(key, block)
end
def self.get(key)
routes.select { |route| route.key == key }.tap do |route|
raise RouteNotFoundError.new(key) if route.empty?
end
end
def routes
@routes ||= []
end
def clear!
#this method just makes testing easier
#perhaps a smell that the singleton complicates the code
#the singleton definitely keeps the DSL sharp though
self.default_adapter = nil
@routes = []
end
end
end
| true |
94acc8ee8dd5cc874b34948881f5762ba4440768 | Ruby | azarei/ruby_training | /pantry.rb | UTF-8 | 405 | 3.34375 | 3 | [] | no_license | class Ingredient
#Sets up my ingredients
attr_reader :name, :type
def initialize(name, type)
@name = name
@type = type
end
end
class IngredientList < Array
def ingredients
self
end
def add(ingredient)
self << ingredient
end
end
class Pantry < IngredientList
require 'set'
def ingredients
self.to_set.to_a
end
end | true |
d3382f5de928166c4861d9fdbed68c4482f1aa3d | Ruby | jakewendt/my | /scripts/archive/rubyprograms/bird.rb | UTF-8 | 233 | 3.578125 | 4 | [] | no_license | class Bird
def preen
puts "I am cleaning my feathers."
end
def fly
puts "I am flying."
end
end
class Penguin<Bird
def fly
puts "Sorry. I'd rather swim."
end
end
p = Penguin.new
p.preen
p.fly | true |
e39963988587bbca62de6137286a936aa979069a | Ruby | mble/parker | /spec/unit/parker/issue_spec.rb | UTF-8 | 1,049 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe Parker::Issue do
subject { described_class.new }
let(:issue) { double(html_url: 'http://www.example.com', number: '3124', title: 'It broke', created_at: Time.now - 432_000) }
describe '#open_for_days' do
it 'returns the number of days the issue is open for' do
expect(subject.send(:open_for_days, issue)).to eq(5)
end
end
describe '#hipchat_issues_info' do
let(:issues) { [issue] }
it 'returns a string containing the url of an issue' do
expect(subject.hipchat_issues_info(issues)).to include('http://www.example.com')
end
it 'returns a string containing the number of an issue' do
expect(subject.hipchat_issues_info(issues)).to include('3124')
end
it 'returns a string containing the title of an issue' do
expect(subject.hipchat_issues_info(issues)).to include('It broke')
end
it 'returns a string containing the number of days an issue has been open for' do
expect(subject.hipchat_issues_info(issues)).to include('5')
end
end
end
| true |
074ca2a7d315a739dadd863bfec1aa24a937d06f | Ruby | biscar/patterns | /lib/expressions/and_exp.rb | UTF-8 | 694 | 2.953125 | 3 | [
"MIT"
] | permissive | module Expressions
class AndExp < Expressions::BooleanExp
def post_initialize(args = {})
@boolean_exp1 = args[:boolean_exp1]
@boolean_exp2 = args[:boolean_exp2]
end
def evaluate(context)
boolean_exp1.evaluate(context) && boolean_exp2.evaluate(context)
end
def replace(name, boolean_exp)
Expressions::AndExp.new(boolean_exp1: boolean_exp1.replace(name, boolean_exp),
boolean_exp2: boolean_exp2.replace(name, boolean_exp))
end
def copy
Expressions::AndExp.new(boolean_exp1: boolean_exp1.copy, boolean_exp2: boolean_exp2.copy)
end
private
attr_reader :boolean_exp1, :boolean_exp2
end
end
| true |
fb4d5e52941868b4017422fb9273a48bf10b5a84 | Ruby | jw20191n/ruby-objects-has-many-through-readme-nyc-clarke-web-082619 | /lib/waiter.rb | UTF-8 | 688 | 3.09375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class Waiter
attr_accessor :name, :yrs_exp
@@all = []
def initialize(name, yrs_exp)
@name = name
@yrs_exp = yrs_exp
@@all << self
end
def new_meal(customer, total, tip)
Meal.new(self, customer, total, tip)
end
def meals
Meal.all.select {|meal| meal.waiter == self}
end
def best_tipper
hightest_tip = 0
meals.select do |meal|
if meal.tip > hightest_tip
hightest_tip = meal.tip
end
end
highest_tip_meal = meals.find {|meal| meal.tip == hightest_tip}
highest_tip_meal.customer
end
def self.all
@@all
end
end | true |
b3a927da814bc71e92e67f34a92e8732412808f7 | Ruby | aibek1392/dumbo-web-051319 | /06-inheritance/lib/mammal.rb | UTF-8 | 233 | 3.171875 | 3 | [] | no_license | class Mammal < Animal
def initialize(name)
super(name)
@warm_blooded = true
end
def sleep
"I'm not an emoji..."
end
def give_live_birth(baby_name)
"I have given birth to a beautiful #{baby_name}"
end
end
| true |
240b7001319205b9c5ab2ed77b3ca3377c8ac5c7 | Ruby | tyranja/rubyist | /self.rb | UTF-8 | 292 | 3.125 | 3 | [] | no_license | class C
def x
puts "This is method x"
puts self
end
def y
puts "This is method y"
puts self
self.x
end
def self.test
puts self
end
#def C.no_dot
#puts "As long as self is C, you can call this method with no dot."
#end
#no_dot
end
# C.no_dot
| true |
5a3202777e6471f14839373afd141440b28ac2ce | Ruby | mskeen/adventofcode | /2015/day23/turing_lock.rb | UTF-8 | 1,604 | 3.40625 | 3 | [] | no_license | class Computer
attr_accessor :registers
PARSER = /((?<instruction>hlf|tpl|inc|jie|jio|jmp) (?<register>a|b)*(, )*(?<offset>[+\-\d]+)*)/
INSTRUCTIONS = {
"hlf" => { cmd: -> (c, reg, off) { c.registers[reg] /= 2; c.jump(1) } },
"tpl" => { cmd: -> (c, reg, off) { c.registers[reg] *= 3; c.jump(1) } },
"inc" => { cmd: -> (c, reg, off) { c.registers[reg] += 1; c.jump(1) } },
"jmp" => { cmd: -> (c, reg, off) { c.jump(off) } },
"jie" => { cmd: -> (c, reg, off) { c.jump(c.registers[reg] % 2 == 0 ? off : 1) } },
"jio" => { cmd: -> (c, reg, off) { c.jump(c.registers[reg] == 1 ? off : 1) } }
}
def initialize(program, a_init = 0, b_init = 0)
@registers = { "a" => a_init, "b" => b_init }
@instructions = program.split("\n")
@stack_pointer = 0
end
def jump(distance)
@stack_pointer += distance.to_i
end
def execute_instruction
if m = @instructions[@stack_pointer].match(PARSER)
# puts "a: #{@registers["a"]} b: #{@registers["b"]} ptr: #{@stack_pointer} #{m["instruction"]} reg: #{m['register']} offset: #{m['offset']}"
INSTRUCTIONS[m["instruction"]][:cmd].call(self, m["register"], m["offset"].to_i)
else
exit "PROGRAM ERROR with offset #{@stack_pointer}: #{@instructions[@stack_pointer.to_i]}"
end
end
def run
loop do
execute_instruction
break if @stack_pointer < 0 || @stack_pointer >= @instructions.size
end
end
end
begin
c = Computer.new(File.read("./input.txt"))
c.run
puts c.registers["b"]
c2 = Computer.new(File.read("./input.txt"), 1)
c2.run
puts c2.registers["b"]
end | true |
be9a098c34d3c94152fb7d53c3ca723b58bd5a7d | Ruby | wipegup/backend_prework | /day_1/lrthw/ex11.rb | UTF-8 | 514 | 4.375 | 4 | [] | no_license | print "How old are you? "
age = gets.chomp
print "How tall are you? "
height = gets.chomp
print "How much do you weigh? "
weight = gets.chomp
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."
### chomp removes the carriage return "\n" from the end of a strings
### `gets` prompts the user for input., and returns a string with a newline
### at the end
print "Where are you from?"
loc = gets.chomp
print "What is your favorite food?"
food = gets.chomp
puts "You're from #{loc} and like #{food}"
| true |
04390762ababa199eb17ac5124895bbba499fcfb | Ruby | mimizotti/date_night | /test/binary_search_tree_test.rb | UTF-8 | 2,862 | 3.390625 | 3 | [] | no_license | gem 'minitest', '~> 5.2'
require 'minitest/autorun'
require 'minitest/pride'
require_relative '../lib/binary_search_tree'
require_relative '../lib/node'
require 'pry'
class BinarySearchTreeTest < Minitest::Test
def test_tree_adds_new_node_and_returns_depth
tree = BinarySearchTree.new
assert_equal(0, tree.insert(61, "Bill & Ted's Excellent Adventure"))
assert_equal(1, tree.insert(16, "Johnny English"))
assert_equal(1, tree.insert(92, "Sharknado 3"))
assert_equal(2, tree.insert(50, "Hannibal Buress: Animal Furnace"))
end
def test_tree_verifies_or_rejects_presence_of_score
tree = BinarySearchTree.new
tree.insert(16, "Johnny English")
tree.insert(92, "Sharknado 3")
tree.insert(50, "Hannibal Buress: Animal Furnace")
assert tree.include?(16)
refute tree.include?(72)
end
def test_tree_reports_depth_where_a_score_appears
tree = BinarySearchTree.new
tree.insert(16, "Johnny English")
tree.insert(92, "Sharknado 3")
tree.insert(50, "Hannibal Buress: Animal Furnace")
assert_equal(1, tree.depth_of(92))
assert_equal(2, tree.depth_of(50))
end
def test_max_returns_highest_score_in_tree
tree = BinarySearchTree.new
tree.insert(16, "Johnny English")
tree.insert(92, "Sharknado 3")
tree.insert(50, "Hannibal Buress: Animal Furnace")
tree.insert(61, "Bill & Ted's Excellent Adventure")
assert_equal({"Sharknado 3"=>92}, tree.max)
end
def test_min_returns_lowest_score_in_tree
tree = BinarySearchTree.new
tree.insert(92, "Sharknado 3")
tree.insert(16, "Johnny English")
tree.insert(50, "Hannibal Buress: Animal Furnace")
tree.insert(61, "Bill & Ted's Excellent Adventure")
assert_equal({"Johnny English"=>16}, tree.min)
end
def test_sort_returns_an_array_of_data_in_ascending_order
tree = BinarySearchTree.new
tree.insert(16, "Johnny English")
tree.insert(92, "Sharknado 3")
tree.insert(50, "Hannibal Buress: Animal Furnace")
tree.insert(61, "Bill & Ted's Excellent Adventure")
assert_equal([{"Johnny English"=>16}, {"Hannibal Buress: Animal Furnace"=>50},
{"Bill & Ted's Excellent Adventure"=>61}, {"Sharknado 3"=>92}], tree.sort)
end
def test_load_where_return_value_is_number_of_movies
tree = BinarySearchTree.new
assert_equal(99, tree.load('../lib/movies.txt'))
end
def test_health_of_tree
skip
tree = BinarySearchTree.new
tree.insert(98, "Animals United")
tree.insert(58, "Armageddon")
tree.insert(36, "Bill & Ted's Bogus Journey")
tree.insert(93, "Bill & Ted's Excellent Adventure")
tree.insert(86, "Charlie's Angels")
tree.insert(38, "Charlie's Country")
tree.insert(69, "Collateral Damage")
assert_equal([[98, 7, 100]], tree.health(0))
assert_equal([[58, 6, 85]], tree.health(1))
assert_equal([[36, 2, 28], [93, 3, 42]], tree.health(2))
end
end
| true |
6b3654c393a8774d13cb174487d528eb88222b49 | Ruby | Beekasha/triangle-classification-onl01-seng-ft-012120 | /lib/triangle.rb | UTF-8 | 832 | 3.5 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Triangle
attr_accessor :length_1, :length_2, :length_3
def initialize(length_1, length_2, length_3)
@length_1 = length_1
@length_2 = length_2
@length_3 = length_3
@sides = [length_1, length_2, length_3]
end
def kind
validate_triangle
if (length_1 == length_2) && (length_2 == length_3)
:equilateral
elsif
(length_1 == length_2) || (length_1 == length_3) || (length_2 == length_3)
:isosceles
else
:scalene
end
end
def validate_triangle
real_triangle = [(length_1 + length_2 > length_3), (length_2 + length_3 > length_1), (length_1 + length_3 > length_2)]
@sides.each do |side|
real_triangle << false if side <= 0
raise TriangleError if real_triangle.include?(false)
end
end
class TriangleError < StandardError
end
end
| true |
7e50fc10d75118ddadc4eccf8338f97a2515ac77 | Ruby | xurde/quizzr | /app/models/quizz.rb | UTF-8 | 2,342 | 2.953125 | 3 | [] | no_license | class Quizz < ActiveRecord::Base
belongs_to :user
belongs_to :winner, :class_name => 'User'
has_many :answers
has_many :clues
validates_presence_of :user_id, :question, :correct_answer
validates_associated :user
after_create :post_to_user_twitter
def is_open?
self.closed_at.nil?
end
def is_solved?
!self.winner_id.nil?
end
def is_won_by?(user)
self.winner == user
end
def is_responded?(user)
!self.response_by(user).nil?
end
def just_solved?
@solved
end
def just_revealed?
@revealed
end
def just_new_clue?
@new_clue
end
def response_by(user)
last_answer = self.answers.find(:first, :conditions => "user_id = #{user.id}" , :order => 'created_at DESC')
if last_answer && (last_answer.created_at >= self.updated_at)
last_answer
else
nil
end
end
def answered_by?(user)
!self.response_by(user).nil?
end
def validate_response(answer) #Validates answers
answer.downcase.normalize == self.correct_answer.downcase.normalize #Compares normalized strings
end
def win!(user) #Validates answers
@solved = true
self.winner_id = user.id
self.closed_at = Time.now
self.save
end
# def close!(user)
# self.closed_by = user.id
# self.closed_at = Time.now
# end
def reveal!
@revealed = true
self.closed_at = Time.now
self.save
end
def add_clue!(clue_text)
clue = Clue.new
clue.quizz = self
clue.text = clue_text
if clue.save
@new_clue = true
self.updated_at = Time.now
self.save
return true
else
return false
end
end
private #private methods
def post_to_user_twitter
if !self.user.twitter_username.nil?
logger.info("DEBUG >>> begin quizzing for #{self.user.login}")
twitter = Twitter::Base.new(self.user.twitter_username, self.user.twitter_password)
twitter.post( question_crop(self.question, 100) + " ♣ http://quizzr.net/#{self.user.login}/quizz/#{self.id.to_s}")
logger.info("DEBUG >>> #{self.user.login} quizzed #{self.question}")
end
end
def question_crop(question, limit)
if question.size > limit
question[0,(limit - 4)] << '...'
else
question
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.