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
1403cbb042125b1617cb7ee524499c0c83788148
Ruby
malachispencer/bookmarks-manager
/lib/bookmark_tag.rb
UTF-8
528
2.765625
3
[]
no_license
require_relative './database_connection.rb' class BookmarkTag attr_reader :tag_id, :bookmark_id def initialize(tag_id:, bookmark_id:) @tag_id = tag_id @bookmark_id = bookmark_id end def self.create(tag_id:, bookmark_id:) result = DatabaseConnection.query( "INSERT INTO bookmarks_tags (tag_id, bookmark_id) VALUES ('#{tag_id}', '#{bookmark_id}') RETURNING tag_id, bookmark_id;" ) BookmarkTag.new( tag_id: result[0]['tag_id'], bookmark_id: result[0]['bookmark_id'] ) end end
true
fb409515a7076e656e624f7285989c9db3765dda
Ruby
abdulrahman86/rubyproject
/lib/singleton.rb
UTF-8
134
2.9375
3
[ "MIT" ]
permissive
class Test def hello puts 'hello' end end class Test2 < Test def hello1 hello end end x = Test2.new() x.hello1
true
0b053c49d82e970ecbbdd6bb95fa9275b6003ed0
Ruby
tienle/cassandra-model
/lib/cassandra-model/types.rb
UTF-8
800
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module CassandraModel class StringType def self.load(v) return '' unless v s = v.to_s s.clone.force_encoding('UTF-8') if (RUBY_VERSION > '1.9' && s.encoding.name.downcase != 'utf-8') s end end class IntegerType def self.load(v) v && v.to_i end end class FloatType def self.load(v) v && v.to_f end end class DatetimeType def self.dump(v) v && v.strftime('%FT%T%z') end def self.load(v) v && ::DateTime.strptime(v, '%FT%T%z') end end class JsonType def self.dump(v) v && ::JSON.dump(v) end def self.load(v) v && ::JSON.load(v) end end class BooleanType def self.dump(v) v ? '1' : '0' end def self.load(v) v == '1' end end end
true
b552b636359f602122c55896eb0ec5a5786f2acc
Ruby
adrienbourgeois/fredwina
/spec/model/dog_spec.rb
UTF-8
2,382
3.28125
3
[]
no_license
require_relative '../../config' RSpec.describe 'dog' do describe 'move' do subject { Dog.new([1,2,'N']) } it { expect(subject).to respond_to(:move) } it 'returns the coord the dog would have if it executes the motion' do expect(subject.move).to eq(Position.new([1,3])) end end describe 'move!' do subject { Dog.new([1,1,'N']) } let(:paddock) { Paddock.new([5,5],[subject]) } it { expect(subject).to respond_to(:move!) } it 'moves the dog to his new position' do subject.move!(paddock) expect(subject.position).to eq(Position.new([1,2])) end context 'when the dog try to go outside the paddock' do subject { Dog.new([5,5,'N']) } let(:paddock) { Paddock.new([5,5],[subject]) } it 'raises an error' do expect{ subject.move!(paddock) }.to raise_error("Dogs have to stay inside of the paddock") end end context 'when a dog try to bump into another dog' do subject { Dog.new([5,4,'N']) } let(:dog2) { Dog.new([5,5,'N']) } let(:paddock) { Paddock.new([5,5],[subject,dog2]) } it 'raises an error' do expect{ subject.move!(paddock) }.to raise_error("Dogs cannot bump into each other") end end end describe 'turn' do subject { Dog.new([1,2,'N']) } it { expect(subject).to respond_to(:turn) } context 'turn to the left' do subject { Dog.new([1,2,'N']) } it "changes the dog's direction" do subject.turn('L') expect(subject.position.direction.west?).to be(true) end end context 'turn to the right' do subject { Dog.new([1,2,'N']) } it "changes the dog's direction" do subject.turn('R') expect(subject.position.direction.east?).to be(true) end end end describe 'execute' do subject { Dog.new([1,2,'N']) } let(:paddock) { Paddock.new([5,5],[subject]) } context 'with M' do it 'calls move' do expect(subject).to receive(:move!) subject.execute(paddock,'M') end end context 'with L or R' do it 'calls turn' do expect(subject).to receive(:turn).with('L') subject.execute(paddock,'L') end end context 'otherwise' do it 'raises an error' do expect{ subject.execute(paddock,'A') }.to raise_error("Invalid order") end end end end
true
7c41b3f0eb9fe7cce199f4837fb540490c57cd8e
Ruby
tracycaruso/MuralWorks
/app/services/instagram_service.rb
UTF-8
752
2.8125
3
[]
no_license
class InstagramService attr_reader :user def initialize(user) @user = user end def get_user_instagrams client = Instagram.client(:access_token => user.token) image_data = [] client.user_recent_media.each do |media| if media.tags == ["harrisburgmuralproject"] image_data << { 'image' => media.images.standard_resolution.url, 'latitude' => get_latitude(media), 'longitude' => get_longitude(media) } end end image_data end def get_latitude(media) if media.location media.location.latitude else nil end end def get_longitude(media) if media.location media.location.longitude else nil end end end
true
bb06edc4fd761fbaec13e4248ab93b1e8338e07a
Ruby
akm/object_pascal_analyzer
/lib/object_pascal_analyzer/pascal_file.rb
UTF-8
657
2.96875
3
[ "MIT" ]
permissive
require "object_pascal_analyzer" require "object_pascal_analyzer/pascal_class" module ObjectPascalAnalyzer class PascalFile attr_reader :klass, :name, :classes def initialize(name) @name = name @classes = [] end def add_class(name) PascalClass.new(self, name).tap{|r| @classes << r} end def find_class(name) @classes.detect{|c| c.name == name} end def class_by(name) find_class(name) || add_class(name) end def to_hash { path: name, classes: classes.map(&:to_hash) } end def functions classes.map(&:functions).flatten end end end
true
3c50d5eaa09c84502a94798f787cb4beacff56dd
Ruby
SalesFunnel/sinatra
/apps/store/data_store.rb
UTF-8
420
2.53125
3
[]
no_license
require 'json' require_relative '../helper/data_helper' class DataStore include DataHelper def initialize(settings) @settings = settings end def get_all_data data_hash = parse_data p @settings.name p 'get all data' data_hash end def update_item p 'do something update' end def delete_item p 'do something delete' end def add_item p 'do something add' end end
true
a09d1cf17e1993c0bbd93b22ce07ed6c6e88e80e
Ruby
Madhanag0pal/Problem_Solving
/Tarifa/tarifa.rb
UTF-8
91
2.65625
3
[]
no_license
bl = x = gets.to_i n = gets.to_i for i in 1..n bl += x - gets.to_i end puts bl
true
c53c51fcdeecc2ccf8158b310ae783b5fd8af93d
Ruby
jordandavidson1990/homework_3
/exercise_c_uk.rb
UTF-8
1,394
3.6875
4
[]
no_license
united_kingdom = [ { name: "Scotland", population: 5295000, capital: "Edinburgh" }, { name: "Wales", population: 3063000, capital: "Swansea" }, { name: "England", population: 53010000, capital: "London" } ] # 1. Change the capital of Wales from `"Swansea"` to `"Cardiff"`. a = united_kingdom[1][:capital] a.replace("Cardiff") # 2. Create a Hash for Northern Ireland and add it to the `united_kingdom` array (The capital is Belfast, and the population is 1,811,000). northern = [name: "Northern Ireland", population: 1811000, capital: "Belfast"] ul_uk = united_kingdom + northern p ul_uk # 3. Use a loop to print the names of all the countries in the UK. for capital in united_kingdom p capital end # 4. Use a loop to find the total population of the UK. # def count_eggs(array) # total_eggs = 0 # # for bird in array # total_eggs += bird[:eggs] # # bird[:eggs] = 0 # end # return total_eggs.to_s() + " eggs colleted" # end a = united_kingdom[0][:population] b = united_kingdom[1][:population] c = united_kingdom[2][:population] d = united_kingdom[3][:population] countries_pop = [a, b, c, d] # def count(array) # for def count_population(countries_pop) total_population = 0 for population in countries_pop total_population += population end return total_population.to_s() end p count_population(united_kingdom)
true
f6a2d6cc989fb73d3ccff774430dd91876d310de
Ruby
chameleon-bi/chambi_oa
/app/validators/url_validator.rb
UTF-8
549
2.578125
3
[ "MIT" ]
permissive
# Custom validator to validate URLs class UrlValidator < ActiveModel::EachValidator # Validates URLs to include full protocol, subdomain, domain, TLD (or sTLD) def validate_each(record, attribute, value) unless value =~ URL_REGEX record.errors[attribute] << (options[:message] || 'is not a valid web address') end return nil if value.blank? record.errors[attribute] << 'must include http:// or https://' unless value.include?('http') record.errors[attribute] << 'cannot contain commas' if value.include?(',') end end
true
54247f5bbc7c7a825c2b9e6d5bcc9fc957039dde
Ruby
ckhsponge/railsvendor
/vendor/plugins/active_merchant/lib/active_merchant/billing/credit_card.rb
UTF-8
5,298
2.984375
3
[ "MIT" ]
permissive
require 'time' require 'date' require 'active_merchant/billing/expiry_date' module ActiveMerchant #:nodoc: module Billing #:nodoc: # == Description # This credit card object can be used as a stand alone object. It acts just like an ActiveRecord object # but doesn't support the .save method as its not backed by a database. # # For testing purposes, use the 'bogus' credit card type. This card skips the vast majority of # validations. This allows you to focus on your core concerns until you're ready to be more concerned # with the details of particular creditcards or your gateway. # # == Testing With CreditCard # Often when testing we don't care about the particulars of a given card type. When using the 'test' # mode in your Gateway, there are six different valid card numbers: 1, 2, 3, 'success', 'fail', # and 'error'. # #-- # For details, see CreditCardMethods#valid_number? #++ # # == Example Usage # cc = CreditCard.new( # :first_name => 'Steve', # :last_name => 'Smith', # :month => '9', # :year => '2010', # :type => 'visa', # :number => '4242424242424242' # ) # # cc.valid? # => true # cc.display_number # => XXXX-XXXX-XXXX-4242 # class CreditCard include CreditCardMethods include Validateable ## Attributes cattr_accessor :require_verification_value self.require_verification_value = true # Essential attributes for a valid, non-bogus creditcards attr_accessor :number, :month, :year, :type, :first_name, :last_name # Required for Switch / Solo cards attr_accessor :start_month, :start_year, :issue_number # Optional verification_value (CVV, CVV2 etc). Gateways will try their best to # run validation on the passed in value if it is supplied attr_accessor :verification_value # Provides proxy access to an expiry date object def expiry_date ExpiryDate.new(@month, @year) end def expired? expiry_date.expired? end def name? first_name? && last_name? end def first_name? !@first_name.blank? end def last_name? !@last_name.blank? end def name "#{@first_name} #{@last_name}" end def verification_value? !@verification_value.blank? end # Show the card number, with all but last 4 numbers replace with "X". (XXXX-XXXX-XXXX-4338) def display_number self.class.mask(number) end def last_digits self.class.last_digits(number) end def validate validate_essential_attributes # Bogus card is pretty much for testing purposes. Lets just skip these extra tests if its used return if type == 'bogus' validate_card_type validate_card_number validate_verification_value validate_switch_or_solo_attributes end def self.requires_verification_value? require_verification_value end private def before_validate #:nodoc: self.month = month.to_i self.year = year.to_i self.number = number.to_s.gsub(/[^\d]/, "") self.type.downcase! if type.respond_to?(:downcase) self.type = self.class.type?(number) if type.blank? end def validate_card_number #:nodoc: errors.add :number, "is not a valid credit card number" unless CreditCard.valid_number?(number) unless errors.on(:number) || errors.on(:type) errors.add :type, "is not the correct card type" unless CreditCard.matching_type?(number, type) end end def validate_card_type #:nodoc: errors.add :type, "is required" if type.blank? errors.add :type, "is invalid" unless CreditCard.card_companies.keys.include?(type) end def validate_essential_attributes #:nodoc: errors.add :first_name, "cannot be empty" if @first_name.blank? errors.add :last_name, "cannot be empty" if @last_name.blank? errors.add :month, "is not a valid month" unless valid_month?(@month) errors.add :year, "expired" if expired? errors.add :year, "is not a valid year" unless valid_expiry_year?(@year) end def validate_switch_or_solo_attributes #:nodoc: if %w[switch solo].include?(type) unless valid_month?(@start_month) && valid_start_year?(@start_year) || valid_issue_number?(@issue_number) errors.add :start_month, "is invalid" unless valid_month?(@start_month) errors.add :start_year, "is invalid" unless valid_start_year?(@start_year) errors.add :issue_number, "cannot be empty" unless valid_issue_number?(@issue_number) end end end def validate_verification_value #:nodoc: if CreditCard.requires_verification_value? errors.add :verification_value, "is required" unless verification_value? end end end end end
true
6d348d1858b412d796be066753650d425de8e1c3
Ruby
spoonm/idarub
/demos/gameoflif.rb
UTF-8
1,106
3.890625
4
[]
no_license
#!/usr/bin/env ruby # # Game of life yo # # circular board # crappy and sloppy implementation, don't reuse for anything # class GameOfLif attr_accessor :board def self.new_random(height, width) new((0..height).map { (0..width).map { rand(2) } }) end def initialize(_board = [[]]) self.board = _board end def num_neighbors(y, x) h, w = height, width board[y - 1 ][x - 1 ] + board[y - 1 ][x ] + board[y - 1 ][(x+1)%w] + board[y ][x - 1 ] + board[y ][(x+1)%w] + board[(y+1)%h][x-1 ] + board[(y+1)%h][x ] + board[(y+1)%h][(x+1)%w] end def alive?(y, x) board[y][x] == 1 end def height board.length end def width board[0].length end def output str = '' board.each do |col| col.each do |cell| str << (cell == 0 ? ' ' : '*') end str << "\n" end return str end def next_board (0..height-1).map do |y| (0..width-1).map do |x| n = num_neighbors(y, x) if alive?(y, x) (n == 2 || n == 3) ? 1 : 0 else (n == 3) ? 1 : 0 end end end end def step self.board = next_board end end
true
f7c15de768549e2da6bdd29cad43f9bd0704b461
Ruby
crabtw/home-config
/bin/seq-rename
UTF-8
1,159
3.015625
3
[]
no_license
#!/usr/bin/env ruby require 'optparse' def nat_ord s s.split(/(\d+)|(\D+)/).select {|c| c != ''}.map do |c| x = c.to_i x > 0 || c[0] == '0' ? x : c end end class Fixnum alias :old_cmp :<=> def <=> a case a when Fixnum then old_cmp a when String then -1 end end end class String alias :old_cmp :<=> def <=> a case a when String then old_cmp a when Fixnum then 1 end end end if __FILE__ == $0 options = {} OptionParser.new do |opts| opts.on('-s', '--start N', Integer, 'Start number (default 1)') {|v| options[:start] = v} opts.on('-l', '--len N', Integer, 'Minimal length (default log10(number of files) + 1)') {|v| options[:len] = v} opts.on('-d', '--dryrun', 'Don\'t rename files') {options[:dryrun] = true} end.parse! i = options[:start] || 1 len = options[:len] || Math.log10(ARGV.size).floor + 1 ARGV.sort_by {|f| nat_ord f}.each do |old| ext = File.extname old new = i.to_s.rjust(len, '0') new << '_' while File.exist?(new + ext) new += ext puts "#{old} => #{new}" File.rename(old, new) unless options[:dryrun] i += 1 end end
true
1ffc704dbaeb7553d3e5c4e8b9a3af998b14ad70
Ruby
benjamin-korobkin/Web_Design_Adaleg
/Ruby/fib.rb
UTF-8
326
3.53125
4
[]
no_license
def fib(n) num0 = 0 num1 = 1 if n == 1 then return num0 elsif n == 2 then return num1 else for x in 1..(n-2) do num2 = num0 + num1 num0 = num1 num1 = num2 end end return num2 end puts fib(1) puts fib(2) puts fib(3) puts fib(4) puts fib(5) puts fib(6) puts fib(7) puts fib(8)
true
802fba9256b8e112a43e7b7c2ca72eb5289f7467
Ruby
EDalSanto/LaunchSchool
/exercises/120_OOP/med1/circular_queue.rb
UTF-8
1,490
3.921875
4
[]
no_license
class CircularQueue def initialize(size) @queue = [] @max_size = size end def enqueue(element) dequeue if @queue.size == @max_size @queue.push(element) end def dequeue @queue.shift end end class CircularQueueLONG def initialize(size) @queue = Array.new(size) @next_index = 0 @longest_index = 0 end def update_position(index) index = (index + 1) % @queue.size end def enqueue(element) if @queue.all? { |n| !n.nil? } @longest_index = update_position(@longest_index) end @queue[@next_index] = element @next_index = update_position(@next_index) end def dequeue to_pop = @queue[@longest_index] @queue[@longest_index] = nil @longest_index = update_position(@longest_index) unless to_pop.nil? to_pop end end queue = CircularQueue.new(3) puts queue.dequeue == nil queue.enqueue(1) queue.enqueue(2) puts queue.dequeue == 1 queue.enqueue(3) queue.enqueue(4) puts queue.dequeue == 2 queue.enqueue(5) queue.enqueue(6) queue.enqueue(7) puts queue.dequeue == 5 puts queue.dequeue == 6 puts queue.dequeue == 7 puts queue.dequeue == nil queue = CircularQueue.new(4) puts queue.dequeue == nil queue.enqueue(1) queue.enqueue(2) puts queue.dequeue == 1 queue.enqueue(3) queue.enqueue(4) puts queue.dequeue == 2 queue.enqueue(5) queue.enqueue(6) queue.enqueue(7) puts queue.dequeue == 4 puts queue.dequeue == 5 puts queue.dequeue == 6 puts queue.dequeue == 7 puts queue.dequeue == nil
true
a544db67090bf173598c4e93cd634ddc50831b49
Ruby
hsheikhm/airport_challenge
/lib/plane.rb
UTF-8
274
3.015625
3
[]
no_license
class Plane attr_reader :status, :location def initialize @status = :flying @location = :air end def flying @status = :flying @location = :air self end def landed @status = :landed @location = :airport self end def flying? @status == :flying end end
true
53488fe8865df1c266cda7c97401e37c5a0746bd
Ruby
acantu101/triangle-classification-v-000
/lib/triangle.rb
UTF-8
994
3.1875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Triangle def initialize(a, b, c) @triangle_sides = [] @triangle_sides << a @triangle_sides << b @triangle_sides << c @a = a @b = b @c = c end def valid? sum_one_two = @triangle_sides[0] + @triangle_sides[1] sum_one_three = @triangle_sides[0] + @triangle_sides[2] sum_two_three = @triangle_sides[1] + @triangle_sides[2] if (@triangle_sides.none? {|side| side <= 0}) && sum_one_two > @triangle_sides[2] && sum_one_three > @triangle_sides[1] && sum_two_three > @triangle_sides[0] return true else raise TriangleError return false end end def kind if valid? == true && @a == @b && @b == @c return :equilateral elsif valid? && @a == @b || @b == @c || @a == @c return :isosceles elsif valid? && @a != @b && @b != @c return :scalene else raise TriangleError end end class TriangleError < StandardError end end
true
76d2db878aeffd06342356e5bc714e2d8812d05a
Ruby
runeni/brew-temper
/app.rb
UTF-8
1,105
2.515625
3
[]
no_license
require "sinatra" require "sinatra/activerecord" require "time" require "pp" set :database, "sqlite3:///temper.db" class Measure < ActiveRecord::Base def nice_time self.created_at.strftime("%Y-%m-%d %H:%M") end end get '/measures.json' do content_type :json Measure.all.to_json end get '/measure/:at' do content_type :json Measure.find_by_created_at(params[:at]).to_json end get '/last.json' do content_type :json Measure.last.to_json end get '/measures/:created_at/after.json' do content_type :json created_at = Time.parse(params[:created_at]) Measure.where("created_at >= '#{created_at}'").map{|m| {measure: {created_at: m.nice_time, temp: m.temp}}}.to_json end get '/last' do m = Measure.last "<h1>#{m.created_at} : #{m.temp}</h1>" end get '/graph' do # @temps = Measure.where("created_at > '2013-09-14'").all #@temps = Measure.where("created_at > '2013-09-14' and created_at like '%:00'").all @temps = Measure.where("created_at >= '2013-10-13' and created_at like '%0'").order("id desc").limit(5) erb :graph end get '/countries' do erb :countries end
true
5e0c9e2fb04bcee57bbfedf68c12d525dfbaa74b
Ruby
pmarreck/ruby-snippets
/null_object.rb
UTF-8
305
3.15625
3
[]
no_license
class NullObject def method_missing(*args) self end def initialize @origin = caller.first end def nil?; true; end end def Maybe(value) value.nil? ? NullObject.new : value end foo = nil p Maybe(foo).bar.baz + 5 p NullObject.new || 5 p Maybe('ABC').downcase.strip.tr_s('^a-z0-9', '-')
true
2fb1cd3783241ce808dc45b2faa0d8da050bf972
Ruby
thesilentc/oo-barking-dog-v-000
/lib/dog.rb
UTF-8
275
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Dog attr_accessor :name def bark puts "woof!" end end # class Dog # def name # setter (or writer method?) # @name # end # def name=(dog_name) # getter (or reader method?) # @name = dog_name # end # def bark # puts "woof!" # end # end
true
90298f9d2f52720a796f050f556e7567d1e28554
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/800/feature686/method_source/13944.rb
UTF-8
196
3.28125
3
[]
no_license
def combine_anagrams(words) h = {} words.each do |word| word2 = word.downcase.chars.sort h.has_key?(word2) ? (h[word2] = (h[word2] + [word])) : (h[word2] = [word]) end h.values end
true
05a96354c20f2035f23d82785e012c7619fe3545
Ruby
dugancathal/ladder-board
/app/models/leader_board.rb
UTF-8
488
3.140625
3
[]
no_license
class LeaderBoard attr_reader :points, :rank def initialize(users) @users = users @lowest_rank = 1 @current_board = [] end def rankings current_rank = 1 current_score = @users.first.score number_passed = 0 @users.map do |player| if current_score > player.score current_score = player.score current_rank += number_passed number_passed = 0 end number_passed += 1 [current_rank, player] end end end
true
dd974e752cc60dcc11bb7a406ed35b516fbad60d
Ruby
johnsafe/send_cloud
/lib/send_cloud.rb
UTF-8
3,066
2.5625
3
[ "MIT" ]
permissive
require File.join(File.dirname(__FILE__), 'send_cloud','version.rb') module SendCloud class EmailRecord attr_accessor :api_user,:api_key,:format require 'net/https' require 'uri' def initialize(args={}) args[:format]||='xml' raise ArgumentError.new('user missing') if args[:api_user].nil? raise ArgumentError.new('key missing') if args[:api_key].nil? self.api_key=args[:api_key];self.api_user=args[:api_user];self.format=args[:format] end def method_missing(method,args) # 命名规则:以'_'分割成数组,最后一个元素为动作词,其余的重新以'_'组合成模块名称 motion,model = separate_model_and_motion(method) args.merge!({:api_user => self.api_user, :api_key => self.api_key}) url = "https://sendcloud.sohu.com/webapi/#{model}.#{motion}.#{self.format}" post_api(url, args) end def separate_model_and_motion(method) method_array = method.to_s.split('_') raise ArgumentError.new('method format is wrong!') if method_array.size<2 [method_array.pop,method_array.join('_')] end # 给列表发送 def send_to_list(args) necessary_args = [:subject,:template_invoke_name,:from,:fromname,:use_maillist,:to] url = "https://sendcloud.sohu.com/webapi/mail.send_template.#{self.format}" necessary_args.to_a.each do |key| raise ArgumentError.new("#{key.to_s} is nil") if args[key].nil? end args.merge!({:api_user => self.api_user, :api_key => self.api_key}) post_api(url, args) end # 给一个用户发送 def send_to_user(args) necessary_args = [:subject,:template_invoke_name,:from,:fromname,:substitution_vars] url = "https://sendcloud.sohu.com/webapi/mail.send_template.#{self.format}" necessary_args.to_a.each do |key| raise ArgumentError.new("#{key.to_s} is nil") if args[key].nil? end args.merge!({:api_user => self.api_user, :api_key => self.api_key}) post_api(url, args) end # 普通发送(不使用邮件模板) def send_email(args) necessary_args = [:to,:subject,:html,:from] url = "https://sendcloud.sohu.com/webapi/mail.send.#{self.format}" necessary_args.to_a.each do |key| raise ArgumentError.new("#{key.to_s} is nil") if args[key].nil? end args.merge!({:api_user => self.api_user, :api_key => self.api_key,:use_maillist=>'false'}) post_api(url, args) end private # post 方式 def post_api(api, args) uri = URI.parse api http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true req = Net::HTTP::Post.new(uri.request_uri) req.set_form_data(args) http.request(req).body end # get 方式 def get_api(api, args) uri = URI.parse api uri.query = args.collect { |a| "#{a[0]}=#{URI::encode(a[1].to_s)}" }.join('&') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true req = Net::HTTP::Get.new(uri.request_uri) http.request(req).body end end end
true
48302760e1545fd826f522c02953b408c8a2d317
Ruby
mcs526/RubyExploration
/DaffyDuckified.rb
UTF-8
430
4.1875
4
[]
no_license
print "Your input please: " #.chomp removes the newline that is created as a defult from gets user_input = gets.chomp #the use of the "!" is used so the user_input string is modified-in-place user_input.downcase! if user_input.include? "s" user_input.gsub!(/s/, "th") else print "your phrase can't be Daffy Duckified!" #"end" is always used to end an if else statement end puts "Your phrase Daffy Duckified is #{user_input}"
true
99aca3737d26e6049edd68e78353b75d6da5603e
Ruby
elizabethhyer/grid_monsters_web
/db/seeds.rb
UTF-8
3,100
2.921875
3
[ "MIT" ]
permissive
### SEED DATABASE ### ## Users ## dracula = User.create(:name => "Dracula", :username => "vampman2000", :password => "hooray4blood") the_mummy = User.create(:name => "The King", :username => "linenlover404", :password => "asleep4ages") the_blob = User.create(:name => "The Blob", :username => "huskyguy", :password => "shapeshifter") gelatinous_cube = User.create(:name => "Cube", :username => "gelatinous_cube", :password => "dndnd") the_dark_spirit = User.create(:name => "Dark Spirit", :username => "tall_dark_n_sexy", :password => "dementorsRcool") the_programmer = User.create(:name => "Mr. Roboto", :username => "the_programmer", :password => "StepFord") ## Profiles ## vampy = Profile.create(:name => "Dracula", :species => "vampire", :age => 2000, :bio => "Very busy and very wealthy. Just looking for a nice undead girl to live out my eternity feasting on the innocent with. Last time I did something like this was when Lonely Hearts ads were a thing, and I was catfished by Harry Powers! True story. If you let the right one in, I'll tell you all about it.") thats_a_wrap = Profile.create(:name => "The Mummy King", :species => "undead human", :age => 4100, :bio => "I'm new to this whole dating game, since my partners in the land of the living were all chosen for me. I guess I should say that I live in a museum, so the only thing to eat is the guards who cross the threshold of the mummy, but my decor game is on point. I'm happy to meet at your place though, as long as your sheets are made from linen. I'm very picky.") blobby_knight = Profile.create(:name => "The Blob", :species => "blob", :age => 1, :bio => "I'm really tired of people telling me I don't look the same in person as I do in my photos. Please, I'm just a blob, standing in front of a computer, saying that if you reject me because of my looks, I'm going to get just a little bit blobbier. (I'm going to absorb you, if I hadn't made that clear)") the_gelatinous_curtain = Profile.create(:name => "Gelatinous Cube", :species => "standard DND monster", :age => 1000000000, :bio => "Honestly I am too old for the games... you're either interested or not. Likes: picking fights with bands of travelers; dislikes: vegans.") ghost = Profile.create(:name => "Dark Spirit", :species => "ghost", :age => 30, :bio => "I think there's so much more to be said for how romantic it is to haunt couples on their moonlit walks. Too many other ghosts stick to houses or graveyards, and I just want someone who craves a bit of ADVENTURE and ROMANCE, you know?") roboto = Profile.create(:name => "Mr. Roboto", :species => "humanoid", :age => 45, :bio => "I have no interest in killing you and replacing you with the robots I learned how to build during my tenure at Disney Land. ... So, when would you like to meet?") ## Associations ## vampy.user = dracula vampy.save thats_a_wrap.user = the_mummy thats_a_wrap.save blobby_knight.user = the_blob blobby_knight.save the_gelatinous_curtain.user = gelatinous_cube the_gelatinous_curtain.save ghost.user = the_dark_spirit ghost.save roboto.user = the_programmer roboto.save
true
1bd7aaf957e058b0777134aa10cf8efd9e3c9056
Ruby
viditn91/vinsol-training
/Ruby_exercise/Sales_tax/lib/product.rb
UTF-8
370
2.78125
3
[]
no_license
class Product attr_reader :name, :price, :import_status, :exemption attr_accessor :sales_tax, :price_incld_tax def initialize(name, import_status, exemption, price) @name, @import_status, @exemption, @price = name, import_status, exemption, price end def is_imported? @import_status =~ /yes/i end def is_exempted? @exemption =~ /yes/i end end
true
f474583486844bcd0fc67b9b4bb42c15f2a21c8c
Ruby
jtlai0921/PG20249_example
/PG20249_sample/Ruby268-SampleProgram-UTF8/Ch2/sample038-02.rb
UTF-8
164
2.9375
3
[]
no_license
p "1".to_f #=> 1.0 p "1.2".to_f #=> 1.2 p "a".to_f #=> 0.0 p Float("1") #=> 1.0 p Float("1.2") #=> 1.2 p Float("a") #=> ArgumentError: invalid value for Float: "a"
true
ae39918ab40947c414035c120f792f159dedb95f
Ruby
BettyHoPro/2AllPlayer
/helper.rb
UTF-8
1,239
3.5625
4
[]
no_license
require './game' require './player' require './question' ##--- Game helpers ---## ---> these twos can just be a turn class itself def check_current_player?(current_player, player1, player2, non_current_player) question = Question.new puts "" puts "----- NEW TURN -----" if current_player == 1 @non_current_player = player2 puts "Player #{@current_player}: #{question.ask}" answer = gets.chomp.to_i question.answer_correct?(answer, player1, @non_current_player) switch_player?(@current_player, player1, player2, @non_current_player) else @non_current_player = player1 puts "Player #{@current_player}: #{question.ask}" answer = gets.chomp.to_i question.answer_correct?(answer, player2, @non_current_player) switch_player?(@current_player, player1, player2, @non_current_player) end end def switch_player?(current_player, player1, player2, non_current_player) puts "P1: #{player1.blood}/3 vs P2: #{player2.blood}/3" if current_player == 1 @current_player = 2 check_current_player?(@current_player, player1, player2, non_current_player) else @current_player = 1 check_current_player?(@current_player, player1, player2, non_current_player) end end
true
8bbf0c2c930439ef7af78e002a3c12babcf4c899
Ruby
Shonda860/linked-lists
/lib/linked_list.rb
UTF-8
1,510
3.625
4
[ "MIT" ]
permissive
require_relative "node" class LinkedList attr_reader :head def initialize @head = nil end # Time complexity - O(1) # Space complexity - O(1) def add_first(data) #head starts as nil first = Node.new(data, @head) #(3,nil) @head = first # reassign first to be head # head = 3 return first end # Time complexity - O(1) # Space complexity - O(1) def get_first if @head.nil? #nil will only recongize nil return else @head.data end end # Time complexity - O(n) # Space complexity - O(1) def length current = @head sum = 0 until current.nil? sum += 1 current = current.next end return sum end # Time complexity - O(n) # Space complexity - O(1) def add_last(data) if @head.nil? add_first(data) return end last = Node.new(data) current = @head until current.next.nil? current = current.next end current.next = last end # Time complexity - 0(n) # Space complexity - O(1) def get_last if @head.nil? return nil end current = @head until current.next.nil? current = current.next end return current.data end # Time complexity - O(n) # Space complexity - O(1) def get_at_index(index) if @head.nil? return nil end counter = 0 current = @head until counter == index || current.next.nil? current = current.next counter += 1 end return current.data end end
true
985a6587d7281f0cd98ac4c4f9db33918c6cc57e
Ruby
OMGDuke/learn_to_program
/ch12-new-classes-of-objects/happy_birthday.rb
UTF-8
468
3.78125
4
[]
no_license
def happy_birthday puts "What year were you born in? (ie 1970)" year = gets.chomp puts "What month were you born in? (ie 11)" month = gets.chomp puts "what day were you born on? (ie 26)" day = gets.chomp birthday = Time.local(year,month,day) puts "Your birthday is #{birthday.strftime("%d-%m-%Y")}" age = Time.now - birthday age = age/31622400 puts "You are #{age.to_i} years old" age.to_i.times do puts "SPANK!" end end happy_birthday
true
6839b81f7c4d48e32e6d38a8bf2e43f5d4f39112
Ruby
veloso/aiqueburro
/aiqueburro.rb
UTF-8
2,691
2.703125
3
[]
no_license
#!ruby19 # encoding: utf8 # author: tiago veloso require 'rubygems' require 'twitter' @config = YAML::load(File.open('/opt/aiqueburro/config.yml')) #abre o config.yml somente-leitura na memória @config2 = YAML::load(File.open('/opt/aiqueburro/config_1.yml', 'r+')) #r+ significa leitura e escrita httpauth = Twitter::HTTPAuth.new(@config['user'], @config['passwd']) #autentica com o Twitter @aiqueburro = Twitter::Base.new(httpauth) #cria novo objeto da classe Twitter e atribuiu à variável @aiqueburro def twitta(msg,id) if msg.length<=140 #option = ":in_reply_to_status_id => #{id}" #exemplo de uso de JSON (que não funciona, aliás ;~) @aiqueburro.update(msg) #,query={} puts msg end end def atualizabaseusuarios() File.open('/opt/aiqueburro/config_1.yml', 'r+') do |file| YAML.dump(@config2, file) end puts "Base atualizada." end puts "--" puts "Início: #{Time.now}" system "notify-send aiqueburro-inicio" puts "--" nvezes = @config['termoerrado'].size #todos os termos #nvezes = 10 #define quantos termos serão pesquisados, sequencialmente e em ordem decrescente nvezes.times do #numerotermo = rand(@config['termoerrado'].size)+1 # usa os termos aleatoriamente, não sequencialmente numerotermo = nvezes #procura por todas os termos, não por um número limitado termoerrado = @config['termoerrado'][numerotermo] termocerto = @config['termocerto'][numerotermo] pesquisa = "\""+termoerrado+"\" -RT -@aiqueburro -formspring.me -from:#{@config['user']}" ultimousuario = @config2['ultimo'][numerotermo] quantostweets = 10 mensagens = Twitter::Search.new(pesquisa).since(ultimousuario).per_page(quantostweets) #per_page() - até quantas correções (tweets enviados) ele vai fazer pra cada termo puts "Pesquisando por \"#{termoerrado}\"..." puts "O último a dizer foi #{ultimousuario}" xvezes=0 #POG mensagens.each do |msg| #if msg.from_user == ultimousuario then break end # para a iteração quando alcança o usuário já corrigido frase = @config['frase'][rand(@config['frase'].size)+1] #@usuario = msg.from_user id = msg.id # pegar o id do tweet puts "id = #{id}" msg = ("@#{msg.from_user} \"#{termoerrado}\"?! #{frase} O certo é: #{termocerto}!") twitta(msg,id) #begin POG puts "xvezes antes = #{xvezes}" if xvezes==0 then @config2['ultimo'][numerotermo] = id end #define que o usuário que ele passou foi o último xvezes+=1 puts "xvezes depois = #{xvezes}" # end POG atualizabaseusuarios() end nvezes-=1 puts "nvezes = #{nvezes}" puts "--" end atualizabaseusuarios() puts "Fim: #{Time.now}" system "notify-send aiqueburro-fim"
true
ac6dbd5c75653b0d0d86188abae9eefd5d316838
Ruby
ga-wolf/wdi-21
/05-ruby/loops/loop.rb
UTF-8
1,233
4.125
4
[]
no_license
# while some_condition # # Some code to execute # end # while true # puts "This isn't that bad of an idea" # end # Infinite loops aren't as bad as JS, CTRL + C is to quit # Loops # Starting Point # Increment or a Step # End Condition # i = 0 # while i <= 5 # puts "I: #{i}" # i += 1 # end # # x = 5 # while x >= 1 # puts "X: #{x}" # x -= 1 # end # countdown = 5 # # Until the condition evaluates to true, keep running it # until countdown == 0 # puts countdown # countdown -= 1 # end # puts "Blast off!" # ITERATORS # 5.times do |i| # puts "This happened: #{i}" # end # # 10.times do |index| # puts "An iteration ran. Index: #{index}" # end 5.downto(1) do |num| # puts "An iteration ran. Num: #{num}" end start = 4 end_num = 8 start.upto(end_num) do |current_num| # puts "Current Num: #{current_num}" end for i in 1..5 # Generate an inclusive range puts "Index: #{i}" end p Random.rand() # => random number between 0 and 1 p Random.rand( 10 ) # => random integer up to 10 p Random.rand( 15.0 ) # => random float up to 10 p Random.rand( 10..20 ) # => random integer between 10 and 20 (inclusive range) p Random.rand( 3...19 ) # => random integer between 3 and 18 (exclusive range)
true
f0702ef74daa66eaba05b7fd490cc558aae60b3f
Ruby
rockshandy/raildoku
/app/controllers/sudoku_controller.rb
UTF-8
4,330
2.734375
3
[]
no_license
require 'local_search' class SudokuController < ApplicationController include LocalSearch def index @board = Board.new #example end # stat a new board, should be ajax, perhaps should start solving in background def init # the javascript puts an extra comma at end so get rid of it #val = Board.generate_value(params[:board][:value].chomp(',')) #TODO: try to make this an initialize thing? @board = Board.new(params[:board]) #@board = Board.new() @board.value = Board.generate_value(@board.value.chomp(','), @board.width, @board.height) if @board.save head :created else render :json => {:error => @board.errors} end end # should be ajax call eventually to the background def solve @board = Board.new(params[:board]) @board.value = Board.generate_value(@board.value.chomp(','), @board.width, @board.height) puts 'running the local search' # height and width flipped since passing the number of blocks not dimensions # this just happens to work that way solve = (solve_sudoku(@board.value, :xblks => @board.height,:yblks => @board.width)); if solve['error'] render :json => {:error => solve['error']} else @sol = Solution.new(:value=>solve['board']) @board.solutions << @sol # TODO: May want to return the board that was passed in so can check if that's what originally entered?' @board.save # TODO: make the local search return what the board was if a limit was reached solve['board'] = @sol.decode render :json => solve end end def hint value = Board.generate_value(params[:value].chomp(','), params[:width], params[:height]) data = create_node_consistent_board(value, params[:height].to_i, params[:width].to_i) render :json => data end # TODO: add a save button to keep saving boards perhaps and put in sessions def update end # Easy test setup to run the boards for our report def test #each board is an array entry, the comma string simple board representation cases = [ # 2x2 blocks example for completeness, solves with constraints '1,2,3,,,4,,,,,1,,2,,,0', # 3x2 blocks example to show unsymettric solving ability '1,,,,,,,3,,,,,,,6,,,,,,,1,,,4,,,,2,,6,,,,,4', # easy 3x3 block from hw '6,,,7,,3,,,9,2,,,,,,,,4,,3,,9,,1,,2,,,5,,2,,6,,8,,8,,,,3,,,,2,,1,,4,,9,,6,,,2,,5,,4,,7,,3,,,,,,,,6,1,,,3,,7,,,5', # medium 3x3 blocks from hw '1,9,,,6,,7,,8,,,,,,7,,,5,7,,,2,3,,,,,,1,,,,,5,,,3,,6,,,,4,,9,,,9,,,,,7,,,,,,1,5,,,3,5,,,9,,,,,,9,,3,,7,,,5,2', # hard 3x3 blocks from hw '9,,,4,,,6,,,,,7,,,,,,3,,,,1,2,,,,,1,2,,,4,3,,5,,7,,,,,,,,4,,4,,7,6,,,8,9,,,,,7,1,,,,6,,,,,,9,,,,,4,,,8,,,2' # A 4x4 block puzzle for the heck of it ] lengths = [[2,2],[3,2],[3,3],[3,3],[3,3]] errs = [] cases.each_with_index do |val, i| puts lengths[i][0].to_s + lengths[i][1].to_s @board = Board.new(:value => Board.generate_value(val, lengths[i][0], lengths[i][1]), :width => lengths[i][0], :height => lengths[i][1]) @board.save # for loop through heuristics, minConflicts and the default better heuristic ['minConflicts', nil].each do | hn | solve = (solve_sudoku(@board.value, :xblks => @board.height, :yblks => @board.width, :heuristic => hn)); if solve['error'] errs.push "@#{i},#{hn || 'mostConstrained'}: " + solve['error'] @sol = Solution.new(:time => solve['time'], :generated => solve['num_boards'], :hn => hn || 'mostConstrained' ) else @sol = Solution.new(:value=> solve['board'], :time => solve['time'], :generated => solve['num_boards'], :hn => hn || 'mostConstrained') @board.solutions << @sol # TODO: May want to return the board that was passed in so can check if that's what originally entered?' @board.save puts "\n" end end end render :index end end
true
4f75216f4f0012c99c5e5099b07e84b334180e81
Ruby
NUBIC/katas
/anagrams/anagram_runner.rb
UTF-8
520
3
3
[]
no_license
require File.expand_path("../anagram", __FILE__) require 'benchmark' require 'benchmark/ips' word_list = File.readlines("wordlist.txt").collect(&:chomp) Benchmark.ips do |suite| [(1000..1010), (1000..1100), (1000..2000), (1000..11000), (0..-1)].each do |range| suite.report("sets #{range.inspect} #{range.last - range.first}") do Anagram.new(word_list[range]).sets end end end Benchmark.bm do |suite| suite.report("on word list file") do Anagram.new(File.new("wordlist.txt")).sets end end
true
902a2ac88a49c012f45c115db8830aadcda91e94
Ruby
nateReiners/minesweeper
/minesweeper.rb
UTF-8
1,148
3.453125
3
[]
no_license
require_relative 'board' class Minesweeper attr_reader :board def initialize(board = Board.new) @board = board end def valid_move?(pos) pos.is_a?(Array) && pos.length == 2 && !board.grid[pos[0]][pos[1]].visible end def make_move(pos) board.grid[pos[0]][pos[1]].make_visible end def play_turn board.render pos = nil until valid_move?(pos) puts "enter coordinates as 'x,y' to 'click' a square" pos = gets.chomp.split(",").map(&:to_i) end make_move(pos) # need to fix this method!!!! board.reveal_all_adj(pos) end def run play_turn until won? || game_over? board.render if won? puts "You Win!" else puts "You lost!" end end def game_over? board.grid.each do |row| bombs = row.select { |el| el.bomb } return true if bombs.any? { |el| el.visible } end false end def won? board.grid.each do |row| non_bombs = row.reject { |el| el.bomb } return true if non_bombs.all? { |el| el.visible } end false end end if __FILE__ == $PROGRAM_NAME x = Minesweeper.new x.run end
true
cf25fb5661d2709bfefa335c73992b0d6669444c
Ruby
mairon/pratic
/vendor/plugins/brazilian-rails/brnumeros/lib/brnumeros/number_portuguese.rb
UTF-8
4,526
2.8125
3
[ "MIT" ]
permissive
# encoding: UTF-8 module Extenso @@unidade = { 0 => "CERO", 1 => "UN", 2 => 'DOS', 3 => "TRES", 4 => "CUATRO", 5 => "CINCO", 6 => "SEIS", 7 => "SIETE", 8 => "OCHO", 9 => "NUEVE", } @@dezena = { 10 => "DIEZ", 11 => "ONCE", 12 => "DOCE", 13 => "TRECE", 14 => "CATORCE", 15 => "QUINCE", 16 => "DIECISEIS", 17 => "DIECISIETE", 18 => "DIECIOCHO ", 19 => "DIECINUEVE", 20 => "VEINTE", 30 => "TREINTA", 40 => "CUARENTA", 50 => "CINCUENTA", 60 => "SESENTA", 70 => "SETENTA", 80 => "OCHENTA", 90 => "NOVENTA" } @@centena = {100 => "CIEN", 200 => "DOSCIENTOS", 300 => "TRESCIENTOS", 400 => "CUATRO", 500 => 'QUINIENTOS', 600 => "SEISCIENTOS", 700 => "SETECIENTOS", 800 => "OCHOCIENTOS", 900 => "NOVECIENTOS"} # Escreve o numero por extenso. # # Exemplo: # 1.por_extenso ==> 'um' # 100.por_extenso ==> 'cem' # 158.por_extenso ==> 'cento e cinquenta e oito' def por_extenso Extenso.por_extenso(self) end # Alias para o metodo por_extenso alias_method :to_extenso, :por_extenso # Escreve o numero por extenso. # # Exemplo: # Extenso.por_extenso(1) ==> "um" # Extenso.por_extenso(100) ==> "cem" # Extenso.por_extenso(158) ==> "cento e cinquenta e oito" def Extenso.por_extenso(numero) negativo=(numero<0)? "menos " : "" n=numero.to_i.abs return case n when 0..9 then negativo + @@unidade[n].to_s when 10..19 then negativo + @@dezena[n].to_s when 20..99 v=n % 10 if v== 0 negativo + @@dezena[n].to_s else "#{negativo}#{@@dezena[n-v]} y #{por_extenso(v)}" end when 100 negativo+"CIEN" when 101..999 v=n % 100 if v== 0 negativo + @@centena[n].to_s else "#{negativo}#{@@centena[n-v]} Y #{por_extenso(v)}" end when 1000..999999 m,c=n/1000,n%1000 %(#{negativo}#{por_extenso(m)} MIL#{c > 0 ? " Y #{por_extenso(c)}":''}) when 1_000_000..999_999_999 mi,m=n/1_000_000,n%1_000_000 %(#{negativo}#{por_extenso(mi)} MIL#{mi > 1 ? 'LONES':'LON'}#{m > 0 ? " Y #{por_extenso(m)}" : ''}) when 1_000_000_000..999_999_999_999 bi,mi=n/1_000_000_000,n%1_000_000_000 %(#{negativo}#{por_extenso(bi)} BIL#{bi > 1 ? 'LONES':'LON'}#{mi > 0 ? " Y #{por_extenso(mi)}" : ''}) when 1_000_000_000_000..999_999_999_999_999 tri,bi=n/1_000_000_000_000,n%1_000_000_000_000 %(#{negativo}#{por_extenso(tri)} TRIl#{tri > 1 ? 'LONES':'LON'}#{bi > 0 ? " Y #{por_extenso(bi)}" : ''}) else raise "Valor excede o permitido: #{n}" end end end module ExtensoReal include Extenso # Escreve por extenso em reais. # # Exemplo: # 1.por_extenso_em_reais ==> 'um real' # (100.58).por_extenso_em_reais ==> 'cem reais e cinquenta e oito centavos' def por_extenso_em_reais ExtensoReal.por_extenso_em_reais(self) end # Alias para por_extenso_em_reais alias_method :to_extenso_real, :por_extenso_em_reais # Escreve o numero por extenso em reais. # # Exemplo: # Extenso.por_extenso_em_reais(1) ==> "um real" # Extenso.por_extenso_em_reais(100) ==> "cem reais" # Extenso.por_extenso_em_reais(100.58) ==> "cem reais e cinquenta e oito centavos" def ExtensoReal.por_extenso_em_reais(valor) negativo=(valor<0)? " negativo" : "" negativos=(valor<0)? " negativos" : "" valor = valor.abs return 'grátis' if valor == 0 case valor when Integer extenso = Extenso.por_extenso(valor) if extenso =~ /^(.*)(ão$|ões$)/ complemento = 'de ' else complemento = '' end %(#{extenso} #{valor <= 1 ? "real#{negativo}": "#{complemento}reais#{negativos}"}) when Float real,cents=("%.2f" % valor).split(/\./).map{ |m| m.to_i} valor_cents=Extenso.por_extenso(cents%100) valor_cents+= case cents.to_i%100 when 0 then "" when 1 then " centavo" when 2..99 then " centavos" end if real.to_i > 0 "#{ExtensoReal.por_extenso_em_reais(real.to_i)}#{cents > 0 ? ' Y' + valor_cents + negativos : real.to_i > 1 ? negativos : negativo }" else if (cents.to_i%100)==1 "#{valor_cents}#{negativo}" else "#{valor_cents}#{negativos}" end end else ExtensoReal.por_extenso_em_reais(valor.to_s.strip.gsub(/[^\d]/,'.').to_f) end end end Numeric.send(:include, ExtensoReal)
true
a33016a9dbe8bf4e6cd9626dc6bb1edb7bb67b32
Ruby
m-mrcr/jungle_beats
/test/linked_list_test.rb
UTF-8
2,851
3.265625
3
[]
no_license
require './test/test_helper' class LinkedListTest < MiniTest::Test def setup @list = LinkedList.new end def test_it_exists assert_instance_of LinkedList, @list end def test_it_has_attributes assert_nil @list.head end def test_it_can_append_to_head @list.append("doop") assert_instance_of Node, @list.head assert_equal "doop", @list.head.data end def test_it_can_display_count_of_single_appended_node @list.append("doop") assert_equal 1, @list.count end def test_it_can_display_attribute_of_single_node_as_part_of_string @list.append("doop") assert_equal "doop", @list.to_string end def test_it_can_functionally_have_multiple_nodes @list.append("doop") assert_nil @list.head.next_node @list.append("deep") assert_nil @list.head.next_node.next_node assert_equal "deep", @list.head.next_node.data end def test_it_can_return_count_for_multiple_nodes @list.append("doop") assert_equal 1, @list.count @list.append("deep") assert_equal 2, @list.count end def test_it_can_convert_multiple_nodes_to_string @list.append("doop") assert_equal "doop", @list.to_string @list.append("deep") assert_equal "doop deep", @list.to_string end def test_it_can_prepend_data @list.append("plop") assert_equal "plop", @list.to_string @list.append("suu") assert_equal "plop suu", @list.to_string @list.prepend("dop") assert_equal "dop plop suu", @list.to_string assert_equal 3, @list.count end def test_it_can_insert_data_given_an_index @list.append("plop") assert_equal "plop", @list.to_string @list.append("suu") assert_equal "plop suu", @list.to_string @list.prepend("dop") assert_equal "dop plop suu", @list.to_string @list.insert(1, "woo") assert_equal "dop woo plop suu", @list.to_string assert_equal 4, @list.count end def test_it_can_find_find_by_index_and_num_of_nodes @list.append("deep") @list.append("woo") @list.append("shi") @list.append("shu") @list.append("blop") assert_equal "deep woo shi shu blop", @list.to_string assert_equal "shi", @list.find(2, 1) assert_equal "woo shi shu", @list.find(1, 3) end def test_it_can_tell_whether_it_includes_a_given_value @list.append("deep") @list.append("woo") @list.append("shi") @list.append("shu") @list.append("blop") assert @list.includes?("deep") refute @list.includes?("dep") end def test_it_can_remove_last_node @list.append("deep") @list.append("woo") @list.append("shi") @list.append("shu") @list.append("blop") assert_equal "deep woo shi shu blop", @list.to_string @list.pop assert_equal "deep woo shi shu", @list.to_string @list.pop assert_equal "deep woo shi", @list.to_string end end
true
6c91f0330f8d2af85249cfec084b3db6c0accfbf
Ruby
omikron15/Ruby_Poker_App
/models/specs/player_spec.rb
UTF-8
414
2.8125
3
[]
no_license
require 'minitest/autorun' require 'minitest/rg' require_relative '../Player.rb' class TestPlayer < Minitest::Test def setup() options1 = { "name" => "Connor", "colour" => "Blue" } @player1 = Player.new(options1) end def test_name() assert_equal("Connor", @player1.name) end def test_colour() assert_equal("Blue", @player1.colour) end end #End of TestPlayer class
true
30eb7f9a11d1fa158955c57f19d90fa4bebc501e
Ruby
onkar-josh/GitTraining
/calculator.rb
UTF-8
599
3.953125
4
[]
no_license
class Calculator def substract(a,b) puts a-b end def multiplication(a,b) puts a*b end def squre(x) puts x * x end def addition(a,b) puts a + b end def powering(num) puts num**num; end def divide(operand1, operand2) begin puts (operand1 / operand2) rescue puts "Division by zero is not allowed" end end end #Creating object of the Calculator Class calc = Calculator.new #Fuction call of calculator class calc.addition(5,10) calc.squre(5) calc.divide(6,2) calc.divide(6,0) calc.multiplication(2,4) calc.substract(7,3)
true
7b3e90fba609b00fc390ea36166ffb1e8fab0bc2
Ruby
mac718/Launch_School
/small_problems/easy_6/find_the_duplicate.rb
UTF-8
225
3.46875
3
[]
no_license
def find_dup(arr) dup = arr.reject { |num| arr.count(num) < 2 } dup[0] end # or def find_dup(arr) iterated_nums = [] arr.each do |num| return num if iterated_nums.include?(num) iterated_nums << num end end
true
54bbb0ffe950c897bc4627f5b4a3efdca9345f80
Ruby
kg-coderta/atcoder
/GIGAcode2019.rb
UTF-8
1,285
3.21875
3
[]
no_license
A a = gets.split.map(&:to_i) p a[0]*a[1]**2 B a = gets.split.map(&:to_i) ans= 0 for num in 1..a[0] do b= gets.split.map(&:to_i) ans+=1 if b[0] >= a[1] && b[1] >= a[2] && b[0]+b[1] >= a[3] end p ans C #(2)まで a = gets.to_i b = gets.split.map(&:to_i) c = gets.split.map(&:to_i) upper_sum = 0 can_buy = 1000000000 for num in 0..a-1 do upper_sum += b[num] if upper_sum >= c[num] && c[num] < can_buy can_buy = c[num] end end if can_buy == 1000000000 can_buy = -1 end p can_buy D #(1)のみ a = gets.split.map(&:to_i) b=gets.to_i if a[2]+b <=a[3] puts 1 else puts 0 end E #(1)のみ a = gets.split.map(&:to_f) b = gets.split.map(&:to_f) if b[1]>= a[1] puts sprintf("%.15f", a[1]/b[0]) else puts "impossible" end #(2)RE a = gets.split.map(&:to_f) b = gets.split.map(&:to_f) c = gets.split.map(&:to_f) d= (a[1]-c[0])/c[1] if b[1]>= a[1] && b[0] >=c[1] puts a[1]/b[0] elsif b[1]>= a[1] && b[1]+ c[2] >= a[1] && b[0] < c[1] puts c[0]/b[0] + d elsif b[1] < a[1] && b[1]+ c[2] >= a[1] puts c[0]/b[0] + d else puts "impossible" end F #(2)までRE a = gets.split.map(&:to_i) b = gets.to_i ans = b+1 for num in 1..b do c = gets.split.map(&:to_i) if c[1] == 1 ans = ans -1 end end if c[1] == a[1] ans = ans - 1 end p ans G H
true
b6c5686b4892473ad3b323713356bf6bcdd3bf20
Ruby
harr1193/cartoon-collections-cb-gh-000
/cartoon_collections.rb
UTF-8
702
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def roll_call_dwarves(dwarves)# code an argument here # Your code here dwarves.each_with_index { |name, i| puts "#{i+1}. #{name}" } end def summon_captain_planet(planeteer)# code an argument here # Your code here planeteer_new = [] planeteer_new = planeteer.collect do |name| name.capitalize + "!" end planeteer_new end def long_planeteer_calls(calls)# code an argument here # Your code here calls.any? { |word| word.length > 4 } ? true : false end def find_the_cheese(array)# code an argument here # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] array.each { |cheese| return cheese if cheese_types.include?(cheese) } return nil end
true
7368848646b55def0e8abda769f3863c7e118d9e
Ruby
marzily/sales_engine
/lib/invoice.rb
UTF-8
1,386
2.734375
3
[]
no_license
require_relative 'model_object' require_relative 'transaction' class Invoice < ModelObject attr_reader :customer_id, :merchant_id, :status def initialize(data, invoice_repo) super @customer_id = data[:customer_id].to_i @merchant_id = data[:merchant_id].to_i @status = data[:status] end def transactions repository.engine.transaction_repository.find_all_by_invoice_id(id) end def invoice_items repository.engine.invoice_item_repository.find_all_by_invoice_id(id) end def items invoice_items.map(&:item).compact end def customer repository.engine.customer_repository.find_by_id(customer_id) end def merchant repository.engine.merchant_repository.find_by_id(merchant_id) end def success? transactions.any?(&:success?) end def charge(card_info = {}) transaction_repo = repository.engine.transaction_repository card_info[:id] = transaction_repo.all.last.id + 1 card_info[:invoice_id] = self.id card_info[:created_at] = Time.now.to_s card_info[:updated_at] = Time.now.to_s new_trans = Transaction.new(card_info, transaction_repo) transaction_repo.collection << new_trans unless transaction_repo.all_by_invoice_id.has_key?(id) transaction_repo.all_by_invoice_id[id] = [new_trans] else transaction_repo.all_by_invoice_id[id] << new_trans end end end
true
bcbea74444ac8f684eb5c12b0ffd09f08a06960c
Ruby
gillsinaglass/hikr
/app/models/hike.rb
UTF-8
1,017
2.703125
3
[]
no_license
class Hike < ApplicationRecord belongs_to :trail belongs_to :user def self.completed_hikes Hike.all.select do |hike| hike.updated_at != hike.created_at end end def start_time d = DateTime.parse(self.created_at.to_s) d.strftime('%I:%M %p') end def status if self.updated_at == self.created_at return "Pending" else return self.end_time end end def end_time d = DateTime.parse(self.updated_at.to_s) d.strftime('%I:%M %p') end def length_of_hike if self.status == "Pending" return nil else d = DateTime.parse((self.created_at - self.updated_at).to_s) return d.strftime('%M min %S secs') end end def get_trail_length @trail_length = self.trail.distance end def avg_mile_pace avg = @hike_minutes.to_f / @trail_length.to_f sec = (avg.round(3) * 60).to_i min, sec = sec.divmod(60) hour, min = min.divmod(60) return "%02d:%02d:%02d" % [hour, min, sec] + " per mile" end end
true
5d31a7af10d85c96a0887deab3e5ff311b12ce60
Ruby
cielavenir/procon
/yukicoder/tyama_yukicoder216.rb
UTF-8
140
2.765625
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby h=Hash.new(0) gets $<.map{|e|e.split.map(&:to_i)}.transpose.each{|x,y|h[-y]+=x} puts h.max_by{|k,v|[v,k]}[0]==0 ? :YES : :NO
true
eff67e21cb9bd7604d3121df146bc53aee867a37
Ruby
willmanduffy/Plex-Ruby
/lib/plex-ruby.rb
UTF-8
1,282
2.75
3
[ "MIT" ]
permissive
require 'nokogiri' require 'open-uri' require 'cgi' module Plex # Converts camel case names that are commonly found in the Plex APIs into # ruby friendly names. I.E. <tt>playMedia</tt> -> <tt>play_media</tt> # # @param [String] camel case name to be converted # @return [String] snake case form def self.underscore(string) string.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end # Converts ruby style snake case names into the cammel case names that are # used in the Plex APIs. I.E. <tt>play_media</tt> -> <tt>playMedia</tt> def self.camelize(string, first_letter_uppercase = false) if first_letter_uppercase string.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } else string.to_s[0].chr.downcase + camelize(string, true)[1..-1] end end end require 'plex-ruby/parser' require 'plex-ruby/server' require 'plex-ruby/client' require 'plex-ruby/library' require 'plex-ruby/section' require 'plex-ruby/video' require 'plex-ruby/media' require 'plex-ruby/part' require 'plex-ruby/stream' require 'plex-ruby/tags' require 'plex-ruby/show' require 'plex-ruby/season' require 'plex-ruby/episode' require 'plex-ruby/movie'
true
94bb3a12380330537e40a20498773d91f56cc792
Ruby
idanci/ofx
/lib/ofx/parser/ofx102.rb
UTF-8
667
2.671875
3
[ "MIT" ]
permissive
module OFX module Parser class OFX102 < BaseParser VERSION = "1.0.2" def self.parse_headers(header_text) # TODO: refactor # Change single CR's to LF's to avoid issues with some banks header_text.gsub!(/\r(?!\n)/, "\n") # Parse headers. When value is NONE, convert it to nil. headers = header_text.to_enum(:each_line).inject({}) do |memo, line| _, key, value = *line.match(/^(.*?):(.*?)\s*(\r?\n)*$/) unless key.nil? memo[key] = value == "NONE" ? nil : value end memo end return headers unless headers.empty? end end end end
true
027948b51ffeb987444ef995da05c259bbd168f4
Ruby
ccahill1117/definer
/app.rb
UTF-8
1,672
2.609375
3
[ "MIT" ]
permissive
require('sinatra') require('sinatra/reloader') also_reload('lib/**/*.rb') require('./lib/definer') require('pry') get ('/') do @library = Word.all() @library = Word.sort_alphabetical() erb(:input) end post ('/') do word = params["word"] definition = params["def"] image = "" if (word == "") || (definition == "") @error = "you need to enter a word and definition!" @library = Word.all() @library = Word.sort_alphabetical() elsif Word.reject_double(word) == true @error = "word is already used" @library = Word.all() @library = Word.sort_alphabetical() else @error = "" word = Word.new({:word=> word, :definition=> definition, :image=> image}) word.save() @library = Word.all() @library = Word.sort_alphabetical() end erb(:input) end get ('/words/:id') do @word = Word.find(params[:id]) @library = Word.all() erb(:word) end post ('/words/:id') do word = Word.find(params[:id]) Word.delete_word(word) redirect('/') end post ('/words/:id/deletedef/:index') do @word = Word.find(params[:id]) delete_index = params[:index].to_i() @word.definitions.delete_at(delete_index) erb(:word) end post('/words/:id/others') do word = params["word"] antonym = params["opposite"] image = params["image"] @word = Word.find(params[:id]) @word.word = word @word.antonym = antonym @word.image = image erb(:word) end post('/words/:id/defs') do @word = Word.find(params[:id]) addl_def = params["alt_def"] (@word.definitions).push(addl_def) erb(:word) end post('/words/<%= @word.id %>') do delete_word = Word.find(params[:id]) Word.delete_word(delete_word) erb(:item) end
true
4c605226ce074f5dc63a16c563a76966422750f9
Ruby
kswhyte/black_thursday
/lib/merchant.rb
UTF-8
659
2.5625
3
[]
no_license
class Merchant attr_reader :id, :name, :created_at, :updated_at def initialize(merchant, merchant_repository_parent = nil) @merchant_repository_parent = merchant_repository_parent @id = merchant[:id].to_i @name = merchant[:name] @created_at = Time.parse(merchant[:created_at]) @updated_at = Time.parse(merchant[:updated_at]) end def items @merchant_repository_parent.find_items_by_merchant_id(id) end def invoices @merchant_repository_parent.find_invoices_by_merchant_id(id) end def customers @merchant_repository_parent.find_customers_by_merchant_id(id) end end
true
e1b80238b085b21fbf7ce9d82ad4140cf1ada2bf
Ruby
happyhappyhappyhappy/rubycode
/atcoderruby/begineersSelection/chap2/PASTFILES/ABC081A_1.rb
UTF-8
270
3.515625
4
[]
no_license
# Problem https://atcoder.jp/contests/abc081/tasks/abc081_a # Ruby 1st Try one,two,three = gets.chomp('\n').split('') answer = 0 if one == '1' answer = answer + 1 end if two == '1' answer = answer + 1 end if three == '1' answer = answer + 1 end puts(answer)
true
63763c0730701694c3424374bebc5a10052b5ff5
Ruby
dudekmch/Robo
/app/helpers/adresses_helper.rb
UTF-8
227
2.671875
3
[]
no_license
module AdressesHelper def full_name(address) names = [address.last_name, address.first_name] names.join(' ') end def city_zipcode(address) data = [address.city, address.zip_code] data.join(' ') end end
true
a1ce9732ab83930a214081c8628e1ba159512a39
Ruby
akiradeveloper/haskeller
/lib/haskeller/lazy/enumerable.rb
UTF-8
730
3.125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Enumerable def mapL(&blk) Enumerator.new do |y| self.each do |x| y << (blk.call x) end end end def filterL(&blk) Enumerator.new do |y| self.each do |x| y << x if blk.call(x) end end end def zipL( *its ) es = [] es << self its.each do |it| es << it end Lazy.zip( es ) end def takeL(n) e = to_enum Enumerator.new do |y| n.times do y << e.next end end end def take_whileL(&blk) e = to_enum Enumerator.new do |y| while( x=e.next; blk.call(x) ) do y << x end end end end if __FILE__ == $0 inf = 0..1.0/0 p inf.take_whileL { |x| x < 100 }.to_a end
true
55ff1b7a755fe6b5440a9993878c7379c7719777
Ruby
runewit/Lab3-Chat-Client
/Server.rb
UTF-8
3,245
3.359375
3
[]
no_license
require 'socket' class Server def initialize() @server = TCPServer.new 9001 #port 9001 @disconnect = false @users = [] @usercode = [] run_server(@server) end def run_server(server) loop do Thread.start(server.accept) do |client| client.puts "Hello there, what is your name?" name = client.gets puts "#{name.strip} connected" if @users != [] for person in @usercode person.puts "#{name.strip} has connected" end end @users<<name.strip @usercode<<client client.puts "Hi #{name.strip} The time is #{Time.now}" client.puts "You are now connected the chat service." while @disconnect == false interperate(client) end end end end def search_username(usercode) snum = 0 print "searching for name: " for code in @usercode if code == usercode puts "#{@users[snum]}" return @users[snum] else snum = snum + 1 end end end def search_usercode(reciever_name) num = 0 puts "searching for code" for name in @users if name.strip == reciever_name.strip return @usercode[num] else num = num + 1 end end end def interperate(client) message = client.gets case message.strip when "DISCONNECT" @newlista=[] @newlistb=[] client_name = search_username(client) for user in @usercode user.puts "#{client_name} has disconnected" end remove_from_lists(client_name,client) client.close puts "#{client_name} disconnected" when "USERLIST" n=0 client.puts "#{@users}" puts "#{@users[0]}: #{@usercode[0]}" puts "#{@users[1]}: #{@usercode[1]}" puts "#{@users[2]}: #{@usercode[2]}" when "BROADCAST" client.puts "What message would you like to broadcast? Enter below." message = client.gets name = search_username(client) for user in @usercode user.puts "Global Broadast from #{name}: #{message}" end when "SEND" client.puts "What message would you like to send? Enter below." message = client.gets client.puts "whom should recieve this message? Enter below." reciever = client.gets is_there = @users.include? reciever.strip if is_there == false client.puts "The user #{reciever.strip} is not connected." else reciever_code = search_usercode(reciever) puts "#{client} sending a message to #{reciever.strip}" client_name = search_username(client) reciever_code.puts "Message from #{client_name}: #{message}" client.puts "Message sent." end else client.puts "You gave the command: #{message}" client.puts "This is not an accepted command." client.puts "The possible commands are: DISCONNECT, USERLIST, BROADCAST, SEND" end end def remove_from_lists(user, id) for name in @users if name != user @newlista<<name end end @users = @newlista for code in @usercode if code != id @newlistb<<code end end @usercode = @newlistb end end Server.new
true
0d34188a81a5ec8f066775faf3ba4bdddc97f8ed
Ruby
chrabyrd/project_euler
/problem_31.rb
UTF-8
1,008
4.0625
4
[]
no_license
=begin In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p How many different ways can £2 be made using any number of coins? =end coins = [0, 1, 2, 5, 10, 20, 50, 100, 200] def brute_force_count #I've tried for a week to figure out dynamic programming or recursion. Right now only this method works for me. (0..200).step(200) do |r| (0..200).step(100) do |s| (0..200).step(50) do |t| (0..200).step(20) do |u| (0..200).step(10) do |v| (0..200).step(5) do |w| (0..200).step(2) do |x| (0..200).step(1) do |y| count += 1 if r + s + t + u + v + w + x + y == 200 end end end end end end end end print count end brute_force_count
true
4060a22e16e95b2e997a368fff7da72a91a01d2d
Ruby
missamii/GA-Mirror
/w11/Classwork/ruby_testing/stackqueue_rspec/spec/queue_spec.rb
UTF-8
1,309
3.203125
3
[]
no_license
require_relative '../queue' RSpec.describe do before :each do @queue = Queue.new end describe '#new' do it "should take no arguments and return a stack object" do expect(@queue).to be_an_instance_of Queue end end describe '#add' do it "should add an element to a queue and return the element" do el = @queue.add(3) expect(el).to equal(3) el_again = @queue.add(4) expect(el_again).to equal(4) end end describe '#remove' do it 'should return the element from the front of the queue' do @queue.add(3) @queue.add(4) @queue.add(5) el = @queue.remove expect(el).to equal(3) end it 'should remove the element from the front of the queue' do @queue.add(3) @queue.add(4) @queue.add(5) @queue.remove el = @queue.remove expect(el).to equal(4) end end describe '#peek' do it 'should return the first item in the queue' do @queue.add(3) @queue.add(4) @queue.add(5) el = @queue.peek expect(el).to equal(3) end it 'should not remove the element from the front of the queue' do @queue.add(3) @queue.add(4) @queue.add(5) @queue.peek el = @queue.peek expect(el).to equal(3) end end end
true
80d041e068157e433b2b448da2c11b3ea5b4c492
Ruby
fregas/RubyRapper
/rapper.rb
UTF-8
1,728
2.65625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby # vim: set ft=ruby require 'bundler' # require_relative '../lib/dpx_active_tags' Bundler.require # require 'pg' # Output a table of current connections to the DB #conn = PG.connect( dbname: 'postgres' ) #conn.exec( "SELECT * FROM pg_stat_activity" ) do |result| # puts " PID | User | Query" # result.each do |row| # # puts " %7d | %-16s | %s " % # # row.values_at('procpid', 'usename', 'current_query') # puts " #{row.values_at('procid')}| #{row.values_at('usename')} | #{row.values_at('current_query')}" # end #end class DbConnection def initialize(connection) @conn = PG.connect(connection) end def query(query: nil, parameters: [], klass: nil, &mapper) result = @conn.exec_params(query, parameters ) list = [] if block_given? result.each do |row| list << mapper.call(row) end else result.each do |row| obj = klass.new columns = row.keys columns.each do |col| puts col if obj.respond_to? :"#{col}=" obj.send(:"#{col}=", row[col]) end end list << obj end end return list end end class Stat attr_accessor :procpid, :usename, :current_query end conn = DbConnection.new(dbname: 'postgres') #results = conn.query query: "select usename, 999 as procpid from pg_stat_activity" do |row| # stat = Stat.new # stat.procpid = row.values_at('procpid') # stat.usename = row.values_at('usename') # stat.current_query = row.values_at('current_query') # stat #end #puts results[0].inspect results = conn.query(query: "select usename, pid as procpid from pg_stat_activity", klass: Stat) puts results[0].inspect
true
1dd4d19a83e331f57437b6c320088677947c350e
Ruby
ForestJay/AllY0urBas1czRBel0ngT0Us
/test_missing_number.rb
UTF-8
346
2.765625
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true # Written by Forest J. Handford (She/Her) require_relative 'missing_number' require 'minitest/autorun' # Class for testing class TestMissingNumber < Minitest::Test def test_find_missing missing_number = MissingNumber.new assert_equal 7, missing_number.find_missing assert_equal 71, missing_number.sum end end
true
bc2a4e05f866f26c6331c88aeeb5ad1cfaf910b5
Ruby
sullerandras/garfield-ocr-ruby
/app/entities/line.rb
UTF-8
276
2.984375
3
[]
no_license
require 'entities/bw_image' class Line < Bubble def initialize(bubble) super bubble.top, bubble.left, false (bubble.top..bubble.bottom).each do |row| (bubble.left..bubble.right).each do |col| add row, col, bubble[row, col] == BWImage::WHITE end end end end
true
e26aeb027b470477ca347d1bb063c3633773f2d5
Ruby
smoline/departures
/app/models/departure_matrix.rb
UTF-8
603
3.015625
3
[]
no_license
require 'matrix' module DepartureMatrix def airports_matrix!(counts:, field1: "origin", field2: "dest") h_matrix = counts.each_with_object({}) do |record, hash| hash[record[field1]] ||= Hash.new(0) hash[record[field1]][record[field2]] = Integer(record["count"]) end airports = h_matrix.keys.sort total = Float(h_matrix.values.flat_map(&:values).sum) matrix = Matrix.build(airports.count) do |row, column| origin = airports[row] dest = airports[column] h_matrix.fetch(origin, {}).fetch(dest, 0) / total end [airports, matrix] end end
true
002f8ff834c09a122a0d92fe2c82aacda007b920
Ruby
rahuks123/saas201
/saas201/day3/experiment3.rb
UTF-8
277
3.890625
4
[]
no_license
class Sample def initialize (na) @name=na puts "this is in the constructor #{@name}" end def display(tname) vd=tname puts"the name is #{vd}" end def tota x=(tn) puts"the last name is#{x}" end end obj=Sample.new("rahul") obj.display "vineth" obj.tota("harsha")
true
288cc6e4d5ce5e537f9ab88e8fbf5768e00546ff
Ruby
iliabylich/pattern_matching
/bin/ruby.pm
UTF-8
487
2.5625
3
[]
no_license
#!/usr/bin/env ruby ROOT = File.expand_path('../..', __FILE__) $: << File.join(ROOT, 'lib') require 'pattern_matching' def run_file(filepath) if ENV['DEBUG'] puts puts "[DEBUG] Running #{filepath}:" puts PatternMatching .process(File.read(filepath)) .split("\n") .map .with_index { |line, index| "#{(index + 1).to_s.rjust(6)}: #{line}" } puts end PatternMatching.require(filepath) end ARGV.each do |filepath| run_file(filepath) end
true
ede65c051d17746d4cdf3c517a5fac1dbd4115be
Ruby
misyo98/order_management
/app/services/update_delivery_date.rb
UTF-8
395
2.65625
3
[]
no_license
class UpdateDeliveryDate def self.call(customer, day = nil) new(customer, day).call end def initialize(customer, day) @customer = customer @day = day&.to_date end def call LineItem.for_customer(customer.id).with_state(:delivery_arranged).each do |item| item.set_appointment_date(day) if day.present? end end private attr_reader :customer, :day end
true
587669e79f43827b290b1c17c1c2de5ffb264e1d
Ruby
jurre/Enigma
/lib/rotor.rb
UTF-8
1,164
3.515625
4
[ "MIT" ]
permissive
class Rotor attr_accessor :rotor_values, :position, :notch # rotor values are accessible for testing purposes only def initialize(values, start_position, notch) left_row = ('A'..'Z').to_a * 2 # create an array with the alphabet twice, just like that # create a twodimentional array where the first dimension is # the alphabet and the second dimention is the provided string with values @rotor_values = left_row.zip(values.split('') * 2) @position = start_position @start_position = start_position @notch = notch end def shift_up! @position += 1 end def reset! @position = @start_position end def right right = @rotor_values.map { |rotor_value| r[1] } right.slice(@position, 26) end def left left = @rotor_values.map { |rotor_value| r[0] } left.slice(@position, 26) end def convert(index, direction) raise "unvalid direction, valid directions are :left and :right" unless direction == :left or :right if direction == :left left.index(right[index]) elsif direction == :right right.index(left[index]) end end def shift? left[0] == @notch end end
true
b830e4b91a303589cd057ff72da02720df14b21b
Ruby
beneggett/hw
/led-demo.rb
UTF-8
2,610
3.28125
3
[]
no_license
require 'dino' require 'httparty' class HW attr_accessor :board def initialize @board = Dino::Board.new(Dino::TxRx.new) end def leds [blue, red, green, yellow ] end def blue Dino::Components::Led.new(pin: 4, board: board) end def red Dino::Components::Led.new(pin: 5, board: board) end def green Dino::Components::Led.new(pin: 6, board: board) end def yellow Dino::Components::Led.new(pin: 7, board: board) end def pin_names [{name: "yellow", led: yellow.pin}, {name: "blue", led: blue.pin}, {name: "green", led: green.pin}, {name: "red", led: red.pin}] end def button Dino::Components::Button.new(pin: 13, board: board) end def blink(led, delay = 0.1) led.send(:on) sleep delay led.send(:off) sleep delay end def cycle delay = 0.005 leds.cycle do |led| blink(led, delay) delay *= 1.1 puts delay break if delay >= 0.29 end end def spin_the_wheel say('spinning the wheel') time = 0 delay = 0.001 leds.cycle do |led| delay += rand(0.002..0.03) time += delay blink(led, delay) if delay >= 0.33 puts time winner = pin_names.find{|pin| pin[:led] == led.pin}[:name] puts "#{winner.capitalize} wins!" led.on say("#{winner.capitalize} wins, you sweet sweet druggie!") break end # break if button.down end end def who_picks_lunch? say('who gets to pick lunch today?') time = 0 delay = 0.001 leds.cycle do |led| delay += rand(0.002..0.03) time += delay blink(led, delay) if delay >= 0.33 puts time winner = pin_names.find{|pin| pin[:led] == led.pin}[:name] case winner when 'yellow' picker = 'cody' when 'green' picker = 'Andy' when 'blue' picker = 'ben' when 'red' picker = 'quintin' end puts "#{picker.capitalize} wins!" led.on say("#{picker.capitalize} gets to pick lunch today, and cody pays. you lucky dog!") break end # break if button.down end end def say(message) text = message key = 'c3d6f27dbd254282becd156f3db13206' returned_mp3 = HTTParty.get("http://api.voicerss.org/?key=#{key}&src=#{text}'&hl=en-us&f=48khz_16bit_stereo") file = 'speak.mp3' File.open(file, 'w') { |file| file.write(returned_mp3.parsed_response) } `omxplayer --vol -2000 speak.mp3` end def activate! button.down do spin_the_wheel end sleep end end
true
cb3eef2cd0a3d1bf06e6294b7a6b30dd822ffe26
Ruby
wisetara/4.5.4_Game_of_Life
/lib/Board.rb
UTF-8
558
3.3125
3
[]
no_license
class Board attr_reader :width, :height, :spaces def initialize(width, height) @width = width @height = height @spaces = [] end def Board.create(width, height) new_board = Board.new(width, height) end def populate(width, height) 1.upto(width) do |width| 1.upto(height) do |height| @spaces << Cell.new(width,height) end end end def mark_cell(x_coord, y_coord) live_cell = @spaces.detect do |cell| (cell.x == x_coord) && (cell.y == y_coord) end live_cell.mark << "A" end end
true
0b87338085838002a1d91fe4fb1d714e019565eb
Ruby
thoughtbot/factory_bot
/spec/support/matchers/delegate.rb
UTF-8
1,099
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
RSpec::Matchers.define :delegate do |delegated_method| chain :to do |target_method| @target_method = target_method end chain :as do |method_on_target| @method_on_target = method_on_target end chain :with_arguments do |args| @args = args end match do |instance| @instance = instance @args ||= [] return_value = "stubbed return value" method_on_target = @method_on_target || delegated_method stubbed_target = double("stubbed_target", method_on_target => return_value) allow(@instance).to receive(@target_method).and_return stubbed_target begin @instance.send(delegated_method, *@args) == return_value rescue NoMethodError false end end failure_message do if Class === @instance message = "expected #{@instance.name} " prefix = "." else message = "expected #{@instance.class.name} " prefix = "#" end message << "to delegate #{prefix}#{delegated_method} to #{prefix}#{@target_method}" if @method_on_target message << ".#{@method_on_target}" end message end end
true
70f92b48f47d2854bb8ff24f5e86213aa26c4c28
Ruby
mwagner19446/wdi_work
/w01/d04/Jenn_Dodd/receipt_generator.rb
UTF-8
408
3.53125
4
[]
no_license
#GATHER USER INFO puts "Where did you shop?" place = gets.chomp puts "What good/service did you buy?" bought = gets.chomp puts "What was the cost of said item?" print "$" cost = gets.chomp.to_f #MAKE THE NEW FILE f = File.new("receipt.txt", "w") f.puts "Company Name: #{place}" f.puts "Good/Service Provided: #{bought}" f.puts "Cost: $#{cost}" f.puts f.puts "Thank you for your patronage!" f.close
true
bbd946210c115239b708080f9029595bb583f039
Ruby
tonyhammond/yads
/tools/clients/ruby/doi/yadt.rb
UTF-8
2,959
3.09375
3
[]
no_license
#!/usr/local/bin/ruby ######################################################################## # # yadt - Yet Another DOI Tool (this version for Ruby) # # Author - Tony Hammond <tony_hammond@harcourt.com> # ######################################################################## require 'dataObject' require 'getoptlong' class YADT attr_reader :opts YADT_VERSION = '0.1' def initialize _options = GetoptLong.new( [ "-r", "--random", GetoptLong::NO_ARGUMENT ], # Random DOI [ "-x", "--xml", GetoptLong::NO_ARGUMENT ], # Print XML [ "-d", "--dump", GetoptLong::NO_ARGUMENT ], # Dump [ "-t", "--types", GetoptLong::NO_ARGUMENT ], # Types [ "-v", "--values", GetoptLong::NO_ARGUMENT ], # Values [ "-k", "--kernel", GetoptLong::NO_ARGUMENT ], # Kernel Metadata [ "-m", "--metadata", GetoptLong::NO_ARGUMENT ], # Profile Metadata [ "-u", "--username", GetoptLong::REQUIRED_ARGUMENT ],# Authorized Username [ "-p", "--password", GetoptLong::REQUIRED_ARGUMENT ],# Authorized Password [ "-h", "--help", GetoptLong::NO_ARGUMENT ], # Help [ "-V", "--version", GetoptLong::NO_ARGUMENT ] # Version ) @opts = {} _options.each { |key, val| @opts[key] = val } _options.terminate end def YADT._version print <<EOT This is YADT (Yet Another DOI Tool, Ruby version #{YADT_VERSION}) This program is free software you can redistribute it and/or modify it under the same terms as Ruby itself. EOT exit end def YADT._usage print <<EOT Usage: yadt [options] <doi> ... -r : get random DOI -x : print DataObject as XML -d : print dump of the DataGroups -t : print the DataObject data types -v : print the DataObject values -k : print DOI Kernel Metadata -m : print DOI Application Profile Metadata -u username : authorized username -p password : authorized password -h : print this help message -V : print the version number of yadt EOT exit end end y = YADT.new if y.opts.key?('-h') then YADT._usage end if y.opts.key?('-V') then YADT._version end args = ARGV args << "?" if y.opts.key?('-r') while (doi = args.shift) doi.sub!(/^doi:/, "") # Remove possible URI scheme d = DataObject.get(doi) if y.opts.key?('-u') then d.authUsername = y.opts['-u'] end if y.opts.key?('-p') then d.authPassword = y.opts['-p'] end y.opts.each do |key, val| case key when /^-+x/ then puts d when /^-+d/ then d.dumpDataGroups when /^-+t/ then puts d.dataTypes when /^-+v/ then puts d.dataValues when /^-+k/ then puts d.kernelMetadata when /^-+m/ then puts d.profileMetadata end end end __END__
true
b9b8343dd5b50550bcb69e08716871d0bc3d694c
Ruby
OlegSliusar/binary_tree
/test.rb
UTF-8
726
2.90625
3
[]
no_license
require_relative 'tree' require 'yaml' new_tree = Tree.new ary = [7, 8, 3, 13, 6, 4, 14, 1, 10] new_tree.build_tree(ary) puts YAML::dump(new_tree) File.open('tree.yaml', 'w') do |file| file.puts YAML::dump(new_tree) end puts "#" * 50 puts YAML::dump(new_tree.breadth_first_search(13)) File.open('found_node_bfs.yaml', 'w') do |file| file.puts YAML::dump(new_tree.breadth_first_search(13)) end puts "#" * 50 puts YAML::dump(new_tree.depth_first_search(13)) File.open('found_node_dfs.yaml', 'w') do |file| file.puts YAML::dump(new_tree.depth_first_search(13)) end puts "#" * 50 File.open('found_node_dfs_rec.yaml', 'w') do |file| file.puts YAML::dump(new_tree.dfs_rec(13)) end puts YAML::dump(new_tree.dfs_rec(13))
true
a18567c0f6949628c4ff6a76a83645d6e6f02404
Ruby
Gallup93/pantry_2003
/lib/cook_book.rb
UTF-8
604
3.28125
3
[]
no_license
class CookBook attr_reader :recipes def initialize @recipes = [] end def add_recipe(recipe) @recipes << recipe end def ingredients all_ingredients = [] @recipes.each do |recipe| recipe.ingredients_required.each {|key, value| all_ingredients << key.name} end all_ingredients.uniq end def highest_calorie_meal highest_calories = 0 result = nil @recipes.each do |recipe| calories = recipe.total_calories if calories > highest_calories highest_calories = calories result = recipe end end result end end
true
1a024e72d180c9c92ebd93c7bda3287df664fbab
Ruby
VMJ-GG/Generic
/lib/euler/lib/euler/arguments.rb
UTF-8
673
3.140625
3
[ "MIT" ]
permissive
require 'ostruct' module Euler # Arguments Objects are an Hash like structure used to store data about algorithm # functionalities like needed arguments. # # Required options fields are: # - arguments -> Every arguments necessary to algorithm for working # (WARNING: don't confuse it with body arguments) # - body_arguments -> Every arguments that as to be given to algorithm's body # (to be more clear: these arguments are used in each body cycle) # class Arguments attr_reader :body def initialize @hash = OpenStruct.new @body = [] end def method_missing(meth, *args) @hash.send(meth, *args) end end end
true
cc9c4c3ecc291ec0903ea65c551f1446e2992a73
Ruby
amsmyth1/yardsourcing-engine
/spec/facades/yards_facade_spec.rb
UTF-8
3,098
2.53125
3
[]
no_license
require 'rails_helper' RSpec.describe YardsFacade do describe "class methods" do it ".find_yards" do @yard1 = create(:yard, host_id: 1) @yard2 = create(:yard, host_id: 2) @yard3 = create(:yard, host_id: 1) @yard4 = create(:yard, host_id: 2) @yard5 = create(:yard, host_id: 1) @yard6 = create(:yard, host_id: 1) expect(YardsFacade.find_yards(1, 1)).to eq([@yard1, @yard3, @yard5, @yard6]) end describe ".create_yard" do before :each do @yard_params = ({ id: 1, host_id: 1, email: "host_eamil@domain.com", name: 'yard', street_address: '123 Fake St.', city: 'Denver', state: 'CO', zipcode: '12345', price: 20.00, description: 'description', availability: 'availability', payment: 'venmo', photo_url_1: 'url1', photo_url_2: 'url2', photo_url_3: 'url3', }) @purposes = create_list(:purpose, 3) end it "creates a yard if params and purposes are provided" do expect(YardsFacade.create_yard(@yard_params, @purposes)).to be_a(Yard) end it "returns an error if purposes are not provided" do expect(YardsFacade.create_yard(@yard_params, nil)[:error]).to eq("You must select at least one purpose") end end describe ".update_yard" do before :each do @yard = create(:yard) @yard_params = ({ id: 1, host_id: 1, email: "host_eamil@domain.com", name: 'yard', street_address: '123 Fake St.', city: 'Denver', state: 'CO', zipcode: '12345', price: 20.00, description: 'description', availability: 'availability', payment: 'venmo', photo_url_1: 'url1', photo_url_2: 'url2', photo_url_3: 'url3', }) @purposes = create_list(:purpose, 3) end it "creates a yard if params and purposes are provided" do expect(YardsFacade.update_yard(@yard.id, @yard_params, @purposes)).to be_a(Yard) end it "returns an error if purposes are not provided" do expect(YardsFacade.update_yard(@yard.id, @yard_params, nil)[:error]).to eq("You must select at least one purpose") end end it ".create_yard_purposes" do yard = create(:yard) purpose1 = create(:purpose) purpose2 = create(:purpose) purpose_ids = [purpose1.id, purpose2.id] YardsFacade.create_yard_purposes(yard, purpose_ids) expect(YardPurpose.all.count).to eq(2) end end end
true
05c67cac8b3d75de7512be46839f12b07dbb5997
Ruby
fig/scheduleless
/app/models/calculators/coworkability/rating.rb
UTF-8
449
2.953125
3
[]
no_license
module Calculators module Coworkability class Rating def self.for(score) new(score: score).rating end def initialize(score:) @score = score end def rating if score >= 900 :red elsif score >= 450 :orange elsif score >= 250 :yellow else :green end end private attr_reader :score end end end
true
4d3d36d3e0040035d0b7d0f23287dbaaed5a777b
Ruby
SarahCyrDesign/ttt-with-ai-project-v-000
/bin/tictactoe
UTF-8
1,063
3.484375
3
[]
no_license
#!/usr/bin/env ruby require_relative '../config/environment' def self.start # for bin Game.start puts "Welcome to Tic Tac Toe!" puts "How many players? 0, 1, 2?" input = gets.strip.to_i if input == 0 puts "Computer \"X\" Vs Computer \"O\" game start!" game = Game.new(Players::Computer.new("X"), Players::Computer.new("O")) game.play elsif input == 1 puts "Who should go first?" puts "1 = Player 1(Me) or 2 = Player 2(Computer)?" player_choice_input = gets.strip.to_i player_choice_input == 1 ? game = Game.new(Players::Human.new("X"), Players::Computer.new("O")) : game = Game.new(Players::Computer.new("X"), Players::Human.new("O")) game.play else input == 2 puts "2 player game, start! Player \"X\", Your turn!" game = Game.new game.play end end play_again = "y" while play_again == "y" self.start puts "Play again? y/n" play_again = gets.strip.downcase end puts "Thank you for playing :)"
true
96eb3001674ab364e73589f909b190400d039d24
Ruby
RSijelmass/url-shortener
/app/models/url_parser.rb
UTF-8
257
2.75
3
[]
no_license
class UrlParser SHORTHAND_LIMIT = 5 def self.is_valid_url?(potential_url) valid = potential_url && potential_url.match(/\A#{URI::regexp}\z/) !!valid end def self.create_shorthand SecureRandom.alphanumeric[0...SHORTHAND_LIMIT] end end
true
1256257167bacce1900894392bb01c6a1085879a
Ruby
MrAaronOlsen/headcount
/test/statewide_test_repository_test.rb
UTF-8
4,307
2.625
3
[]
no_license
require_relative 'test_helper' class StatewideTestRepositoryTest < MiniTest::Test def test_that_it_is_a_statewide_test_repository assert_instance_of StatewideTestRepository, StatewideTestRepository.new end def test_that_it_collects_unique_names str = StatewideTestRepository.new str.load_data({:statewide_testing => { :third_grade => "./data/3rd grade students scoring proficient or above on the CSAP_TCAP.csv"}}) assert_equal str.collect_names.count, str.collect_names.uniq.count end def test_it_finds_by_name str = StatewideTestRepository.new str.load_data({:statewide_testing => { :third_grade => "./data/3rd grade students scoring proficient or above on the CSAP_TCAP.csv"}}) statewide_test = str.find_by_name("ADAMS COUNTY 14") assert_instance_of StatewideTest, statewide_test assert_equal statewide_test.name, "ADAMS COUNTY 14" end def test_it_cant_find_by_name str = StatewideTestRepository.new str.load_data({:statewide_testing => { :third_grade => "./data/3rd grade students scoring proficient or above on the CSAP_TCAP.csv"}}) assert_nil str.find_by_name("NEVERLAND") end def test_it_can_load_dynamic_csvs_1 str = StatewideTestRepository.new loaded = str.load_data({:statewide_testing => { :third_grade => "./test/fixtures/3rd_grade_fixture.csv"}}) expected = {:third_grade => [{location: "Colorado", score: "Math", timeframe: "2008", dataformat: "Percent", data: "0.697"}, {location: "Colorado", score: "Reading", timeframe: "2008", dataformat: "Percent", data: "0.703"}, {location: "Colorado", score: "Writing", timeframe: "2008", dataformat: "Percent", data: "0.501"}]} assert_equal expected, loaded end def test_it_can_load_dynamic_csvs_2 str = StatewideTestRepository.new loaded = str.load_data({:statewide_testing => { :writing => "./test/fixtures/average_proficiency_writing_fixture.csv"}}) expected = {:writing => [ {location: "Colorado", race_ethnicity: "All Students",timeframe: "2011",dataformat: "Percent", data: "0.5531"}, {location: "Colorado", race_ethnicity: "Asian",timeframe: "2011",dataformat: "Percent", data: "0.6569"}, {location: "Colorado", race_ethnicity: "Black",timeframe: "2011",dataformat: "Percent", data: "0.3701"}]} assert_equal expected, loaded end def test_it_can_give_districts_data str = StatewideTestRepository.new loaded = str.load_data({:statewide_testing => { :third_grade => "./test/fixtures/3rd_grade_fixture.csv", :writing => "./test/fixtures/average_proficiency_writing_fixture.csv"}}) expected = { name: "COLORADO", :third_grade => [ {location: "Colorado", score: "Math", timeframe: "2008", dataformat: "Percent", data: "0.697"}, {location: "Colorado", score: "Reading", timeframe: "2008", dataformat: "Percent", data: "0.703"}, {location: "Colorado", score: "Writing", timeframe: "2008", dataformat: "Percent", data: "0.501"} ], :writing => [ {location: "Colorado", race_ethnicity: "All Students",timeframe: "2011",dataformat: "Percent", data: "0.5531"}, {location: "Colorado", race_ethnicity: "Asian",timeframe: "2011",dataformat: "Percent", data: "0.6569"}, {location: "Colorado", race_ethnicity: "Black",timeframe: "2011",dataformat: "Percent", data: "0.3701"}] } assert_equal expected, str.find_by_name('COLORADO').data end def test_it_loads_all_files str = StatewideTestRepository.new str.load_data({:statewide_testing => { :third_grade => "./data/3rd grade students scoring proficient or above on the CSAP_TCAP.csv", :eighth_grade => "./data/8th grade students scoring proficient or above on the CSAP_TCAP.csv", :math => "./data/Average proficiency on the CSAP_TCAP by race_ethnicity_ Math.csv", :reading => "./data/Average proficiency on the CSAP_TCAP by race_ethnicity_ Reading.csv", :writing => "./data/Average proficiency on the CSAP_TCAP by race_ethnicity_ Writing.csv"}}) assert_equal "COLORADO", str.find_by_name("COLORADO").name end end
true
3e7c2ee5df10eca3c6fcac1814a1395709b9a858
Ruby
AakashOfficial/ThreatExchange
/ruby/example/lib/example.rb
UTF-8
621
3.3125
3
[ "BSD-3-Clause" ]
permissive
def parse(dataset) printf "\nResults: \n" if dataset.kind_of?(String) puts dataset elsif dataset.kind_of?(Hash) unless dataset.empty? dataset.each { |data| p data } else puts 'No data found.' end else puts dataset end end def banner(header) puts '-'*80 puts header puts '-'*80 end def spinner(fps=30) chars = %w[| / - \\] delay = 1.0/fps iter = 0 spinner = Thread.new do while iter do print chars[(iter+=1) % chars.length] sleep delay print "\b" end end yield.tap{ iter = false spinner.join } end
true
f663033cd68e3b84835c2dbbcf410a7551b65580
Ruby
nineties/math
/numeric/ex4/diff.rb
UTF-8
93
2.53125
3
[]
no_license
include Math x = PI/3 h = 10.0**-10 puts (sin(x+h)-sin(x))/h puts 2*cos(x+h/2)*sin(h/2)/h
true
b7e4a38ef4ac62fd1fbfa7940a577a298788f9c8
Ruby
jtescher/descriptive-statistics
/lib/descriptive-statistics/shape.rb
UTF-8
816
3.046875
3
[ "MIT" ]
permissive
module DescriptiveStatistics module Shape def skewness return if length == 0 return 0 if length == 1 sum_cubed_deviation / ((length - 1) * cubed_standard_deviation.to_f) end def kurtosis return if length == 0 return 0 if length == 1 sum_quarted_deviation / ((length - 1) * quarted_standard_deviation.to_f) end private def sum_cubed_deviation precalculated_mean = mean inject(0) {|sum, value| sum + (value - precalculated_mean) ** 3} end def cubed_standard_deviation standard_deviation ** 3 end def sum_quarted_deviation precalculated_mean = mean inject(0) {|sum, value| sum + (value - precalculated_mean) ** 4} end def quarted_standard_deviation standard_deviation ** 4 end end end
true
8884fda078e572b709af4bc57e925e371841962a
Ruby
CamleGem/GemRepo
/interrupt.rb
UTF-8
551
2.96875
3
[]
no_license
ltotal = 0 ctotal = 0 wtotal = 0 ARGV.each do |file| begin file_obj = File.open(file) l = 0 c = 0 w = 0 file_obj.each_line do |line| l += 1 c += line.size line.sub!(/^\s+/, "") arg = line.split(/\s+/) w += arg.size end ltotal += l ctotal += c wtotal += w printf("%s %d %d %d %s\n", file, l, c, w, 'Total') rescue => exp puts "#{exp.class} #{exp.message}" ensure file_obj.close puts "pass!!" end end printf("%d %d %d %s\n", ltotal, ctotal, wtotal, 'Total')
true
274b437c7ca7e2fdebb1ca38946b152638c9b077
Ruby
tamu222i/ruby01
/tech-book/2/2-17.rb
UTF-8
61
2.8125
3
[]
no_license
# 関数の定義 def add(a, b) a + b end print add(1, 2)
true
09a2221df858863b2a987359ff9abcccee276bea
Ruby
nist/ACIM
/tools/extract_lessons/test/test_config_extract.rb
UTF-8
1,351
2.734375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'test/unit' require_relative '../lib/config_extract' class ConfigExtractTest < Test::Unit::TestCase def test_valid_config_file config = ConfigExtract.new assert_equal ConfigExtract, config.class assert_equal false, config.config.empty? end # def test_invalid_config_file # config = ConfigExtract.new('invalid_file.json') # assert_equal true, config.config.empty? # end def test_languages config = ConfigExtract.new assert_equal ['de','en','es','fr','it','nl','pt'], config.languages end def test_urls config = ConfigExtract.new assert_equal ["lektionen.acim.org", "lessons.acim.org", "lecciones.acim.org", "lecons.acim.org", "lezioni.acim.org", "lessen.acim.org", "licoes.acim.org"], config.urls end def test_url_valid_language config = ConfigExtract.new assert_equal "lessons.acim.org", config.url('en') end def test_url_invalid_language config = ConfigExtract.new assert_equal nil, config.url('ZZ') end def test_valid_language config = ConfigExtract.new assert_equal true, config.language_valid?("en") end def test_invalid_language config = ConfigExtract.new assert_equal false, config.language_valid?("zz") end def test_empty_language config = ConfigExtract.new assert_equal false, config.language_valid?('') end end
true
f0c98582c9695008c6a38ae875b758d300e79755
Ruby
peregrinebalas/enigma
/lib/interface.rb
UTF-8
230
2.890625
3
[]
no_license
module Interface def read_file file = File.open(ARGV[0], 'r') file.read end def new_file File.open(ARGV[1], 'w') end def write_file(alteration) new_file.write(alteration) new_file.close end end
true
79bf2ecefbcff4f230dfeb3ff69e8d10756d4a34
Ruby
rfc2822/meta-tags
/lib/meta_tags/controller_helper.rb
UTF-8
1,562
2.671875
3
[ "MIT" ]
permissive
module MetaTags # Contains methods to use in controllers. # # You can define several instance variables to set meta tags: # @page_title = 'Member Login' # @page_description = 'Member login page.' # @page_keywords = 'Site, Login, Members' # # Also you can use {InstanceMethods#set_meta_tags} method, that have the same parameters # as {ViewHelper#set_meta_tags}. # module ControllerHelper def self.included(base) base.send :include, InstanceMethods base.alias_method_chain :render, :meta_tags end module InstanceMethods # Processes the <tt>@page_title</tt>, <tt>@page_keywords</tt>, and # <tt>@page_description</tt> instance variables and calls +render+. def render_with_meta_tags(*args, &block) meta_tags = {} meta_tags[:title] = @page_title if @page_title meta_tags[:keywords] = @page_keywords if @page_keywords meta_tags[:description] = @page_description if @page_description set_meta_tags(meta_tags) render_without_meta_tags(*args, &block) end # Set meta tags for the page. # # See <tt>MetaTags.set_meta_tags</tt> for details. def set_meta_tags(meta_tags) meta_tags ||= {} meta_tags[:open_graph] = meta_tags.delete(:og) if meta_tags.key?(:og) self.meta_tags.deep_merge!(meta_tags || {}) end protected :set_meta_tags # Get meta tags for the page. def meta_tags @meta_tags ||= {} end protected :meta_tags end end end
true
e76941abc7cb7b379664c589ad8e2a5e2efd4bcc
Ruby
clock-rick/TestRedirects
/redirects.rb
UTF-8
3,071
3.53125
4
[]
no_license
require 'selenium-webdriver' require 'csv' require 'chromedriver/helper' require 'colorize' require 'net/http' =begin This test will open two csv files, the first with original urls and the second with the redirects. The test will compare take the original url and record the redirect in browser. Then compare it to the url from the second csv. The results will be displayed in the output screen. The failures will be recorded into a new csv. =end class Redirects options = Selenium::WebDriver::Chrome::Options.new options.add_argument('--headless') driver = Selenium::WebDriver::Driver.for :chrome, options: options url_hash = {} csv_array = [] row_counter = 2 # Change this value to 1 if your csv does not have a header. driver =begin This section reads the redirects csv and places each row of information into the array. Since both the 'to url' and the 'from url' are contained within the same row, they both are contained in the value of each array key. You will need to either update the path and csv name to what you want or edit the csv itself with your new redirects. =end CSV.foreach('Redirects.csv', headers: true) { |row| csv_array << row.to_s} =begin This section iterates through the csv array and splits the from url and to url into a new array so each url is associated to its own key then that the values are associated from the new array to a new hash called 'url_hash'. In the hash the from url is the key and the to url is the value. =end csv_array.each { |word| @my_word = word.split(',') url_hash[@my_word[0]] = @my_word[1]} =begin In this section we direct the driver to proceed to the 'from_url'. If the redirect is in place by the developer than the redirect will initiate automatically and direct the driver to the 'to_url'. The 'redirected_to' variable grabs the current url which should be the where the driver was redirected to. We then compare that 'redirected_to' url to the 'to_url' from the redirects spreadsheet and do a compare. If it's a pass then the snippet prints out the 'from_url' and to_url and marks it as a Pass. If it does not match, we print the 'from_url' and 'to_url' and the 'redirected_url' and we mark it as a fail. All fails are captured into a new csv. You should go into the snippet and name the new csv to something relevant to the project. After the run is complete the driver quits. =end url_hash.each { |from_url, to_url| response = Net::HTTP.get_response(URI(from_url)) location = response['location'] redirected_to= location.to_s.downcase from_actual = from_url.to_s.downcase.strip to_actual = to_url.to_s.downcase.strip if redirected_to == to_actual puts "ROW #{row_counter}: PASS ".green + from_actual + ' >>> '.green + to_actual else puts "ROW #{row_counter}: Fail ".red + from_actual + ' >>> '.red + to_actual + ' Redirected to '.red + redirected_to CSV.open('RedirectFails.csv', 'a') { |csv| csv << [from_actual, to_actual, redirected_to]} end row_counter += 1 } driver.quit rescue StandardError => e puts e end
true
6bf926e50f0882fcb3992267517e469bdab04c75
Ruby
jhardy3/IronhackCourse
/UnitTest/lexiconomitron_spec.rb
UTF-8
869
3.3125
3
[]
no_license
require "rspec" require "./Lexiconomitron" describe "Lexiconomitron" do let(:lexi) { Lexiconomitron.new } describe '#eat_t' do let(:input) {"great scott!"} let(:output) {"grea sco!"} it "removes every letter t from the input" do lexi = Lexiconomitron.new expect(lexi.eat_t(input)).to eq(output) end end describe '#shazam' do let(:input) {["This", "is", "a", "boring", "test"]} let(:output) {["sih", "se"]} it "reverses every string in array" do lexi = Lexiconomitron.new expect(lexi.shazam(input)).to eq(output) end end describe '#oompa_loompa' do let(:input) {["if", "you", "wanna", "be", "my", "lover"]} let(:output) {["if", "you", "be", "my"]} it "only prints words < 3" do lexi = Lexiconomitron.new expect(lexi.oompa_loompa(input)).to eq(output) end end end
true
7e2ac0d10b4276f434c51594095c86ef4dffe936
Ruby
nricheton/FaitesLesComptes
/lib/pdf_document/page.rb
UTF-8
2,980
2.96875
3
[ "Apache-2.0" ]
permissive
# coding: utf-8 require 'pdf_document/table' module PdfDocument class Page attr_reader :number, :table, :document def initialize(number, doc) @number = number @document = doc end def stamp document.stamp end def top_left "#{document.organism_name}\n#{document.exercice}" end def title document.title end def subtitle document.subtitle end def top_right I18n::l(document.created_at, :format=>"Edition du\n%e %B %Y\nà %H:%M:%S") end def table_title pdf_table.title end def table_columns_widths document.columns_widths end def total_columns_widths document.total_columns_widths end def table_lines pdf_table.prepared_lines.collect {|l| format_line(l)} end def table_lines_depth pdf_table.depths end def table_total_line format_line pdf_table.total_line end # forunit le report def table_report_line return document.first_report_line if @number == 1 # première page r = document.page(@number -1).table_to_report_line r[0] = 'Reports' r end # additionne la ligne de report (si elle existe) et la ligne de total def table_to_report_line # cas où la ligne de report n'existe pas # on prend la ligne total et on change juste le titre unless table_report_line r = table_total_line else r =[] table_report_line.each_with_index do |v,i| r << french_format(french_to_f(v) + french_to_f(table_total_line[i])) end end r[0] = last_page? ? 'Total général' : 'A reporter' r end # indique si on est sur la dernière page def last_page? @number == document.nb_pages end protected # construit une table en donnant comme argument la page et le document # def pdf_table @table ||= Table.new(self) end # appelle la méthode french_format pour chaque élément de ligne def format_line(l) l.collect {|v| french_format(v)} end # est un proxy de ActionController::Base.helpers.number_with_precicision # TODO faire un module qui gère ce sujet car utile également pour table.rb def french_format(r) return '' if r.nil? return ActionController::Base.helpers.number_with_precision(r, :precision=>document.precision) if r.is_a? Numeric r end # transforme un string représentant un nombre en format français, par exemple # '1 300,25' en un float que le programme saura additionner. # # On prévoit le cas ou number serait malgré tout Numeric en retournant la valeur # # TODO faire une sous classe de Float qui sache additionner nativement le # format français. def french_to_f(number = 0) number.is_a?(Numeric) ? number : number.gsub(',', '.').gsub(' ', '').to_f rescue 0 end end end
true
8d90aa9efcdf010be019f779175c45b1c2de5c91
Ruby
DouglasAllen/ruby-kickstart-4-rdoc
/session2/notes/05-other-useful-array-methods.rb
UTF-8
668
3.59375
4
[]
no_license
class Session02Notes =begin === Useful methods chars = ['a', 'b', 'c'] # Concatenate with + chars + ['d', 'e'] # => ["a", "b", "c", "d", "e"] # Append to an array chars # => ["a", "b", "c"] chars << 'd' chars # => ["a", "b", "c", "d"] # Replace chars[1] = 'Bee' chars # => ["a", "Bee", "c", "d"] # Delete index chars.delete_at 1 chars # => ["a", "c", "d"] # Delete object chars.delete 'c' chars # => ["a", "d"] # Insert index = 1 chars.insert index, 'b' , 'c' chars # => ["a", "b", "c", "d"] # Sorting ['c', 'b', 'd', 'a'].sort # => ["a", "b", "c", "d"] =end def session2_05_other_useful_array_methods;end end
true
d4808fb78806c907bdb3d05bc563df79c334e6ea
Ruby
dmono/rock-paper-scissors
/lib/rock.rb
UTF-8
208
2.859375
3
[]
no_license
require_relative 'move' class Rock < Move def initialize @value = 'rock' @initial = 'R' end def beats?(other_move) other_move.value == 'scissors' || other_move.value == 'lizard' end end
true
2547091ec390e8589b45a2c68a0c121514e1c9b5
Ruby
ivancarrascal/Generation-projects
/facetoface/semana_1/functions2.rb
UTF-8
400
3.953125
4
[]
no_license
def power_formula(base_chemical) sugar = base_chemical * 500 spice = sugar / 1000 everything_nice = sugar / 100 return sugar, spice, everything_nice end chemical_x = 10000 blossom, buttercup, bubbles = power_formula(chemical_x) puts "Using the value #{chemical_x} as our base chemical" puts "We get values of #{blossom} for blossom, #{buttercup} for buttercup, and #{bubbles} for bubbles."
true
0cf607e2c67d7f0e4a74e12436e60b81c6c09ffc
Ruby
tompave/prime_numbers
/lib/prime_numbers/renderer.rb
UTF-8
1,133
3.21875
3
[ "MIT" ]
permissive
module PrimeNumbers class Renderer def initialize(table) @table = table end def render buffer = [] buffer << render_header buffer << render_separator table.size.times do |row| buffer << render_row(row) end buffer.join("\n") end private attr_reader :table def render_header buffer = format(" ", gutter_width) buffer << table.columns.map do |column| format(column.header, column.width) end.join end def render_separator buffer = "-" * (gutter_width + 2) + "+" buffer << table.columns.map do |column| "-" * (column.width + 2) + "+" end.join end def render_row(row) buffer = format(table.primes[row], gutter_width) table.columns.each do |column| value = column[row].value buffer << format(value, column.width) end buffer end def format(value, column_width) width = column_width + 1 "%#{width}s |" % value end def gutter_width @gutter_width ||= table.primes.last.to_s.length end end end
true
1603deeb048a0ff783d91604bd5649beaa84b3b3
Ruby
mrdevin/scss-lint
/lib/scss_lint/linter/declaration_order.rb
UTF-8
918
2.71875
3
[ "MIT" ]
permissive
module SCSSLint # Checks the order of nested items within a rule set. class Linter::DeclarationOrder < Linter include LinterRegistry DECLARATION_ORDER = [ Sass::Tree::ExtendNode, Sass::Tree::PropNode, Sass::Tree::RuleNode, ] def visit_rule(node) children = node.children.select { |n| important_node?(n) } .map { |n| n.class } sorted_children = children.sort do |a, b| DECLARATION_ORDER.index(a) <=> DECLARATION_ORDER.index(b) end if children != sorted_children add_lint(node.children.first, MESSAGE) end yield # Continue linting children end private MESSAGE = 'Rule sets should start with @extend declarations, followed by ' \ 'properties and nested rule sets, in that order' def important_node?(node) DECLARATION_ORDER.include? node.class end end end
true
6758d25e784dea0c3a926fd290db8442830fac56
Ruby
MisterAreBe/rb-tic-tac-toe
/app_2.rb
UTF-8
4,868
2.734375
3
[]
no_license
require 'sinatra' require_relative 'ttt_require_me.rb' enable :sessions get '/' do erb :index, :layout => :layout end post '/play' do session[:size] = params[:size] || 3 session[:board] = Game_board.new(session[:size].to_i) session[:playerx] = params[:playerx] || '' session[:playero] = params[:playero] || '' redirect '/board' end get '/board' do # Where the game is played board = session[:board] playerx = session[:playerx] || '' playero = session[:playero] || '' winner = session[:winner] || '' if board.is_a?(Array) session[:turn] = 0 else session[:turn] = board.turn end show_board = session[:show_board] || "hide" show_players = session[:show_players] || "show" show_set_up = session[:show_set_up] || "show" show_winner = session[:show_winner] || "hide" show_reset = session[:show_reset] || "hide" temp_arr = [show_set_up, show_winner, show_reset] if temp_arr.any? {|v| v == "show"} show_options = "show" else show_options = "hide" end if winner == "x" winner = "Vegeta has won!" elsif winner == "o" winner = "Goku has won!" elsif winner == "Draw" winner = "Draw!" else winner = '' end bot_bot = session[:comp_vs_comp] || "not_bot" erb :board, :layout => :layout, locals: {board: board, winner: winner, show_board: show_board, show_players: show_players, show_set_up: show_set_up, show_winner: show_winner, show_reset: show_reset, show_options: show_options, bot_bot: bot_bot, google_name: google_name} end post '/move' do # Proccessing moves turn = session[:turn] temp = params[:tile] || '' temp = temp.split(',') tile = [] temp.each do |v| tile << v.to_i end # Player vs Computer --start if session[:xhelp] && !session[:ohelp] && turn.even? if session[:board].check_place(tile[0], tile[1]) session[:playerx].place_piece(tile[0], tile[1]) if session[:board].winner_is?() == false session[:playero].move() end end elsif session[:ohelp] && !session[:xhelp] && !turn.even? if session[:board].check_place(tile[0], tile[1]) session[:playero].place_piece(tile[0], tile[1]) if session[:board].winner_is?() == false session[:playerx].move() end end # Player vs Computer --end # For PvP turn taking --start elsif session[:xhelp] && turn.even? if session[:board].check_place(tile[0], tile[1]) session[:playerx].place_piece(tile[0], tile[1]) end elsif session[:ohelp] && !turn.even? if session[:board].check_place(tile[0], tile[1]) session[:playero].place_piece(tile[0], tile[1]) end # For PvP turn taking --end # For Computer vs Computer --start elsif !session[:xhelp] && !session[:ohelp] session[:playerx].move() if session[:board].winner_is?() == false session[:playero].move() end if session[:comp_vs_comp] == "bot battle" && turn > 0 sleep(1) end end # For Computer vs Computer --end session[:show_board] = "show" session[:show_players] = "hide" session[:show_set_up] = "hide" session[:show_winner] = "hide" session[:show_reset] = "hide" if session[:board].winner_is?() != false session[:winner] = "#{session[:board].winner_is?()}" session[:show_winner] = "show" session[:show_reset] = "show" session[:comp_vs_comp] = "not_bot" end redirect '/board' end post '/set_up' do # Set up the board to start a game session[:size] = params[:grid_size] || 3 session[:board] = x = params[:playerx] o = params[:playero] session[:xhelp] = false session[:ohelp] = false case x when 'easy' session[:playerx] = Random_ai.new('x', session[:board]) when 'medium' session[:playerx] = Sequential_ai.new('x', session[:board]) when 'hard' session[:playerx] = Unbeatable_ai_2.new('x', session[:board]) when 'human' session[:playerx] = Base_ai.new('x', session[:board]) session[:xhelp] = true end case o when 'easy' session[:playero] = Random_ai.new('o', session[:board]) when 'medium' session[:playero] = Sequential_ai.new('o', session[:board]) when 'hard' session[:playero] = Unbeatable_ai_2.new('o', session[:board]) when 'human' session[:playero] = Base_ai.new('o', session[:board]) session[:ohelp] = true end if session[:ohelp] && !session[:xhelp] session[:playerx].move() elsif !session[:xhelp] && !session[:ohelp] session[:comp_vs_comp] = "bot battle" end session[:show_board] = "show" redirect '/board' end post '/start_over' do # Set the board and player choices back to blank redirect '/' end post '/reset' do # Reset the board but keep the players session[:board].reset() if session[:ohelp] && !session[:xhelp] session[:playerx].move() elsif !session[:xhelp] && !session[:ohelp] session[:comp_vs_comp] = "bot battle" end redirect '/board' end
true
6e9c723228321e31ed4cb5e3cd314d347eab4eb1
Ruby
trueknightwhosayni/ni
/lib/ni/action_chain.rb
UTF-8
2,615
2.640625
3
[ "MIT" ]
permissive
module Ni class ActionChain attr_accessor :name, :description, :received_values, :returned_values, :units, :failure_callback, :rescues def initialize(klass, name, description, &block) @interactor_klass = klass @name = name, @description = description @units = block_given? ? [block.to_proc] : [] @failure_callback = nil @rescues = [] @returned_values = [] self ensure update_chain end # Params methods def receive(*args) @received_values = args self ensure update_chain end def provide(*args) @returned_values = args self ensure update_chain end # Flow methods def then(*args, **options, &block) if block_given? @units << block.to_proc else @units << chain_builder(args, options) end self ensure update_chain end def isolate(*args, **options, &block) if block_given? raise 'Not Implemented yet' else first, last = args @units << Ni::Flows::IsolatedInlineInteractor.new(first, (last || :perform), options) end self ensure update_chain end def failure(&block) @failure_callback = block.to_proc self ensure update_chain end def rescue_from(*args, &block) args = [Exception] if args.empty? @rescues << [args, block.to_proc] self ensure update_chain end def wait_for(condition, options={}) @units << Ni::Flows::WaitForCondition.new(condition, @interactor_klass, options) self ensure update_chain end def branch(*args, **options, &block) @units << Ni::Flows::BranchInteractor.new(@interactor_klass, args, options, &block) self ensure update_chain end def terminate! @units << "context.terminate!" ensure update_chain end def cancel! @units << "context.cancel!" ensure update_chain end def failure! @units << "context.failure!" ensure update_chain end def success! @units << "context.success!" ensure update_chain end private def chain_builder(args, options) first, last = args case first when Symbol, String first when Class Ni::Flows::InlineInteractor.new(first, (last || :perform), options) else raise 'Invalid chain options' end end def update_chain @interactor_klass.defined_actions[name] = self end end end
true
421f81536610f82a3580134ce52e2111c9530730
Ruby
EricRicketts/LaunchSchool
/exercises/Ruby/object_oriented_programming/easy/one/exercise_eight_test.rb
UTF-8
512
3.34375
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require 'pry-byebug' class ExerciseEightTest < Minitest::Test class Rectangle def initialize(height, width) @height = height @width = width end def area @height * @width end end class Square < Rectangle def initialize(side) super(side, side) end end def test_one expected = "area of square = 25" result = "area of square = #{Square.new(5).area}" assert_equal(expected, result) end end
true
23643a61f0d8233f50e12aaa40f6459880cce08d
Ruby
katharinap/orange
/app/models/course.rb
UTF-8
1,534
2.5625
3
[]
no_license
# == Schema Information # # Table name: courses # # id :integer not null, primary key # name :string # date :date # user_id :integer # created_at :datetime not null # updated_at :datetime not null # class Course < ApplicationRecord belongs_to :user validates :name, presence: true validates :date, presence: true delegate :url_helpers, to: 'Rails.application.routes' KNOWN = { 'Krav Level 1' => { short_title: 'KM 1', color: COLORS[0] }, 'Krav Level 2' => { short_title: 'KM 2', color: COLORS[1] }, 'Sparring' => { short_title: 'Sparring', color: COLORS[2] }, 'Krav Weapons' => { short_title: 'Weapons', color: COLORS[3] }, 'JCF' => { short_title: 'JCF', color: COLORS[4] }, 'Pit' => { short_title: 'Pit', color: COLORS[5] }, 'Other' => { short_title: 'Other', color: COLORS[6] } }.freeze def color entry = KNOWN[name] || KNOWN['Other'] entry[:color] end def self.calendar_data(*users) courses = [] if users.size > 1 users.each_with_index do |user, idx| courses += user.courses.map { |c| c.user_calendar_data(idx) } end else courses += users.first.courses.map(&:calendar_data) end courses end def calendar_data { title: name, date: date, edit_url: url_helpers.edit_course_path(self), color: color } end def user_calendar_data(color_idx) calendar_data.merge( color: COLORS[color_idx], tip: user.login ) end end
true
c9dadf2cf09ca147c23739e78113c9b9515c110f
Ruby
roryg11/interview
/lib/address.rb
UTF-8
509
2.890625
3
[]
no_license
require_relative 'geocoding' class Address attr_accessor :lat, :lng, :full_address def reverse_geocoded_by Geocoder.search([@lat, @lng]).first.address end def get_coordinates Geocoder.search(@full_address) end def get_distance_from(addressTo, address) addressToCoordinates = Geocoder.search(addressTo).first.coordinates addressFromCoordinates = Geocoder.search(@address.full_address); addressFromCoordinates.distance_to([addressTo.latitude, addressTo.longitude]) end end
true
056586d9df36150d25d9ae8adeefbf7cf2e16c81
Ruby
mislav/tolk
/lib/tolk/import.rb
UTF-8
1,244
2.65625
3
[ "MIT" ]
permissive
module Tolk module Import def self.included(base) base.send :extend, ClassMethods end module ClassMethods def import_secondary_locales locales = I18n.available_locales - [self.primary_locale.name.to_sym] phrases = Tolk::Phrase.all locales.each {|name| import_locale(name.to_s, phrases) } end def import_locale(locale_name, phrases) locale = Tolk::Locale.find_or_create_by_name(locale_name) data = load_translations(locale.name.to_sym) count = 0 data.each do |key, value| phrase = phrases.detect {|p| p.key == key} if phrase translation = phrase.translations.detect {|t| t.locale_id == locale.id } translation ||= locale.translations.new(:phrase => phrase) translation.text = value count += 1 if (translation.new_record? or translation.changed?) and translation.save else puts %([ERROR] Key '%s' was found in "%s" locale but the %s translation is missing) % [key, locale_name, Tolk::Locale.primary_language_name] end end puts %([INFO] Imported #{count} keys from "#{locale_name}" locale) end end end end
true
f2dde4c332dcf157de5cd0eb11a6b2460285f8e5
Ruby
Barteezy/rake-warmup
/Rakefile
UTF-8
1,011
3.578125
4
[]
no_license
desc "Print a nice greeting" task :greet do puts "Hello there" end desc "Prints your favorite food is" task :print_favorite_food do ENV["FAVORITE_FOOD"] = "Pizza" puts "Favorite Food is: #{ENV["FAVORITE_FOOD"]}" end task :first do puts "First!" end task :second => :first do puts "Second!" end task :wake_up do puts "I'm awake!" end task :gets_dressed => :wake_up do puts "I'm dressed" end # - Write a rake task called `ready_for_class`, that depends on tasks called `wake_up`, # `eat_breakfast`, and `brush_teeth`. task :brush_teeth => :eat_breakfast do puts "brush brush brush" end task :eat_breakfast => :wake_up do puts "I'm eating" end task :ready_for_class => :brush_teeth do puts "I'm ready for class" end namespace :greeting do desc "Say hello" task :hello do puts "Hello there" end desc "Say howdy" task :howdy do puts "Howdy partner" end end task :default => [:wake_up]
true
6ab38a7aa329f2fd57a7bededea9ddce464fbdf2
Ruby
marysadness/CS262
/homework01/01-4-homework.rb
UTF-8
204
2.609375
3
[]
no_license
class CustomeTime < Time def time_now() return Time.now() end def time_day() t = Time.local(time_now()) return t.friday? end def local_zone() return Time.time_now().zone end end
true