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
51a107c8653be0cbc22b4e118a89e372f17c5ce6
Ruby
Chanic/Ruby-Projects
/CalcSlap.rb
UTF-8
2,281
3.65625
4
[]
no_license
puts 'Welcome to CalcSlap v0.6' puts '' puts '' puts 'What type of calculation would you like to run?' puts '' puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'Close\' to close.' command = gets.chomp while command != 'Close' #if command != 'Add' # or command != 'Sub' # or command != 'Div' # or command != 'Mul' # puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'End\' to close.' #else if command == 'Add' puts 'Now please enter the first number, press enter, then the second number with a final enter' addone = gets.chomp addtwo = gets.chomp puts addone.to_f + addtwo.to_f puts 'Would you like to make another calulation?' puts '' puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'End\' to close.' command = gets.chomp end if command == 'Sub' puts 'Now please enter the first number, press enter, then the second number with a final enter' subone = gets.chomp subtwo = gets.chomp puts 'Your answer is:' puts subone.to_f - subtwo.to_f puts '' puts '' puts '' puts 'Would you like to make another calulation?' puts '' puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'End\' to close.' end if command == 'Div' puts 'Now please enter the first number, press enter, then the second number with a final enter' divone = gets.chomp divtwo = gets.chomp puts divone.to_f / divtwo.to_f puts 'Would you like to make another calulation?' puts '' puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'End\' to close.' end if command == 'Mul' puts 'Now please enter the first number, press enter, then the second number with a final enter' mulone = gets.chomp multwo = gets.chomp puts '' puts mulone.to_f * multwo.to_f puts '' puts 'Would you like to make another calulation?' puts '' puts 'Please use \'Add\' for addition, \'Sub\' for subtract, \'Div\' for divide or \'Mul\' for multiplication. Please type \'End\' to close.' end if command == 'Close' puts 'Bye!' end end #end
true
0347523068fbf855d80a84e9525278b810c0a399
Ruby
yxia521/solutions-to-intro-to-programming
/Chapter_9_More_Stuff/exercise_5.rb
UTF-8
501
3.34375
3
[]
no_license
def execute(block) block.call end execute { puts "Hello from inside the execute method!" } # Error # block.rb1:in `execute': wrong number of arguments (0 for 1) (ArgumentError) from test.rb:5:in `<main>' # This error message informs you that Ruby can't execute line 5, because on line 1 the number of argument # of execute is wrong. There should be 1 argument but you give 0. # Without a &, Ruby doesn't recognize block as an argument. # To fix this, we should write a &block
true
e82ff57103ecd6d380d4f73aa64e3dcc3e481513
Ruby
smhaggerty/hackerrank_challenges
/ruby/ruby-tutorial/enumerables/reduce.rb
UTF-8
98
3.078125
3
[]
no_license
def sum_terms(n) # your code here (1..n).reduce(0) {|sum, num| sum += (num * num + 1)} end
true
ea055690804a7af816f3b44bc90200c373afec3d
Ruby
ShadowManu/SigulabRails
/app/models/consumable.rb
UTF-8
1,008
2.75
3
[ "MIT" ]
permissive
require "unicode_utils" class Consumable < ActiveRecord::Base validates :name, :presence => {:message => "no puede ser blanco"} validates :dependency, :presence => {:message => "no puede ser blanco"} validates :location, :presence => {:message => "no puede ser blanco"} validates :responsible, :presence => {:message => "no puede ser blanco"} def self.search(query) query=UnicodeUtils.upcase(query, :es) where("name like ?", "%#{query}%") end before_save :uppercase_fields before_update :uppercase_fields private def uppercase_fields self.name=UnicodeUtils.upcase(self.name, :es) self.material=UnicodeUtils.upcase(self.material, :es) self.quantity=UnicodeUtils.upcase(self.quantity, :es) self.location=UnicodeUtils.upcase(self.location, :es) self.responsible=UnicodeUtils.upcase(self.responsible, :es) self.bill=UnicodeUtils.upcase(self.bill, :es) self.buy_order=UnicodeUtils.upcase(self.buy_order, :es) self.dependency=UnicodeUtils.upcase(self.dependency, :es) end end
true
f0a6da83d3a0fea81df4aa36fde8a9b68dd2d2be
Ruby
rymon23/w2d4
/execution_time_diffs_algos/execution.rb
UTF-8
2,276
3.703125
4
[]
no_license
require "byebug" # list = [ 0, 3, 5, 4, -5, 10, 1, 90 ] def my_min(list) current_min = nil #o(1) list.each_with_index do |el, i| #O(n) list.each_with_index do |el2, j| #O(n) if j > i #O(1) current_min ||= el #O(1) current_min = (current_min < el2) ? current_min : el2 #O(1) current_min = (current_min < el) ? current_min : el #O(1) end end end current_min #O(1) end # p my_min(list) def my_min2(list) list.inject do |acc, el| #O(n) if acc < el #O(1) acc #O(1) else el #O(1) end end end # p my_min2(list) # def largest_contiguous_subsum(list) # max_sum = nil # (0...list.length - 1).each do |i| # (i...list.length).each do |j| # # debugger # subarr = list[i..j] # sum = subarr.sum # max_sum ||= sum # if max_sum < sum # max_sum = sum # end # end # end # max_sum # end def largest_contiguous_subsum(list) max_sum = nil #O(1) sub_arr_holder = [] #O(1) (0...list.length - 1).each do |i| #O(n) (i...list.length).each do |j| #O(n) subarr = list[i..j] #O(n) sub_arr_holder << subarr #O(1) ?????? end end sub_arr_holder.inject do |acc, arr| #O(n) + #O(1) + #O(1) if acc.sum > arr.sum #O(n) + #O(n) + #O(1) acc #O(1) else arr #O(1) end end.sum #O(n) end def largest_contiguous_subsum(list) largest = nil #O(1) running = nil #O(1) list.each do |el| #O(n) largest ||= el #O(1) if running.nil? || running < 0 #O(1) running = el #O(1) else running += el #O(1) end if largest < running #O(1) largest = running #O(1) end end largest #O(1) end # list = [2, 3, -6, 7, -6, 7] # p largest_contiguous_subsum(list) # => 8 # list = [-5, -1, -3] # p largest_contiguous_subsum(list) # => -1 (from [-1]) # def first_anagram?(str1, str2) # hash = Hash.new(0) # hash2 = Hash.new(0) # str1.each_char {|char| hash[char] += 1} # str2.each_char {|char| hash2[char] += 1} # hash == hash2 # end def first_anagram?(str1, str2) str1.split("").permutation.to_a.map do |arr| arr.join end.include?(str2) end p first_anagram?("gizmobdfhksqrsgq", "sally") #=> false puts p first_anagram?("elvis", "lives") #=> true
true
1d7e343fe2fdb67ff3acab3c655cd0115af8e7fb
Ruby
Nimzyow/boris_bikes
/spec/docking_station_spec.rb
UTF-8
1,652
2.859375
3
[]
no_license
require "docking_station" require "bike" shared_context "common" do let(:bike) {Bike.new} end describe DockingStation do include_context "common" context "methods" do it "responds to #release_bike" do expect(subject).to respond_to(:release_bike) end it "#release_bike prevents release if currently_docked.length = 0" do expect{subject.release_bike}.to raise_error end it "#release_bike" do subject.dock_bike({bike:bike}) expect(subject.release_bike).to be_an_instance_of(Bike).and respond_to(:working?) end it "#dock_bike pushes Bike instance into currently_docked array" do expect{subject.dock_bike({bike:bike})}.to change{subject.currently_docked.length}.by(1) end it "#dock_bike prevents push into currently_docked array if = capacity" do 8.times {subject.dock_bike({bike:bike})} expect{subject.dock_bike({bike:bike})}.to raise_error end it "#show_docked_bikes returns number of bikes on the docking station" do subject.dock_bike({bike:bike}) subject.dock_bike({bike:bike}) subject.dock_bike({bike:bike}) expect(subject.show_docked_bikes).to eq(subject.currently_docked.length).or eq("No bikes here currently") end end context "has attributes" do it "currently_docked" do expect(subject).to have_attributes(currently_docked: []) end it "capacity with default of 8" do expect(subject).to have_attributes(capacity: 8) end it "capacity with custom capcaity" do subject = described_class.new({capacity: 10}) expect(subject).to have_attributes(capacity: 10) end end end
true
214bde8783427e98562bccf657d331319540845e
Ruby
kzk/holt-winters
/lib/holt_winters_factory.rb
UTF-8
396
2.5625
3
[ "Apache-2.0" ]
permissive
require 'holt_winters.rb' class HoltWintersFactory def self.create(alpha, attrs={}) if (attrs.has_key? :beta) HoltWintersDouble.new(alpha, attrs[:beta]) elsif (attrs.has_key? :beta) && (attrs.has_key? :gamma) && (attrs.has_key? :period) HoltWintersTriple.new(alpha, attrs[:beta], attrs[:gamma], attrs[:period]) else HoltWintersSimple.new(alpha) end end end
true
c711467bcf82318c0692e40d099cf14f04d62e8c
Ruby
jimmikmak/Ruby_course
/Strings I/case_bang_methods.rb
UTF-8
822
4.0625
4
[]
no_license
# frozen_string_literal: true # Case Methods puts 'hello12'.capitalize puts 'heLLo!@'.capitalize puts 'Hello 56'.capitalize puts 'hello world'.capitalize.class puts 'james123'.upcase puts 'wa wa wa wa wa'.upcase lowercase = "I'm patient" uppercase = lowercase.upcase p uppercase p 'JAMES'.downcase p 'jaMEs'.swapcase # Reverse Method puts 'Ruby'.reverse puts '!@#%&*'.reverse.class # puts "ruby is fun".upcase.reverse.downcase # Bang Method word = 'hello' p word word.capitalize! p word word.upcase! p word word.downcase! p word word.reverse! p word word.swapcase! p word # include? Method name = 'Snow White' p name.include?(' ') p name.downcase.include?('s') # empty? & nil? methods p ''.empty? p 'James'.empty? p ''.nil? puts name = 'Donald Duck' last_name = name[100, 4] p last_name p last_name.nil?
true
2c85ab1291549c8890800e8f112012a9b90285b9
Ruby
cybool/junos-automation-examples
/ruby/ruby-language-intro.rb
UTF-8
316
2.875
3
[]
no_license
#!/usr/bin/ruby def process_interface(interface) if interface =~ /ge-.*/ yield "#{interface} is gigabit" else yield "#{interface} is of unknown speed" end end interfaces = ["ge-1/0/5", "fxp0"] interfaces.each do |intf| process_interface(intf) { |str| puts str } end 3.times { puts "---------" }
true
4f8eee5001ed2c5fc554fbcc88b7eea004be4946
Ruby
PaulGTN/Exo-Ruby
/exo_07_c.rb
UTF-8
231
2.921875
3
[]
no_license
user_name = gets.chomp puts user_name # a Pose question, obtient réponse et répète, b idem mais avec une meilleure ergonomie utilisateur, c juste un écran noir si on ne sait pas ce qu'on doit faire, moins complet que les autres
true
49155ba4082ad4ce497f1e0ff115601d1af83be9
Ruby
SoniaDumitru/collections_practice_vol_2-chicago-web-career-040119
/collections_practice.rb
UTF-8
891
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#'Return true if every element of the tools array #starts with an "r" and false otherwise. def begins_with_r(array) array.all? do |word| word[0] == "r" end end #return all elements that contain the letter 'a' (filter) def contain_a(array) array.select do |word| word.include?("a") end end #Return the first element that begins #with the letters 'wa' def first_wa(array) array.find do |word| word[0,2] == "wa" end end # remove anything that's not # a string from an array def remove_non_strings(array) array.delete_if do |word| word.is_a?(String) == false end end #count how many times #something appears in an array def count_elements(array) array.count do |word| end #combines two nested data structures into one def merge_data(array) end #find all cool hashes def find_cool(array) end #organizes the schools by location def organize_schools(array) end
true
ca1aa8f8f99736b3080f42c94260f8fc4af06950
Ruby
daniellacosse/app-academy
/Week 2; OO Design/W2D4_Checkers/lib/checker.rb
UTF-8
2,741
3.21875
3
[]
no_license
# coding: utf-8 require "debugger" class Checker attr_accessor :pos, :kinged attr_reader :color, :board def initialize(pos, color, board) @pos, @color, @board = pos, color, board @kinged = false end def to_s kinged ? "☹" : "☺" end def perform_moves(dirs) if valid_move_seq?(dirs) perform_moves!(dirs) else raise MoveError end end def perform_moves!(dirs) dirs_arr = dirs.split(" ") if dirs_arr.length > 1 dirs_arr.each{ |dir| perform_jump(dir) } else begin perform_slide(dirs_arr.first) rescue MoveError perform_jump(dirs_arr.first) end end end def valid_move_seq?(dirs) board_dup = board.deep_dup begin board_dup[pos].perform_moves!(dirs) rescue MoveError return false end true end def required_move? unless any_valid_jumps?.empty? # grow any_valid_jumps? # get longest branch end def any_valid_jumps? valid_jumps = ['l', 'r', 'bl', 'br'].select do |cmd| valid_jump = true pos_jump_move = direction_toggle(cmd, 2) begin perform_jump(pos_jump_move) rescue MoveError vaild_jump = false end valid_jump end # return coordinates of valid jumps -- test each for more valid jumps end private def perform_slide(dir) raise MoveError if !kinged && dir.include?("b") new_pos = direction_toggle(dir) handle_mov_errors(new_pos) move_to!(new_pos) nil end def perform_jump(dir) raise MoveError if !kinged && dir.include?("b") new_pos = direction_toggle(dir, 2) jum_pos = direction_toggle(dir) handle_mov_errors(new_pos) handle_jump_errors(jum_pos) move_to!(new_pos) board[jum_pos] = nil nil end def direction_toggle(char, mag = 1) case char when 'l' return delt(-mag, mag) when 'r' return delt(mag, mag) when 'bl' return delt(-mag, -mag) when 'br' return delt(mag, -mag) else raise ArgumentError end end def move_to!(new_pos) board[pos], board[new_pos] = nil, board[pos] self.pos = new_pos maybe_promote nil end def maybe_promote self.kinged = true if (pos.last == 0) && (color == :red) self.kinged = true if (pos.last == 7) && (color == :black) end def delt(dx, dy) dy = (color == :black) ? dy : -dy [pos.first + dx, pos.last + dy] end def handle_mov_errors(new_pos) raise MoveError unless board.in_grid?(new_pos) raise MoveError if board[new_pos] end def handle_jump_errors(jum_pos) raise MoveError unless board[jum_pos] && board[jum_pos].color != color end end class MoveError < StandardError end
true
981b7c15d2f4751e3d87dd2596d32d3c73565506
Ruby
cbp10/chitter-challenge
/spec/peep_spec.rb
UTF-8
796
2.578125
3
[]
no_license
require 'peep' describe '.all' do describe 'can see all peeps' do it 'returns all peeps sent' do connection = PG.connect(dbname: 'chitter_test') connection.exec("INSERT INTO peeps (peep, user_id) VALUES ('Hello', '#{user_id}');") connection.exec("INSERT INTO peeps (peep, user_id) VALUES ('Hey', '#{user_id}');") connection.exec("INSERT INTO peeps (peep, user_id) VALUES ('Hi', '#{user_id}');") peeps = Peep.all peep = peeps.first expect(peep.peep).to eq "Hi" expect(peeps.length).to eq 3 end end end describe '.create' do describe 'can add a peep' do it 'returns a peep posted' do Peep.create("Hello peeps!", user_id) peep = Peep.all.first expect(peep.peep).to eq "Hello peeps!" end end end
true
fcd015678045e442adab9ae255762acf1a9cbf9c
Ruby
jlonetree/ruby-enumerables-cartoon-collections-lab-part-1-atx01-seng-ft-082420
/cartoon_collections.rb
UTF-8
230
3.828125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def greet_characters(array) array.each do |list_dwarves| puts "Hello #{list_dwarves.capitalize}!" end end def list_dwarves(array) array.each_with_index do |dwarves, number| puts "#{number + 1}. #{dwarves}" end end
true
e992272cfa73b5eb6fb3c21d49803c26574e5d09
Ruby
andersontylerb/week1-input_output
/input_output.rb
UTF-8
105
2.9375
3
[]
no_license
puts "welcome name" name = [] name << gets.chomp puts "hi #{name}" name << gets.chomp puts "hi #{name}"
true
7162f9d86f3a22b4a6ffcfa6ae40defe87309b9b
Ruby
msynko/ruby_fundamentals2
/exercise7.rb
UTF-8
215
3.109375
3
[]
no_license
def wrap_text(word1,word2) return (word2 + word1 + word2) end puts wrap_text("Marina", "~~~") hashtags = wrap_text("new message", "###") equals= wrap_text(hashtags, "===") puts wrap_text(equals, "---")
true
519c1ad790b6ebe6088cbc1020a9f7aacb581681
Ruby
maximpertsov/upwords
/test/game_test.rb
UTF-8
669
2.796875
3
[ "MIT" ]
permissive
require 'test_helper' class GameTest < Minitest::Test include Upwords def setup @game = Game.new @game.add_player("Max") @game.add_player("Jordan") end def teardown @game.exit_game if @game.running? end def test_has_game_objects assert_kind_of(Board, @game.board) end def test_can_play_letter_at_cursor_posn @game.current_player.take_letter("C") @game.play_letter("C") assert_equal "C", @game.board.top_letter(*@game.cursor.pos) end def test_can_play_letter_at_given_posn @game.current_player.take_letter("C") @game.play_letter("C", 4, 5) assert_equal "C", @game.board.top_letter(4, 5) end end
true
31c8c321e30401db460fa504b9dc9ce659f0715d
Ruby
eedgarr/Block
/chain/etc/ac.rb
UTF-8
197
2.5625
3
[]
no_license
aaaaaaaa = ["pork steak", "noodle", "orange", "sapporo beer"].sort.reverse 1.upto(10) do aaaaaaaa.each do |bbbbbbb| puts bbbbbbb.capitalize + "!." + "good".upcase.capitalize + ".$" end end
true
6e582f2bc15d4152c96945bd571a2515c53dc5e6
Ruby
wulymammoth/rom-cassandra
/lib/rom/cassandra/migrations/migrator.rb
UTF-8
2,831
2.9375
3
[ "MIT" ]
permissive
# encoding: utf-8 module ROM::Cassandra module Migrations # Class Migrator finds the migration files and migrates Cassandra cluster # to the required version using method [#apply]. # # The class is responcible for searching files and deciding, # which of them should be runned up and down. Every single migration # is applied or rolled back using `RunnerUp` and `RunnerDown` classes. # # @example # migrator = Migrator.new(hosts: ["127.0.0.1"], port: 9042) # # # Applies all migrations # migrator.apply # # # Rolls back all migrations # migrator.apply version: 0 # # # Moves to the required version (before the year 2016) # migrator.apply version: 20151231235959 # class Migrator # @!attribute [r] session # # @return [ROM::Cassandra::Session] The session to the Cassandra cluster # attr_reader :session # @!attribute [r] logger # # @return [::Logger] The logger used by the migrator # attr_reader :logger # @!attribute [r] root # # @return [Array<String>] The root path for migrations # attr_reader :root # @!attribute [r] paths # # @return [Array<String>] The list of paths to migration files # attr_reader :paths # Initializes a migrator with Cassandra uri settings. # # Can specify logger and path as well. # # @param [ROM::Cassandra::Session] session # @option options [::Logger] :logger # @option options [String] :path # # See [ROM::Cassandra::Session] for other avaliable options for URI # def initialize(session, options = {}) @session = session @logger = options.fetch(:logger) { Logger.new } @root = options.fetch(:path) { DEFAULT_PATH } @paths = Dir[File.join(root, "*.rb")].sort end # Migrates the Cassandra cluster to selected version # # Applies all migrations if a version is skipped. # Rolls all migrations back if a version is set to 0. # # @option options [Integer, nil] :version # # @return [undefined] # def apply(options = {}) version = options.fetch(:version) { ALL_VERSIONS } migrate_to version rollback_to version end private def migrate_to(version) paths .reject { |path| GET_VERSION[path] > version } .each { |path| RunnerUp.apply(session, logger, path) } end def rollback_to(version) paths .select { |path| GET_VERSION[path] > version } .reverse_each { |path| RunnerDown.apply(session, logger, path) } end end # class Migrator end # module Migrations end # module ROM::Cassandra
true
f5229e303eece21b20a976e7f0ec775725c36f7e
Ruby
obsidian-btc/subst-attr
/test/bench/strict_null_object_attribute.rb
UTF-8
615
2.5625
3
[ "MIT" ]
permissive
require_relative 'bench_init' module Strict class SomeDependency def a_method; end end class Example extend SubstAttr::Macro subst_attr :some_attr, SomeDependency end end context "String" do example = Strict::Example.new context "Methods not on the impersonated class" do test "The attribute's value doesn't respond" do begin example.some_attr.some_method rescue => error end assert error end end context "Methods on the impersonated class" do test "The attribute's value responds" do example.some_attr.a_method end end end
true
d026393afcb6526252c9533b0a0071ddbfaa7b0f
Ruby
kvokka/activevalidation
/lib/active_validation/registry.rb
UTF-8
1,108
2.765625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module ActiveValidation class Registry include Enumerable attr_reader :name def initialize(name) @name = name @items = Concurrent::Map.new end def clear @items.clear end def each(&block) @items.values.uniq.each(&block) end def find(item_name) @items.fetch(normalize_name(item_name)) rescue KeyError => e raise key_error_with_custom_message(e, item_name) end alias [] find def register(name, item) @items[normalize_name(name)] = item end def registered?(name) @items.key?(normalize_name(name)) end def delete(name) @items.delete(normalize_name(name)) end private def key_error_with_custom_message(key_error, item_name) message = key_error.message.sub("key not found", %(#{@name} not registered: "#{item_name}")) error = KeyError.new(message) error.set_backtrace(key_error.backtrace) error end def normalize_name(key) key.respond_to?(:to_sym) ? key.to_sym : key.to_s.to_sym end end end
true
c68fa384307eef7acf0ed4f44f74038f527d1bd0
Ruby
pfspence/rubicon
/generators/sequencer.rb
UTF-8
340
2.796875
3
[]
no_license
class Sequencer attr_accessor :settings def initialize(args) set_settings({"key"=> "foobar"}) end def set_settings(settings) @settings = settings end def process() data = [] metadata =[] data = ["10","11","12","13","14","15"] result = Hash.new result['data'] = data result['metadata'] = [] return result end end
true
0834693fb4c5206657a251b09cfe1457920d27bf
Ruby
NREL/OpenStudio-analysis-spreadsheet
/measures/AedgSmallToMediumOfficeRoofConstruction/measure.rb
UTF-8
31,247
2.59375
3
[]
no_license
#see the URL below for information on how to write OpenStudio measures # http://openstudio.nrel.gov/openstudio-measure-writing-guide #see the URL below for information on using life cycle cost objects in OpenStudio # http://openstudio.nrel.gov/openstudio-life-cycle-examples #see the URL below for access to C++ documentation on model objects (click on "model" in the main window to view model objects) # http://openstudio.nrel.gov/sites/openstudio.nrel.gov/files/nv_hash/cpp_documentation_it/model/html/namespaces.html #load OpenStudio measure libraries require "#{File.dirname(__FILE__)}/resources/OsLib_AedgMeasures" require "#{File.dirname(__FILE__)}/resources/OsLib_Constructions" #start the measure class AedgSmallToMediumOfficeRoofConstruction < OpenStudio::Ruleset::ModelUserScript include OsLib_AedgMeasures include OsLib_Constructions #define the name that a user will see, this method may be deprecated as #the display name in PAT comes from the name field in measure.xml def name return "AedgSmallToMediumOfficeRoofConstruction" end #define the arguments that the user will input def arguments(model) args = OpenStudio::Ruleset::OSArgumentVector.new #make an argument for material and installation cost material_cost_insulation_increase_ip = OpenStudio::Ruleset::OSArgument::makeDoubleArgument("material_cost_insulation_increase_ip",true) material_cost_insulation_increase_ip.setDisplayName("Increase Cost per Area of Construction Where Insulation was Improved ($/ft^2).") material_cost_insulation_increase_ip.setDefaultValue(0.0) args << material_cost_insulation_increase_ip #make an argument for material and installation cost material_cost_sri_increase_ip = OpenStudio::Ruleset::OSArgument::makeDoubleArgument("material_cost_sri_increase_ip",true) material_cost_sri_increase_ip.setDisplayName("Increase Cost per Area of Construction Where Solar Reflectance Index (SRI) was Improved. ($/ft^2).") material_cost_sri_increase_ip.setDefaultValue(0.0) args << material_cost_sri_increase_ip return args end #end the arguments method #define what happens when the measure is run def run(model, runner, user_arguments) super(model, runner, user_arguments) #use the built-in error checking if not runner.validateUserArguments(arguments(model), user_arguments) return false end # assign the user inputs to variables material_cost_insulation_increase_ip = runner.getDoubleArgumentValue("material_cost_insulation_increase_ip",user_arguments) material_cost_sri_increase_ip = runner.getDoubleArgumentValue("material_cost_sri_increase_ip",user_arguments) # no validation needed for cost inputs, negative values are fine, however negative would be odd choice since this measure only improves vs. decreases insulation and SRI performance # global variables for costs expected_life = 25 years_until_costs_start = 0 material_cost_insulation_increase_si = OpenStudio::convert(material_cost_insulation_increase_ip,"1/ft^2","1/m^2").get material_cost_sri_increase_si = OpenStudio::convert(material_cost_sri_increase_ip,"1/ft^2","1/m^2").get running_cost_insulation = 0 running_cost_sri = 0 #prepare rule hash rules = [] #climate zone, roof type, thermal transmittance (Btu/h·ft2·°F), SRI # IEAD rules << ["1","IEAD",0.048,78.0] # R-20.0 ci. rules << ["2","IEAD",0.039,78.0] # R-25.0 ci. rules << ["3","IEAD",0.039,78.0] # R-25.0 ci. rules << ["4","IEAD",0.032,0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ["5","IEAD",0.032,0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ["6","IEAD",0.032,0] # R-30.0 ci., SRI Comply with Standard 90.1 rules << ["7","IEAD",0.028,0] # R-35.0 ci., SRI Comply with Standard 90.1 rules << ["8","IEAD",0.028,0] # R-35.0 ci., SRI Comply with Standard 90.1 # Attic rules << ["1","Attic",0.027,78.0] # R-38.0 rules << ["2","Attic",0.027,78.0] # R-38.0 rules << ["3","Attic",0.027,78.0] # R-38.0 rules << ["4","Attic",0.021,0] # R-49.0, SRI Comply with Standard 90.1 rules << ["5","Attic",0.021,0] # R-49.0, SRI Comply with Standard 90.1 rules << ["6","Attic",0.021,0] # R-49.0, SRI Comply with Standard 90.1 rules << ["7","Attic",0.017,0] # R-60.0, SRI Comply with Standard 90.1 rules << ["8","Attic",0.017,0] # R-60.0, SRI Comply with Standard 90.1 # Metal rules << ["1","Metal",0.041,78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ["2","Metal",0.041,78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ["3","Metal",0.041,78.0] # R-19.0 + R-10.0 FC (confirm same change as K12 using 0.041 vs. 0.057) rules << ["4","Metal",0.035,0] # R-19.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ["5","Metal",0.031,0] # R-25.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ["6","Metal",0.031,0] # R-25.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ["7","Metal",0.029,0] # R-30.0 + R-11 Ls, SRI Comply with Standard 90.1 rules << ["8","Metal",0.026,0] # R-25.0 + R-11 + R-11 Ls, SRI Comply with Standard 90.1 #make rule hash for cleaner code rulesHash = {} rules.each do |rule| rulesHash["#{rule[0]} #{rule[1]}"] = {"conductivity_ip" => rule[2], "sri" => rule[3]} end #get climate zone climateZoneNumber = OsLib_AedgMeasures.getClimateZoneNumber(model,runner) #climateZoneNumber = "4" # this is just in for quick testing of different climate zones # add message for climate zones 4-8 about SRI (while the office AEDG doesn't mention this in table like the K-12 AEDG does, still seems like relevant message.) if climateZoneNumber == false return false elsif climateZoneNumber.to_f > 3 runner.registerInfo("For Climate Zone #{climateZoneNumber} Solar Reflectance Index (SRI) should comply with Standard 90.1.") end # get starting r-value and SRI ranges startingRvaluesExtRoof = [] startingRvaluesAtticInterior = [] startingSriExtRoof = [] # flag for roof surface type for tips ieadFlag = false metalFlag = false atticFlag = false # affected area counter insulation_affected_area = 0 sri_affected_area = 0 # construction hashes (construction is key, value is array [thermal transmittance (Btu/h·ft2·°F), SRI,rule thermal transmittance (Btu/h·ft2·°F), rule SRI,classification string) ieadConstructions = {} metalConstructions = {} atticConstructions = {} #will initially load all constructions used in model, and will delete later if passes test # this contains constructions that should not have exterior roofs assigned otherConstructions = [] # make array for spaces that have a surface with at least one exterior attic surface atticSpaces = [] # loop through constructions constructions = model.getConstructions constructions.each do |construction| #skip if not used next if not construction.getNetArea > 0 #skip if not opaque next if not construction.isOpaque # get construction and standard constructionStandard = construction.standardsInformation # get roof type intendedSurfaceType = constructionStandard.intendedSurfaceType constructionType = constructionStandard.standardsConstructionType # get conductivity conductivity_si = construction.thermalConductance.get r_value_ip = OpenStudio::convert(1/conductivity_si,"m^2*K/W","ft^2*h*R/Btu").get # get SRI (only need of climate zones 1-3) sri = OsLib_Constructions.getConstructionSRI(construction) # flags for construction loop ruleRvalueFlag = true ruleSriFlag = true # IEAD and Metal roofs should have intendedSurfaceType of ExteriorRoof if intendedSurfaceType.to_s == "ExteriorRoof" if constructionType.to_s == "IEAD" #store starting values startingRvaluesExtRoof << r_value_ip startingSriExtRoof << sri ieadFlag = true # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} IEAD"] if 1/r_value_ip > ruleSet["conductivity_ip"] ruleRvalueFlag = false end if sri < ruleSet["sri"] ruleSriFlag = false end if not ruleRvalueFlag or not ruleSriFlag ieadConstructions[construction] = {"conductivity_ip" => 1/r_value_ip,"sri" => sri,"transmittance_ip_rule" => ruleSet["conductivity_ip"],"sri_rule" => ruleSet["sri"],"classification" => "ieadConstructions"} end elsif constructionType.to_s == "Metal" #store starting values startingRvaluesExtRoof << r_value_ip startingSriExtRoof << sri metalFlag = true # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Metal"] if 1/r_value_ip > ruleSet["conductivity_ip"] ruleRvalueFlag = false end if sri < ruleSet["sri"] ruleSriFlag = false end if not ruleRvalueFlag or not ruleSriFlag metalConstructions[construction] = {"conductivity_ip" => 1/r_value_ip,"sri" => sri,"transmittance_ip_rule" => ruleSet["conductivity_ip"],"sri_rule" => ruleSet["sri"],"classification" => "metalConstructions"} end else # create warning if a construction passing through here is used on a roofCeiling surface with a boundary condition of "Outdoors" otherConstructions << construction end elsif intendedSurfaceType.to_s == "AtticRoof" or intendedSurfaceType.to_s == "AtticWall" or intendedSurfaceType.to_s == "AtticFloor" #store starting values atticFlag = true atticConstructions[construction] = {"conductivity_ip" => 1/r_value_ip,"sri" => sri} # will extend this hash later else # create warning if a construction passing through here is used on a roofCeiling surface with a boundary condition of "Outdoors" otherConstructions << construction end # end of intendedSurfaceType == "ExteriorRoof" end #end of constructions.each do # create warning if construction used on exterior roof doesn't have a surface type of "ExteriorRoof", or if constructions tagged to be used as roof, are used on other surface types otherConstructionsWarned = [] atticSurfaces = [] # to test against attic spaces later on surfaces = model.getSurfaces surfaces.each do |surface| if not surface.construction.empty? construction = surface.construction.get # populate attic spaces if surface.outsideBoundaryCondition == "Outdoors" and atticConstructions.include? construction if not surface.space.empty? if not atticSpaces.include? surface.space.get atticSpaces << surface.space.get end end elsif atticConstructions.include? construction atticSurfaces << surface end if surface.outsideBoundaryCondition == "Outdoors" and surface.surfaceType == "RoofCeiling" if otherConstructions.include? construction and not otherConstructionsWarned.include? construction runner.registerWarning("#{construction.name} is used on one or more exterior roof surfaces but has an intended surface type or construction type not recognized by this measure. As we can not infer the proper performance target, this construction will not be altered.") otherConstructionsWarned << construction end else if ieadConstructions.include? construction or metalConstructions.include? construction runner.registerWarning("#{surface.name} uses #{construction.name} as a construction that this measure expects to be used for exterior roofs. This surface has a type of #{surface.surfaceType} and a a boundary condition of #{surface.outsideBoundaryCondition}. This may result in unexpected changes to your model.") end end #end of surface.outsideBoundaryCondition end # end of if not surface.construction.empty? end # end of surfaces.each do # hashes to hold classification of attic surfaces atticSurfacesInterior = {} # this will include paris of matched surfaces atticSurfacesExteriorExposed = {} atticSurfacesExteriorExposedNonRoof = {} atticSurfacesOtherAtticDemising = {} # look for attic surfaces that are not in attic space or matched to them. atticSpaceWarning = false atticSurfaces.each do |surface| if not surface.space.empty? space = surface.space.get if not atticSpaces.include? space if surface.outsideBoundaryCondition == "Surface" #get space of matched surface and see if it is also an attic next if surface.adjacentSurface.empty? adjacentSurface = surface.adjacentSurface.get next if adjacentSurface.space.empty? adjacentSurfaceSpace = adjacentSurface.space.get if not atticSpaces.include? adjacentSurfaceSpace atticSpaceWarning = true end else atticSpaceWarning = true end end end end if atticSpaceWarning runner.registerWarning("#{surface.name} uses #{construction.name} as a construction that this measure expects to be used for attics. This surface has a type of #{surface.surfaceType} and a a boundary condition of #{surface.outsideBoundaryCondition}. This may result in unexpected changes to your model.") end # flag for testing interiorAtticSurfaceInSpace = false # loop through attic spaces to classify surfaces with attic intended surface type atticSpaces.each do |atticSpace| atticSurfaces = atticSpace.surfaces # array for surfaces that don't use an attic construction surfacesWithNonAtticConstructions = [] # loop through attic surfaces atticSurfaces.each do |atticSurface| next if atticSurface.construction.empty? construction = atticSurface.construction.get if atticConstructions.include? construction conductivity_ip = atticConstructions[construction]["conductivity_ip"] r_value_ip = 1/conductivity_ip sri = atticConstructions[construction]["sri"] else surfacesWithNonAtticConstructions << atticSurface.name next end # warn if any exterior exposed roof surfaces are not attic. if atticSurface.outsideBoundaryCondition == "Outdoors" # only want to change SRI if it is a roof if atticSurface.surfaceType == "RoofCeiling" # store starting value for SRI startingSriExtRoof << sri atticSurfacesExteriorExposed[atticSurface] = construction else atticSurfacesExteriorExposedNonRoof[atticSurface] = construction end elsif atticSurface.outsideBoundaryCondition == "Surface" #get space of matched surface and see if it is also an attic next if atticSurface.adjacentSurface.empty? adjacentSurface = atticSurface.adjacentSurface.get next if adjacentSurface.space.empty? adjacentSurfaceSpace = adjacentSurface.space.get if atticSpaces.include? adjacentSurfaceSpace and atticSpaces.include? atticSpace atticSurfacesOtherAtticDemising[atticSurface] = construction else # store starting values startingRvaluesAtticInterior << r_value_ip atticSurfacesInterior[atticSurface] = construction interiorAtticSurfaceInSpace = true #this is to confirm that space has at least one interior surface flagged as an attic end else runner.registerWarning("Can't infer use case for attic surface with an outside boundary condition of #{atticSurface.outsideBoundaryCondition}.") end end #end of atticSurfaces.each do # warning message for each space that has mix of attic and non attic constructions runner.registerWarning("#{atticSpace.name} has surfaces with a mix of attic and non attic constructions which may produce unexpected results. The following surfaces use constructions not tagged as attic and will not be altered: #{surfacesWithNonAtticConstructions.sort.join(",")}.") # confirm that all spaces have at least one or more surface of both exterior attic and interior attic if not interiorAtticSurfaceInSpace runner.registerWarning("#{atticSpace.name} has at least one exterior attic surface but does not have an interior attic surface. Please confirm that this space is intended to be an attic and update the constructions used.") end # see if attic is part of floor area and/or if it has people in it if atticSpace.partofTotalFloorArea runner.registerWarning("#{atticSpace.name} is part of the floor area. That is not typical for an attic.") end if atticSpace.people.size > 0 runner.registerWarning("#{atticSpace.name} has people. That is not typical for an attic.") end end # end of atticSpaces.each do # hash to look for classification conflicts in attic constructions atticConstructionLog = {} # test attic constructions and identify conflicts # conflict resolution order (insulation,sri,nothing-for demising) atticSurfacesInterior.each do |surface,construction| next if atticConstructionLog[construction] == "atticSurfacesInterior" conductivity_ip = atticConstructions[construction]["conductivity_ip"] # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Attic"] if conductivity_ip > ruleSet["conductivity_ip"] atticConstructions[construction] = {"conductivity_ip" => conductivity_ip,"sri" => "NA","transmittance_ip_rule" => ruleSet["conductivity_ip"],"sri_rule" => "NA","classification" => "atticSurfacesInterior"} else # delete const from main hash atticConstructions.delete(construction) end atticConstructionLog[construction] = "atticSurfacesInterior" #pass in construction object and the type of rule it was tested against end atticSurfacesExteriorExposed.each do |surface,construction| next if atticConstructionLog[construction] == "atticSurfacesExteriorExposed" sri = atticConstructions[construction]["sri"] # warn user if construction used on attic interior surface if atticConstructionLog[construction] == "atticSurfacesInterior" runner.registerWarning("#{surface.name} appears to be an exterior surface but uses a construction #{construction.name} that is also used on interior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next end # test construction against rules ruleSet = rulesHash["#{climateZoneNumber} Attic"] if sri < ruleSet["sri"] atticConstructions[construction] = {"conductivity_ip" => "NA","sri" => sri,"transmittance_ip_rule" => "NA","sri_rule" => ruleSet["sri"],"classification" => "atticSurfacesExteriorExposed"} else # delete const from main hash atticConstructions.delete(construction) end atticConstructionLog[construction] = "atticSurfacesExteriorExposed" #pass in construction object and the type of rule it was tested against end atticSurfacesOtherAtticDemising.each do |k,construction| next if atticConstructionLog[construction] == "atticSurfacesOtherAtticDemising" sri = atticConstructions[construction]["sri"] # warn user if construction used on attic interior surface if atticConstructionLog[construction] == "atticSurfacesInterior" runner.registerWarning("#{surface.name} appears to be an exterior surface but uses a construction #{construction.name} that is also used on interior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next elsif atticConstructionLog[construction] == "atticSurfacesExteriorExposed" runner.registerWarning("#{surface.name} appears to be an surface between two attic spaces uses a construction #{construction.name} that is also used on exterior attic surfaces. The construction was classified and tested as an insulated interior attic construction. You may see unexpected results.") next end # delete const from main hash. atticConstructions.delete(construction) # No rule test needed for demising. atticConstructionLog[construction] = "atticSurfacesOtherAtticDemising" #pass in construction object and the type of rule it was tested against end # delete constructions from hash that are non used on roof attic surfaces, but are exterior exposed atticSurfacesExteriorExposedNonRoof.each do |surface,construction| if atticSurfacesExteriorExposed.has_value? construction #make sure I'm checking for value not key runner.registerWarning("#{surface.name} is a non-roof surface but uses a construction that the measure is treating as an exterior attic roof. Having this associated with a non-roof surface may increase affected area of SRI improvements.") else atticConstructions.delete(construction) end end # alter constructions and add lcc constructionsToChange = ieadConstructions.sort + metalConstructions.sort + atticConstructions.sort constructionsToChange.each do |construction,hash| #gather insulation inputs if not hash["transmittance_ip_rule"] == "NA" # gather target decrease in conductivity conductivity_ip_starting = hash["conductivity_ip"] conductivity_si_starting = OpenStudio::convert(conductivity_ip_starting,"Btu/ft^2*h*R","W/m^2*K").get r_value_ip_starting = 1/conductivity_ip_starting # ft^2*h*R/Btu r_value_si_starting = 1/conductivity_si_starting # m^2*K/W conductivity_ip_target = hash["transmittance_ip_rule"].to_f conductivity_si_target = OpenStudio::convert(conductivity_ip_target,"Btu/ft^2*h*R","W/m^2*K").get r_value_ip_target = 1/conductivity_ip_target # ft^2*h*R/Btu r_value_si_target = 1/conductivity_si_target # m^2*K/W # infer insulation material to get input for target thickness minThermalResistance = OpenStudio::convert(1,"ft^2*h*R/Btu","m^2*K/W").get inferredInsulationLayer = OsLib_Constructions.inferInsulationLayer(construction,minThermalResistance) rvalue_si_deficiency = r_value_si_target - r_value_si_starting # add lcc for insulation lcc_mat_insulation = OpenStudio::Model::LifeCycleCost.createLifeCycleCost("LCC_Mat_Insulation - #{construction.name}", construction, material_cost_insulation_increase_si, "CostPerArea", "Construction", expected_life, years_until_costs_start) lcc_mat_insulation_value = lcc_mat_insulation.get.totalCost running_cost_insulation += lcc_mat_insulation_value # adjust existing material or add new one if inferredInsulationLayer["insulationFound"] #if insulation layer was found # gather inputs for method target_material_rvalue_si = inferredInsulationLayer["construction_thermal_resistance"] + rvalue_si_deficiency # run method to change insulation layer thickness in cloned material (material,starting_r_value_si,target_r_value_si, model) new_material = OsLib_Constructions.setMaterialThermalResistance(inferredInsulationLayer["construction_layer"],target_material_rvalue_si) # connect new material to original construction construction.eraseLayer(inferredInsulationLayer["layer_index"]) construction.insertLayer(inferredInsulationLayer["layer_index"],new_material) # get conductivity final_conductivity_si = construction.thermalConductance.get final_r_value_ip = OpenStudio::convert(1/final_conductivity_si,"m^2*K/W","ft^2*h*R/Btu").get # report on edited material runner.registerInfo("The R-value of #{construction.name} has been increased from #{OpenStudio::toNeatString(r_value_ip_starting,2,true)} to #{OpenStudio::toNeatString(final_r_value_ip,2,true)}(ft^2*h*R/Btu) at a cost of $#{OpenStudio::toNeatString(lcc_mat_insulation_value,2,true)}. Increased performance was accomplished by adjusting thermal resistance of #{new_material.name}.") else # inputs to pass to method conductivity = 0.045 # W/m*K thickness = rvalue_si_deficiency * conductivity # meters addNewLayerToConstruction_Inputs = { "roughness" => "MediumRough", "thickness" => thickness, # meters, "conductivity" => conductivity, # W/m*K "density" => 265.0, "specificHeat" => 836.8, "thermalAbsorptance" => 0.9, "solarAbsorptance" => 0.7, "visibleAbsorptance" => 0.7, } # create new material if can't infer insulation material (construction,thickness, conductivity, density, specificHeat, roughness,thermalAbsorptance, solarAbsorptance,visibleAbsorptance,model) newMaterialLayer = OsLib_Constructions.addNewLayerToConstruction(construction,addNewLayerToConstruction_Inputs) # get conductivity final_conductivity_si = construction.thermalConductance.get final_r_value_ip = OpenStudio::convert(1/final_conductivity_si,"m^2*K/W","ft^2*h*R/Btu").get # report on edited material runner.registerInfo("The R-value of #{construction.name} has been increased from #{OpenStudio::toNeatString(r_value_ip_starting,2,true)} to #{OpenStudio::toNeatString(final_r_value_ip,2,true)}(ft^2*h*R/Btu) at a cost of $#{OpenStudio::toNeatString(lcc_mat_insulation_value,2,true)}. Increased performance was accomplished by adding a new material layer to the outside of #{construction.name}.") end # end of if inferredInsulationLayer[4] #add to area counter insulation_affected_area += construction.getNetArea # OpenStudio handles matched surfaces so they are not counted twice. end # end if not hash[transmittance_ip_rule] == "NA" #gather sri inputs if hash["sri_rule"] == 78.0 and hash["sri_rule"] > hash["sri"] #hard assign material properies that will result in an SRI of 78 setConstructionSurfaceProperties_Inputs = { "thermalAbsorptance" => 0.86, "solarAbsorptance" => 1 - 0.65, } #alter surface properties (construction,roughness,thermalAbsorptance, solarAbsorptance,visibleAbsorptance) surfaceProperties = OsLib_Constructions.setConstructionSurfaceProperties(construction,setConstructionSurfaceProperties_Inputs) sri = OsLib_Constructions.getConstructionSRI(construction) # add lcc for SRI lcc_mat_sri = OpenStudio::Model::LifeCycleCost.createLifeCycleCost("LCC_Mat_SRI - #{construction.name}", construction, material_cost_sri_increase_si, "CostPerArea", "Construction", expected_life, years_until_costs_start) lcc_mat_sri_value = lcc_mat_sri.get.totalCost running_cost_sri += lcc_mat_sri_value #add to area counter sri_affected_area += construction.getNetArea # report performance and cost change for material, or area runner.registerInfo("The Solar Reflectance Index (SRI) of #{construction.name} has been increased from #{OpenStudio::toNeatString(hash["sri"],0,true)} to #{OpenStudio::toNeatString(sri,0,true)} for a cost of $#{OpenStudio::toNeatString(lcc_mat_sri_value,0,true)}. Affected area is #{OpenStudio::toNeatString(OpenStudio::convert(construction.getNetArea,"m^2","ft^2").get,0,true)} (ft^2)") end end # populate AEDG tip keys aedgTips = [] if ieadFlag aedgTips.push("EN01","EN02","EN17","EN19","EN21","EN22") end if atticFlag aedgTips.push("EN01","EN03","EN17","EN19","EN20","EN21") end if metalFlag aedgTips.push("EN01","EN04","EN17","EN19","EN21") end # create not applicable of no constructions were tagged to change # if someone had a model with only attic floors and no attic ceilings current logic would flag as not applicable, but a warning would be issued alerting them of the issue (attic surface being used outside of attic space) if aedgTips.size == 0 runner.registerAsNotApplicable("No surfaces use constructions tagged as a roof type recognized by this measure. No roofs were altered.") return true end # populate how to tip messages aedgTipsLong = OsLib_AedgMeasures.getLongHowToTips("SmMdOff",aedgTips.uniq.sort,runner) if not aedgTipsLong return false # this should only happen if measure writer passes bad values to getLongHowToTips end #reporting initial condition of model startingRvalue = startingRvaluesExtRoof + startingRvaluesAtticInterior #adding non attic and attic values together runner.registerInitialCondition("Starting R-values for constructions intended for insulated roof surfaces range from #{OpenStudio::toNeatString(startingRvalue.min,2,true)} to #{OpenStudio::toNeatString(startingRvalue.max,2,true)}(ft^2*h*R/Btu). Starting Solar Reflectance Index (SRI) for constructions intended for exterior roof surfaces range from #{OpenStudio::toNeatString(startingSriExtRoof.min,0,true)} to #{OpenStudio::toNeatString(startingSriExtRoof.max,0,true)}.") #reporting final condition of model insulation_affected_area_ip = OpenStudio::convert(insulation_affected_area,"m^2","ft^2").get sri_affected_area_ip = OpenStudio::convert(sri_affected_area,"m^2","ft^2").get runner.registerFinalCondition("#{OpenStudio::toNeatString(insulation_affected_area_ip,0,true)}(ft^2) of constructions intended for roof surfaces had insulation enhanced at a cost of $#{OpenStudio::toNeatString(running_cost_insulation,0,true)}. #{OpenStudio::toNeatString(sri_affected_area_ip,0,true)}(ft^2) of constructions intended for roof surfaces had the Solar Reflectance Index (SRI) enhanced at a cost of $#{OpenStudio::toNeatString(running_cost_sri,0,true)}. #{aedgTipsLong}") return true end #end the run method end #end the measure #this allows the measure to be use by the application AedgSmallToMediumOfficeRoofConstruction.new.registerWithApplication
true
0e252a1dec3bbad5aa51272acddda057ecb8f37c
Ruby
catd825/ruby-enumerables-hashes-and-enumerables-nyc01-seng-ft-062220
/lib/cruise_ship.rb
UTF-8
534
3.65625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# passengers = { # suite_a: "Amanda Presley", # suite_b: "Seymour Hoffman", # suite_c: "Alfred Tennyson", # suite_d: "Charlie Chaplin", # suite_e: "Crumpet the Elf" # } def select_winner(passengers) winner = "" #create new variable passengers.each do |suite, name| #iterate over passenger array - suite & name. used each vs collect/map since we do not want the key/value pair, just the winner's name. if suite == :suite_a && name.start_with?("A") # if the suite is suite a and name starts with A, then that is the winner winner = name end end winner end
true
05d09268d140e77a057665b41ef54d4a3f7fabc5
Ruby
abwinkler999/minormud
/minormud.rb
UTF-8
2,633
3.5625
4
[]
no_license
require 'socket' require 'term/ansicolor' require 'colorize' require 'pry' # a Player has an associated Character, and a socket through which he is connecting class Player attr_accessor :character, :socket def initialize(incoming_socket) @socket = incoming_socket end def create_character(name) @character = Character.new @character.name = name end def readin return @socket.gets.chomp end end class Character attr_accessor :name end # there is only one Mud. @all_players should be a class variable. class Mud def initialize @all_players = Array.new @color = Term::ANSIColor @system = Character.new @system.name = "System" end def send(message, recipient) # communique = @color.bold, @color.green, message, @color.clear communique = message.green # recipient.socket.puts communique.join recipient.socket.puts communique end def broadcast(message, originator = nil) originator ||= @system message = "#{originator.character.name}: #{message}" @all_players.each { |x| send(message, x)} end def sys_message(message) message = "#{@system.name}: #{message}" @all_players.each { |x| send(message, x)} end def bust_a_prompt(recipient) recipient.socket.print "> " end def shut_down_socket(target) target.socket.puts "Logging out." @all_players.delete target sys_message("#{target.character.name} logged out.") target.socket.close end def parse(this_player) line = this_player.readin if line.length == 0 this_player.socket.puts "Pardon?" bust_a_prompt(this_player) return end puts "#{this_player.character.name}: #{line}" case line when "look" send("You are in a little, uninteresting room.\n", this_player) @all_players.each { |x| send("#{x.character.name} is here.", this_player) } bust_a_prompt(this_player) when "logout" shut_down_socket(this_player) when "shutdown" sys_message("Shutting down NOW!") Thread.main.exit else broadcast(line, this_player) bust_a_prompt(this_player) end end def startup server = TCPServer.new(3939) puts "*** STARTING UP ***" while (conn = server.accept) Thread.new(conn) do |c| puts "New connection detected." this_player = Player.new(c) this_player.socket.print "What is your name? " this_player.create_character(this_player.readin) this_player.socket.puts "Welcome, #{this_player.character.name}!" sys_message("#{this_player.character.name} has connected.") bust_a_prompt(this_player) @all_players << this_player loop do parse(this_player) end end end end end minormud = Mud.new minormud.startup
true
bcd63701b59b4045a937f1fe0ce6a5bb14518a37
Ruby
DanielSLew/Ruby_Small_Problems
/Object_Oriented_Programming/OOBasics_Class_Objects2/public_secret.rb
UTF-8
308
4.0625
4
[]
no_license
# Use the following code # create a class named Person with an instance variable named @secret # use a setter method to add a value to @secret # use a getter method to print @secret class Person attr_accessor :secret end person1 = Person.new person1.secret = 'Shh.. this is a secret!' puts person1.secret
true
5df12818606825f860d5d07c4ee4b43094f1928b
Ruby
gavinmcgimpsey/launch-school-3
/reduce.rb
UTF-8
168
3.1875
3
[]
no_license
def reduce(arr, accumulator = 0) counter = 0 while counter < arr.length accumulator = yield(accumulator, arr[counter]) counter += 1 end accumulator end
true
454c9f569c9d471de14ed42dd38d74d7c1f64b47
Ruby
fosterv2/ruby-array-practice-oxford-comma-lab-seattle-web-030920
/lib/oxford_comma.rb
UTF-8
254
3.40625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) # count = 0 # while count < (array.length - 1) # # end if array.length == 1 array[0] elsif array.length == 2 array.join(" and ") else ending = array.pop "#{array.join(", ")}, and #{ending}" end end
true
dd02b226dcb84a98871147aaa52a162f7992cc4c
Ruby
ForEverRoice/arreglos_archivos
/presencial1/startwatch1.rb
UTF-8
347
3.015625
3
[]
no_license
pasos = ['100', '21', '231as', '2031', '1052000', '213b', 'b123'] def clear_steps(steps) filtrado_letras = steps.reject do |x| /[aA-zZ]/.match(x) end convertido = filtrado_letras.map do |x| x.to_i end filtrado_pasos = convertido.select do |x| x >= 200 and x <= 10000 end return filtrado_pasos end clear_steps(pasos)
true
56f2fb578d3fde51c77388a84c3a3a35df890fce
Ruby
cha63506/Purrfect-Match
/app/models/pet.rb
UTF-8
1,352
2.59375
3
[]
no_license
class Pet < ActiveRecord::Base belongs_to :shelter has_many :pet_breeds has_many :breeds, through: :pet_breeds has_many :favorite_pets has_many :users, through: :favorite_pets # def self.species # @species = ["barnyard", "bird", "cat", "dog", "horse", "pig", "reptile", "smallfurry"] # end def search Pet.find(:all, :conditions => conditions) end end def species_conditions ["pets.species == params['pets']['species']"] end def zip_conditions ["pets.species == params['pets']['species']"] end # def keyword_conditions # ["pets.species = params['pets']['species']"] unless keywords.blank? # end # def minimum_price_conditions # ["products.price >= ?", minimum_price] unless minimum_price.blank? # end # def maximum_price_conditions # ["products.price <= ?", maximum_price] unless maximum_price.blank? # end # def category_conditions # ["products.category_id = ?", category_id] unless category_id.blank? # end # def conditions # [conditions_clauses.join(' AND '), *conditions_options] # end # def conditions_clauses # conditions_parts.map { |condition| condition.first } # end # def conditions_options # conditions_parts.map { |condition| condition[1..-1] }.flatten # end # def conditions_parts # private_methods(false).grep(/_conditions$/).map { |m| send(m) }.compact # end # end
true
e0623edc22ca979a9873da480f6eebf4e64d4b43
Ruby
adamsanderson/cesspit
/lib/cesspit/cli.rb
UTF-8
576
2.734375
3
[ "MIT" ]
permissive
class Cesspit::CLI attr_reader :cesspit attr_reader :in, :out def initialize(options) @cesspit = Cesspit.new @in = options[:in] @out = options[:out] || STDOUT options[:css_paths].each do |path| cesspit.read_css(path) end if options[:html_paths] options[:html_paths].each do |path| cesspit.read_html(path) end end end def read_from(stream) stream.each(Cesspit::FILE_DELIMITER) do |html| cesspit.scan_html(html) end end def report out.puts(cesspit.to_s) end end
true
52b792f25e38ab81ef01da0af1b0dcdc2a409c1b
Ruby
Ido-Efrati/tripper
/app/models/exchange.rb
UTF-8
1,143
2.90625
3
[]
no_license
# @author Jesika Haria class Exchange < ActiveRecord::Base belongs_to :trip has_many :costs, dependent: :destroy validates :units, presence: true, uniqueness: { scope: :trip_id } validates :rate, presence: true, numericality: { greater_than: 0 } # Default resources and rates associated with trip on creation def self.set_defaults(trip_id) Exchange.create(rate: 1, :units => "dollars", trip_id: trip_id) Exchange.create(rate: 1, :units => "hours driven", trip_id: trip_id) end # Returns zip of exchange resource IDs with exchange resource name # eg (1, 'dollars') (2, 'hours driven') def self.get_exchange_select(trip_id) exchanges = Trip.find(trip_id).exchanges exchange_ids = exchanges.collect { |exchange| exchange.id } exchange_units = exchange_ids.collect { |exchange_id| Exchange.find(exchange_id).units } return exchange_units.zip(exchange_ids) end # Returns true if the unit is dollars and false otherwise # Used to ensure that you can't change the name for dollars or delete it def self.can_delete(exchange_id) return Exchange.find(exchange_id).units != "dollars" end end
true
b9d84c4f0f645a8f7ebebe7597523d2c9ff61e51
Ruby
minnonong/Codecademy_Ruby
/05. Loops & Iterators/05_11.rb
UTF-8
300
3.890625
4
[]
no_license
# 05_11 The .each Iterator =begin each : 객체의 각 요소에 하나씩 수식 적용 가능. 사용법 - object.each { |item| 실행 할 코드 } or object.each do |item| 실행 할 코드 end =end array = [1,2,3,4,5] array.each do |x| x += 10 puts "#{x}" end
true
a54fc1424438daaaf166e9a25742f51286ba34ea
Ruby
sinventor/my-list
/scripts/sort_by_date_asc.rb
UTF-8
734
2.65625
3
[]
no_license
file = ARGV.first lines = File.readlines(file) first_indexes = [] no_sorted_indexes = [] lines.each_with_index do |line, i| first_indexes << i if line.strip[0] != "*" no_sorted_indexes << i if line.strip[0] == "*" && line.match(/.+hab.+post\/.+/).nil? end listed_lines = lines.select{ |line| line.strip[0] == "*" && !line.strip.match(/.+habrahabr.ru\/post\/(\d)+\//).nil? } listed_lines.sort!{|a,b| a[/.+post\/((\d)+)/, 1].to_i <=> b[/.+post\/((\d)+)/, 1].to_i} written_strings = [] first_indexes.each { |i| written_strings << lines[i] } listed_lines.each { |line| written_strings << line } no_sorted_indexes.each { |i| written_strings << lines[i] } File.open(file, "w") do |f| written_strings.each {|curr| f.write curr} end
true
2adec523aafcb3f831190bee1387f62a2f134dbb
Ruby
snowhork/type_struct
/lib/type_struct/hash_of.rb
UTF-8
488
3
3
[ "MIT" ]
permissive
require "type_struct/union" class TypeStruct class HashOf include Unionable attr_reader :key_type, :value_type def initialize(key_type, value_type) @key_type = key_type @value_type = value_type end def ===(other) return false unless Hash === other other.all? do |k, v| @key_type === k && @value_type === v end end def to_s "#{self.class}(#{@key_type}, #{@value_type})" end alias inspect to_s end end
true
9c98f9be1aca7cb012b05e30b00ff1635fc44d43
Ruby
DeveloperAlan/WDI_SYD_7_Work
/w01/d02/eugenius/while.rb
UTF-8
433
4.09375
4
[]
no_license
=begin puts "what is 2 to the 16th power?" answer = gets.chomp.to_i while (2**16) != answer print "wrong try again" answer = gets.chomp.to_i end puts "good job" =end # Use a while loop to let the user guess again until he/she gets the answer right. # Once the user guesses right, print "Good Job" begin puts "What is the answer to 2 to the 16th power?" answer = gets.chomp.to_i end until (2**16) == answer puts "good job"
true
7dd44745748c9145b5bbff0e39b9a71922b93a73
Ruby
szek/redbubble-challenge
/spec/slugger_spec.rb
UTF-8
420
2.828125
3
[]
no_license
require_relative '../app/modules/slugger' class Foo include Slugger end describe Slugger do it "returns a valid slug" do expect(Foo.new.slug_for('valid slug')).to eq 'valid-slug' end it "downcases" do expect(Foo.new.slug_for('VALID SLUG')).to eq 'valid-slug' end it "strips slugs of non alphanumeric characters" do expect(Foo.new.slug_for('VALID $%@!(*) SLUG')).to eq 'valid-slug' end end
true
ee4f55532c52a2bc449e0873662a78969475ab5f
Ruby
Watson-Derek/RB101
/Exercises/Medium1/fibonacci_procedural.rb
UTF-8
303
3.5625
4
[]
no_license
def fibonacci(num) return 1 if num <= 2 num1 = 1 num2 = 1 final = 0 (num - 2).times do final = num1 + num2 num2 = num1 num1 = final end final end p fibonacci(20) == 6765 p fibonacci(100) == 354224848179261915075 # p fibonacci(100_001) # => 4202692702.....8285979669707537501
true
e87d1223a6058d76d5b3c6737ef0cae7bde0a4d1
Ruby
hybitz/hyacc
/app/models/career.rb
UTF-8
652
2.5625
3
[ "MIT" ]
permissive
class Career < ApplicationRecord belongs_to :employee belongs_to :customer validates :project_name, :presence => true before_save :update_names # マスタの名称を明細自身に設定する def update_names self.customer_name = customer.formal_name_on(end_to) end def duration_ym duration = (end_to_or_today - start_from).to_i return duration/365, duration%365/31 + (duration%365%31 > 0 ? 1 : 0) end def is_up_to_today today = Date.today end_to - today > 0 end def end_to_or_today if is_up_to_today Date.today else end_to end end end
true
95b4c192a3b95d5228079b7be3b5a319710bfbff
Ruby
KMyatThu/Bulletin_Board
/app/models/post.rb
UTF-8
830
2.546875
3
[]
no_license
class Post < ApplicationRecord belongs_to :created_user, class_name: "User", foreign_key: "create_user_id" belongs_to :updated_user, class_name: "User", foreign_key: "updated_user_id" validates :title, presence: true validates :description, presence: true def self.to_csv CSV.generate do |csv| csv << column_names all.each do |post| csv << post.attributes.values_at(*column_names) end end end def self.import(file,current_user_id) CSV.foreach(file.path, headers: true) do |row| post = Post.new post.title = row[0] post.description = row[1] post.status = row[2] post.create_user_id = current_user_id post.updated_user_id = current_user_id post.created_at = Time.now post.updated_at = Time.now post.save! end end end
true
212d5f8e7b48169939893b590c7c49ba400fce8d
Ruby
gabe-vazquez-blk/silicon-valley-code-challenge-nyc-web-051319
/tools/console.rb
UTF-8
890
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative '../config/environment.rb' def reload load 'config/environment.rb' end # Insert code here to run before hitting the binding.pry # This is a convenient place to define variables and/or set up new object instances, # so they will be available to test and play around with in your console s1 = Startup.new("We", "Charlie","we.com") s2 = Startup.new("Google", "Mike","google.com") s3 = Startup.new("Apple", "Steve","apple.com") vc1 = VentureCapitalist.new("Gabe", 1000000000) vc2 = VentureCapitalist.new("Nev", 2000000000) vc3 = VentureCapitalist.new("Mom", 30) fr1 = FundingRound.new(s1, vc1, "Series A", 100.00) fr2 = FundingRound.new(s2, vc2, "Series B", 200.00) fr3 = FundingRound.new(s3, vc3, "Series C", 300.00) s1.sign_contract(vc2,"series C",400.0) vc1.offer_contract(s3, "Angel", 200.0) binding.pry 0 #leave this here to ensure binding.pry isn't the last line
true
baaba38cbfc88b8d428cb2bdb1c9f3c4cbafc2e7
Ruby
red-data-tools/red-chainer
/lib/chainer/hyperparameter.rb
UTF-8
460
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Chainer class Hyperparameter attr_reader :parent def initialize(parent: nil) @parent = parent end def method_missing(name) @parent.instance_variable_get("@#{name}") end def get_dict d = @parent.nil? ? {} : @parent.get_dict self.instance_variables.each do |m| unless m == :@parent d[m.to_s.delete('@')] = self.instance_variable_get(m) end end d end end end
true
7230d56ef94609e4c6400da84e676a55c5bd767b
Ruby
Jennifer-Wang/test-first-ruby
/lib/01_temperature.rb
UTF-8
87
3
3
[]
no_license
def ftoc(f) return (f - 32) * (5.0 / 9) end def ctof(c) return c*(9.0/5) +32 end
true
76b5648adc566da643d804512879c28fdaad0f1e
Ruby
jverbosky/minedminds_homework
/modules/mined_mineds_puts/Custom_Modulos.rb
UTF-8
690
3.328125
3
[]
no_license
# Module for custom modulo methods # Required by Method_Variations.rb module module Custom_Modulos # Custom modulo method that targets remainder after float division def Custom_Modulos.evenly_divisible(dividend, divisor) quotient = dividend.to_f / divisor remainder = quotient - quotient.to_int if remainder > 0 return false else return true end end # Custom modulo method that uses base conversion and index slicing def Custom_Modulos.base_slice(number, base) converted = number.to_s(base) ones_place = converted[-1] if ones_place.to_i == 0 return true else return false end end end
true
bbbbaec727a4aa58c6118e569eda09773e298c55
Ruby
ElliottAYoung/Dungeonator
/lib/dungeonator.rb
UTF-8
799
2.84375
3
[ "MIT" ]
permissive
require "dungeonator/version" module Dungeonator def self.dungeon_name "The #{Dungeonator.second_word.sample} Of #{Dungeonator.fourth_word.sample}" end private def self.second_word ["Clearing", "Tomb", "Lair", "Peak", "Gathering", "Forest", "Mountain", "Island", "City", "Ascent", "Secret", "Rise", "Purge", "Fall", "Treasure", "House", "Crypt", "Cavern", "Trials", "Mystery", "Knights", "Kingdom", "Mine", "Path", "Lord"] end def self.fourth_word ["The Kobold King", "Pelor", "Kobolds", "The Goblin King", "The Forgotten", "Goblins", "The Kobold Queen", "The Goblin Queen", "The Fire Drake", "Kord", "The Undead", "The Ancients", "Order", "Crows", "The Lich", "Boccob", "Moradin", "The Ring", "Mysterious Origins", "The Mummy", "The Divines", "Eternal Youth"] end end
true
7e17d53121543073766da0a8f3db7fdf8f0a0c7b
Ruby
LannTheStupid/pawn_inclination
/table_test.rb
UTF-8
267
2.96875
3
[]
no_license
require 'text-table' array = [ ['S', '+', '!M!', 'C'], [2, 43, 456, -123] ] puts array.to_table(:first_row_is_head => false) table = Text::Table.new table.head = ['S', '+', '!M!', 'C'] table.rows << [2, 43, 456, -123] table.align_row 2, :right puts table
true
f0b792103bfad6129a1dfdd4216b70da5442e6bd
Ruby
XiaoA/tealeaf-precourse
/07_arrays/solution7_corrected.rb
UTF-8
116
2.953125
3
[]
no_license
hachi = [1, 2, 3, 4, 5, 6, 7, 8] hachi2 = [] hachi.each do |num| hachi2 << num + 2 end p hachi p hachi2
true
7ffcc6606d2521ab71dd9fe95cba9e666d7e7592
Ruby
kalina/project-euhler
/Project Euler/problem1.rb
UTF-8
168
3.3125
3
[]
no_license
#{{{ #1 to 999 filter { x => x % 3 == 0 || x % 5 == 0 } sum #}}} sum = 0 digits = Array(1..999) puts digits.find_all{|x| x % 3 == 0 || x % 5 == 0 }.inject(:+)
true
d3a51a01e2f7530c9a7bf1d2e819dc78f093cd21
Ruby
MatteoTHP/Morpion
/app.rb
UTF-8
1,459
3.15625
3
[]
no_license
# lignes très pratiques qui appellent les gems du Gemfile. On verra plus tard comment s'en servir ;) - # ça évite juste les "require" partout require 'bundler' Bundler.require # lignes qui appellent les fichiers lib/game.rb et lib/player.rb require_relative 'lib/game' require_relative 'lib/player' require_relative 'lib/show' require_relative 'lib/board' require_relative 'lib/boardcase' class Application def perform # TO DO : méthode qui initialise le jeu puis contient des boucles while #pour faire tourner le jeu tant que la partie n'est pas terminée. puts "🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥" puts "-------------------------------------------------" puts "| Bienvenue sur 'Le Tic Tac Toe des familles'! |" puts "| 🔥 Si tu perds le Démon dévorera ton âme! 🔥 |" puts "-------------------------------------------------" puts " 😈... by Satan ©️ " puts puts " Une petite partie de morpion ?" puts puts " Joueur 1, quel est votre nom ?" player1_name = gets.chomp puts " Joueur 2 , quel est votre nom ?" player2_name = gets.chomp my_game = Game.new(player1_name, player2_name) is_victory = false while is_victory == false && my_game.board.full? == false is_victory = my_game.turn end my_game.game_end end end Application.new.perform
true
901de5a47acb98651b6a9da8b78ebb4ba3403972
Ruby
gching/csc_sql
/test_input.rb
UTF-8
390
3.171875
3
[]
no_license
## test_input.rb ## Gavin Ching ## February 17, 2014 ## This file is used to test files for input #################### Reading from File ########################### puts "Insert file name:" ## Get the file name of the file being read. filename = gets.chomp ## Open the file to read each line and output it File.open(filename, "r").each_line do |line| output = line.chomp puts output end
true
110f69fde9a36c6653b531462f5d819fe9f97b67
Ruby
lukeperrin10/ruby
/My_group.rb
UTF-8
266
3.5
4
[]
no_license
my_group = [] person_1 = %w{Kim 30 Man} person_2 = %w{Jack 47 Man} person_3 = %w{Sophie 19 Woman} my_group = [person_1,person_2, person_3] my_group.each do |person| puts "Hi my name is #{person[0]} I am a #{person[2]} and am #{person[1]} years old!" end
true
88ec17fd16f3a1b47147c46f4c68dd73a1fa86a5
Ruby
craigaup/hcc_raceday_backend
/test/models/craft_test.rb
UTF-8
10,748
2.5625
3
[]
no_license
require 'test_helper' class CraftTest < ActiveSupport::TestCase def setup Distance.all.each do |d| d.year = DateTime.now.in_time_zone.year d.save end %i[one two oneout twoout].each do |sym| craft = crafts(sym) craft.year = DateTime.now.in_time_zone.year craft.save end @craft = crafts(:one) end test 'should be valid' do pp @craft.errors unless @craft.valid? #byebug assert @craft.valid? %i[one two oneout twoout].each do |sym| assert crafts(sym).valid? end end test 'self.findMinCanoeNumber' do assert Craft.findMinCanoeNumber, 100 Datum.setValue('firstcanoenumber', '101', 2017) assert Craft.findMinCanoeNumber(2017), 101 Datum.setValue('firstcanoenumber', '101', DateTime.now.in_time_zone.year) assert Craft.findMinCanoeNumber, 101 end test 'self.findMaxCanoeNumber' do assert Craft.findMaxCanoeNumber, 500 Datum.setValue('lastcanoenumber', '501', 2017) assert Craft.findMaxCanoeNumber(2017), 501 Datum.setValue('lastcanoenumber', '501', DateTime.now.in_time_zone.year) assert Craft.findMaxCanoeNumber, 501 end test 'self.valid_canoenumber?' do Datum.setValue('firstcanoenumber', '102', 2017) assert Craft.findMinCanoeNumber(2017), 102 Datum.setValue('lastcanoenumber', '502', 2017) assert Craft.findMaxCanoeNumber(2017), 502 Datum.setValue('firstcanoenumber', '101', DateTime.now.in_time_zone.year) assert Craft.findMinCanoeNumber, 101 Datum.setValue('lastcanoenumber', '501', DateTime.now.in_time_zone.year) assert Craft.findMaxCanoeNumber, 501 # valid list - 2017 [102, 502, 302].each do |number| assert Craft.valid_canoe_number?(number, '2017'), "#{number} should be valid" assert Craft.valid_canoe_number?(number.to_s, '2017'), "#{number} should be valid as a string" end # invalid list - 2017 [101, 503, 800, 50].each do |number| assert_not Craft.valid_canoe_number?(number, '2017'), "#{number} shouldn't be valid" assert_not Craft.valid_canoe_number?(number.to_s, '2017'), "#{number} shouldn't be valid as a string" end # valid list - this year [101, 501, 302].each do |number| assert Craft.valid_canoe_number?(number), "#{number} should be valid" assert Craft.valid_canoe_number?(number.to_s), "#{number} should be valid as a string" end # invalid list - this year [100, 502, 800, 50].each do |number| assert_not Craft.valid_canoe_number?(number), "#{number} shouldn't be valid" assert_not Craft.valid_canoe_number?(number.to_s), "#{number} shouldn't be valid as a string" end end test 'checkCanoeNumberValue and number must be a number' do check_validity(@craft, 'number', [100, 500, 450], [nil, 1, 550, 99, 501, 'a', ' ', '']) end test 'checkStatusIsValid' do check_validity(@craft, 'status', ['IN', 'OUT', 'WD', 'DNS', 'Withdrawn', 'Non-Starter'], [nil, 1, 'a', 'DNF', '', ' ']) end test 'year must be a number' do check_validity(@craft, 'year', [2016, 2017, DateTime.now.in_time_zone.year], [nil, 'a', ' ', '']) end test 'entered must be a number' do check_validity(@craft, 'entered', [DateTime.now.in_time_zone, DateTime.now.in_time_zone - 1.year, '4/4/16 13:00', '13:00'], [nil, 'a', ' ', '']) end test 'time must be a number' do check_validity(@craft, 'time', [DateTime.now.in_time_zone, DateTime.now.in_time_zone - 1.year, '4/4/16 13:00', '13:00'], [nil, 'a', ' ', '']) end test 'self.getFieldInfo' do assert_equal Craft.getFieldInfo, \ {100 => {number: 100, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:02 UTC'.to_datetime.in_time_zone, distance: 12400}, 101 => {number: 101, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:03 UTC'.to_datetime.in_time_zone, distance: 12400}} end test 'self.getStatus' do assert_equal Craft.getStatus(@craft.number), \ {number: 100, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:02 UTC'.to_datetime.in_time_zone, distance: 12400} end test 'self.find_last_entry' do tmphistory = Craft.getHistory('ALL', 'ALL', DateTime.now.in_time_zone.year) assert_equal Craft.find_last_entry(tmphistory, @craft.number), {number: 100, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:02 UTC'.to_datetime.in_time_zone, distance: 12400} end test 'self.getHistory' do assert_equal Craft.getHistory('ALL', 'ALL', DateTime.now.in_time_zone.year), \ {100 => {"Alpha" => [{number: 100, checkpoint: "Alpha", status: "IN", time: 'Tue, 04 Apr 2017 13:00:00 UTC'.\ to_datetime.in_time_zone, distance: 12400}, {number: 100, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:02 UTC'.\ to_datetime.in_time_zone, distance: 12400}]}, 101 => {"Alpha" => [{number: 101, checkpoint: "Alpha", status: "IN", time: 'Tue, 04 Apr 2017 13:00:01 UTC'.\ to_datetime.in_time_zone, distance: 12400}, {number: 101, checkpoint: "Alpha", status: "OUT", time: 'Tue, 04 Apr 2017 13:00:03 UTC'.\ to_datetime.in_time_zone, distance: 12400}]}} end test 'self.getAllCheckpointInfo and self.overallStatus' do output = {} output['Alpha'] = [] output['Alpha'][100] = {} output['Alpha'][100]['IN'] = crafts(:one) output['Alpha'][100]['OUT'] = crafts(:oneout) output['Alpha'][101] = {} output['Alpha'][101]['IN'] = crafts(:two) output['Alpha'][101]['OUT'] = crafts(:twoout) assert_equal output, Craft.getAllCheckpointInfo assert_equal output, Craft.overallStatus end test 'overdue?' do assert_not @craft.overdue? end test 'self.getData' do output = [crafts(:twoout), crafts(:two), crafts(:oneout), crafts(:one)] assert_equal output, Craft.getData('Alpha', 'ALL') end test 'self.displayCheckpointInfo' do output = {100=>{"IN"=>{"status"=>"IN", "time"=>"23:00:00", "overdue"=>false}, "OUT"=>{"status"=>"OUT", "time"=>"23:00:02", "overdue"=>false}}, 101=>{"IN"=>{"status"=>"IN", "time"=>"23:00:01", "overdue"=>false}, "OUT"=>{"status"=>"OUT", "time"=>"23:00:03", "overdue"=>false}}} assert_equal output, Craft.displayCheckpointInfo('Alpha') end test 'self.getAllCheckpointHistory' do output = {"Alpha"=>{100=>{:number=>100, :checkpoint=>"Alpha", :status=>"OUT", :time=>'Tue, 04 Apr 2017 13:00:02 UTC'\ .to_datetime.in_time_zone, :distance=>12400}, 101=>{:number=>101, :checkpoint=>"Alpha", :status=>"OUT", :time=>'Tue, 04 Apr 2017 13:00:03 UTC'\ .to_datetime.in_time_zone, :distance=>12400}}, "___timings"=>{"Alpha"=>[]}, "___lastseen"=>{100=>"Alpha", 101=>"Alpha"}, "___lastdata"=>{100=>crafts(:oneout), 101=>crafts(:twoout)}, "___averages"=>{}, "___overdue"=>{100=>false, 101=>false}, "___count"=>{"Alpha"=>{"IN"=>0, "OUT"=>2, "WD"=>0, 'DISQ' => 0}}, "___orderedcheckpoints"=>{"Start"=>nil, "Alpha"=>"Start", "Bravo"=>"Alpha", "Charlie"=>"Bravo", "Delta"=>"Charlie", "Echo"=>"Delta", "Foxtrot"=>"Echo", "Golf"=>"Foxtrot", "Hotel"=>"Golf", "India"=>"Hotel", "Juliet"=>"India", "Kilo"=>"Juliet", "Lima"=>"Kilo", "Mike"=>"Lima", "November"=>"Mike", "Oscar"=>"November", "Papa"=>"Oscar", "Quebec"=>"Papa", "Sierra"=>"Quebec", "Tango"=>"Sierra", "Finish"=>"Tango"}} assert_equal output, Craft.getAllCheckpointHistory(nil) end test 'self.caclOverdue' do now = DateTime.now.in_time_zone [1, 44].each do |min| assert Craft.calcOverdue('OUT', now, now - 60.minutes, min * 60), \ "#{min} minutes should be true" end assert_not Craft.calcOverdue('IN', now, now - 60.minutes, 120 * 60) [45, 60].each do |min| assert_not Craft.calcOverdue('IN', now, now - 60.minutes, min * 60), \ "#{min} minutes should be false" end end test 'self.finish_info' do output = {100=>{:distance=>12400, :time=>'Tue, 04 Apr 2017 13:00:02 UTC'.to_datetime\ .in_time_zone}, 101=>{:distance=>12400, :time=>'Tue, 04 Apr 2017 13:00:03 UTC'.to_datetime\ .in_time_zone}} assert_equal output, Craft.finish_info end test 'self.getTimeFormat' do assert_equal '3:02', Craft.getTimeFormat([1,2,3]) assert_equal '6:05', Craft.getTimeFormat([4,5,6], false) assert_equal '12:11:10', Craft.getTimeFormat([10,11,12], true) end # test 'self.' do # test 'self.' do # Craft.send(:public, :getTimeFormat) # byebug # end end
true
9b7e2c2f59bccbfd2270bbf1c9807fd00ba2c9c9
Ruby
ifcwebserver/IFCWebServer-Extensions
/extensions/byclass/IfcDateTime.rb
UTF-8
793
2.734375
3
[]
no_license
class IFCDATEANDTIME def date_time dateComponent= self.dateComponent.to_obj timeComponent = self.timeComponent.to_obj dateComponent.monthComponent = '0' + dateComponent.monthComponent.to_s if dateComponent.monthComponent.to_s.size == 1 dateComponent.dayComponent = '0' + dateComponent.dayComponent.to_s if dateComponent.dayComponent.to_s.size == 1 timeComponent.minuteComponent = '0' + timeComponent.minuteComponent.to_s if timeComponent.minuteComponent.to_s.size == 1 timeComponent.hourComponent = '0' + timeComponent.hourComponent.to_s if timeComponent.hourComponent.to_s.size == 1 "#{dateComponent.yearComponent}-#{dateComponent.monthComponent}-#{dateComponent.dayComponent} #{timeComponent.hourComponent}:#{timeComponent.minuteComponent}" end end
true
02cc56ffe06370f9d2134f63a62a312011414fc3
Ruby
cmoir97/Film-Shop-Inventory
/film_shop/models/production_company.rb
UTF-8
1,633
3.109375
3
[]
no_license
require_relative('../db/sql_runner') class ProductionCompany attr_reader :id attr_accessor :name def initialize(options) @id = options['id'].to_i @name = options['name'] end def save() sql = "INSERT INTO production_companies ( name ) VALUES ( $1 ) RETURNING id" values = [@name] result = SqlRunner.run(sql, values) @id = result.first['id'] end def update() sql = "UPDATE production_companies SET name = $1 WHERE id = $2" values = [@name, @id] SqlRunner.run(sql, values) end def delete() sql = "DELETE FROM production_companies WHERE id = $1" values = [@id] SqlRunner.run(sql, values) end def directors() sql = "SELECT d.* FROM directors d INNER JOIN films f ON f.director_id = d.id WHERE f.production_company_id = $1;" values = [@id] results = SqlRunner.run(sql, values) return results.map { |directors| Director.new(directors) } end def self.all() sql = "SELECT * FROM production_companies" hashes_of_companies = SqlRunner.run(sql) company_hashes = hashes_of_companies.map { |company_hash| ProductionCompany.new(company_hash) } return company_hashes end def self.find(id) sql = "SELECT * FROM production_companies WHERE id = $1" values = [id] result = SqlRunner.run(sql, values).first production_company = ProductionCompany.new(result) return production_company end def self.find_film(id) sql = "SELECT films.* FROM films WHERE production_company_id = $1" values = [id] result = SqlRunner.run( sql,values ) return result.map{ |film| Film.new(film)} end end
true
ff0dd09c8676e77bb5923449b562fa0b0d0d08af
Ruby
skuan/src
/awesome.rb
UTF-8
621
4.28125
4
[]
no_license
#Fizzbuzz seq = (1..100) #instinctually set a variable = to the range 1.100 inclusive although I saw online that you can directly run a .each on (1..100) w/o defining a variable. seq.each do |i| #element i for integer, with the following conditional block if i % 15 == 0 puts "FizzBuzz" #noticed when I didn't put i % 15 first, it was ignored. I went with i % 15 based on mathematical knowledge and convenience. I saw online you could do "if i % 3 == 0 and i % 5 == 0 puts 'FizzBuzz'" elsif i % 3 == 0 puts "Fizz" elsif i % 5 == 0 puts "Buzz" else puts i end #closes conditional block end
true
9adf3ed53a3cf63e8e77b5bd6bc5b9ee0ba87e53
Ruby
RJ-Ponder/RB101
/exercises/medium_2/4_matching.rb
UTF-8
1,756
4.53125
5
[]
no_license
=begin Write a method that takes a string as an argument, and returns true if all parentheses in the string are properly balanced, false otherwise. To be properly balanced, parentheses must occur in matching '(' and ')' pairs. Note that balanced pairs must each start with a (, not a ). Problem - determine if the string has balanced parenthesis Rules - If there is a "(" there must be a corresponding ")" - There cannot be a ")" when the balance is 0 or else you can't close it Algorithm - "(" is left and is +1 - ")" is right and is -1 - balance = 0 - iterate through the string - if there is a "(" balance += 1 - if there is a ")" balance -= 1 - return false if balance is ever < 0 - test if balance == 0 at the end =end def balanced?(string) balance = 0 string.each_char do |char| balance += 1 if char == "(" balance -= 1 if char == ")" return false if balance < 0 end balance == 0 end p balanced?('What (is) this?') == true p balanced?('What is) this?') == false p balanced?('What (is this?') == false p balanced?('((What) (is this))?') == true p balanced?('((What)) (is this))?') == false p balanced?('Hey!') == true p balanced?(')Hey!(') == false p balanced?('What ((is))) up(') == false p balanced?("(hi") == false p balanced?("(hi)") == true p balanced?("(()) hi") == true p balanced?(")(") == false p balanced?("()((((()))))(())()") == true p balanced?("(()())()(())()(") == false p balanced?("") == true =begin Further Exploration There are a few other characters that should be matching as well. Square brackets and curly brackets normally come in pairs. Quotation marks (single and double) also typically come in pairs and should be balanced. Can you expand this method to take into account those characters? =end
true
c357ecb4bd89d099647bad46e473c61fa3fc68ac
Ruby
antman999/project-02
/lib/movie.rb
UTF-8
1,244
3.21875
3
[]
no_license
require 'pry' class Movie < ActiveRecord::Base has_many :rentals has_many :reviews has_many :users, through: :rentals has_many :critics, through: :reviews end # attr_accessor :title, :rating, :category # @@all = [] # def initialize (title, rating, category) # @title = title # @rating = rating # @category = category # @@all << self # end # #Get a list of all Movies # def self.all # @@all # end # def new_movie # self.new("back to the future 2",87,"Family") # end # # Get an array of all the rentals a certain Movie has # def rentals # Rental.all.select do |v| # v.movie == self # end # end # #get the users from a movie rented # def users # rentals.map do |v| # v.user # end # end # def best_rated # best = Movie.all.map do |v| # v.rating # end # best.max # end # def reviews # Review.all.select do |review| # review.movie == self # end # end # def critics # reviews.map do |review| # review.critic # end # end # end #
true
21581c957cc49e5cb98ed3b2a05bbcfcbdc51770
Ruby
StephenWattam/ImputeCaT
/lib/impute/summarise/audience_level.rb
UTF-8
3,454
3.140625
3
[]
no_license
module Impute::Summarise class AudienceLevel < Heuristic # Initialise the audience level heuristic using a # # cat => Fleisch-Kincaid reading score hash # # ** Ensure that the categories are given in-order! def initialize(categories) @categories = categories @fkscorer = FleschKincaidRanker.new() end # value def summarise(document, existing_metadatum_value = nil) text = document.text score = @fkscorer.reading_ease(text) return 1 if score.nil? # Compute distance to each ideal cat_scores = {} @categories.each do |cat, ideal_score| distance = (ideal_score - score).to_f.abs cat_scores[cat] = distance end level = cat_scores.sort_by{|_, y| y}.first.first warn "[audlvl] Score for #{text.split.length} words is #{score} = #{level}" return level end # Return non-normalised distance def difference(prototype_value, document_value) position_a = @categories.keys.index(prototype_value) || 0 position_b = @categories.keys.index(document_value) || 0 (position_a - position_b).to_f end # Return distance, normalised 0-1 def norm_distance(prototype_value, document_value) max = @categories.length # Normalise return (difference(prototype_value, document_value) / max.to_f).abs end def to_s "<Heuristic:#{self.class}>" end end class FleschKincaid < Heuristic # Initialise the audience level heuristic using a # def initialize @fkscorer = FleschKincaidRanker.new() end # value def summarise(document, existing_metadatum_value = nil) text = document.text score = @fkscorer.reading_ease(text) return 1 if score.nil? warn "[flesch] Score for #{text.split.length} words is #{score}" return score end # Return non-normalised distance def difference(prototype_value, document_value) (prototype_value - document_value).to_f end # Return distance, normalised 0-1 def norm_distance(prototype_value, document_value) end def to_s "<Heuristic:#{self.class}>" end end class FleschKincaidRanker # require 'text-hyphen' require 'syllables' # In words MAX_SENTENCE_LENGTH = 100 def reading_ease(str) sentence_count = 0 syllable_count = 0 word_count = 0 # Split by words words_in_this_sentence = 0 str.split.each do |w| # Test sentence ends words_in_this_sentence += 1 if words_in_this_sentence > MAX_SENTENCE_LENGTH || w =~ /[\.!?]$/ words_in_this_sentence = 0 sentence_count += 1 end # add syllable count syllable_count += count_syllables(w) # And inc word count word_count += 1 end return nil if word_count == 0 sentence_count += 1 # Compute the score fkscore = 206.835 - 1.015 * (word_count.to_f / sentence_count.to_f) - 84.6 * (syllable_count.to_f / word_count.to_f) # require 'pry'; pry binding return fkscore end private # Count syllables in a word def count_syllables(word) word_syllable_counts = Syllables.new(word).to_h return word_syllable_counts[word_syllable_counts.keys.first].to_i # @hyphenator.visualise(word).each_char.to_a.count('-') + 1 end end end
true
4a7507a2948b253f31163c64e3cc8ff2150f10e2
Ruby
pitr12/OpenCoroprate-mass-licences
/scraper.rb
UTF-8
1,915
2.765625
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require 'json' require 'turbotlib' require 'nokogiri' require 'faraday' require 'roo' def self.get_xls_links(doc, cell) table = doc.search('table')[1] list = [] table.search('tr').each do |tr| td = tr.search('td')[cell] links = td.search('a').map { |link| "http://www.mass.gov" + link['href'] } list += links.select { |link| link.include?('.xls') }.uniq end list end Turbotlib.log("Starting run...") # optional debug logging body = Faraday.get('http://www.mass.gov/ocabr/licensee/license-types/insurance/individual-and-business-entity-licensing/licensed-listings.html').body doc = Nokogiri::HTML(body) #cell 1 = agencies, cell 2 = individuals agency_xls_links = get_xls_links(doc, 1) individuals_xls_links = get_xls_links(doc, 2) class IndividualRowParser def self.parse(row, xls_link) { number: row[0].to_i, license: row[1], licensure: row[3], individual: row[5], adress: row[7], city: row[8], state: row[9], zip: row[10], phone: row[12], email: row[14], source_url: xls_link, sample_date: Time.now } end end class AgencyRowParser def self.parse(row, xls_link) { number: row[0].to_i, license: row[1], licensure: row[4], agency: row[6], adress: row[8], city: row[9], state: row[11], zip: row[12], phone: row[16], source_url: xls_link, sample_date: Time.now } end end def parse_xls2(xls_link, parser) xls = Roo::Excel.new(xls_link) (xls.first_row..xls.last_row).each do |row_number| row = xls.row(row_number) puts JSON.dump(parser.parse(row,xls_link)) if row[0] end end agency_xls_links.each do |xls_link| parse_xls2(xls_link, AgencyRowParser) end individuals_xls_links.each do |xls_link| parse_xls2(xls_link, IndividualRowParser) end
true
52960a96ef5993dd761c1a548f77917a8554050b
Ruby
npmcdn-to-unpkg-bot/KouhaiDash
/app/models/google_account.rb
UTF-8
1,551
2.625
3
[]
no_license
# == Schema Information # # Table name: google_accounts # # id :integer not null, primary key # user_id :integer # access_token :string # refresh_token :string # expires_at :datetime # gmail :string # created_at :datetime not null # updated_at :datetime not null # require 'net/http' require 'json' class GoogleAccount < ActiveRecord::Base before_validation :lower_gmail #associations belongs_to :user has_many :text_pages #validations validates :gmail, presence: true, uniqueness: { case_sensitive: false } validates :user_id, presence: true def to_params {'refresh_token' => refresh_token, 'client_id' => ENV.fetch('GOOGLE_API_CLIENT_ID'), 'client_secret' => ENV.fetch('GOOGLE_API_CLIENT_SECRET'), 'grant_type' => 'refresh_token'} end def request_token_from_google url = URI("https://accounts.google.com/o/oauth2/token") Net::HTTP.post_form(url, self.to_params) end def refresh! response = request_token_from_google data = JSON.parse(response.body) if response.code=='200' update_attributes(access_token: data['access_token'],expires_at: Time.now + (data['expires_in'].to_i).seconds) else update_attributes(refresh_token: '') end end def expired? expires_at < Time.now end def fresh_token refresh! if expired? access_token end protected def lower_gmail self.gmail = self.gmail.downcase end end
true
27864dd42ba282b5887d1d4aa9dde3d5230312de
Ruby
brunovongxay/exercice-pair-programming
/exo_14.rb
UTF-8
119
3.34375
3
[]
no_license
puts "Choississez un nombre" number = gets.chomp.to_i i=number number.times do puts "#{i-=1}" end
true
c57b594445292b998e09ba8f5f881285acd992e3
Ruby
quintel/merit
/spec/merit/participants/user/price_sensitive_spec.rb
UTF-8
3,983
2.75
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'spec_helper' # Users should be set up with "want" amounts of: # # point 0 = 1.0 # point 1 = 2.0 # RSpec.shared_examples('a price-sensitive User') do context 'when the "want" price is 15' do let(:price_curve) { [15, 15] } context 'when the "offer" price is 2.5 and amount is 0.5' do it 'accepts 0.5 energy when desiring 1' do expect(ps.barter_at(0, 0.5, 2.5)).to eq(0.5) end it 'accepts 0.5 energy when desiring 2' do expect(ps.barter_at(1, 0.5, 2.5)).to eq(0.5) end it 'calculates total production in MJ' do ps.barter_at(1, 0.5, 2.5) expect(ps.production).to eq(0.5 * Merit::MJ_IN_MWH) end it 'calculates total production in MWh' do ps.barter_at(1, 0.5, 2.5) expect(ps.production(:mwh)).to eq(0.5) end end context 'when the "offer" price is 2.5 and amount is 5' do it 'accepts 1 energy when desiring 1' do expect(ps.barter_at(0, 5.0, 2.5)).to eq(1) end it 'accepts 2.0 energy when desiring 2.0' do expect(ps.barter_at(1, 5.0, 2.5)).to eq(2) end end context 'when the "offer" price is 10 and amount is 1' do it 'accepts 1 energy when desiring 1' do expect(ps.barter_at(0, 1.0, 10.0)).to eq(1) end it 'accepts 1 energy when desiring 2' do expect(ps.barter_at(1, 1.0, 10.0)).to eq(1) end end context 'when the "offer" price is 20 and amount is 1' do it 'accepts no energy when desiring 1' do expect(ps.barter_at(0, 1.0, 20.0)).to eq(0) end it 'accepts no energy when desiring 2' do expect(ps.barter_at(1, 1.0, 20.0)).to eq(0) end end end context 'when offered an excess of 0.25' do let(:assign_excess) { ps.assign_excess(0, 0.25) } it 'sets the load to 0.25' do assign_excess expect(ps.load_at(0)).to eq(0.25) end it 'returns 0.25' do expect(assign_excess).to eq(0.25) end context 'when offered another 0.5' do before { assign_excess } let(:assign_excess_2) { ps.assign_excess(0, 0.5) } it 'sets the load to 0.75' do assign_excess_2 expect(ps.load_at(0)).to eq(0.75) end it 'returns 0.5' do expect(assign_excess_2).to eq(0.5) end end context 'when offered another 10' do before { assign_excess } let(:assign_excess_2) { ps.assign_excess(0, 10.0) } it 'sets the load to 1' do assign_excess_2 expect(ps.load_at(0)).to eq(1) end it 'returns 0.75' do expect(assign_excess_2).to eq(0.75) end end end end RSpec.describe Merit::User::PriceSensitive do let(:ps) do described_class.new( user, Merit::CostStrategy::FromCurve.new(nil, Merit::Curve.new(price_curve)) ) end let(:price_curve) { [5.0, 10.0] } include_examples 'a flex' do let(:flex) do described_class.new( Merit::User.create( key: :a, total_consumption: 1.0, load_profile: Merit::Curve.new([1.0, 2.0] * 4380) ), Merit::CostStrategy::FromCurve.new(nil, Merit::Curve.new(price_curve)) ) end end describe 'wrapping a TotalConsumption' do let(:user) do Merit::User.create( key: :a, total_consumption: 1.0, load_profile: Merit::Curve.new([1.0, 2.0] * 4380) ) end include_examples 'a price-sensitive User' end describe 'wrapping a WithCurve' do let(:user) do Merit::User.create( key: :a, load_curve: Merit::Curve.new([1.0, 2.0]) ) end include_examples 'a price-sensitive User' end describe 'wrapping a ConsumptionLoss' do let(:user) { Merit::User.create(key: :a, consumption_share: 0.5) } it 'raises an IllegalPriceSensitiveUser' do expect { ps }.to raise_error(Merit::IllegalPriceSensitiveUser) end end end
true
09d705cf63224a838df71b350555f7073eb9319c
Ruby
MiguelSilva1997/battleship_rails
/app/models/turn_helper.rb
UTF-8
401
2.5625
3
[]
no_license
module TurnHelper def before_save_validation(game, player_id, coord) return "game_over", false if game.phase == "game_over" return "not_your_turn", false if game.next_player != player_id unless ("A".."J").to_a.include?(coord[0]) && ("0".."9").to_a.include?(coord[1]) return "invalid_coordinate", false end return ["", true] end end
true
84b3db6449caf1730e271c2cd70fdfd8e3dbdf52
Ruby
starapor/slippers
/lib/engine/slippers_nodes.rb
UTF-8
4,539
2.625
3
[ "MIT" ]
permissive
module Slippers module AttributeToRenderNode def eval(object_to_render, template_group) [object_to_render].flatten.inject('') { |rendered, item| rendered + render(value_of(item, template_group), template_group) } end def value_of(item, template_group) return default_string(template_group) if attribute == '' return item.to_s if attribute == 'it' return item[to_sym] if item.respond_to?(:[]) && item[to_sym] return item.send(attribute) if item.respond_to?(attribute) default_string(template_group) end def render(object_to_render, template_group) substitue_null_values(object_to_render) return template_group.render(object_to_render) if template_group && template_group.has_registered?(object_to_render.class) return object_to_render.compact.join(seperator) if object_to_render.respond_to?('join') object_to_render.to_s end def substitue_null_values(object_to_render) return unless null_values && object_to_render.respond_to?('map!') object_to_render.map!{|x| if x then x else null_values end } end def to_sym attribute.to_sym end def null_values end def seperator end def attribute text_value end private def default_string(template_group) return Slippers::Engine::DEFAULT_STRING unless template_group template_group.default_string end end class AttributeWithExpressionOptionNode < Treetop::Runtime::SyntaxNode include AttributeToRenderNode def seperator seperator_value.seps.to_s if seperator_value.elements end def null_values null_subtitute.nulls.to_s if null_subtitute.elements end end class TemplateNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group) apply_attribute_to_subtemplate(object_to_render, template_group) end def apply_attribute_to_subtemplate(item, template_group) return invoke_misisng_handler unless template_group subtemplate = template_group.find(template_path.to_s) return invoke_misisng_handler(template_group.missing_handler) unless (subtemplate && subtemplate.respond_to?('render')) subtemplate.render(item) end private def invoke_misisng_handler(missing_handler=Slippers::Engine::MISSING_HANDLER) return missing_handler.call(template_path.to_s) if missing_handler.arity == 1 missing_handler.call end end class AnonymousTemplateNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group) apply_attribute_to_subtemplate(object_to_render, template_group) end def apply_attribute_to_subtemplate(item, template_group) SlippersParser.new.parse(anonymous_template_words.to_s).eval(item, template_group) end end class ApplyAttributeToTemplateNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group) [object_to_render].flatten.inject('') { |rendered, item| rendered + find_attribute_and_render(item, template_group) } end def find_attribute_and_render(item, template_group) object_to_render = attribute.value_of(item, template_group) [object_to_render].flatten.inject('') { |rendered, i| rendered + template.apply_attribute_to_subtemplate(i, template_group).to_s } end end class ConditionalTemplateNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group) attribute = if_clause.value_of(object_to_render, template_group) if (attribute && attribute != default_string(template_group)) then if_expression.eval(object_to_render, template_group) else if else_clause.elements then else_clause.else_expression.eval(object_to_render, template_group) else default_string(template_group) end end end private def default_string(template_group) return Slippers::Engine::DEFAULT_STRING unless template_group template_group.default_string end end class TemplatedExpressionNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group) foo.eval(object_to_render, template_group) end end class ExpressionNode < Treetop::Runtime::SyntaxNode def eval(object_to_render, template_group=nil) before.eval(object_to_render, template_group) + expression_to_render.eval(object_to_render, template_group) + space.eval + after.eval(object_to_render, template_group) end end end
true
4aa4a0746979b8b3fd180cc0254ad0f3dff9a039
Ruby
stashchenkoksu/exercism
/queen_attack/main.rb
UTF-8
715
3.40625
3
[]
no_license
require_relative 'lib/queen_attack' require_relative 'lib/readme_viewer' def get_argv(first_coord, second_coord) 2.times { |i| first_coord << ARGV[i].to_i } 2.times { |i| second_coord << ARGV[i + 2].to_i } end def get_user_input(first_coord, second_coord) puts 'Enter first pair of coordinates' print 'x: ' first_coord << gets.to_i print 'y: ' first_coord << gets.to_i puts 'Enter second pair of coordinates' print 'x: ' second_coord << gets.to_i print 'y: ' second_coord << gets.to_i end first_coord = [] second_coord = [] ARGV.length == 4 ? get_argv(first_coord, second_coord) : get_user_input(first_coord, second_coord) puts Queens.new(white: first_coord, black: second_coord).attack?
true
65fc81d0dad4be70d48d4b52e5fb73799bf59e2a
Ruby
blackjackshellac/giddy
/test/giddy/gstat_spec.rb
UTF-8
2,759
2.640625
3
[]
no_license
# # # require 'fileutils' require './lib/giddy/gstat' describe Gstat do before(:all) do @home_dir=FileUtils.pwd @test_dir="test" FileUtils.chdir(@test_dir) { %x/echo > empty/ %x/echo "not empty" > file/ %x/ln -s file file_symlink/ %x/ln -s . dir_symlink/ @empty="empty" @file ="file" @file_symlink="file_symlink" @dir_symlink="dir_symlink" } @pack="10,8,4096,f,0xfd,0x00,27131915,1,0100664,1201,1201,1374430943,1374430943,1374430943" end before(:each) do FileUtils.chdir(@test_dir) end describe "initialize" do it "fails to create a new Gstat if file is null" do expect { Gstat.new(nil)}.to raise_error end it "fails to create a new Gstat if file is not found" do expect { Gstat.new("foo bar baz")}.to raise_error end it "creates a new Gstat for a regular file" do expect { Gstat.new(@file) }.to_not raise_error end it "creates a new Gstat for a directory" do expect { Gstat.new(".") }.to_not raise_error end it "creates a new Gstat for a file symlink" do expect { Gstat.new(@file_symlink) }.to_not raise_error end it "creates a new Gstat for a directory symlink" do expect { Gstat.new(@dir_symlink) }.to_not raise_error end it "creates a new Gstat using pack data" do gs=Gstat.new(@file, @pack) gs.pack.should == @pack end end describe "test properties" do it "sets the name property" do gs=Gstat.new(@file) gs.name.should == @file end it "sets the sha for a file" do gs=Gstat.new(@file, @pack) gs.stat_sha2.should == "64e6ef8f20cfc54e508f7d14d27e5e2c68ca90286dbf600e6320857fd452d85e" end it "sets the gstat for a file" do gs=Gstat.new(@file, @pack) gs.pack.should == @pack end end describe "test comparison" do it "is not equal if parameter is null" do gs=Gstat.new(@file) gs.eql?(nil).should be false end it "is equal for same data" do gs=Gstat.new(@file, @pack) gt=Gstat.new(@file, @pack) gs.eql?(gt).should be true end it "is not equal for same file, different stat" do gs=Gstat.new(@file, @pack) # this will be new stat data gt=Gstat.new(@file) gs.eql?(gt).should be false end it "is not equal for symlink and the file to which it is linked" do gs=Gstat.new(@file) gl=Gstat.new(@file_symlink) gs.eql?(gl).should be false end it "is equal for same directory" do gs=Gstat.new(@home_dir) gt=Gstat.new(@home_dir) gs.eql?(gt).should be true end it "is equal for different directory" do gs=Gstat.new(@home_dir) gt=Gstat.new(".") gs.eql?(gt).should be false end end after(:each) do FileUtils.chdir(@home_dir) end after(:all) do FileUtils.chdir(@test_dir) { %x/rm -fv empty file file_symlink dir_symlink/ } end end
true
9d6434b9c4a7f2fe60febcb88acfd9857fd4a501
Ruby
TheCalebThornton/slcsp
/spec/models/plan_spec.rb
UTF-8
2,861
2.515625
3
[]
no_license
require 'models/plan' describe Plan do describe '.find_all_by_state_and_rate_area_and_metal_level' do testCsvPath = "#{File.join(File.dirname(__FILE__), '../resources/plansSmallTest.csv')}" context 'given nil state' do it 'returns empty list' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, nil, '12', 'gold') expect(plans).to eql [] end end context 'given nil rate' do it 'returns empty list' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, 'OH', nil, 'silver') expect(plans).to eql [] end end context 'given nil metal_level' do it 'returns empty list' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, 'OH', '12', nil) expect(plans).to eql [] end end context 'given nil csv file path' do it 'returns empty list' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(nil, 'OH', '12', 'bronze') expect(plans).to eql [] end end context 'given state/rate_area/metal_level combo not in file' do it 'returns empty list' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, 'OH', 43, 'ilver') expect(plans).to eql [] end end context 'given state/rate_area/metal_level combo in file' do it 'returns location object' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, 'FL', '60', 'Silver') expect(plans[0].plan_id).to eql '26325VH2723968' expect(plans[0].state).to eql 'FL' expect(plans[0].metal_level).to eql 'Silver' expect(plans[0].rate).to eql '421.43' expect(plans[0].rate_area).to eql '60' end end context 'given multiple state/rate_area/metal_level combo entries in file' do it 'returns first location object' do plans = Plan.find_all_by_state_and_rate_area_and_metal_level(testCsvPath, 'IL', '5', 'Gold') expect(plans[0].plan_id).to eql '09846WB8636631' expect(plans[0].state).to eql 'IL' expect(plans[0].metal_level).to eql 'Gold' expect(plans[0].rate).to eql '361.69' expect(plans[0].rate_area).to eql '5' expect(plans[1].plan_id).to eql '09846WB8636632' expect(plans[1].state).to eql 'IL' expect(plans[1].metal_level).to eql 'Gold' expect(plans[1].rate).to eql '345' expect(plans[1].rate_area).to eql '5' expect(plans[2].plan_id).to eql '09846WB8636633' expect(plans[2].state).to eql 'IL' expect(plans[2].metal_level).to eql 'Gold' expect(plans[2].rate).to eql '71.8' expect(plans[2].rate_area).to eql '5' end end end end
true
7a3b5cad0d6f084fa4b3547ec26caba84b120472
Ruby
mjrudin/twitter
/user.rb
UTF-8
2,162
2.9375
3
[]
no_license
require 'json' require_relative 'twitter_session' require 'addressable/uri' class User @@users = [] def self.users @@users end def self.make_new(user_array) user_array.map do |user| User.new(user["screen_name"]) end end def initialize(username) @username = username @@users << self end def followers json = TwitterSession.access_token.get( "https://api.twitter.com/1.1/followers/list.json").body grab_screen_names(json) end def followed_users json = TwitterSession.access_token.get( "https://api.twitter.com/1.1/friends/list.json").body grab_screen_names(json) end def timeline json = TwitterSession.access_token.get( "https://api.twitter.com/1.1/statuses/user_timeline.json").body Status.parse(json) end def grab_screen_names(json) users = JSON.parse(json)["users"] User.make_new(users) users.empty? ? [] : users.map do |user| user["screen_name"] end end end class EndUser < User @@current_user def self.set_user_name(user_name) @@current_user = EndUser.new(user_name) end def self.me @@current_user end def post_status(status_text) begin http = TwitterSession.access_token.post(format_status(status_text)) raise "ERROR! #{http.to_s}" unless http.to_s.include?("HTTPOK") rescue Exception => e puts e.message end end def format_status(status_text) Addressable::URI.new( :scheme => "https", :host => "api.twitter.com", :path => "1.1/statuses/update.json", :query_values => {:status => status_text}).to_s end def direct_message(other_user, text) begin http = TwitterSession.access_token.post(format_message(other_user,text)) raise "ERROR! #{http.to_s}" unless http.to_s.include?("HTTPOK") rescue Exception => e puts e.message end end def format_message(other_user, text) Addressable::URI.new( :scheme => "https", :host => "api.twitter.com", :path => "1.1/direct_messages/new.json", :query_values => {:screen_name => other_user, :text => text}).to_s end end
true
319cd2dc5fc0b199d88202e661f99692f9512d67
Ruby
kristastadler/backend_module_0_capstone
/day_1/ex7.rb
UTF-8
523
4.25
4
[]
no_license
#print "How old are you? " #age = gets.chomp #print "How tall are you? " #height = gets.chomp #print "How much do you weigh? " #weight = gets.chomp #puts "So, you're #{age} old, #{height} tall and #{weight} heavy." print "Where were you born? " location = gets.chomp print "What is your birthday? " birthday = gets.chomp print "What is your mom's name? " mom_name = gets.chomp print "What is your dad's name? " dad_name = gets.chomp puts "So, you were born on #{birthday} in #{location} to #{mom_name} and #{dad_name}."
true
31932929e7b41c7b125b2524c07bf2009b01f056
Ruby
peppyheppy/jekyll
/lib/jekyll/migrators/mephisto.rb
UTF-8
3,960
2.8125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# Quickly hacked together my Michael Ivey # Based on mt.rb by Nick Gerakines, open source and publically # available under the MIT license. Use this module at your own risk. require 'rubygems' require 'sequel' require 'fastercsv' require 'fileutils' require File.join(File.dirname(__FILE__),"csv.rb") # NOTE: This converter requires Sequel and the MySQL gems. # The MySQL gem can be difficult to install on OS X. Once you have MySQL # installed, running the following commands should work: # $ sudo gem install sequel # $ sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config module Jekyll module Mephisto #Accepts a hash with database config variables, exports mephisto posts into a csv #export PGPASSWORD if you must DEFAULT_USER_ID = 1 def self.postgres(c) sql = <<-SQL BEGIN; CREATE TEMP TABLE jekyll AS SELECT title, permalink, body, published_at, filter FROM contents WHERE user_id IN (%s) AND type = 'Article' ORDER BY published_at; COPY jekyll TO STDOUT WITH CSV HEADER; ROLLBACK; SQL command = %Q(psql -h #{c[:host] || "localhost"} -c "#{sql.strip}" #{c[:database]} #{c[:username]} -o #{c[:filename] || "posts.csv"}) puts command `#{command}` CSV.process end # This query will pull blog posts from all entries across all blogs. If # you've got unpublished, deleted or otherwise hidden posts please sift # through the created posts to make sure nothing is accidently published. ARTICLE_QUERY = <<-SQL SELECT id, permalink, body, published_at, title, filter, comments_count FROM contents WHERE user_id = 2 AND type = 'Article' AND published_at IS NOT NULL ORDER BY published_at SQL ARTICLE_TAGS_QUERY = <<-SQL SELECT LOWER(tags.name) AS name FROM tags JOIN taggings ON taggings.tag_id = tags.id WHERE taggings.taggable_type = 'Content' AND taggings.taggable_id = %s SQL ARTICLE_COMMENTS_QUERY = <<-SQL SELECT title, body, author, author_url, author_email, author_ip, published_at, filter FROM contents WHERE article_id = %s ORDER BY published_at SQL def self.process(dbname, user, pass, host = 'localhost') db = Sequel.mysql(dbname, :user => user, :password => pass, :host => host, :encoding => 'utf8') FileUtils.mkdir_p "_posts" db[(ARTICLE_QUERY % (ENV['USER_IDS'] || DEFAULT_USER_ID))].each do |post| title = post[:title] slug = post[:permalink] date = post[:published_at] content = post[:body] comments = [] db[(ARTICLE_COMMENTS_QUERY % post[:id])].each do |comment| comments << { title: comment[:title], body: comment[:body].to_s, name: comment[:author], email: comment[:author_email], ip: comment[:author_ip], published_at: comment[:published_at], } end tags = [] db[(ARTICLE_TAGS_QUERY % post[:id])].each do |tag| tags << tag end filter = post[:filter].gsub('_filter','').strip name = [date.year, date.day, date.month, slug].join('-') + ".#{filter.size > 0 ? filter : 'html'}" data = { 'mt_id' => post[:id], 'layout' => 'post', 'title' => title.to_s, 'tags' => tags, 'comments' => comments, }.delete_if { |k,v| v.nil? || v == ''}.to_yaml File.open("_posts/#{name}", "w") do |f| f.puts data f.puts "---" f.puts content end end end end end
true
a05675e47d547c0e56634119cde77f06cf59bb61
Ruby
jcovell/my-first-repository
/flow/cx4.rb
UTF-8
97
3.640625
4
[]
no_license
# Example 4: must use "then" keyword when using 1-line syntax if x == 3 then puts "x is 3" end
true
c7de705a8198c35355b6fba72619104189635779
Ruby
bwarminski/tree
/tree.rb
UTF-8
811
3.25
3
[]
no_license
#!/usr/bin/env ruby Counter = Struct.new(:dirs, :files) do def index(filepath) File.directory?(filepath) ? self.dirs += 1 : self.files += 1 end def output "\n#{dirs} directories, #{files} files" end end def tree(counter, directory, prefix = '') filepaths = Dir[File.join(directory, '*')] filepaths.each_with_index do |filepath, index| counter.index(filepath) relative = File.basename(filepath) if index == filepaths.length - 1 puts "#{prefix}└── #{relative}" tree(counter, filepath, "#{prefix} ") else puts "#{prefix}├── #{relative}" tree(counter, filepath, "#{prefix}│ ") end end end directory = ARGV.first || '.' puts directory counter = Counter.new(0, 0) tree(counter, directory) puts counter.output
true
b96b38c243dd2190b81691cbddb2b5313f091605
Ruby
gearjosh/linda_the_sphinx
/spec/sphinx_spec.rb
UTF-8
547
2.953125
3
[]
no_license
require 'pry' require 'sphinx' describe '#Sphinx' do describe '#riddle' do it 'returns a riddle' do linda = Sphinx.new expect(linda.riddle1).to(eq('What gets wetter and wetter the more it dries?')) end it 'returns a second riddle' do linda = Sphinx.new expect(linda.riddle2).to(eq('What can travel around the world while staying in a corner?')) end it 'returns a third riddle' do linda = Sphinx.new expect(linda.riddle3).to(eq('What gets broken without being held?')) end end end
true
039dc14d6bd300fa71f2409b1622b88d771e10dd
Ruby
PhilippePerret/Collecte
/module/extract_formats/HTML/Film/Note/helper.rb
UTF-8
548
2.609375
3
[]
no_license
# encoding: UTF-8 class Film class Note def as_link link("note #{id}", {href: '#', onclick:"return ShowNote(#{id})"}) end # Retourne le code HTML de la note comme fiche def as_fiche div( closebox("return HideCurFiche()") + div("Note #{id}", class: 'titre') + libval('Description', content_displayed, class: 'description'), {class: 'fiche note hidden', id: "fiche-note-#{id}"} ) end def content_displayed # Note : content est un Film::TextObjet content.to_html end end #/Note end #/Film
true
634d4e859f3fad8eb06a3f954f90ff935d7b3e18
Ruby
brightchimp/twitter
/lib/twitter/base.rb
UTF-8
314
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Twitter class Base def initialize(hash={}) hash.each do |key, value| instance_variable_set(:"@#{key}", value) unless value.nil? end self end def to_hash Hash[instance_variables.map{|ivar| [ivar[1..-1].to_sym, instance_variable_get(ivar)]}] end end end
true
b6d63f0183c92e7f86fdbe46bed4ad8727a63f92
Ruby
bbensky/dishlist
/recipe.rb
UTF-8
5,277
3.765625
4
[]
no_license
# require 'pry' # Display list of recipes # Prompt user to add a recipe # Recipes consist of ingredients, quantities, units of measurement # Verbs: # Add ingredients and quantities to a recipe require 'yaml' class Recipe attr_accessor :title, :directions, :ingredients, :tags def initialize @title = "" @name = "" @ingredients = [ ] @directions = "" @tags = [ ] end def info=(recipe_hash) @title = recipe_hash[:title] @ingredients = recipe_hash[:ingredients] @directions = recipe_hash[:directions] @tags = recipe_hash[:tags] end def add_title(title) @title = title end def add_ingredient(ingredient) @ingredients << ingredient end def add_directions(string) @directions = string end def add_tag(tag) @tags << tag end def retrieve # Not sure if this method belongs in this class. end def to_s "\n#{@title.upcase}\n\nIngredients:\n#{@ingredients.join("\n")}\n\n" \ "Directions: #{@directions}\n\nTags: #{@tags.join(', ')}\n" end end class List # could contain logic for loading and saving the list, as well as manipulating the list (such as sorting recipes by name) def initialize @list = YAML.load(File.read("recipes_list.yml")) end def read @list end def add(recipe_object) new_recipe = { title: recipe_object.title, ingredients: recipe_object.ingredients, directions: recipe_object.directions, tags: recipe_object.tags } @list << new_recipe end def write File.open("recipes_list.yml", "w") { |file| file.write(@list.to_yaml) } end end class RecipeSession def initialize # Separated out the List#read method to allow recipes to be added to the list. @recipes = List.new @access_recipes = @recipes.read @current_user_input = nil end def session system 'clear' welcome_message loop do display_recipes user_menu_choice case @choice when 'q' break when 'n' enter_new_recipe else display_single_recipe end system 'clear' end @recipes.write goodbye_message end def user_menu_choice choice = nil loop do puts "Please choose an option:" puts "View a recipe (Enter a recipe number)" puts "Add a new recipe (press N)" puts "Exit the program (press Q)" puts "" choice = gets.chomp.downcase break if valid_menu_options.include?(choice) puts "Sorry, invalid answer." end @choice = choice end def valid_menu_options menu_options = ['n', 'q'] (1..@access_recipes.count).each { |num| menu_options << num.to_s } menu_options end def display_recipes @access_recipes.each_with_index do |recipe, idx| puts "#{idx+1}. #{recipe[:title]}" end puts "" end def display_single_recipe system 'clear' @current_recipe = Recipe.new @current_recipe.info = @access_recipes[@choice.to_i - 1] puts @current_recipe puts "" loop do puts "Press Enter to return to the main menu." answer = gets.chomp break if answer.size.zero? puts "Sorry, invalid answer." end end def enter_new_recipe loop do @new_recipe = Recipe.new @new_recipe.add_title(user_input('What is the name of the recipe?')) enter_ingredients @new_recipe.add_directions(user_input('What are the directions?')) enter_tags @recipes.add(@new_recipe) puts "Enter another recipe? (y/n)" answer = nil loop do answer = gets.chomp.downcase[0] break if ['y', 'n'].include?(answer) puts "Sorry, that is not a valid answer." end break if answer == 'n' end puts "" end def user_input(question) answer = nil loop do puts question answer = gets.chomp break if !answer.length.zero? && answer[0] != ' ' puts "Sorry, that is not a valid answer." puts "" end puts "" answer end def enter_ingredients @current_user_input = nil loop do loop do puts "Please enter an ingredient or 'd' for done." puts "Example: 1/4 cup milk" puts "" @current_user_input = gets.chomp break if !@current_user_input.length.zero? && @current_user_input[0] != ' ' puts "Sorry, that is not a valid ingredient." end break if @current_user_input == 'd' @new_recipe.add_ingredient(@current_user_input) puts "" end end def enter_tags @current_user_input = nil loop do loop do puts "Please enter a tag or 'd' for done." puts "Example: breakfast" puts "" @current_user_input = gets.chomp break if !@current_user_input.length.zero? && @current_user_input[0] != ' ' puts "Sorry, that is not a valid tag." end break if @current_user_input == 'd' @new_recipe.add_tag(@current_user_input) puts "" end end def welcome_message puts "Welcome to the Recipe List." puts end def goodbye_message puts "Goodbye!" end end RecipeSession.new.session
true
3ca9e176ee8707fe2b28a74c2836cb65150c2b97
Ruby
anikonchuk/crud-with-validations-lab-v-000
/app/models/song.rb
UTF-8
755
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base validates :title, :artist_name, presence: true validates :released, inclusion: { in: [true, false] } validates :release_year, presence: true, if: :released? validate :release_date_in_the_past? validate :same_artist_same_year? def release_date_in_the_past? if release_year.present? && release_year > Date.today.year errors.add(:release_year, "must be less than or equal to this year") end end def released? released == true end def same_artist_same_year? if release_year.present? && Song.find_by(title: title, artist_name: artist_name, release_year: release_year) errors.add(:title, "cannot be the same title if the artist and release year are the same") end end end
true
26714b7c69cf5d41592090766cefcda281c47da0
Ruby
kakuda/myfiles
/home/libs/ruby/japanese.rb
UTF-8
2,529
2.671875
3
[]
no_license
$KCODE = 'u' require 'jcode' class JapaneseExtractor def initialize end def extract_addr(str) return str.scan(/([一-龠]+[都|道|府|県|][一-龠]+[市|区|町|村|])/u) end def is_zenkaku_katakana(str) (?:\xE3\x81[\x81-\xBF]|\xE3\x82[\x80-\x93]) end def extract_person_name(str) return str.scan(/[、|の](.*?)[が|(|は]/u).flatten # return str.scan(/[、|・|の](.*?)[が|は|(]/u).flatten.select {|x| x.split(//u).length < 8 } end end jp = JapaneseExtractor.new sentense = '「仮面ライダーシリーズに出演したい」と芸能界デビューしたGカップの爆乳ボディーのグラビアアイドル、大空かのん(20)が25日にファーストDVD「発掘美少女09」(グラッツコーポレーション、3990円)を発売PRのため、東京・大手町のZAKZAK編集部に来社した。' puts jp.extract_person_name(sentense) sentense = 'リンパ腫のため3月下旬に入院、治療に専念してきた元花組トップの愛華みれ(43)は前日の14日から「シンデレラ the ミュージカル」の稽古に復帰した。' p jp.extract_person_name(sentense) sentense = '愛知県岡崎市の東名高速道路で16日午後に発生したバスジャック事件。' puts jp.extract_addr(sentense) sentense = '歌手の浜崎あゆみが女性下着メーカー・ワコール社のアジア向け新広告で、初の下着姿を披露していることが16日(水)明らかになった。' puts jp.extract_person_name(sentense) sentense = '情報サイト『ZAKZAK』主催による『第1回 日本グラビアアイドル大賞』をタレントの小倉優子が受賞し16日(水)、東京・大手町の同編集部で行われた表彰式に出席した。' puts jp.extract_person_name(sentense) sentense = '他にはハンドボール日本代表の宮崎大輔(27)やタレント・にしおかすみこ(33)らが参加する。' puts jp.extract_person_name(sentense) sentense = '「仮面ライダーシリーズに出演したい」と芸能界デビューしたGカップの爆乳ボディーのグラビアアイドル、大空かのん(20)が25日にファーストDVD「発掘美少女09」(グラッツコーポレーション、3990円)を発売PRのため、東京・大手町のZAKZAK編集部に来社した。' puts jp.extract_person_name(sentense)
true
18416808c64b110c34ef54eb8386924ecc2d1e20
Ruby
helloRupa/active-record-lite
/lib/02_searchable.rb
UTF-8
396
2.609375
3
[]
no_license
require_relative 'db_connection' require_relative '01_sql_object' module Searchable def where(params) where_str = params.keys.join(' = ? AND ') + ' = ?' res = DBConnection.execute(<<-SQL, *params.values) SELECT * FROM #{table_name} WHERE #{where_str} SQL res.map { |row| new(row) } end end class SQLObject extend Searchable end
true
10d697dfae76d1a0a22ec643873e603ba41efe68
Ruby
alexcoplan/toomuchsupport
/lib/core_ext/string.rb
UTF-8
666
3.609375
4
[]
no_license
class String # remove last (or more) chars from string def clip n=1 self[0..-n-1] end def clip! n=1 self.replace(clip n) end # this is truly a magnificent core extension # it let's you do stuff like "foo".foo? # => true # TODO: fuzzy matching for underscores/spaces def method_missing sym raise NoMethodError.new("Undefined method #{sym} for String") unless sym.to_s.end_with? "?" this = self.downcase.gsub("_"," ") that = sym.to_s.clip # remove ? that = that.downcase.gsub("_"," ") this == that end # this handy little helper evals code the OO way :) def to_proc eval "Proc.new do\n#{self}\nend" end end
true
f8742e286a694a246a73e2dd40106e814efe45a9
Ruby
JohnAjaka/deli-counter-onl01-seng-ft-052620
/deli_counter.rb
UTF-8
720
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
katz_deli = [] def line(line_array) waiting_array = [] if line_array.size == 0 puts "The line is currently empty." else line_array.each_with_index do |name, index| waiting_array.push("#{index + 1}. #{name}") end puts "The line is currently: #{waiting_array.join(" ")}" end end def take_a_number(line_array, name) line_array.size == 0 line_array.push("#{name}") puts "Welcome, #{name}. You are number #{line_array.size} in line." end def now_serving(line_array) if line_array.size == 0 puts "There is nobody waiting to be served!" else puts "Currently serving #{line_array.first}." line_array.shift end end
true
e09095e2e7e826741045864e091c4328e84e5bee
Ruby
minucos/ruby-challenge
/spec/receipt_spec.rb
UTF-8
978
3.0625
3
[]
no_license
require "receipt" require "basket" require "item" require "tax" describe Receipt do let(:basket) { Basket.new } let(:gst) { Tax.new("GST",10)} let(:import) { Tax.new("import",5)} let(:item_1) { Item.new(qty: 1, name: "book", price: 12.49,taxes: [], imported: false) } let(:item_2) { Item.new(qty: 1, name: "music CD", price: 14.99,taxes: [gst], imported: false) } let(:item_3) { Item.new(qty: 1, name: "chocolate bar", price: 0.85,taxes: [], imported: false) } before(:each) do basket.add(item_1) basket.add(item_2) basket.add(item_3) end subject(:receipt) { Receipt.new(basket) } describe "#initialize" do it "sets a basket instance variable" do expect(receipt.basket).to be(basket) end end describe "#to_s" do it "outputs a receipt for all items" do expect(receipt.to_s).to eq( "1, book, 12.49\n1, music CD, 16.49\n1, chocolate bar, 0.85\n\nSales Taxes: 1.50\nTotal: 29.83\n" ) end end end
true
81d654c467965152967e231099573673491f1970
Ruby
aitchiss/music_collection
/console.rb
UTF-8
496
2.671875
3
[]
no_license
require('pry') require_relative('./models/artist.rb') require_relative('./models/album.rb') Album.delete_all Artist.delete_all artist1 = Artist.new( {'name' => "David Bowie"} ) artist1.save artist2 = Artist.new( {'name' => "Bruce Springsteen"} ) artist2.save album1 = Album.new({ 'name' => 'Hunky Dory', 'genre' => 'rock', 'artist_id' => artist1.id }) album1.save album2 = Album.new({ 'name' => 'Born to Run', 'genre' => 'rock', 'artist_id' => artist2.id }) album2.save binding.pry nil
true
5fb05c537aee06ec9f9e7e80f6ceed1d0866773b
Ruby
LShiHuskies/todo-ruby-basics-prework
/lib/ruby_basics.rb
UTF-8
390
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def division(num1, num2) return num1/num2 end def assign_variable(value) return value = value end def argue (phrase) return phrase end def greeting (greeting, name) return "#{greeting}, #{name}" end def return_a_value value = "Nice" return value end def last_evaluated_value return "expert" end def pizza_party (pizza_party = "cheese") return pizza_party end
true
b533d243e64a9ab546c8886ee0bb403b07225e0e
Ruby
petergoldstein/dalli
/test/test_ring.rb
UTF-8
2,641
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true require_relative 'helper' class TestServer attr_reader :name def initialize(attribs, _client_options = {}) @name = attribs end def weight 1 end end describe 'Ring' do describe 'a ring of servers' do it 'have the continuum sorted by value' do servers = ['localhost:11211', 'localhost:9500'] ring = Dalli::Ring.new(servers, TestServer, {}) previous_value = 0 ring.continuum.each do |entry| assert entry.value > previous_value previous_value = entry.value end end it 'raise when no servers are available/defined' do ring = Dalli::Ring.new([], TestServer, {}) assert_raises Dalli::RingError, message: 'No server available' do ring.server_for_key('test') end end describe 'containing only a single server' do it "raise correctly when it's not alive" do servers = ['localhost:12345'] ring = Dalli::Ring.new(servers, Dalli::Protocol::Binary, {}) assert_raises Dalli::RingError, message: 'No server available' do ring.server_for_key('test') end end it "return the server when it's alive" do servers = ['localhost:19191'] ring = Dalli::Ring.new(servers, Dalli::Protocol::Binary, {}) memcached(:binary, 19_191) do |mc| ring = mc.send(:ring) assert_equal ring.servers.first.port, ring.server_for_key('test').port end end end describe 'containing multiple servers' do it 'raise correctly when no server is alive' do servers = ['localhost:12345', 'localhost:12346'] ring = Dalli::Ring.new(servers, Dalli::Protocol::Binary, {}) assert_raises Dalli::RingError, message: 'No server available' do ring.server_for_key('test') end end it 'return an alive server when at least one is alive' do servers = ['localhost:12346', 'localhost:19191'] ring = Dalli::Ring.new(servers, Dalli::Protocol::Binary, {}) memcached(:binary, 19_191) do |mc| ring = mc.send(:ring) assert_equal ring.servers.first.port, ring.server_for_key('test').port end end end it 'detect when a dead server is up again' do memcached(:binary, 19_997) do down_retry_delay = 0.5 dc = Dalli::Client.new(['localhost:19997', 'localhost:19998'], down_retry_delay: down_retry_delay) assert_equal 1, dc.stats.values.compact.count memcached(:binary, 19_998) do assert_equal 2, dc.stats.values.compact.count end end end end end
true
e6ac1a2521d1e455b142b6157f461d4b36d31ae6
Ruby
jamesmoriarty/victoria-exposure-site-bot
/lib/services/download.rb
UTF-8
596
2.546875
3
[]
no_license
require 'csv' require 'open-uri' require_relative '../models/site' module ExposureBot module Service class Download def self.call(logger, csv_url) logger.info("Fetching: #{csv_url}") io = URI.open(csv_url) CSV.parse(io.read, headers: true).map do |row| Site.new( nil, row['Exposure_date'], row['Exposure_time'], row['Site_streetaddress'], row['Site_postcode'].to_i, row['Site_title'].strip, row['Advice_title'] ) end end end end end
true
cf4b7f5a5e4eaba53750071f37b0027ee347462f
Ruby
semyonovsergey/int-brosayZavod
/lesson 4-1/MyApp5.rb
UTF-8
34
2.96875
3
[]
no_license
20.downto(10) do |i| puts i end
true
16384d426c09202fe6ed8ab19f5a4284d6123ea6
Ruby
danielmachado/kermitpfc-core
/lib/kermitpfc.rb
UTF-8
3,592
3.28125
3
[ "MIT" ]
permissive
require_relative 'business/adapter/twitter_adapter' require_relative 'business/converter/twitter_converter' require_relative 'business/converter/random_converter' require_relative 'business/adapter/random_adapter' require_relative 'helper/DAO' require_relative 'helper/websocket_server' require_relative './logging' require 'json' # @author Daniel Machado Fernandez # @version 1.0 # # Masterclass that adapts the rakefile into a class to use the commander gem # @see http://rubydoc.info/gems/commander/4.1.2/frames class KermitPFC # Load the config file def initialize begin cleaning_the_house puts 'pooling' Logging::logger.info('Pooling') pool = [] pool << Thread.new { initialize_websocket_server } puts 'websocket started' Logging::logger.info('WebSocket started') for i in 1..Logging::Settings.twitter.streams puts "adding twitter adapter ##{i}" Logging::logger.info("adding twitter adapter ##{i}") pool << Thread.new { twitter_adapter i } sleep 1 end puts 'twitter adapters added' Logging::logger.info('twitter adapters added') if Logging::Settings.rpg pool << Thread.new { random_adapter } puts 'random adapter added' Logging::logger.info('random adapter added') pool << Thread.new { random_converter } puts 'random converter added' Logging::logger.info('random converter added') end pool << Thread.new { twitter_converter } puts 'twitter converter added' Logging::logger.info('twitter converter added') if pool.class != NilClass pool.each do |thread| thread.join end end rescue Exception => e Logging::logger.error(e) puts e if pool.class != NilClass pool.each do |thread| Thread.kill(thread) end end end end # Deletes the db keys previously used def cleaning_the_house dao = DAO.new dao.clean end # Starts the WebSocket Server def initialize_websocket_server ws = WebSocketServer.new ws.start end # Starts the Twitter Adapter # # @param stream [Integer] the number of the stream def twitter_adapter stream ta = TwitterAdapter.new ta.connect_stream stream end # Starts the Random Adapter # # @param stream [Integer] the number of the stream def random_adapter stream=1 ra = RandomAdapter.new ra.connect_stream stream end # Starts the Twitter Converter def twitter_converter dao = DAO.new 'twitter' z = 0 while true Logging::logger.info "TWEETS: #{z}" status = dao.get_status while status != nil puts 'Status retrieved' tc = TwitterConverter.new usmf = tc.to_usmf status json = usmf.to_hash.to_json if json != 'null' dao.publish json puts 'Published' z = z + 1 end status = dao.get_status end puts 'All the statuses were been sent' sleep 2 end end # Starts the Random Converter def random_converter dao = DAO.new 'rpg' while true status = dao.get_status puts 'Status retrieved' while status != nil rc = RandomConverter.new usmf = rc.to_usmf status dao.publish usmf.to_hash.to_json puts 'Published' status = dao.get_status end puts 'All the statuses were been sent' sleep 2 end end end
true
7a50c2cd6e115d0d91014a7cb9c76f605e61f107
Ruby
Mstaso/programming-univbasics-2-statement-repetition-with-while-nyc04-seng-ft-060120
/lib/count_down.rb
UTF-8
107
3.140625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Write your code here count=10 while count > 0 do puts count count -= 1 end puts "Happy New Year!"
true
682c09cc8d953d53e8297b9e20ac4a43dd3e62d8
Ruby
ReprodSuplem/RTSS_SUMO
/source_code/sumoutil/sample/2018.1005.Yokohama/RealData/bin/SavsLogEntry.rb
UTF-8
3,073
2.53125
3
[]
no_license
#! /usr/bin/env ruby # coding: utf-8 ## -*- mode: ruby -*- ## = Savs Log Entry class ## Author:: Anonymous3 ## Version:: 0.0 2018/12/23 Anonymous3 ## ## === History ## * [2018/12/23]: Create This File. ## * [YYYY/MM/DD]: add more ## == Usage ## * ... def $LOAD_PATH.addIfNeed(path) self.unshift(path) if(!self.include?(path)) ; end $LOAD_PATH.addIfNeed("~/lib/ruby"); $LOAD_PATH.addIfNeed(File.dirname(__FILE__)); #--====================================================================== #++ ## SavsLog handling class. (dummy) class SavsLogEntry #--@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ #++ ## original info in csv ; attr_accessor :csv ; ## scanned table attr_accessor :table ; #--======================================== #------------------------------------------ #++ ## BusStopTable の設定。 def self.setBusStopTable(_table) @@busStopTable = _table ; end #------------------------------------------ #++ ## 初期化。 def initialize() end #------------------------------------------ #++ ## access to value def getValue(key) return @table[key] ; end #------------------------------------------ #++ ## get pickUp bus stop id. def getPickUpBusStop() stop = @@busStopTable.getStopByName(getValue(:pickUpPoint)) ; if(stop.nil?) then raise "wrong bus stop: #{getValue(:pickUpPoint)}" end return stop ; end #------------------------------------------ #++ ## get dropOff bus stop id. def getDropOffBusStop() stop = @@busStopTable.getStopByName(getValue(:dropOffPoint)) ; if(stop.nil?) then raise "wrong bus stop: #{getValue(:dropOffPoint)}" end return stop ; end #------------------------------------------ #++ ## check valid data. def isValid() return !getValue(:demandId).nil? && getValue(:submitTime) ; end #------------------------------------------ #++ ## CSV row scan. ## def scanCsvRow(_row, _keyList, _colIndex) @csv = _row ; @table = SavsLog.scanCsvRowToTable(_row, _keyList, _colIndex, SavsLog::KeyMap) ; return self ; end #------------------------------------------ #++ ## convert to Json ## def toJson() return @table ; end #------------------------------------------ #++ ## convert to Json Strng ## def toJsonString(prettyP = false) _json = toJson() ; if(prettyP) then return JSON.pretty_generate(_json) ; else return JSON.generate(_json) ; end end #------------------------------------------ #++ ## scan Json Object ## def scanJson(_json) @table = _json.dup ; @table.each{|_key, _value| (_,_type) = *(SavsLog::KeyMap[_key]) ; _v = SavsLog.convertValueByType(_value, _type) ; @table[_key] = _v ; } return self ; end end # class SavLog
true
37d9ef219a31fa0b87499868014833ecdba5f474
Ruby
jamesaanderson/trvlr
/app/models/destination.rb
UTF-8
434
2.65625
3
[]
no_license
class Destination attr_accessor :lat, :lng, :name def initialize(name) @name = name coordinates = Geocoder.coordinates(name) @lat = coordinates.first @lng = coordinates.last end def venues FOURSQUARE_CLIENT.search_venues(near: name).venues end def daily_forecast ForecastIO.forecast(lat, lng).daily.data end def lodging GOOGLE_PLACES_CLIENT.spots(lat, lng, types: 'lodging') end end
true
85d20427013670b643e929a92566f7dd7b51f7d8
Ruby
GlyphGryph/thetitansmarket
/lib/data/wound/all.rb
UTF-8
2,265
2.734375
3
[]
no_license
# Rules for decay targets: # An array of options. Each option will be attempted in turn. # Difficulty determines the odds of failing to achieve this goal. A difficulty of zero or a difficulty not set always suceeds. # If no option succeeds, or an option with no id, the wound decays to nothing. # An option with no message is silent, otherwise the owner of the wound receives the message (if they can). WoundTemplate.load([ { :id => :error_wound, :name => "Mysterious Wound", :description => "This wound is impossible to acquire.", :damage => 0, :decay_targets => [ ], }, { :id => :wound, :name => "Wound", :description => "This is a pretty nasty looking gash.", :damage => 1, :decay_targets => [ { :id => :healed_wound, :message => "Your gash has closed, though it is still tender.", :difficulty => 5, }, { :id => :fresh_scar, :message => "Your gash has begun to heal, but unevenly, and has formed a scar.", :difficulty => 7, }, { :id => :infected_wound, :message => "Your gash has become infected, and hurts like hell.", } ], :hindrance => { :mental => 5, :physical => 15, }, }, { :id => :infected_wound, :name => "Festering Wound", :description => "This wound has become infected.", :damage => 1, :decay_targets => [ { :id => :fresh_scar, :message => "The infection has abated, though it left a jagged and irregular scar.", :difficulty => 7, }, { :id => :infected_wound }, ], :hindrance => { :mental => 15, :physical => 15, }, }, { :id => :healed_wound, :name => "Healing Wound.", :description => "This wound is healing nicely.", :decay_targets => [ ], :hindrance => { :physical => 5, }, }, { :id => :fresh_scar, :name => "Fresh Scar", :description => "Your injury has formed a jagged red scar.", :decay_targets => [ { :id => :scar } ], :hindrance => { :physical => 4, }, }, { :id => :scar, :name => "Scar", :description => "A faded scar from an old wound.", :decay_targets => [ { :id => :scar } ], :hindrance => { :physical => 3, }, } ])
true
5977ccac2fd395a418435b7311245eac3df30783
Ruby
hgodinot/hgodinot-Launch_School
/RB_challenges_new/easy/3.rb
UTF-8
744
4.0625
4
[]
no_license
class RomanNumeral ROMANS = { 0 => ["I", "V", "X"], 1 => ["X", "L", "C"], 2 => ["C", "D", "M"], 3 => ["M"]} def initialize(num) @num = num raise ArgumentError.new "Number must be an integer between 1 and 3000" unless valid? end def to_roman array = @num.digits array.map.with_index { |x, idx| digit_to_roman(x, idx)}.reverse.join end def digit_to_roman(num, index) romans = ROMANS[index] case num when (1..3) then romans[0] * num when 4 then romans[0] + romans[1] when (5..8) then romans[1] + romans[0] * (num - 5) when 9 then romans[0] + romans[2] else "" end end private def valid? @num.class == Integer && ((1..3000).include? @num) end end
true
ce5491e13799543784c41e03f28a5fab527dcecb
Ruby
caj/vindinium
/src/tile_creator.rb
UTF-8
377
2.96875
3
[ "MIT" ]
permissive
class TileCreator class << self def create str, x=0, y=0 case str when /( )/ then OpenTile.new $1, x, y when /(@[1234])/ then OpenTile.new $1, x, y when /(##)/ then WallTile.new $1, x, y when /(\$[\-1234])/ then MineTile.new $1, x, y when /(\[\])/ then TavernTile.new $1, x, y else Tile.new $1, x, y end end end end
true
a1a8d24a22f993345d1cef23f49321c4a72bc260
Ruby
byronanderson/confinder
/bin/fetcher
UTF-8
618
2.8125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'redis' require 'redis-queue' require_relative '../lib/confinder/fetcher' def fetch_queue @fetch_queue ||= Redis::Queue.new('waiting', 'processing', redis: redis) end def output_queue @output_queue ||= Redis::Queue.new('waiting_on_writer', 'processing_in_writer', redis: redis) end def redis @redis ||= Redis.new end def each_person while message = fetch_queue.pop message = JSON.parse(message) yield message fetch_queue.commit end end fetcher = Confinder::Fetcher.new each_person do |person| data = fetcher.fetch(person).to_json output_queue.push data end
true
68bdfa478f885d6bb5f6e7ea66366992e19a557c
Ruby
QPC-WORLDWIDE/tem_ruby
/lib/tem/keys/key.rb
UTF-8
1,486
2.953125
3
[ "MIT" ]
permissive
# Superclass for Ruby implementations of the TEM's key operations. # # Author:: Victor Costan # Copyright:: Copyright (C) 2009 Massachusetts Institute of Technology # License:: MIT # Base class for the TEM keys. # # This class consists of stubs describing the interface implemented by # subclasses. class Tem::Key # The OpenSSL key wrapped by this TEM key. attr_reader :ssl_key # Creates a new key based on an OpenSSL key. def initialize(ssl_key) @ssl_key = ssl_key end # This class should not be instantiated directly. private_class_method :new # Serializes this key to the TEM ABI format. def to_tem_key Tem::Abi.to_tem_key self end # Encrypts a block of data into a TEM-friendly format. def encrypt(data) raise "TEM Key class #{self.class.name} didn't implement encrypt" end def decrypt(data) raise "TEM Key class #{self.class.name} didn't implement decrypt" end def sign(data) raise "TEM Key class #{self.class.name} didn't implement sign" end def verify(data) raise "TEM Key class #{self.class.name} didn't implement verify" end # Creates a new TEM key wrapper from a SSL key def self.new_from_ssl_key(ssl_key) if ssl_key.kind_of? OpenSSL::PKey::PKey Tem::Keys::Asymmetric.new ssl_key elsif ssl_key.kind_of? OpenSSL::Cipher or ssl_key.kind_of? String Tem::Keys::Symmetric.new ssl_key else raise "Can't handle keys of class #{ssl_key.class}" end end end # class Tem::Key
true
05d81e4a4df176de222fac10ebc527551e26ae0c
Ruby
ducktyper/polyglot-fun
/ruby/001_fibonacci_sequence.rb
UTF-8
227
3.375
3
[]
no_license
class Fibonacci def calculate index return index if index == 0 || index == 1 if index < 0 calculate(index + 2) - calculate(index + 1) else calculate(index - 2) + calculate(index - 1) end end end
true
354463590a0521de1d249f88895536f1e4c015af
Ruby
shu0000883/testreport1
/tutorial1/whiletest.rb
UTF-8
35
2.671875
3
[]
no_license
i=0 while i < 10 puts i i += 1 end
true
ec3f43fa729225e5f9ccc46bfad17a659ed5abaf
Ruby
jmichlitsch/war_or_peace
/lib/game.rb
UTF-8
2,475
4
4
[]
no_license
require './lib/card' require './lib/deck' require './lib/player' require './lib/turn' def make_deck shuffled_deck = [] suits = [:diamond, :heart, :spade, :club] #Use to_a() to use all numbers in given range value = (2..14).to_a suits.collect do |suit| value.collect do |num| if num > 1 && num < 11 shuffled_deck << Card.new(suit, "#{num}", num) elsif num == 11 shuffled_deck << Card.new(suit, "Jack", num) elsif num == 12 shuffled_deck << Card.new(suit, "Queen", num) elsif num == 13 shuffled_deck << Card.new(suit, "King", num) elsif num == 14 shuffled_deck << Card.new(suit, "Ace", num) end end end deck = shuffled_deck[0..51] end class Game attr_reader :turn def initialize(turn) @turn = turn end def start_message puts "Welcome to War! (or Peace) This game will be played with 52 cards." puts "The players today are Megan and Aurora." puts "Type 'GO' to start the game!" puts "------------------------------------------------------------------" user_input = gets.chomp if user_input == "GO" start_game else start_message end end def start_game counter =0 while counter <1000000 counter +=1 type = turn.type determine_winner = turn.winner turn.award_spoils_of_war(determine_winner) if turn.player1.has_lost == true || turn.loser == turn.player1.name p "*~*~*~* Aurora has won the game! *~*~*~*" break elsif turn.player2.has_lost == true || turn.loser == turn.player2.name p "*~*~*~* Megan has won the game! *~*~*~*" break end if determine_winner == turn.player1.name && type == :basic p "Turn#{counter}: #{turn.player1.name} has won 2 Cards" elsif determine_winner == turn.player2.name && type == :basic p "Turn#{counter}: #{turn.player2.name} has won 2 Cards" elsif determine_winner == turn.player1.name && type == :war p "Turn#{counter}: WAR - #{turn.player1.name} has won 6 Cards" elsif determine_winner == turn.player2.name && type == :war p "Turn#{counter}: WAR - #{turn.player2.name} has won 6 Cards" else p "Turn#{counter}: *Mutually Assured Destruction* 6 cards removed from play" end if counter == 1000000 return puts "---- DRAW ----" end end end end
true
3b0abb337d3f449565701af348baac213cc42732
Ruby
eduardopoleo/algorithm_1
/week_4/scc_dfs.rb
UTF-8
1,624
3.53125
4
[]
no_license
# Get a stack of vertices ordered by dfs_topological_sort # Reverses the graph # Clear the visited bolean # Pops the elements from the stack and uses the dfs_visit t require 'pry' require_relative './graph' $scc = [] $all_scc = [] $sort = [] class DfsGraph < Graph def dfs_topological_sort vertices.each do |v| if v.unseen? dfs_visit_sort(v) end end $sort.reverse end def mark_all_unseen vertices.each do |v| v.seen = false end end def find_by_id(vertex_id) vertices.find { |v| v.id == vertex_id } end # topological sort def dfs_visit_sort(vertex) vertex.mark_as_seen vertex.edges.each do |e| if e.unseen? dfs_visit_sort(e) end end $sort << vertex.id # The edges do not get added right away, # Only the vertex that is gets end def dfs_visit(vertex) vertex.mark_as_seen # each vetices gets added inmmediately to the path $scc << vertex.id vertex.edges.each do |e| if e.unseen? dfs_visit(e) end end end end graph = DfsGraph.new() graph.add_vertex(1,4) graph.add_vertex(4,7) graph.add_vertex(7,1) graph.add_vertex(9,7) graph.add_vertex(9,3) graph.add_vertex(3,6) graph.add_vertex(6,9) graph.add_vertex(8,6) graph.add_vertex(8,5) graph.add_vertex(5,2) graph.add_vertex(2,8) graph.dfs_topological_sort reverted_graph = DfsGraph.revert(graph) reverted_graph.mark_all_unseen while !$sort.empty? do vertex_id = $sort.pop vertex = reverted_graph.find_by_id(vertex_id) if vertex.unseen? reverted_graph.dfs_visit(vertex) $all_scc << $scc $scc = [] end end p $all_scc
true