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
2647b612c8aa3ecaf8153332006b281d30b3289a
Ruby
NicholasJacques/finer_things_club
/app/models/cart.rb
UTF-8
630
3.109375
3
[]
no_license
class Cart attr_reader :data def initialize(data = {}) @data = data || Hash.new end def items @data.map do |item_id, quantity| item = Item.find(item_id) CartItem.new(item, quantity) end end def add_item(item) data[item.id.to_s] ||= 0 data[item.id.to_s] += 1 end def remove_item(item_id) data.delete(item_id) end def update_quantity(cart_params) data[cart_params[:cart_item_id]] = cart_params[:quantity].to_i end def total return 0 if items.empty? items.inject(0) do |sum, cart_item| sum + (cart_item.quantity * cart_item.price) end end end
true
b39f64ad69d000a39d29587f28bca0547257368f
Ruby
mmevans/the-ultimate-fighter
/bin/train.rb
UTF-8
8,388
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def gotrain puts `clear` prompt = TTY::Prompt.new(active_color: :blue) if $user.weeks_trained == 0 && $user.level == 1 prompt.say("#{$user.trainer_name}: Hey there champ! Looks like you've got your first big fight coming up.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: I've made an easy workout routine you can follow to get you prepared for Chuck Cianwood.") prompt.ok(">> Enter") gets array_of_level_1_workouts = [] Workout.all.each do |workout| if workout.level == 1 array_of_level_1_workouts.push(workout.str_workouts, workout.flex_workouts, workout.end_workouts) end end prompt.say("#{$user.trainer_name}: Here are your workouts - #{array_of_level_1_workouts}") prompt.ok(">> Enter") gets goback = prompt.select("Are you ready to start training?", ["Simulate Training", "Back"]) elsif $user.weeks_trained == 3 && $user.level == 2 prompt.say("#{$user.trainer_name}: Congrats on your first big win! Chuck never had a chance. Ha ha ha!") prompt.ok(">> Enter") gets array_of_level_2_workouts = [] Workout.all.each do |workout| if workout.level == 2 array_of_level_2_workouts.push(workout.str_workouts, workout.flex_workouts, workout.end_workouts) end end prompt.say("#{$user.trainer_name}: I went ahead and changed your workout schedule to prepare you for Brawly. I'll tell you more about him closer to the fight.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: Here are your workouts - #{array_of_level_2_workouts}") prompt.ok(">> Enter") gets goback = prompt.select("Are you ready to start training?", ["Simulate Training", "Back"]) elsif $user.weeks_trained == 6 && $user.level == 3 prompt.say("#{$user.trainer_name}: Hot damn, that's two wins in a row! You're making a name for yourself out there.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: Some people are calling you the next Ultimate Fighter! Don't let it get to your head, you still have a long way to go.") prompt.ok(">> Enter") gets array_of_level_3_workouts = [] Workout.all.each do |workout| if workout.level == 3 array_of_level_3_workouts.push(workout.str_workouts, workout.flex_workouts, workout.end_workouts) end end prompt.say("#{$user.trainer_name}: Your next opponent is Maylene. She's got speed and power in her kicks... unlike you! Ha ha ha!") prompt.ok(">> Enter") gets 4.times do print "." sleep(0.5) end prompt.say("\n#{$user.trainer_name}: Jeez I'm kidding!") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: Here are your workouts - #{array_of_level_3_workouts}") prompt.ok(">> Enter") gets goback = prompt.select("Are you ready to start training?", ["Simulate Training", "Back"]) elsif $user.weeks_trained == 9 && $user.level == 4 prompt.say("#{$user.trainer_name}: Congragulations on you're third win! I'm beginning to think you have a shot at the title, but you need at least 4 wins to challenge the champion.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: You'll need to dedicate a lot more time to training from now on. Your next opponent, Korrina, is an animal in the cage.") prompt.ok(">> Enter") gets array_of_level_4_workouts = [] Workout.all.each do |workout| if workout.level == 4 array_of_level_4_workouts.push(workout.str_workouts, workout.flex_workouts, workout.end_workouts) end end prompt.say("#{$user.trainer_name}: Here are your workouts - #{array_of_level_4_workouts}.") prompt.ok(">> Enter") gets goback = prompt.select("Are you ready to start training?", ["Simulate Training", "Back"]) elsif $user.weeks_trained == 12 && $user.level == 5 prompt.say("#{$user.trainer_name}: Holy shit you fucking madman. The absolute madman! I always knew you had it in you, ever since your first fight with Chuck.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: But this is it.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: No more games...") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: No more cheap tricks...") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: You're fighting the reigning Ultimate Fighter: Mike Tyson. He's the toughest motherfucker to walk into that octagon.") prompt.ok(">> Enter") gets prompt.say("#{$user.trainer_name}: .......") array_of_level_5_workouts = [] Workout.all.each do |workout| if workout.level == 5 array_of_level_5_workouts.push(workout.str_workouts, workout.flex_workouts, workout.end_workouts) end end prompt.say("#{$user.trainer_name}: Here are your workouts - #{array_of_level_5_workouts}.") goback = prompt.select("Are you ready to start training?", ["Simulate Training", "Back"]) else "error" end if goback == "Back" mainmenu else if $user.level == 1 && $user.weeks_trained == 0 progressbar = ProgressBar.create(:title => "Simulate Training Weeks", :starting_at => 0, :total => 100, :progress_mark => "█") 100.times {progressbar.increment; sleep(0.005)} sleep(0.5) puts `clear` prompt.say("#{$user.trainer_name}: You're all set! Wow three weeks just flew by, ha ha ha ha!") $user.weeks_trained += 3 prompt.ok(">> Enter") gets mainmenu elsif $user.level == 2 && $user.weeks_trained == 3 progressbar = ProgressBar.create(:title => "Simulate Training Weeks", :starting_at => 0, :total => 100, :progress_mark => "█") 100.times {progressbar.increment; sleep(0.005)} sleep(0.5) puts `clear` prompt.say("#{$user.trainer_name}: You're all set! Wow three weeks just flew by, ha ha ha ha!") $user.weeks_trained += 3 prompt.ok(">> Enter") gets mainmenu elsif $user.level == 3 && $user.weeks_trained == 6 progressbar = ProgressBar.create(:title => "Simulate Training Weeks", :starting_at => 0, :total => 100, :progress_mark => "█") 100.times {progressbar.increment; sleep(0.005)} sleep(0.5) puts `clear` prompt.say("#{$user.trainer_name}: You're all set! Wow three weeks just flew by, ha ha ha ha!") $user.weeks_trained += 3 prompt.ok(">> Enter") gets mainmenu elsif $user.level == 4 && $user.weeks_trained == 9 progressbar = ProgressBar.create(:title => "Simulate Training Weeks", :starting_at => 0, :total => 100, :progress_mark => "█") 100.times {progressbar.increment; sleep(0.005)} sleep(0.5) puts `clear` prompt.say("#{$user.trainer_name}: You're all set! Wow three weeks just flew by, ha ha ha ha!") $user.weeks_trained += 3 prompt.ok(">> Enter") gets mainmenu elsif $user.level == 5 && $user.weeks_trained == 12 progressbar = ProgressBar.create(:title => "Simulate Training Weeks", :starting_at => 0, :total => 100, :progress_mark => "█") 100.times {progressbar.increment; sleep(0.005)} sleep(0.5) puts `clear` prompt.say("#{$user.trainer_name}: You're all set! Wow three weeks just flew by, ha ha ha ha!") $user.weeks_trained += 3 prompt.ok(">> Enter") gets mainmenu else puts "Hey it looks like you've already done your training! Head over to the airport and catch your flight!" prompt.ok(">> Enter") gets mainmenu end end end
true
e4f38fb3706d0ed7877445f5424f09c623176cc6
Ruby
Intetaget/Homework
/smartguesser/oo_guesser.rb
UTF-8
895
4
4
[]
no_license
require "./human" require "./random" require "./counting" require "./smart1" require 'pry' class GuessingGame def initialize(player) @player = player end def play number = rand(1..100) result = nil guess = @player.get_guess(result) count = 1 #binding.pry until guess == number if guess > number puts "Too High!" result = :high #Fails right here!!! else puts "Too Low!" result = :low end guess = @player.get_guess(result) count += 1 end puts "You win! Took #{count} tries. The number was #{number}." end end # game1 = GuessingGame.new(CountingPlayer.new) # game2 = GuessingGame.new(RandomPlayer.new) # game3 = GuessingGame.new(RandomPlayer.new) # game4 = GuessingGame.new(HumanPlayer.new) game5 = GuessingGame.new(SmartPlayer.new) #game1.play game5.play #puts "just screwing around"
true
0059fa758fdbb73ad03e05c1cb242570f6a50951
Ruby
simonbalean/deli-counter-ruby-apply-000
/test.rb
UTF-8
557
3.1875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
test1 = ["1a", "1A"] test2 = ["2b", "2B"] test3 = ["3c", "3C"] test4 = ["4d", "4D"] test_total = [test1, test2, test3, test4] # => [["1a", "1A"], ["2b", "2B"], ["3c", "3C"], ["4d", "4D"]] test_number = 7 test_number1 = (1..test_number).to_a # => [1, 2, 3, 4, 5, 6, 7] test_letters = ["A", "B", "C", "D"] test_numbers = [1, 2, 3, 4] test_cool = test_letters*"#{test_numbers}" # => "A[1, 2, 3, 4]B[1, 2, 3, 4]C[1, 2, 3, 4]D" test_letters[0] test_letters[1] test_letters[2] test_letters[3] var1 = (1..1).to_a test_letters[var1.join.to_i]
true
bf88b3dce2c9adc7041f3446a93e7907ab466b33
Ruby
davidrichards/cradle
/lib/basic_repository/basic_repository.rb
UTF-8
895
2.59375
3
[ "MIT" ]
permissive
require 'database_boundary' require 'find_entity_by_id' require 'save_entity' require 'filter_entities' require 'save_database' require 'load_database' module Cradle class BasicRepository < DatabaseBoundary def self.stored_entities @stored_entities ||= {} end def self.overwrite_stored_entities!(value) @stored_entities = value end def find_by_id(id) interactor = FindEntityById.new(id) interactor.execute! end def save(entity) interactor = SaveEntity.new(entity) interactor.execute! end def filter(query) interactor = FilterEntities.new(query) interactor.execute! end def backup_database(*args) interactor = SaveDatabase.new(*args) interactor.execute! end def restore_database(*args) interactor = LoadDatabase.new(*args) interactor.execute! end end end
true
db3e921ce6aebe2d066d5b3bce244029459524d4
Ruby
rvedotrc/sqs-list-queues
/bin/sqs-list-queues
UTF-8
1,558
2.734375
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby require 'optparse' require 'sqs-list-queues' config = SqsListQueues::Config.new opts_parser = OptionParser.new do |opts| opts.banner = "Usage: sqs-list-queues [OPTIONS] [PATTERN ...]" opts.separator "" opts.on("-c", "--counts", "Show message counts") do config.show_counts = true end opts.on("-a", "--arn", "Show queue ARN") do config.show_arn = true end opts.on("-u", "--url", "Show queue URL") do config.show_url = true end opts.on("-j", "--json", "Show output in json format") do config.json_format = true end opts.separator "" opts.separator <<-EOF Lists SQS queues (either all queues, or if at least one PATTERN is given, those queues whose names match at least one PATTERN, implicitly prefixed by "^"). One line is printed to standard output for each queue. If --counts is shown, prefix by the message counts (visible, not visible, and delayed, in that order); then show the queue name, or ARN, or URL. If JSON format is selected, the queue name is always shown, and the ARN and URL can both be selected if desired. Examples: # List all queue names sqs-list-queues # List queues whose names start with either "Foo" or "Bar", showing queue # URLs not names: sqs-list-queues --url Foo Bar # List queues whose names start with "MyQueues", showing message counts: sqs-list-queues --counts MyQueues EOF end opts_parser.parse! unless ARGV.empty? config.patterns = ARGV end config.validate rc = SqsListQueues::Runner.new(config).run exit rc # eof sqs-list-queues
true
078ce514ef0b41f3650f3187bc16965dc52abc2b
Ruby
modulexcite/p2pwebclient
/src/lib/safe_write.rb
UTF-8
1,458
2.703125
3
[ "MIT" ]
permissive
require 'fileutils' class File if RUBY_PLATFORM =~ /mingw|mswin/ FileUtils.touch 'temp_file' @@loc = 'temp_file' else @@loc = '/dev/random' end @@saver_file = File.new @@loc, 'r' def self.append_to to_this_file, data begin to_this = File.new to_this_file, 'a+' size = to_this.write data to_this.close raise 'bad'unless size == data.length return size rescue => e print "EMERGENCY WRITE to #{to_this_file} #{e}\n" begin @@saver_file.close to_this = File.new to_this_file, 'a+' length = to_this.write data to_this.close raise 'bad' unless length == data.length return length rescue => e print "FATAL FAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIL"*10 + e.to_s raise ensure @@saver_file = File.new @@loc, 'r' end end end def self.read_from this_file, length = nil, offset = nil begin out = File.read this_file, length, offset raise 'bad' unless out.length == length if length out rescue => e print "EMERGENCY READ\n" begin @@saver_file.close length = File.read this_file, length, offset raise 'bad' unless length == length if length return length rescue => e print "222222FAIIIIILLLLLL #{e}"*10 raise ensure @@saver_file = File.new '/dev/random', 'r' end end end end
true
f9828e0d01e9eb98c02c9c4a147252c7916f6ff1
Ruby
vdk88/seek
/lib/seek/bio_schema/bio_schema.rb
UTF-8
1,713
2.71875
3
[ "JSON", "BSD-3-Clause" ]
permissive
module Seek module BioSchema # Main entry point for generating Schema.org JSON-LD for a given resource. # # Example: Seek::BioSchema::BioSchema.new(Person.find(id)).json_ld class BioSchema include ActionView::Helpers::SanitizeHelper attr_reader :resource # initialise with a resource def initialize(resource) @resource = resource end # returns the JSON-LD as a String, for the resource def json_ld unless supported? raise UnsupportedTypeException, "Bioschema not supported for #{resource.class.name}" end json = {} json['@context'] = resource_decorator.context json['@type'] = resource_decorator.schema_type json.merge!(attributes_from_csv_mappings) JSON.pretty_generate(json) end # whether the resource BioSchema was initialized with is supported def supported? BioSchema.supported?(resource) end # test directly (without intializing) whether a resource is supported def self.supported?(resource) SUPPORTED_TYPES.include?(resource.class) end private SUPPORTED_TYPES = [Person, Project].freeze def resource_decorator @decorator ||= ResourceDecorators::Factory.instance.get(resource) end def attributes_from_csv_mappings result = {} CSVReader.instance.each_row do |row| next unless row.matches?(resource) if (value = row.invoke(resource_decorator)) result[row.property.strip] = value end end result end def process_mapping(method) resource.try(method) end end end end
true
bd235a72aba271c5c101429b882d7f0e955a9175
Ruby
arakawamoriyuki/tensorflow_learn
/workspace/coursera/ruby/standard_deviation.rb
UTF-8
544
3.328125
3
[]
no_license
# 標準偏差の計算 require 'complex' avg = 60 player_length = 10 a_points = [0,5,10,70,80,80,82,85,93,95] b_points = [50,52,54,60,60,60,61,61,70,72] tests = {a: a_points, b: b_points} tests.each do |type, points| points.unshift(result = 0) # 分散値の計算 dispersion = points.reduce do |result, point| result += ((point - avg) ** 2) * 1.0 # *1.0 = cast float end dispersion /= player_length puts "#{type} #{dispersion}" # 標準偏差の計算 deviation = Math.sqrt(dispersion) puts "#{type} #{deviation}" end
true
29db94bf18fe6bb60ccbd9cfc0a6acaec77c76f2
Ruby
thrigby/funshine
/my_game.rb
UTF-8
1,234
3.3125
3
[]
no_license
require 'rubygems' require 'gosu' require_relative 'player' require_relative 'ball' class MyGame < Gosu::Window def initialize super(400, 400, false) #false means don't take up the whole screen @player1 = Player.new(self, 50) @balls = 2.times.map {Ball.new(self)} @bg_image = Gosu::Image.new(self, "images/white.png", true) @running = true end def update if @running if button_down? Gosu::Button::KbLeft @player1.move_left end if button_down? Gosu::Button::KbRight @player1.move_right end if button_down? Gosu::Button::KbUp @player1.move_up end if button_down? Gosu::Button::KbDown @player1.move_down end @balls.each {|ball| ball.update} if @player1.hit_by? @balls # stop_game! end else #the game is currently stopped if button_down? Gosu::Button::KbEscape restart_game end end end def draw @bg_image.draw(0, 0, 0) @balls.each { |ball| ball.draw } @player1.draw end def stop_game! @running = false end def restart_game @running = true @balls.each { |ball| ball.reset! } end end window = MyGame.new window.show
true
d86f5fee9f5e41ee070296ad6a338c61c1738bf9
Ruby
michaeltelford/ruby_graphql_api
/src/graph_handler.rb
UTF-8
1,729
2.828125
3
[ "MIT" ]
permissive
require "rack" require "graphql" # required here and not in the graphql dir *.rb files. require_relative "helpers" require_relative "graphql/schema" # Class providing handlers for the GraphQL engine. class GraphHandler include Rack::Utils # /graphql endpoint http handler. # The query and variables come from the URL or the body; # once retrieved, they are passed to a generic handler for validation and # then given to the graphql engine for processing. def call(env) begin case env["REQUEST_METHOD"] when "GET" query_params = parse_nested_query env.fetch('QUERY_STRING', {}) query = query_params.fetch 'query', '' variables = query_params.fetch 'variables', {} handler query, variables when "POST" payload = env.fetch 'request.payload', {} query = payload.fetch 'query', '' variables = payload.fetch 'variables', {} handler query, variables else respond 405, body: "Method not allowed" end rescue => ex Log.error "#{ex.class} - #{ex.message}" respond 500, body: "Internal server error" end end private # Generic handler which returns the graphql server response. def handler(query, variables) return respond 400, body: "Missing query" if query.empty? response = exec_schema query, variables respond 200, headers: CONTENT_TYPE_JSON, body: response.to_h end # Query the graphql schema and return the GraphQL::Query::Result. def exec_schema(query, variables) Schema.execute(query) end end
true
77600fd2d9bfa53101e249f842de3d51e73633d9
Ruby
fdumontmd/books-code
/7languages7weeks/ruby/guess.rb
UTF-8
228
3.59375
4
[]
no_license
def play() target = rand(10) guess = -1 while target != guess puts 'Guess a number' guess = gets().to_i puts 'too high' if target < guess puts 'too low' if target > guess end puts 'got it' end play()
true
5e63f8d50558f3842c4cc253fee212d4eb4de611
Ruby
ayush268/certification
/certification_app/app/helpers/courses_helper.rb
UTF-8
470
2.640625
3
[]
no_license
module CoursesHelper def course_status(course) # Periods are assumed in hours registration_period = 1 course_period = registration_period + 1 hours_elapsed = (DateTime.now.to_i - course.accepted_time.to_i) / 60 case true when hours_elapsed < registration_period return "Registration Period" when hours_elapsed < course_period return "Course Ongoing" else return "Course Completed" end end end
true
d974280e9895dcaa73c7a8b58b33855eb1700238
Ruby
RJ-Ponder/RB101
/exercises/easy_5/08alpha.rb
UTF-8
757
3.71875
4
[]
no_license
WORD_NUMBERS = { "zero" => 0, "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "eleven" => 11, "twelve" => 12, "thirteen" => 13, "fourteen" => 14, "fifteen" => 15, "sixteen" => 16, "seventeen" => 17, "eighteen" => 18, "nineteen" => 19 } def alphabetic_number_sort(array) alpha_words = WORD_NUMBERS.keys.sort alpha_numbers = [] alpha_words.each do |word| alpha_numbers << WORD_NUMBERS[word] end alpha_numbers end p alphabetic_number_sort((0..19).to_a) #== [8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17, 6, 16, 10, 13, 3, 12, 2, 0]
true
44d6464f2e583eb3f7f524e88065f042cdac8ac3
Ruby
dmdinh22/Lesson1
/rps.rb
UTF-8
1,276
4.15625
4
[]
no_license
# Pseudo Code (LOGIC) # 1. all players pick either rock, paper, or scissors # 2. compare: paper > rock, rock > scissors, scissors > paper, or tie if same # 3. play again? ACTIONS = { 'r' => 'rock', 'p' => 'paper', 's' => 'scissors' } def winning_message(action) case action when 'r' puts "Rock smashes scissors." when 'p' puts "Paper suffocates rock." when 's' puts "Scissors snips paper." end end loop do begin puts "Choose 'r' for rocks, 'p' for paper, or 's' for scissors." player_action = gets.chomp.downcase end until ACTIONS.keys.include?(player_action) computer_action = ACTIONS.keys.sample if player_action == computer_action puts "It's a tie!" elsif player_action == 'r' && computer_action == 's' winning_message(player_action) puts "You won!" elsif player_action == 'p' && computer_action == 'r' winning_message(player_action) puts "You won!" elsif player_action == 's' && computer_action == 'p' winning_message(player_action) puts "You won!" else winning_message(computer_action) puts "Computer beat you!" end puts "Would you like to keep playing? (y/n)" break if gets.chomp.downcase != 'y' end puts "Thanks for playing Rock, Paper, Scissors. Have a great day!"
true
4225ccd2c9c49f2b18b2fca88da2a1b85d0d28bc
Ruby
gentilfp/oxford_learners_dictionaries
/lib/oxford_learners_dictionaries/definition.rb
UTF-8
724
2.796875
3
[ "MIT" ]
permissive
require 'nokogiri' module OxfordLearnersDictionaries class Definition attr_reader :text, :examples def initialize page @page = page @examples = Array.new end def parse_single_definition text = @page.css('.def') @text = text.count > 0 ? text[0].text : text.text @examples.push(::OxfordLearnersDictionaries::Example.new(@page.css('.x-g'))) self end def parse_multiple_definitions index @text = @page.css('.def')[index].text return self if @page.css('.x-gs')[index].nil? @page.css('.x-gs')[index].css('.x-g').each do |example| @examples.push(::OxfordLearnersDictionaries::Example.new(example)) end self end end end
true
c853c681a17dbc84306f7d19ec6304dc7f46ea02
Ruby
orestiss/maze_challenge
/path_finding/spec/grid_spec.rb
UTF-8
821
2.796875
3
[ "MIT" ]
permissive
require "spec_helper" describe Grid do context "load grid from file" do let(:grid) do builder = GridBuilder.new grid = builder.get_grid_from_file('./spec/data/maze1.txt') end it "returns the correct neighbors" do expect(grid.is_a? Grid).to eq true neighbors = grid.get_neighbors(Vector[1,1]) expect(neighbors).to include(Vector[1, 2]) expect(neighbors).to include(Vector[2, 1]) expect(neighbors).not_to include(Vector[0, 1]) expect(neighbors).not_to include(Vector[1, 0]) end it "checks if goal is in position" do expect(grid.is_goal?(Vector[3,4])).to eq true expect(grid.is_goal?(Vector[5,5])).to eq false end it "raises an out of bounds exception" do expect {grid.get_neighbors(Vector[15, 15]) }.to raise_error(OutOfBoundsError) end end end
true
7b45b4c6b047820f9bbc09cf9a1fadf24b1aeed8
Ruby
GalaxyAstronaut/ruby-object-attributes-lab-onl01-seng-ft-012120
/lib/person.rb
UTF-8
225
2.6875
3
[]
no_license
class Person # name getter and setter methods def name=(name) @name = name end def name @name end # job getter and setter methods def job=(job) @job = job end def job @job end end
true
c1991710368732273357e27c16bd20850d61afbf
Ruby
SawaiTakahiro/sawaiTest
/twitter/convert_tweet.rb
UTF-8
1,593
3.125
3
[]
no_license
#! ruby -Ku =begin 2016/04/16 twitterのAPI使って見るテスト 「取得→csv保存したやつ」を読み込んで加工するところまで。 =end ########################################################################################## #共通の部分 require "Twitter" require "./library.rb" require "sqlite3" include SQLite3 TABLE_NAME = "arcive" #つぶやきを、見出しとアドレスに分けられたら分ける def text_split(text) matchdata = text.match(/(.*.)(http.*.)/) #分けられなそうなデータはそのまま #アドレスを空で戻している if matchdata == nil title = text address = "" else title = matchdata[1] address = matchdata[2] end return [title, address] end #実際の処理 list_tweet = read_csv("./output.csv") db = SQLite3::Database.new("./arcive.db") #ファイルなかったら作られるから平気 db.execute("create table if not exists #{TABLE_NAME}(id primary key, date, title, address, flag);") #初期化用クエリ db.transaction do list_tweet.each do |tweet| id = tweet[0] date = tweet[1] #つぶやきの内容は、分けられたら分ける data = text_split(tweet[2]) title = data[0].gsub(/'|’/, "’") #半角'を全角にエスケープしとく #なんかブログ名とかで'とか`とか使われていると取り込めないので注意。とりあえず適当な文字に置き換えている address = data[1] query = "insert or ignore into #{TABLE_NAME} values('#{id}', '#{date}', '#{title}', '#{address}', 'false')" db.execute(query) end end
true
bd5f5f839c299d0daa035c4ec16a04b6f62cebf5
Ruby
pankajbarhate13/food_ordering_system
/db/seeds.rb
UTF-8
713
3.078125
3
[]
no_license
require 'csv' class Seeder def initialize create_item create_categories end def create_item contents = CSV.open "./db/db_seed.csv", headers: true, header_converters: :symbol contents.each do |row| name = row[:name] description = row[:description] price = row[:price] category_id = row[:category_id] item = Item.create(category_id: category_id, name: name, description: description, price: price) end end def create_categories categories_names.each do |category_name| Category.create(name: category_name) end end def categories_names ['Sandwiches', 'Beverages', 'Sides', 'Baked Goods'] end end Seeder.new
true
19c2f352954663446e9edc7ce8d98b43771cf6c0
Ruby
UwanaIkaiddiSonos/my-actualize-repo
/http_requests/dictionary_app.rb
UTF-8
545
2.796875
3
[]
no_license
require 'http' key = "" puts "Enter a word:" user_word = gets.chomp response = HTTP.get("https://api.wordnik.com/v4/word.json/#{user_word}/definitions?limit=200&includeRelated=false&useCanonical=false&includeTags=false&api_key=#{key}") define = response.parse definition = response.parse[0]["text"] # #puts response.parse.class # #p response.parse # puts "Definition: #{definition}" i = 0 puts "Top definition:" puts define[0] define.length.times do puts "Other definitions" puts "Definition #{i + 1}" p define[i]["text"] i += 1 end
true
69607ddb3880f47bf8b3969c038d9c38623fa659
Ruby
mateuszstacel/Birthday_web
/app.rb
UTF-8
832
2.5625
3
[]
no_license
require 'sinatra/base' require 'date' require_relative './lib/datee.rb' class Birthday < Sinatra::Base enable :sessions get '/' do erb :index end post '/details' do $name = params[:user_name] @birth_day = params[:birth_day] @birth_month_year = params[:birth_month_year] $full_date = @birth_month_year << "-" << @birth_day redirect '/test' end get '/test' do check = Datee.new month = check.found_month($full_date) days_number = check.days_check(month) a_date = Date.parse(Date.today.to_s) b_date = Date.parse($full_date.to_s) $days_to_birthday = (b_date-a_date).to_i if @birth_day.to_i > days_number.to_ erb :error elsif $full_date.to_s == Date.today.to_s erb :birthday else erb :days_to_birthday end end run! if app_file == $0 end
true
93ae354b126a07cf8418b094ed248cffdfb13a70
Ruby
darren2802/battleship_project
/lib/cell.rb
UTF-8
761
3.125
3
[]
no_license
require_relative './ship' class Cell attr_reader :coordinate, :ship def initialize(coordinate) @coordinate = coordinate @ship = nil @cell_has_been_fired_upon = false end def empty? !@ship end def place_ship(ship) @ship = ship end def fire_upon @ship.hit if !empty? && !@cell_has_been_fired_upon @cell_has_been_fired_upon = true end def fired_upon? @cell_has_been_fired_upon end def render(should_reveal=false) if !empty? && should_reveal return "H" if fired_upon? && [email protected]? return "X" if @ship.sunk? end return "S" if should_reveal && !empty? return "." if !fired_upon? return "M" if empty? if @ship.sunk? "X" else "H" end end end
true
e4b7ceb4c9aaef88705b34cb2e05703f0ff2e606
Ruby
yosuke-yagishita/ruby_study
/C024:ミニ・コンピュータ.rb
UTF-8
347
3.390625
3
[]
no_license
a = 0 b = 0 count = gets.to_i count.times do |c| order, i, num = gets.split(" ").map(&:to_s) if (order == "SET") && (i == "1") a = num.to_i elsif (order == "SET") && (i == "2") b = num.to_i elsif (order == "ADD") b = a + i.to_i elsif (order == "SUB") b = a - i.to_i end end puts "#{a} #{b}"
true
a221eb7d6e4ea763a7282df972735d283357041d
Ruby
Genessis/CI3725-Lanscii
/Entrega3/ruleClasses.rb
UTF-8
5,197
3.109375
3
[]
no_license
#!/usr/bin/env ruby =begin * UNIVERSIDAD SIMÓN BOLÍVAR * Archivo: ruleClasses.rb * * Contenido: * Clases para imprimir el AST de LANSCII * * Creado por: * Genessis Sanchez 11-10935 * Daniela Socas 11-10979 * * Último midificación: 13 de junio de 2015 =end ##################################### # Clases asociadas a instrucciones. # ##################################### class S # Donde scope es de la clase Scope. attr_accessor :scope def initialize(scope) @scope = scope end def printAST(lvl) @scope.printAST(0) end end class Scope # Donde inst es de la clase Instr attr_accessor :inst attr_accessor :decl def initialize(inst, decl = nil) @inst = inst @decl = decl end def printAST(lvl) @inst.printAST(lvl) end end class Decl # Donde type es de la clase Type, listI es de la clase ListI y # decl es de la clase Decl attr_accessor :type attr_accessor :listI attr_accessor :decl def initialize(type, listI, decl = nil) @type = type @listI = listI @decl = decl end end class ListI # Donde id es de la clase Terms (:IDENTIFIER) y listI es de la clase ListI attr_accessor :id attr_accessor :listI def initialize(id, listI = nil) @id = id @listI = listI end end class Instr attr_accessor :opID attr_accessor :branches # Donde nameinst1 puede ser :INSTR, :READ, :WRITE, :ASSIGN, :COND, :IND_LOOP, # => :DET_LOOP o :S y nameinst2 tiene que ser :INSTR. def initialize(nameinst1, inst1, nameinst2 = nil, inst2 = nil) @opID = [nameinst1, nameinst2] @branches = [inst1, inst2] end def printAST(lvl) @branches.each do |branch| if branch != nil if @opID[0] == :INSTR branch.printAST(lvl) else for i in 1..lvl print "| " end puts "#{@opID[0]}: " branch.printAST(lvl+1) end end end end end class Assign attr_accessor :types attr_accessor :branches def initialize(type1, var, type2, expr) @types = [type1, type2] # Donde type1 es :VARIABLE y type2 es :EXPRESSION @branches = [var, expr] # Donde var es clase Term y expr es clase Expr end def printAST(lvl) # Escribirá el nombre de cada operación y llamará a los prints de las clases # => involucradas for i in 0..1 for j in 1..lvl print "| " end puts "#{@types[i]}:" @branches[i].printAST(lvl+1) end end end class Cond attr_accessor :types attr_accessor :elems # Donde type1 es :CONDITION, type2 es :THEN y type3 puede ser :ELSE # Donde expr es de la clase Expr, inst1 e inst2 son de la clase Instr. def initialize(type1, expr, type2, inst1, type3=nil, inst2=nil) @types = [type1, type2, type3] @elems = [expr, inst1, inst2] end def printAST(lvl) for i in 0..2 if @types[i] != nil for j in 1..lvl print "| " end puts "#{@types[i]}:" @elems[i].printAST(lvl+1) end end end end class ILoop attr_accessor :types attr_accessor :elems # Donde type1 es :WHILE y type2 es :DO # Donde expr es de la clase Expr e inst es de la clase Instr def initialize(type1, expr, type2, inst) @types = [type1, type2] @elems = [expr, inst] end def printAST(lvl) for i in 0..1 for j in 1..lvl print "| " end puts "#{@types[i]}:" @elems[i].printAST(lvl+1) end end end class DLoop attr_accessor :types attr_accessor :elems # Donde type1 es :VARIABLE, type2 y type3 son :EXPRESSION y type4 es :INSTR # Donde var es de la clase Var, expr1 y expr2 son de la clase Expr e # => inst es de la clase Instr def initialize(type1, var, type2, expr1, type3, expr2, type4=nil, inst=nil) @types = [type1, type2, type3, type4] @elems = [var, expr1, expr2, inst] end def printAST(lvl) for i in 0..3 if (@elems[i] != nil) for j in 1..lvl print "| " end puts "#{@types[i]}:" @elems[i].printAST(lvl+1) end end end end ################################### # Clases asociadas a expresiones. # ################################### class BinExp attr_accessor :elems attr_accessor :op # Donde type0 es :OPERATION, op puede ser +, -, *, /, %, ~, \/, /\, <, <=, # >, >=, =, ' o &, type1 y type2 son :EXPRESSION y expr1 y expr2 son expresiones def initialize(op, expr1, expr2) @elems = [expr1, expr2] @op = op end def printAST(lvl) for i in 1..lvl print "| " end puts "OPERATION: #{@op}" @elems.each do |elem| elem.printAST(lvl+1) end end end class UnaExp attr_accessor :elem attr_accessor :op def initialize(op, expr) @elem = expr @op = op end def printAST(lvl) for i in 1..lvl print "| " end puts "OPERATION: #{@op}" @elem.printAST(lvl+1) end end # Donde type es :EXPRESSION y expr es una expresion cualquiera class ParExp attr_accessor :type attr_accessor :expr def initialize(type, expr) @type = type @expr = expr end def printAST(lvl) for i in 1..lvl print "| " end puts "#{@type}" @expr.printAST(lvl+1) end end class Terms attr_accessor :nameTerm attr_accessor :term def initialize(nameTerm, term) @nameTerm = nameTerm @term = term end def printAST(lvl) for i in 1..lvl print "| " end case @nameTerm when :IDENTIFIER, :CANVAS, :NUMBER, :TRUE, :FALSE puts "#{@nameTerm}: #{@term}" end end end
true
faec46ab8c3d17fb11571668abd979a700afe759
Ruby
aaroncallagher/ls_101_programming_foundations
/lesson_3/medium_1/question_7.rb
UTF-8
810
4.3125
4
[]
no_license
# limit = 15 # def fib(first_num, second_num) # while second_num < limit # sum = first_num + second_num # first_num = second_num # second_num = sum # end # sum # end # result = fib(0, 1) # puts "result is #{result}" # The problem here is that method definitions do not have access to outside # local variables. They create their own, insular scope. The way to fix this # would be to either add limit as a parameter and pass in 15 in the method call # or to declare the variable inside the scope of the method. For flexibility # purposes, I will add limit as a parameter. def fib(first_num, second_num, limit) while second_num < limit sum = first_num + second_num first_num = second_num second_num = sum end sum end result = fib(0, 1, 15) puts "result is #{result}"
true
80d09b0e37773a82dcf94cbef5bfee6b6f9ca1d1
Ruby
fujisawaryohei/bookshelf
/spec/bookshelf/entities/book_spec.rb
UTF-8
348
2.53125
3
[]
no_license
RSpec.describe Book, type: :entity do it 'can be initialized with attrubutes' do book = Book.new(title: 'Refactoring') expect(book.title). to eq('Refactoring') end it 'add tax to unitPrice' do book = Book.new(title: 'Confident Ruby', author: 'Avdi Grimm', unit_price: 2500) expect(book.total_price).to eq 2500 * 1.08 end end
true
a9a321a249aab26fa4bf0a4db6063c943ae765b7
Ruby
GeoffWilliams/puppetizer
/lib/puppetizer/authenticator.rb
UTF-8
3,537
2.890625
3
[ "Apache-2.0", "MIT" ]
permissive
require 'csv' require 'puppetizer' require 'puppetizer/puppetizer_error' require 'puppetizer/authenticator' module Puppetizer class Authenticator def initialize(password_file, global_username=false) @password_file = password_file if @password_file read_password_file(@password_file) else @passwords = false if global_username @global_username = global_username else @global_username = 'root' end if ENV.has_key? 'PUPPETIZER_USER_PASSWORD' @user_password = ENV['PUPPETIZER_USER_PASSWORD'] else @user_password = false end if ENV.has_key? 'PUPPETIZER_ROOT_PASSWORD' @root_password = ENV['PUPPETIZER_ROOT_PASSWORD'] else @root_password = false end end end def read_password_file(password_file) if File.exists? password_file @passwords = {} # thanks! http://technicalpickles.com/posts/parsing-csv-with-ruby/ body = File.open(password_file) csv = CSV.new(body, :headers => true, :header_converters => :symbol, :converters => :all) # read each line of CVS and magic it into a hash. Use the hostname # field as its key in @passwords and remove this key from the data csv.to_a.map { |row| d = row.to_hash hostname = d.delete(:hostname) @passwords[hostname] = d } else raise PuppetizerError, "File not found: #{password_file}" end end # lookup how (if at all) we should swap users for this host and return # 2 strings - one to use before running a command and one to run # after, eg: "su root -c'" and "'" # a label describing the swap method def swap_user(hostname) # if non-root, use sudo if @passwords ssh_username = read_password_value(hostname, :username) root_password_set = !! read_password_value(hostname, :password_root, false) else ssh_username = @global_username root_password_set = !! @root_password end if ssh_username == "root" user_start = '' user_end = '' type = :none elsif root_password_set # solaris/aix require the -u argument, also compatible with linux user_start = 'su root -c \'' user_end = '\'' type = :su else user_start = 'sudo' user_end = '' type = :sudo end return user_start, user_end, type end def read_password_value(hostname, key, fatal=true) if @passwords.has_key?(hostname) if @passwords[hostname].has_key?(key) @passwords[hostname][key] else if fatal raise PuppetizerError, "#{hostname} missing #{key} in #{@password_file}" end end else raise PuppetizerError, "#{hostname} missing from #{@password_file}" end end def username(hostname) if @passwords read_password_value(hostname, :username) else @global_username end end def user_password(hostname) if @passwords read_password_value(hostname, :password_user) else @user_password end end def root_password(hostname) if @passwords read_password_value(hostname, :password_root) else @root_password end end def pty_required(hostname) return username(hostname) != 'root' end end end
true
ddcdaaa2615e9988262d88b3545a3233c1c7806c
Ruby
Rajanpandey/Coding-Practice
/CodeSignal/Arcade/Intro/1. The Journey Begins/3. checkPalindrome.rb
UTF-8
76
2.796875
3
[]
no_license
def checkPalindrome(inputString) inputString == inputString.reverse end
true
395d2123a87ebdbf8ee44901f602f890cfceecc0
Ruby
bschrag620/oo-student-scraper-v-000
/lib/scraper.rb
UTF-8
1,214
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'pry' require 'nokogiri' class Scraper def self.scrape_index_page(index_url) html = File.open(index_url) doc = Nokogiri::HTML(html) doc.css(".main-wrapper.roster .student-card").collect do |student_card| name = student_card.css("h4").text location = student_card.css(".student-location").text profile_url = student_card.css("a").attribute("href").value {name: name, location: location, profile_url: profile_url} end end def self.scrape_profile_page(profile_url) html = File.open(profile_url) doc = Nokogiri::HTML(html) values = {} doc.css(".vitals-container a").each do |link_data| link = link_data.attribute('href').value if link.include?('twitter') key = :twitter elsif link.include?('facebook') key = :facebook elsif link.include?('linkedin') key = :linkedin elsif link.include?('github') key = :github else key = :blog end values[key] = link end values[:profile_quote] = doc.css(".vitals-text-container .profile-quote").text values[:bio] = doc.css(".details-container .description-holder p").text values end end
true
be9ed731e810039b7c8a0b474b7076a4275cd3bc
Ruby
dissonanz/knife-data-bag-stack
/spec/stack_spec.rb
UTF-8
3,436
2.671875
3
[]
no_license
# # Author: Sean Nolen (<[email protected]>) # Copyright: (c) 2012 Sean Nolen # License: Apache License, Version 2.0 # require 'chef' require 'chef/mixin/stack' include Chef::Mixin::Stack describe Chef::Mixin::Stack do before(:each) do @data_bag_item = Chef::DataBagItem.new @data_bag_item.data_bag("smegheads") @data_bag_item.raw_data = {"id" => "Lister", "name" => "Lister"} @rest = mock("Chef::REST") Chef::REST.stub!(:new).and_return(@rest) end describe "when there is an error" do it "tries to load specified data bags" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) data_bag_stack({"smegheads" => ["Lister"]}) end it "returns error when no input is given" do lambda { data_bag_stack(Hash.new) }.should raise_error ArgumentError end it "returns error when input is not a hash" do [String, Array, Mash].each do |input| lambda { data_bag_stack(input.new) }.should raise_error ArgumentError end end end describe "when one data bag" do describe "when one item" do it "returns the same data bag item when only one is given as string" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) data_bag_stack({"smegheads" => "Lister"})["name"].should == "Lister" end it "returns the same data bag item when only one is given as array" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) data_bag_stack({"smegheads" => ["Lister"]})["name"].should == "Lister" end end #one-item describe "when two or more items" do before do @data_bag_item2 = Chef::DataBagItem.new @data_bag_item2.data_bag("smegheads") @data_bag_item2.raw_data = {"id" => "Rimmer", "name" => "Rimmer"} end it "returns the merged data bag item when two are given" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) @rest.should_receive(:get_rest).with("data/smegheads/Rimmer").and_return(@data_bag_item2.to_hash) data_bag_stack({"smegheads" => ["Lister","Rimmer"]})["name"].should == "Rimmer" end end #two-or-more-items end #one-bag describe "when multiple data bags" do before do @data_bag_item3 = Chef::DataBagItem.new @data_bag_item3.data_bag("computers") @data_bag_item3.raw_data = {"id" => "Holly", "name" => "Holly", "IQ" => 6000} end it "returns the merged data bag item when two are given and second is string" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) @rest.should_receive(:get_rest).with("data/computers/Holly").and_return(@data_bag_item3.to_hash) data_bag_stack({"smegheads" => ["Lister"], "computers" => "Holly"})["name"].should == "Holly" end it "returns the merged data bag item when two are given and second is array" do @rest.should_receive(:get_rest).with("data/smegheads/Lister").and_return(@data_bag_item.to_hash) @rest.should_receive(:get_rest).with("data/computers/Holly").and_return(@data_bag_item3.to_hash) out = data_bag_stack({"smegheads" => ["Lister"], "computers" => ["Holly"] }) out["name"].should == "Holly" out["IQ"].should == 6000 end end #multiple-bags end
true
27281078ac99bbf9cb9488149b33afac35420893
Ruby
malonecab/BowlingGame
/app/models/bowling_game.rb
UTF-8
905
3.140625
3
[ "MIT" ]
permissive
class BowlingGame include Mongoid::Document include Mongoid::Timestamps field :hits, type: Array, default: -> { Array.new() } def score score = 0 index = 0 max_index = (hits.size == 12) ? 10 : hits.size-1 while index < max_index if strike?(index) score += strike_score(index) index += 1 elsif spare?(index) score += spare_score(index) index += 2 else score += hits[index] + hits[index+1] index += 2 end end score end def attempt(pins) hits.push pins end private def strike?(index) hits[index].to_i == 10 end def spare?(index) hits[index].to_i + hits[index+1].to_i == 10 end def strike_score(index) score = 10 if (index+2) <= hits.size-1 score += hits[index+1].to_i + hits[index+2].to_i end score end def spare_score(index) score = 10 + hits[index+2].to_i end end
true
9e0ac0835e7a9b17e492496424db67f7fd3c180b
Ruby
Friendscover/connect_four
/lib/coin.rb
UTF-8
157
2.828125
3
[]
no_license
#has attributes name, icon class Coin attr_accessor :name, :icon def initialize(name = "coin", icon = "☾") @name = name @icon = icon end end
true
d6f177ca9057c63a413ecf885877c0ed14e2dd51
Ruby
eliyooy/prime-ruby-v-000
/prime.rb
UTF-8
178
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(int) if int < 2 return false elsif int == 2 || int == 3 return true elsif int % 2 == 0 || int % 3 == 0 return false else return true end end
true
7db92c5fa386cc1745817c8212dd745d46dc3f3e
Ruby
dkroondijk/CodeCore-Assignments-Week1
/Day3/blog_post.rb
UTF-8
289
2.828125
3
[]
no_license
require "./comment.rb" class BlogPost attr_reader :comments def initialize @comments = [] end def add_comment comments << comment end # def add_comment(comment) # comments << comment # end def delete_comment(index) comments.delete_at(index) end end
true
30a4608676c17bdd29ffc205db9df4997ec0fbf9
Ruby
Bidu/core_ext
/spec/lib/hash_spec.rb
UTF-8
9,570
2.671875
3
[ "MIT" ]
permissive
require 'spec_helper' describe Hash do it_behaves_like 'a class with change_key method' it_behaves_like 'a class with camlize_keys method' it_behaves_like 'a class with underscore_keys method' it_behaves_like 'a class with append_keys method' it_behaves_like 'a class with change_kvalues method' it_behaves_like 'a class with remap method' it_behaves_like 'an object with chain_fetch method' describe :squash do let(:hash) { { a: { b: 1, c: { d: 2 } } } } it 'flattens the hash' do expect(hash.squash).to eq('a.b' => 1, 'a.c.d' => 2) end it { expect { hash.squash }.not_to change { hash } } context 'with array value' do let(:hash) { { a: { b: [1, { x: 3, y: { z: 4 } }] } } } it 'flattens the hash' do expect(hash.squash).to eq('a.b' => [1, { x: 3, y: { z: 4 } }]) end end end describe :sort_keys do it 'sorts keys as symbols' do expect({ b: 1, a: 2 }.sort_keys).to eq(a: 2, b: 1) end it 'sorts keys as string' do expect({ 'b' => 1, 'a' => 2 }.sort_keys).to eq('a' => 2, 'b' => 1) end it 'sorts keys recursively' do expect({ b: 1, a: { d: 3, c: 4 } }.sort_keys).to eq(a: { c: 4, d: 3 }, b: 1) end it 'sorts keys recursively when argumen is passed' do expect({ b: 1, a: { d: 3, c: 4 } }.sort_keys(recursive: true)).to eq(a: { c: 4, d: 3 }, b: 1) end it 'does not sorts keys recursively when argumen is passed' do expect({ b: 1, a: { d: 3, c: 4 } }.sort_keys(recursive: false)).to eq(a: { d: 3, c: 4 }, b: 1) end it 'sort recursevely on many levels' do hash = { b: 1, a: { d: 2, c: { e: 3, f: 4 } } } expected = { a: { c: { f: 4, e: 3 }, d: 2 }, b: 1 } expect(hash.sort_keys(recursive: true)).to eq(expected) end it 'applies to arrays as well' do hash = { b: 1, a: { d: 2, c: [{ e: 3, f: 4 }] } } expected = { a: { c: [{ f: 4, e: 3 }], d: 2 }, b: 1 } expect(hash.sort_keys(recursive: true)).to eq(expected) end end describe :exclusive_merge do let(:subject) { { a: 1, b: 2 } } let(:other) { { b: 3, c: 4 } } it 'merge only the common keys' do expect(subject.exclusive_merge(other)).to eq(a: 1, b: 3) end it 'does not change the original hash' do expect { subject.exclusive_merge(other) }.not_to change { subject } end end describe :exclusive_merge! do let(:subject) { { a: 1, b: 2 } } let(:other) { { b: 3, c: 4 } } it 'merge only the common keys' do expect(subject.exclusive_merge!(other)).to eq(a: 1, b: 3) end it 'does not change the original hash' do expect { subject.exclusive_merge!(other) }.to change { subject } end end describe :to_deep_hash do let(:subject) do { 'person.name' => 'Some name', 'person.age' => 22, 'status' => :success, 'vehicle.fuel' => 'GASOLINE', 'vehicle.doors' => 4 } end let(:expected) do { 'person' => { 'name' => 'Some name', 'age' => 22 }, 'vehicle' => { 'fuel' => 'GASOLINE', 'doors' => 4 }, 'status' => :success } end it 'build a deep hash' do expect(subject.to_deep_hash).to eq(expected) end context 'with indexed keys' do let(:subject) do { 'person[0].name' => 'First person', 'person[0].age' => 22, 'person[1].name' => 'Second person', 'person[1].age' => 27, 'device[0]' => 'GEAR_LOCK', 'device[1]' => 'GPS', 'zipCode' => '122345-123' } end let(:expected) do { 'person' => [ { 'name' => 'First person', 'age' => 22 }, { 'name' => 'Second person', 'age' => 27 } ], 'device' => %w(GEAR_LOCK GPS), 'zipCode' => '122345-123' } end it 'build a deep hash with arrays' do expect(subject.to_deep_hash).to eq(expected) end end context 'with a n level hash' do let(:subject) do { 'quote_request.personal.person.name' => 'Some name', 'quote_request.personal.person.age' => 22, 'quote_request.insurance.vehicle.fuel' => 'GASOLINE', 'quote_request.insurance.vehicle.doors' => 4, 'request.status' => :success, 'trials' => 3 } end let(:expected) do { 'quote_request' => { 'personal' => { 'person' => { 'name' => 'Some name', 'age' => 22 } }, 'insurance' => { 'vehicle' => { 'fuel' => 'GASOLINE', 'doors' => 4 } } }, 'request' => { 'status' => :success }, 'trials' => 3 } end it 'build a deep hash with arrays' do expect(subject.to_deep_hash).to eq(expected) end end context 'with a n level hash and arrays' do let(:subject) do { 'quote_request.personal.person[0].name' => 'Some name 1', 'quote_request.personal.person[0].age' => 22, 'quote_request.personal.person[1].name' => 'Some name 2', 'quote_request.personal.person[1].age' => 23, 'request[0].status.clazz' => String, 'request[1].status.clazz' => Fixnum, 'request[2].status.clazz' => Date, 'trials' => 3 } end let(:expected) do { 'quote_request' => { 'personal' => { 'person' => [ { 'name' => 'Some name 1', 'age' => 22 }, { 'name' => 'Some name 2', 'age' => 23 } ] } }, 'request' => [ { 'status' => { 'clazz' => String } }, { 'status' => { 'clazz' => Fixnum } }, { 'status' => { 'clazz' => Date } } ], 'trials' => 3 } end it 'build a deep hash with arrays' do expect(subject.to_deep_hash).to eq(expected) end end context 'with custom separator' do let(:subject) do { 'person_name' => 'Some name', 'person_age' => 22, 'status' => :success, 'vehicle_fuel' => 'GASOLINE', 'vehicle_doors' => 4 } end it 'build a deep hash with arrays' do expect(subject.to_deep_hash('_')).to eq(expected) end end context 'with custom separator on n level deep hash' do let(:subject) do { 'person_name_clazz' => String } end let(:expected) do { 'person' => { 'name' => { 'clazz' => String } } } end it 'build a deep hash with arrays' do expect(subject.to_deep_hash('_')).to eq(expected) end end end describe '#map_and_find' do let(:hash) { { a: 1, b: 2, c: 3, d: 4 } } let(:value) { hash.map_and_find(&block) } context 'when block returns nil' do let(:block) { proc {} } it { expect(value).to be_nil } end context 'when block returns false' do let(:block) { proc { false } } it { expect(value).to be_nil } end context 'when block returns a true evaluated value' do let(:block) { proc { |_, v| v.to_s } } it { expect(value).to eq('1') } context 'when block returns the key and not the value' do let(:block) { proc { |k, v| v > 1 && k } } it { expect(value).to eq(:b) } end context 'but not for the first value' do let(:transformer) { double(:transformer) } let(:block) { proc { |_, v| transformer.transform(v) } } before do allow(transformer).to receive(:transform) do |v| v.to_s if v > 1 end value end it { expect(value).to eq('2') } it 'calls the mapping only until it returns a valid value' do expect(transformer).to have_received(:transform).exactly(2) end end end context 'when the block accepts one argument' do let(:block) { proc { |v| v } } it do expect(value).to eq([:a, 1]) end end end describe '#map_and_select' do let(:hash) { { a: 1, b: 2, c: 3, d: 4 } } let(:list) { hash.map_and_select(&block) } context 'when block returns nil' do let(:block) { proc {} } it { expect(list).to be_empty } end context 'when block returns false' do let(:block) { proc { false } } it { expect(list).to be_empty } end context 'when block returns a true evaluated value' do let(:block) { proc { |_, v| v.to_s } } it { expect(list).to eq((1..4).map(&:to_s)) } context 'when block returns the key and not the value' do let(:block) { proc { |k, v| v > 1 && k } } it { expect(list).to eq([:b, :c, :d]) } end context 'but not for the first value' do let(:transformer) { double(:transformer) } let(:block) { proc { |_, v| transformer.transform(v) } } before do allow(transformer).to receive(:transform) do |v| v.to_s if v > 1 end list end it { expect(list).to eq(hash.values[1..-1].map(&:to_s)) } it 'calls the mapping only once for each value' do expect(transformer).to have_received(:transform).exactly(4) end end end context 'when the block accepts one argument' do let(:block) { proc { |v| v } } it do expect(list).to eq([[:a, 1], [:b, 2], [:c, 3], [:d, 4]]) end end end end
true
3934cff3e9b7b1238ea7847c545b0768101bc0c0
Ruby
ehayne00/ruby-project-alt-guidelines-london-web-111819
/lib/review.rb
UTF-8
1,095
2.765625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Review < ActiveRecord::Base belongs_to :user belongs_to :dental_hygienist def print_review_details "name: #{self.dental_hygienist.name}, star rating: #{self.star_review}, review: #{self.comment_review}" end def self.find_reviews_by_location(user_input) array = DentalHygienist.find_hygienists_by_location(user_input).map {|hyg| hyg.id} new_array = array.map{|id| Review.find_by({dental_hygienist_id:id})} if new_array.length >=2 || new_array[0] != nil new_array2 = new_array.map{|review| review.print_review_details} puts new_array2 else puts "There are no reviews for hygienists in that location yet" end end def self.find_reviews_by_name(user_input) hygienist = DentalHygienist.find_hygienist_by_name(user_input) array = Review.where(dental_hygienist_id: hygienist.id) new_array = array.map{|review| review.print_review_details} if new_array.length <= 0 puts "There are no reviews for this hygienist yet." else puts new_array end end end
true
5b1e7bfd58f1855957e11c067ca7b21612dc4596
Ruby
atanum/fairwood
/app/controllers/students_controller.rb
UTF-8
5,669
2.65625
3
[]
no_license
class StudentsController < ApplicationController before_action :set_student, only: [:show, :edit, :update, :destroy] # GET /students # GET /students.json def index @students = Student.all end # GET /students/1 # GET /students/1.json def show end # GET /students/new def new @student = Student.new end # GET /students/1/edit def edit end # POST /students # POST /students.json def create @student = Student.new(student_params) respond_to do |format| if @student.save format.html { redirect_to @student, notice: 'Student was successfully created.' } # noinspection RailsParamDefResolve format.json { render :show, status: :created, location: @student } else format.html { render :new } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # PATCH/PUT /students/1 # PATCH/PUT /students/1.json def update respond_to do |format| if @student.update(student_params) format.html { redirect_to @student, notice: 'Student was successfully updated.' } # noinspection RailsParamDefResolve format.json { render :show, status: :ok, location: @student } else format.html { render :edit } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # DELETE /students/1 # DELETE /students/1.json def destroy @student.destroy respond_to do |format| format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' } format.json { head :no_content } end end # noinspection RailsChecklist01 def import # Parse the student data student_data = params[:student_data] ? params[:student_data].read : '' # TODO: Don't assume first row is a header row. Detect it and skip if it's there. row_count = 0 Student.transaction do student_data.split(/[\r\n]/).each do |row| next if row.blank? row_count += 1 # Skip the header row (e.g. first row) in the data next if row_count == 1 student_last, student_first, grade, teacher_last, teacher_first, teacher_title, father_last, father_first, father_email, mother_first, mother_last, mother_email = row.split(',')[1..12] # Find or create the Student student = load_student(student_first, student_last) student.grade = grade if grade.present? # Find or create the teacher teacher = load_teacher(teacher_first, teacher_last) teacher.title = teacher_title if teacher_title.present? # Find or create the parents parents = [] if mother_last.present? mother = load_parent(mother_first, mother_last) mother.email = mother_email if mother_email.present? parents << mother end if father_last.present? father = load_parent(father_first, father_last) father.email = father_email if father_email.present? parents << father end # Create the Family object if it doesn't exist. Drive it from the parent side. # NB: We work under the assumption that a given parent only belongs to one family. If one parent had two # children from two different partners, we may get in trouble here. if parents.empty? # A student *must* have at least one parent! redirect_to students_url, notice: "#{student_first} #{student_last} has no parents! Aborting import; no records changed!" return end # @type [Parent] first_parent = parents.first # @type [Family] family = first_parent.family || first_parent.build_family # Wire things up! parents.each do |parent| # noinspection RubyResolve parent.family = family end student.teacher = teacher student.family = family family.parents = parents # Save one and all! We're probably being overly conservative here... student.save! teacher.save! family.save! parents.each do |parent| parent.save! end end end redirect_to students_url, notice: "#{row_count - 1} student records created." end # @return [Parent] def load_parent(mother_first, mother_last) find_or_instantiate(Parent, mother_last, mother_first) end # @return [Student] def load_student(student_first, student_last) find_or_instantiate(Student, student_last, student_first) end # @return [Teacher] def load_teacher(teacher_first, teacher_last) find_or_instantiate(Teacher, teacher_last, teacher_first) end def search # Search for students based on full-names and last-names that start with the search term. search_for = "#{params[:term]}%" @matches = Student.where('full_name ilike ? or last_name ilike ?', search_for, search_for).limit(10).order("last_name, first_name").pluck(:full_name) render json: @matches end private def find_or_instantiate(klass, last_name, first_name) klass.find_by(last_name: last_name, first_name: first_name) || klass.new(last_name: last_name, first_name: first_name) end # Use callbacks to share common setup or constraints between actions. def set_student @student = Student.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_params params.require(:student).permit(:first_name, :last_name, :grade) end end
true
7edc04306846841af9000a37ec7e69229b35ba77
Ruby
pradeepkhot/Programs
/26:twostringsubstring.rb
UTF-8
431
4.375
4
[]
no_license
#Program to print yes if a letter in given 2 strings match else print no ######################################################################## def string_match(s1,s2) c=0 for line in 0..s1.length-1 for count in 0..s2.length-1 if s1[line]==s2[count] c=c+1 end end end if c>1 puts "yes" else puts "No" end end puts "Enter string1" s1=gets.chomp puts "Enter string2" s2=gets.chomp string_match(s1,s2)
true
03daf54025b4cbd9895e81b001c022e771924a65
Ruby
jeremiahishere/archived_projects
/cucumber_off_rails/lib/cucumber_off_rails/generator.rb
UTF-8
2,837
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'erb' require 'fileutils' require 'ruby-debug' class CucumberOffRails class Generator #require "cucumber_off_rails/generator/options" require "cucumber_off_rails/generator/application" attr_accessor :options, :remote_site, :project_name, :target_dir def initialize(options = {}) self.options = options self.remote_site = options[:remote_site] || "http://www.google.com" self.project_name = options[:project_name] self.target_dir = options[:directory] || self.project_name || "cucumber_off_rails_project" end def run create_files end def create_files unless File.exists?(target_dir) || File.directory?(target_dir) FileUtils.mkdir target_dir else raise "The directory #{target_dir} already exists, aborting. Maybe move it out of the way before continuing?" end output_template_in_target "Gemfile" output_template_in_target "Rakefile" mkdir_in_target "features" output_template_in_target File.join("features", "sample.feature") mkdir_in_target "features/step_definitions" output_template_in_target File.join("features", "step_definitions", "debugging_steps.rb") output_template_in_target File.join("features", "step_definitions", "linking_steps.rb") output_template_in_target File.join("features", "step_definitions", "login_steps.rb") output_template_in_target File.join("features", "step_definitions", "selector_steps.rb") output_template_in_target File.join("features", "step_definitions", "validation_steps.rb") mkdir_in_target "features/support" output_template_in_target File.join("features", "support", "env.rb") output_template_in_target File.join("features", "support", "hooks.rb") output_template_in_target File.join("features", "support", "paths.rb") output_template_in_target File.join("features", "support", "selectors.rb") end def output_template_in_target(source, destination = source) final_destination = File.join(target_dir, destination) template_result = render_template(source) File.open(final_destination, 'w') {|file| file.write(template_result)} $stdout.puts "\tcreate\t#{destination}" end def render_template(source) template_contents = File.read(File.join(template_dir, source)) template = ERB.new(template_contents, nil, '<>') # squish extraneous whitespace from some of the conditionals template.result(binding).gsub(/\n\n\n+/, "\n\n") end def template_dir File.join(File.dirname(__FILE__), 'templates') end def mkdir_in_target(directory) final_destination = File.join(target_dir, directory) FileUtils.mkdir final_destination $stdout.puts "\tcreate\t#{directory}" end end end
true
c774a81009169479cce470a6a3bb070a45f37883
Ruby
hleonov/genXLSParsing
/parsingGem/lib/dsl_parsing_support.rb
UTF-8
1,655
2.65625
3
[]
no_license
require 'open4' require 'json' class DslParsingSupport JAR_PATH = File.expand_path('../../bin/genXlsParsingWithProvenance.jar', __FILE__) TEST_PATH = '/home/bittkomk/randomProjects/genXlsParsingWithProvenance' def self.test_parse_xls_to_json parse_xls_to_json("#{TEST_PATH}/bode-surgical.parser", "#{TEST_PATH}/SEEK-Tierliste_MG_complete.xlsx", "#{TEST_PATH}/gem-parsed-bode-2.json") end def self.parse_xls_to_json parser_def, xls_input_file, json_output_file data_hash = nil if (invoke_cmd create_cmd(parser_def, xls_input_file, json_output_file)) == 0 data_hash = JSON.parse(File.read(json_output_file)) end data_hash end private def self.create_cmd parser_def, xls_input_file, json_output_file, xls_output_file=nil, embed_provenance_information=nil cmd = "java -jar #{JAR_PATH} #{parser_def} -inputFile #{xls_input_file}" cmd = cmd + " -jsonOutputFile #{json_output_file}" if json_output_file cmd = cmd + " -outputFile #{xls_output_file}" if xls_output_file cmd = cmd + " -embedProvencanceInformation" if embed_provenance_information cmd end def self.invoke_cmd cmd # cmd = "java -jar #{JAR_PATH} #{TEST_PATH}/bode-surgical.parser -inputFile #{TEST_PATH}/SEEK-Tierliste_MG_complete.xlsx -jsonOutputFile #{TEST_PATH}/rubyGem-output.json" puts "invoke #{cmd}" output = "" status = Open4::popen4(cmd) do |pid, stdin, stdout, stderr| while((line = stdout.gets) != nil) do output << line end stdout.close stderr.close end puts output.strip status.to_i end end
true
73ebb2e699e66317a4ad9207aa504d3426be0c36
Ruby
sleepingkingstudios/stannum
/lib/stannum/constraints/types/hash_with_string_keys.rb
UTF-8
791
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'stannum/constraints/types' module Stannum::Constraints::Types # Asserts that the object is a Hash with String keys. class HashWithStringKeys < Stannum::Constraints::Types::HashType # @param value_type [Stannum::Constraints::Base, Class, nil] If set, then # the constraint will check the types of each value in the Hash against # the expected type and will fail if any values do not match. # @param options [Hash<Symbol, Object>] Configuration options for the # constraint. Defaults to an empty Hash. def initialize(value_type: nil, **options) super( key_type: Stannum::Constraints::Types::StringType.new, value_type: coerce_value_type(value_type), **options ) end end end
true
3eede7dd1ab35fa13bb1b5b57ae9e9428b3bd21f
Ruby
rob-king/game_of_thrones
/db/seeds.rb
UTF-8
865
3.09375
3
[]
no_license
require 'csv' csv_text = File.read(Rails.root.join('db','got-export.csv')) csv = CSV.parse(csv_text, headers:true) def get_unique_houses(csv) houses = [] csv.each { |row| record = row.to_hash houses << record['allegiances'] } houses.uniq end unique_houses = get_unique_houses(csv) characters = csv.map { |e| e.to_hash } unique_houses.each { |house| banner = House.create(name:house) members = characters.select { |character| character['allegiances'] == house } members.each { |member| banner.characters.create(name: member['name'], gender: member['gender'], culture: member['culture'], born: member['born'], died: member['died'], title: member['title'], alias: member['alias'] ) } } #leaving behind characters with no house in the bad data puts Character.all.count puts House.all.count
true
21e29fc39f7585076e072df80b6a375c9a3e42cd
Ruby
gaofeiii/Dino.account-server
/spec/models/account_spec.rb
UTF-8
1,827
2.5625
3
[]
no_license
require 'spec_helper' describe Account do describe "validations" do before(:each) do @attr = { :username => "gaofei", :email => "[email protected]", :password => "haha123", :password_confirmation => "haha123" } end it "should not be valid when email is invalid" do Account.new(@attr.merge(:email => "bademail")).should_not be_valid end it "should be valid when email is nil" do Account.new(@attr.merge(:email => nil)).should be_valid end it "should be valid when email is blank" do Account.new(@attr.merge(:email => "")).should be_valid end it "should not be valid when email is used" do Account.create @attr Account.new(@attr.merge(:email => "[email protected]")).should_not be_valid end it "should not be valid when password is blank" do Account.new(@attr.merge(:password => "")).should_not be_valid end it "should not be valid when password doesn't match" do Account.new(@attr.merge(:password_confirmation => "bad password")).should_not be_valid end it "should be valid" do Account.new(@attr).should be_valid end it "should create an account" do lambda do Account.create @attr end.should change(Account, :count).by(1) end end describe "methods validations" do before(:each) do @account = FactoryGirl.create(:account) end it "should have a specified to_json method" do @account.to_json.should include("id") @account.to_json.should_not include("created_at") end it "should have a find_by_username_or_email method" do Account.find_by_username_or_email(@account.email).should == @account Account.find_by_username_or_email(@account.username).should == @account end end end
true
1530ee37cea7b7846e42f96a687f44acc6bb1221
Ruby
raymonddoan/jokes_rails_api
/db/seeds.rb
UTF-8
1,556
2.84375
3
[]
no_license
joke_categories = [ "Puns", "Programming", "Knock Knock", "Limericks", ] if Category.all.length == 0 joke_categories.each do |category| Category.create(name: category) puts "created #{category} category" end end if User.count == 0 User.create(username: "Ray", email: "[email protected]", password: "password1", password_confirmation: "password1") User.create(username: "Aidan", email: "[email protected]", password: "password2", password_confirmation: "password2") User.create(username: "Kat", email: "[email protected]", password: "password3", password_confirmation: "password3") end if Joke.count == 0 Joke.create(user_id: 1, category_id: 1, body: "Why did Adele cross the road? To say hello from the other side.") Joke.create(user_id: 1, category_id: 1, body: "What kind of concert only costs 45 cents? A 50 Cent concert featuring Nickelback.") Joke.create(user_id: 1, category_id: 1, body: "What did the grape say when it got crushed? Nothing, it just let out a little wine.") Joke.create(user_id: 1, category_id: 1, body: "Time flies like an arrow. Fruit flies like a banana.") Joke.create(user_id: 2, category_id: 2, body: "Two bytes meet. The first byte asks, “Are you ill?” The second byte replies, “No, just feeling a bit off.”") Joke.create(user_id: 2, category_id: 2, body: "How many programmers does it take to change a light bulb? None – It’s a hardware problem") Joke.create(user_id: 2, category_id: 2, body: "There are only 10 kinds of people in this world: those who know binary and those who don’t.") end
true
a3d0dba9839606ef48ce885cefc3e2ffbad3ac4f
Ruby
jvidalba1/learn-ruby
/Semana 0/problema 2/problema2.rb
UTF-8
278
3.09375
3
[]
no_license
@a = 1 while @a.eql? 1 do puts "Escriba cantidad en pesos" c = gets b = c.to_f / 1700.to_f puts "equivale a #{ b.to_f.round(2) } dolares" puts "para continuar 1, si no 0 " @a = gets.to_i end
true
1337353370135085713f5102b7190e62606d2c8e
Ruby
ddhogan/school-domain-v-000
/lib/school.rb
UTF-8
357
3.703125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School def initialize(roster) @roster = {} end attr_accessor :name attr_reader :roster def add_student(student_name, grade) @roster[grade] ||= [] @roster[grade] << student_name end def grade(num) @roster[num] end def sort sorted = {} @roster.each do |grade, students| sorted[grade] = students.sort end sorted end end
true
2aaddd8cf5993bf4a34ad99e92d6a37d26997a1b
Ruby
sbraford/pubrunner
/lib/pubrunner/octopress_transformer.rb
UTF-8
3,003
3.015625
3
[ "MIT" ]
permissive
module Pubrunner module Transformer class Octopress attr_accessor :post_layout, :post_date, :comments def initialize(book) @book = book @post_layout = 'post' @post_date = Time.now @comments = true # Octopress, by default, shows the most recent posts first. In Archive listings, # it will also show the most recent posts first. To "trick" Octopress into # displaying Chapters One => X, in the order of One, Two, etc ... by default # we will set the *first* chapter as the most recently posted, and the # *last* chapter as the oldest. # Example: # Chapter One - 2012-04-05 20:15 # Chapter Two - 2012-04-05 20:14 # .... @reverse_chronological = true end # Transforms a Pubrunner::Book into Octopress blog entry chapters # Note: we need to transform the markup from Pubdown to HTML. Although Octopress # supports Markdown, it does not handle tab-indentation well and Pubdown-formatted # text ends up looking like bunk. def transform_and_save(target_directory) chapter_date = @post_date @book.chapters.each do |chapter| post = Octopress.front_matter post.sub!('##LAYOUT##', @post_layout) post.sub!('##POST_TITLE##', chapter.title) post.sub!('##DATE##', chapter_date.strftime("%Y-%m-%d %H:%M")) post.sub!('##COMMENTS##', @comments.to_s) content = PubdownProcessor.transform_pubdown_octo(chapter.content) content.each_line do |line| line.rstrip! if '' == line post << "\n" next end if line[0] == "\t" # Line begins with tab line.lstrip! line_new = '<p>' + line + '</p>' else line_new = '<br/><p>' + line + '</p>' end post << "#{line_new}\n" end post_filename = octopressify_filename(chapter.title, chapter_date) post_path = File.join(target_directory, post_filename) f = File.new(post_path, 'w') f.write(post) f.close if @reverse_chronological chapter_date = chapter_date - 60 # Subtract 60 seconds (1 Minute) from the post date else chapter_date = chapter_date + 60 # Add 60 seconds (1 Minute) to each post date end end end def octopressify_filename(title, date) title = title.downcase title.gsub!(/[\s]/, '-') title.gsub!(/[^a-zA-Z0-9-]/, '') date_formatted = date.strftime("%Y-%m-%d") "#{date_formatted}-#{title}.html" end def self.front_matter <<-EOM --- layout: ##LAYOUT## title: ##POST_TITLE## date: ##DATE## comments: ##COMMENTS## --- EOM end end end end
true
2f7a2e1a4263510ee4c79d4329e21ee2c7b78774
Ruby
djvirgen/kronk
/lib/kronk/response.rb
UTF-8
13,675
2.734375
3
[ "MIT" ]
permissive
class Kronk ## # Mock File IO to allow rewinding on Windows platforms. class WinFileIO < StringIO attr_accessor :path def initialize path, str="" @path = path super str end end ## # Standard Kronk response object. class Response class MissingParser < Kronk::Exception; end class InvalidParser < Kronk::Exception; end ENCODING_MATCHER = /(^|;\s?)charset=(.*?)\s*(;|$)/ ## # Read http response from a file and return a Kronk::Response instance. def self.read_file path file = File.open(path, "rb") resp = new file resp.uri = path file.close resp end attr_accessor :body, :code, :raw, :request, :stringify_opts, :time, :uri alias to_s raw ## # Create a new Response object from a String or IO. def initialize io=nil, res=nil, request=nil return unless io io = StringIO.new io if String === io if io && res @_res, debug_io = res, io else @_res, debug_io = request_from_io(io) end @headers = @encoding = @parser = nil @time = 0 raw_req, raw_resp, = read_raw_from debug_io @raw = try_force_encoding raw_resp @request = request || raw_req && Request.parse(try_force_encoding raw_req) @body = try_force_encoding(@_res.body) if @_res.body @body ||= @raw.split("\r\n\r\n",2)[1] @code = @_res.code @uri = @request.uri if @request && @request.uri @uri = URI.parse io.path if File === io @stringify_opts = {} end ## # Accessor for the HTTPResponse instance [] def [] key @_res[key] end ## # Accessor for the HTTPResponse instance [] def []= key, value @_res[key] = value end ## # If time was set, returns bytes-per-second for the whole response, # including headers. def byterate return 0 unless @raw && @time.to_f > 0 @byterate = self.total_bytes / @time.to_f end ## # Size of the body in bytes. def bytes (headers["content-length"] || @body.bytes.count).to_i end ## # Cookie header accessor. def cookie @_res['Cookie'] end ## # Return the Ruby-1.9 encoding of the body, or String representation # for Ruby-1.8. def encoding return @encoding if @encoding @encoding = "utf-8" unless headers["content-type"] c_type = headers["content-type"] =~ ENCODING_MATCHER @encoding = $2 if c_type @encoding ||= "ASCII-8BIT" @encoding = Encoding.find(@encoding) if defined?(Encoding) @encoding end ## # Force the encoding of the raw response and body. def force_encoding new_encoding new_encoding = Encoding.find new_encoding unless Encoding === new_encoding @encoding = new_encoding try_force_encoding @body try_force_encoding @raw @encoding end ## # Accessor for downcased headers. def headers return @headers if @headers @headers = @_res.to_hash.dup @headers.keys.each{|h| @headers[h] = @headers[h].join(", ")} @headers end alias to_hash headers ## # If there was an error parsing the input as a standard http response, # the input is assumed to be a body and HeadlessResponse is used. def headless? HeadlessResponse === @_res end ## # Ruby inspect. def inspect "#<#{self.class}:#{@code} #{self['Content-Type']} #{total_bytes}bytes>" end ## # Returns the body data parsed according to the content type. # If no parser is given will look for the default parser based on # the Content-Type, or will return the cached parsed body if available. def parsed_body new_parser=nil @parsed_body ||= nil return @parsed_body if @parsed_body && !new_parser new_parser ||= parser begin new_parser = Kronk.parser_for(new_parser) || Kronk.find_const(new_parser) rescue NameError raise InvalidParser, "No such parser: #{new_parser}" end if String === new_parser raise MissingParser, "No parser for Content-Type: #{@_res['Content-Type']}" unless new_parser begin @parsed_body = new_parser.parse(self.body) or raise RuntimeError rescue RuntimeError, ::Exception => e msg = ParserError === e ? e.message : "#{new_parser} failed parsing body" msg << " returned by #{@uri}" if @uri raise ParserError, msg end end ## # Returns the parsed header hash. def parsed_header include_headers=true out_headers = headers.dup out_headers['status'] = @code out_headers['http-version'] = @_res.http_version case include_headers when nil, false nil when Array, String include_headers = [*include_headers].map{|h| h.to_s.downcase} out_headers.keys.each do |key| out_headers.delete key unless include_headers.include? key.to_s.downcase end out_headers when true out_headers end end ## # The parser to use on the body. def parser @parser ||= Kronk.parser_for headers["content-type"] end ## # Assign the parser. def parser= parser @parser = Kronk.parser_for(parser) || Kronk.find_const(parser) rescue NameError raise InvalidParser, "No such parser: #{parser}" end ## # Returns the header portion of the raw http response. def raw_header include_headers=true headers = "#{@raw.split("\r\n\r\n", 2)[0]}\r\n" case include_headers when nil, false nil when Array, String includes = [*include_headers].join("|") headers.scan(%r{^((?:#{includes}): [^\n]*\n)}im).flatten.join when true headers end end ## # Returns the location to redirect to. Prepends request url if location # header is relative. def location return @_res['Location'] if !@request || [email protected] @request.uri.merge @_res['Location'] end ## # Check if this is a redirect response. def redirect? @code.to_s =~ /^30\d$/ end ## # Follow the redirect and return a new Response instance. # Returns nil if not redirect-able. def follow_redirect opts={} return if !redirect? Request.new(self.location, opts).retrieve end ## # Returns the raw response with selective headers and/or the body of # the response. Supports the following options: # :no_body:: Bool - Don't return the body; default nil # :show_headers:: Bool/String/Array - Return headers; default nil def selective_string options={} str = @body unless options[:no_body] if options[:show_headers] header = raw_header(options[:show_headers]) str = [header, str].compact.join "\r\n" end str end ## # Returns the parsed response with selective headers and/or the body of # the response. Supports the following options: # :no_body:: Bool - Don't return the body; default nil # :show_headers:: Bool/String/Array - Return headers; default nil # :parser:: Object - The parser to use for the body; default nil # :transform:: Array - Action/path(s) pairs to modify data. # # Deprecated Options: # :ignore_data:: String/Array - Removes the data from given data paths # :only_data:: String/Array - Extracts the data from given data paths # # Example: # response.selective_data :transform => [:delete, ["foo/0", "bar/1"]] # response.selective_data do |trans| # trans.delete "foo/0", "bar/1" # end # # See Kronk::Path::Transaction for supported transform actions. def selective_data options={} data = nil unless options[:no_body] data = parsed_body options[:parser] end if options[:show_headers] header_data = parsed_header(options[:show_headers]) data &&= [header_data, data] data ||= header_data end Path::Transaction.run data, options do |t| # Backward compatibility support t.select(*options[:only_data]) if options[:only_data] t.delete(*options[:ignore_data]) if options[:ignore_data] t.actions.concat options[:transform] if options[:transform] yield t if block_given? end end ## # Returns a String representation of the response, the response body, # or the response headers, parsed or in raw format. # Options supported are: # :parser:: Object/String - the parser for the body; default nil (raw) # :struct:: Boolean - Return data types instead of values # :only_data:: String/Array - extracts the data from given data paths # :ignore_data:: String/Array - defines which data points to exclude # :raw:: Boolean - Force using the unparsed raw response # :keep_indicies:: Boolean - indicies of modified arrays display as hashes. # :show_headers:: Boolean/String/Array - defines which headers to include # # If block is given, yields a Kronk::Path::Transaction instance to make # transformations on the data. See Kronk::Response#selective_data def stringify options={}, &block options = options.empty? ? @stringify_opts : merge_stringify_opts(options) if !options[:raw] && (options[:parser] || parser || options[:no_body]) data = selective_data options, &block DataString.new data, options else selective_string options end rescue MissingParser Cmd.verbose "Warning: No parser for #{@_res['Content-Type']} [#{@uri}]" selective_string options end def merge_stringify_opts options # :nodoc: options = options.dup @stringify_opts.each do |key, val| case key # Response headers - Boolean, String, or Array when :show_headers next if options.has_key?(key) && (options[key].class != Array || val == true || val == false) options[key] = (val == true || val == false) ? val : [*options[key]] | [*val] # String or Array when :only_data, :ignore_data options[key] = [*options[key]] | [*val] else options[key] = val if options[key].nil? end end options end ## # Check if this is a 2XX response. def success? @code.to_s =~ /^2\d\d$/ end ## # Number of bytes of the response including the header. def total_bytes self.raw.bytes.count end private ## # Creates a Net::HTTPRequest instance from an IO instance. def request_from_io resp_io # On windows, read the full file and insert contents into # a StringIO to avoid failures with IO#read_nonblock if Kronk::Cmd.windows? && File === resp_io resp_io = WinFileIO.new resp_io.path, io.read end io = Net::BufferedIO === resp_io ? resp_io : Net::BufferedIO.new(resp_io) io.debug_output = debug_io = StringIO.new begin resp = Net::HTTPResponse.read_new io resp.reading_body io, true do;end rescue Net::HTTPBadResponse ext = "text/html" ext = File.extname(resp_io.path)[1..-1] if WinFileIO === resp_io || File === resp_io resp_io.rewind resp = HeadlessResponse.new resp_io.read, ext rescue EOFError # If no response was read because it's too short unless resp resp_io.rewind resp = HeadlessResponse.new resp_io.read, "html" end end resp.instance_eval do @socket ||= true @read ||= true end [resp, debug_io] end ## # Read the raw response from a debug_output instance and return an array # containing the raw request, response, and number of bytes received. def read_raw_from debug_io req = nil resp = "" bytes = nil debug_io.rewind output = debug_io.read.split "\n" if output.first =~ %r{<-\s(.*)} req = instance_eval $1 output.delete_at 0 end if output.last =~ %r{read (\d+) bytes} bytes = $1.to_i output.delete_at(-1) end output.map do |line| next unless line[0..2] == "-> " resp << instance_eval(line[2..-1]) end [req, resp, bytes] end ## # Assigns self.encoding to the passed string if # it responds to 'force_encoding'. # Returns the string given with the new encoding. def try_force_encoding str str.force_encoding encoding if str.respond_to? :force_encoding str end end ## # Mock response object without a header for body-only http responses. class HeadlessResponse attr_accessor :body, :code def initialize body, file_ext=nil @body = body @raw = body @code = "200" encoding = body.respond_to?(:encoding) ? body.encoding : "UTF-8" @header = { 'Content-Type' => "text/#{file_ext}; charset=#{encoding}" } end ## # Interface method only. Returns nil for all but content type. def [] key @header[key] end def []= key, value @header[key] = value end ## # Interface method only. Returns empty hash. def to_hash head_out = @header.dup head_out.keys.each do |key| head_out[key.downcase] = [head_out.delete(key)] end head_out end end end
true
124320545219be99fba0f80e534cb5db860bd566
Ruby
CodeSmell/advent-of-code
/2018/tests/util/test_Location.rb
UTF-8
523
3
3
[]
no_license
require_relative "../../lib/util/Location.rb" require "test/unit" class Test_Location < Test::Unit::TestCase def test_taxiCabDistance loc = Location.new(3,4) distance = Location.new(1,1).taxiCabDistance(loc) assert_equal(5, distance) end def test_convert_string locString = Location.new(3,4).asString locFromString = Location.convertStringToLocation(locString) assert_equal("3,4", locString) assert_equal(3, locFromString.x) assert_equal(4, locFromString.y) end end
true
bf2355882ec647f878477fb4081d129f1f49af2f
Ruby
peterla/SeatYourself
/test/models/restaurant_test.rb
UTF-8
1,498
2.828125
3
[]
no_license
require 'test_helper' class RestaurantTest < ActiveSupport::TestCase # test "the truth" do # assert true # end test 'one restaurant exists' do r = FactoryGirl.create :restaurant assert_equal 1, Restaurant.all.size, 'Number of restaurants was not equal to 1' end test 'restaurant has at least 1 seat available' do r = FactoryGirl.create :restaurant assert r.available?("2016-05-31", "18:00", 1), 'Restaurant has at least 1 seat available' end test 'restaurant is available at capacity' do r = FactoryGirl.create :restaurant assert r.available?("2016-05-31", "18:00", r.capacity), 'Restaurant cannot book up to capacity' end test 'restaurant cannot be available above to capacity' do r = FactoryGirl.create :restaurant assert_not r.available?("2016-05-31", "18:00", r.capacity + 1), 'Restaurant is available above capacity' end test 'restaurant can accept 1 reservation below capacity' do r = FactoryGirl.create :restaurant reservation = FactoryGirl.create :reservation1 assert r.available?("2016-05-31", "18:00", 0), 'Restaurant cannot accept 1 reservation below capacity' end test 'restaurant cannot accept multiple reservations that add up to above capacity' do r = FactoryGirl.create :restaurant 5.times do reservation = FactoryGirl.create :reservation2 end assert_not r.available?("2016-05-31", "18:00", 5), 'Restaurant accepted multiple reservations that add up to above capacity' end end
true
d064292ed30335df5d8f7cb183b8a83d1a396003
Ruby
loopj/resque-delayable
/lib/resque-delayable/delayed_method.rb
UTF-8
2,041
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module ResqueDelayable require "resque" begin require "resque/scheduler" rescue LoadError end class DelayedMethod attr_accessor :klass attr_accessor :instance attr_accessor :options def initialize(klass, instance = nil, options = {}) unless instance.nil? || ResqueDelayable::ACTIVE_SERIALIZERS.any? {|klass| klass.serialize_match(instance) } raise "Cannot serialize instances of this type (#{instance.class}). Consider creating a serializer." end self.klass = klass self.instance = instance self.options = options end def dequeue(method, *parameters) ::Resque.dequeue(self.klass, method, ::ResqueDelayable::serialize_object(self.instance), *::ResqueDelayable::serialize_object(parameters)) end def method_missing(method, *parameters) if instance.nil? raise NoMethodError.new("undefined method '#{method}' for #{self.klass}", method, parameters) unless klass.respond_to?(method) else raise NoMethodError.new("undefined method '#{method}' for #{self.instance}", method, parameters) unless instance.respond_to?(method) end if self.options[:run_at] if ::Resque.respond_to?(:enqueue_at) ::Resque.enqueue_at(self.options[:run_at], self.klass, method, ::ResqueDelayable::serialize_object(self.instance), *::ResqueDelayable::serialize_object(parameters)) else raise "Cannot use run_at, resque-scheduler not installed" end elsif self.options[:run_in] if ::Resque.respond_to?(:enqueue_in) ::Resque.enqueue_in(self.options[:run_in], self.klass, method, ::ResqueDelayable::serialize_object(self.instance), *::ResqueDelayable::serialize_object(parameters)) else raise "Cannot use run_in, resque-scheduler not installed" end else ::Resque.enqueue(self.klass, method, ::ResqueDelayable::serialize_object(self.instance), *::ResqueDelayable::serialize_object(parameters)) end true end end end
true
b1b2b00f11dafa70984a6c57aa6754ae4c5bfd3f
Ruby
syborg/web_dump
/examples/simple_examples.rb
UTF-8
1,160
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# Simple Examples to show up how to use WebDump # Marcel Massana 1-Sep-2011 require 'rubygems' require 'open-uri' require 'web_dump' MY_URIS = [ 'http://en.wikipedia.org/wiki/Ruby_Bridges', 'http://donaldfagen.com/disc_nightfly.php', 'http://www.rubi.cat/ajrubi/portada/index.php', 'http://www.google.com/cse?q=array&cx=013598269713424429640%3Ag5orptiw95w&ie=UTF-8&sa=Search' ] # all files will be saved in expanded '~/mydir' with file extension '.gz' wd = WebDump.new :base_dir => '~/mydir', :file_ext => '.gz' # Don't care about filenames while saving pages into files puts "Saving data using URIs" MY_URIS.each do |uri| open uri do |u| data = u.read puts wd.save uri, data end end # Possibly mocking?... also don't care about filenames while retrieving pages from files. puts "\nRetrieving data using URIs" MY_URIS.each do |uri| data = wd.read_uri(uri) puts data[0...100].gsub(/\s+/, ' ').strip end # ... or, conversely, use filenames if you need so puts "\nRetrieving data using pathnames" files = Dir[File.expand_path('*.gz', '~/mydir')] files.each do |f| data = wd.read_pathname(f) puts data[0...100].gsub(/\s+/, ' ').strip end
true
c135c75c83cfa2f0ddaa66075b0d54cf31ecaf05
Ruby
avanegasp/MakeitClass
/segundaSemana/sinatra3/app.rb
UTF-8
443
2.890625
3
[]
no_license
require 'sinatra' get '/' do @hi = "Hola Makers!" # @hi = params[:name] erb :index end get '/dog/:name/:apellido' do p params @name = params["name"] @apellido = params["apellido"] erb :dog end todos = [] get '/todos/:todo' do todos.push(params[:todo]) @todos = todos erb :todos end get '/students' do erb :students end get '/equipo/:nombre' do #setear el nombre "Hola mi equipo favorito es #{params[:nombre]}" end
true
a22e25613dbcc34bc6a2469338b84f84d9783c8b
Ruby
arifmahmudrana/ruby-learn
/numbers.rb
UTF-8
219
3.53125
4
[]
no_license
# p p 6.0 + 5, 6 - 5.0, 6 / 0.5, 3 * 2, 5 ** 5 # arithmetic operator precedence # p 2 ** 3 / 2, 2 ** (3 / 2) p 5 + 15 * 20 - 2 / 6 ** 3 - (3 + 1) # parentheses, exponent, multiplication, division, addition, subtraction
true
9933eba7d0655d4759648485a386d57e3c3f7360
Ruby
T-PRAT/thp_POO_game
/app.rb
UTF-8
615
3.09375
3
[]
no_license
require 'bundler' Bundler.require require_relative 'lib/game' require_relative 'lib/player' player1 = Player.new("Josiane") player2 = Player.new("José") puts "\nDébut du combat entre ".yellow + player1.name.blue + " et ".yellow + player2.name.red + " !\n\n" while player1.life_points > 0 && player2.life_points > 0 do puts "Voici l'état de chaque joueur :".blue player1.show_state player2.show_state puts "\nPassons à la phase d'attaque :".red player1.attacks(player2) break unless player2.life_points > 0 player2.attacks(player1) puts if player1.life_points >= 0 && player2.life_points >= 0 end
true
af21964800fbd5a0e609ce5b5897c8f7a8a92f52
Ruby
iga-c/CocktailCrawler
/cocktail.rb
UTF-8
885
3.265625
3
[]
no_license
require 'nokogiri' Material = Struct.new(:name, :volume) class Cocktail attr_reader :name, :make, :materials def initialize(html) doc = Nokogiri::HTML(File.read(html)) @name = doc.xpath('//div[@class="cnt"]/strong').text @make = doc.xpath('/html/body/table/tr/td[2]/div[8]/table/tr/td[2]').text @materials = doc.xpath('//table/tr/td[@width="50"]/div[@align="center"]/../../../tr')[1..-1] .map { |item| item.xpath('td') } .map { |td| Material.new(td[0].text.strip, td[1..-1].text) } end def create?(my_materials) @materials.map(&:name).all? { |item| my_materials.include?(item) } end def recipe print("カクテル名:#{@name}\n") print("材料:\n") @materials.each { |material| print("#{material.name}:#{material.volume}\n") } print("作り方:\n") print("#{@make}\n") end end
true
6f237861d182cd7fd59dc8631e252c3ee27e06c0
Ruby
torubylist/ruby_learning
/meta_ruby/my_time.rb
UTF-8
194
3.4375
3
[]
no_license
class Fixnum def my_times &block i = 0 while i < self yield(i) i += 1 end return self end end p 5.my_times{|x| puts "hello #{x}"} p 5.my_times{ puts "hello "}
true
55767157d2c0ee171aa0b9178bc9802f846745ee
Ruby
gatperdut/chatomud
/app/lib/chato_mud/mixins/characters/skill_set/definition.rb
UTF-8
2,892
2.6875
3
[]
no_license
module ChatoMud module Mixins module Characters module SkillSet module Definition def all_skill_labels [ :unskilled, :beginner, :novice, :amateur, :familiar, :talented, :adroit, :master, :grandmaster, :heroic, :godlike ] end def all_rank_rates [ :limited, :below_average, :standard, :above_average, :plus ] end alias all_category_rank_rates all_rank_rates def all_skills all_melee_skills + all_ranged_skills + all_martial_skills + all_athletics_skills + all_communication_skills + all_forging_skills end def all_skills_and_skill_categories all_skills + all_skill_categories end def all_weapon_skills all_melee_skills + all_ranged_skills end def all_skill_categories [ :melee, :ranged, :martial, :athletics, :communication, :forging ] end def all_melee_skills [ :light_edge, :medium_edge, :heavy_edge, :medium_blunt, :heavy_blunt, :light_pierce, :medium_pierce, :polearm ] end def all_ranged_skills [ :archery, :crossbow ] end def all_martial_skills [ :armor_use, :block, :parry, :dual_wield, :throwing ] end def all_athletics_skills [ :body_development, :dodge, :brawl ] end def all_communication_skills all_language_skills + all_script_skills end def all_language_skills [ :quenya, :telerin, :sindarin, :adunaic, :westron, :rohirric, :khuzdul, :entish, :valarin, :black_speech ] end def all_script_skills [ :cirth, :sarati, :tengwar ] end def all_forging_skills [ :metalworking ] end end end end end end
true
fb1084401f8edbe0ce9bc98f488c41f4ea8bf3c1
Ruby
scarroll32/Conjugate
/spec/common_spec.rb
UTF-8
907
2.921875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require 'rspec' require 'conjugate' describe 'Helper Conjugations' do describe 'methods testing' do it '.conjugate calls Spanish' do verb = Conjugate.conjugate({language: 'spanish', verb: 'comprar', tense: :present, pronoun: :yo}) expect(verb).to eq('compro') verb = Conjugate.conjugate({language: 'es', verb: 'comprar', tense: :present, pronoun: :yo}) expect(verb).to eq('compro') end it '.conjugate calls french' do verb = Conjugate.conjugate({language: 'french', verb: 'jouer', tense: :present, pronoun: :je}) expect(verb).to eq('joue') verb = Conjugate.conjugate({language: 'fr', verb: 'jouer', tense: :present, pronoun: :je}) expect(verb).to eq('joue') end it 'fails with other language' do expect { Conjugate.conjugate({language: 'japanese'}) }.to raise_error(ArgumentError) end end end
true
1e18f853695ce0a435dc2f0b3b2f16e96c65ae59
Ruby
Dervol03/a_types
/lib/a_types/decorators/numeric_wrap.rb
UTF-8
1,797
3.421875
3
[ "MIT" ]
permissive
require_relative 'wrapper' module ATypes # Adds numeric methods to any wrapped object. class NumericWrap < Wrapper # Returns the numeric value of this wrapped object. Depending on its class, # different strategies will be applied in the course: # - Strings will be parsed for their content and return nil if it does not # match any number # - true/false will return 1 / -1 # - Numerics will return themselves # - Other objects will simply return nil # # @return [Fixnum, Float, nil] the number that could be interpreted from the # wrapped object. def to_num strategy = "convert_#{content.class.name.downcase}" respond_to?(strategy, true) ? send(strategy, content) : nil end # Tries to convert the given object to a numerical value, according to the # rules of {#to_num}. Returns nil if no conversion is possible. # # @param [Object] source to be converted # @return [Fixnum, Float, nil] the result of the conversion to a numeric # value. def self.try_convert(source) new(source).to_num end private def convert_string(content) if content =~ Matchers::FIXNUM content.to_i elsif content =~ Matchers::FLOAT content.sub(',', '.').to_f end end def convert_trueclass(_content) 1 end def convert_falseclass(_content) -1 end def convert_array(content) convert_string(content.join) end def convert_fixnum(content) content end alias convert_bignum convert_fixnum alias convert_numeric convert_fixnum alias convert_integer convert_fixnum alias convert_float convert_fixnum alias convert_bigdecimal convert_fixnum end # NumericWrap end # ATypes
true
0af1b62e019a6452ca9960ba6e1a4796c5b9bece
Ruby
d4l3k/GitStats
/main.rb
UTF-8
2,980
2.53125
3
[ "MIT" ]
permissive
require 'bundler' Bundler.require :default, :development get '/' do "Hi there! Bob!" end configure do if not Dir.exists? "/tmp/checkout" Dir.mkdir "/tmp/checkout" end end helpers do def get_user_commits user response = Curl::Easy.perform("https://api.github.com/users/#{user}/events") do |curl| curl.headers["User-Agent"] = "d4l3k" end events = MultiJson.load(response.body) commits = [] events.each do |event| if event["type"]=="PushEvent" commits += event["payload"]["commits"] end end commits end def get_user_commits_multi user responses = {} requests = [] (1..10).each do |i| requests.push "https://api.github.com/users/#{user}/events?page=#{i}" end m = Curl::Multi.new m.pipeline = true # add a few easy handles requests.each do |url| responses[url] = "" c = Curl::Easy.new(url) do|curl| curl.headers["User-Agent"] = "d4l3k" curl.follow_location = true curl.on_body{|data| responses[url] << data; data.size } end m.add(c) end m.perform do puts "idling... can do some work here, including add new requests" end commits = [] responses.each do|url, data| events = MultiJson.load(data) events.each do |event| if event.is_a? Array binding.pry end if event["type"]=="PushEvent" commits += event["payload"]["commits"] end end end commits end def get_commit_info commits responses = {} m = Curl::Multi.new m.pipeline = true # add a few easy handles commits.each do |commit| url = commit["url"] responses[url] = "" c = Curl::Easy.new(url) do|curl| curl.headers["User-Agent"] = "d4l3k" curl.follow_location = true curl.on_body{|data| responses[url] << data; data.size } end m.add(c) end m.perform do puts "idling... can do some work here, including add new requests" end end end =begin get '/:user/' do commits = get_user_commits_multi params[:user] info = get_commit_info commits binding.pry end =end get '/:user/:repo/' do user = params[:user] repo = params[:repo] remote = "[email protected]:#{user}/#{repo}.git" puts remote system("git", "clone", "-n", remote, "/tmp/checkout/#{user}-#{repo}") text = `git_time_extractor /tmp/checkout/#{user}-#{repo}` data = CSV.parse(text) time = 0 commits = 0 data.each do |line| commits += 1 time += line[1].to_i end "Number of coding sessions: #{commits}, Hours: #{time/60.0}" end
true
6a7b0ce9a8841162043e76349bfb0c8f6e8b8e09
Ruby
adev73/siwapp
/lib/model_csv.rb
UTF-8
524
2.515625
3
[ "MIT" ]
permissive
require 'csv' module ModelCsv # Enumerator that generates csv lines def csv_stream(results, fields, meta_attributes_keys) Enumerator.new do |y| # header line y << CSV.generate_line(fields + meta_attributes_keys) # items results.includes(items: [:taxes]).find_each do |i| meta_attributes_values = meta_attributes_keys.map {|key| i.meta[key]} y << CSV.generate_line( fields.map {|field| i.send(field)} + meta_attributes_values ) end end end end
true
ebbd18956aad43a80376f169fd5b0bae27969b1c
Ruby
setonparish/flockbot
/lib/flockbot/errors.rb
UTF-8
788
2.640625
3
[ "MIT" ]
permissive
require "faraday" module Flockbot class FlockbotError < StandardError; end; class TransactionError < FlockbotError; end # # If the request to Flocknotes is an http status 200 response, but the action # being performed is not successful, Flocknote will return a { success: false } # status with an error, so raise this. # class CustomErrors < Faraday::Response::Middleware def on_complete(env) case env[:status] when 200 return unless env.response_headers["content-type"] == "application/json" json = env.body.is_a?(String) ? JSON.parse(env.body) : env.body return unless json.has_key?("success") if !json["success"] raise Flockbot::TransactionError.new(json["message"]) end end end end end
true
9f9e733faba333fce361193a659bf8ca890f84a3
Ruby
tonekk/link-grabber
/test/models/custom_attribute_test.rb
UTF-8
3,336
2.546875
3
[]
no_license
require 'test_helper' describe CustomAttribute do before do @custom_attribute = Fabricate.build(:custom_attribute, name: 'test', pretty_name: 'Test') end it "should return right value for metric :eq" do @custom_attribute.metrics = :eq build_test_values(@custom_attribute, 'A', 'foo', 'B', 'bar', 'C', 'baz') lead = Fabricate(:lead, data: {"test" => 'B'}) @custom_attribute.get_custom_value_for(lead).must_equal 'bar' end it "should return right value for metric :gt" do @custom_attribute.metrics = :gt build_test_values(@custom_attribute, '10', 'foo', '15', 'bar', '20', 'baz') lead1 = Fabricate(:lead, data: {"test" => 25}) lead2 = Fabricate(:lead, data: {"test" => 15}) lead3 = Fabricate(:lead, data: {"test" => 5}) # 25 is greater than 20, so 20 should be matched ('baz') @custom_attribute.get_custom_value_for(lead1).must_equal 'baz' # 15 is equal to 15, so 10 should be matched ('foo') @custom_attribute.get_custom_value_for(lead2).must_equal 'foo' # 5 is greater than none of the given values, should result in nil @custom_attribute.get_custom_value_for(lead3).must_equal nil end it "should return right value for metric :lt" do @custom_attribute.metrics = :lt build_test_values(@custom_attribute, '10', 'foo', '15', 'bar', '20', 'baz') lead1 = Fabricate(:lead, data: {"test" => 5}) lead2 = Fabricate(:lead, data: {"test" => 15}) lead3 = Fabricate(:lead, data: {"test" => 25}) # 5 is lower than 10, so 10 should be matched ('baz') @custom_attribute.get_custom_value_for(lead1).must_equal 'foo' # 15 is equal to 15, so 20 should be matched ('baz') @custom_attribute.get_custom_value_for(lead2).must_equal 'baz' # 25 is lower than none of the given values, should result in nil @custom_attribute.get_custom_value_for(lead3).must_equal nil end it "should return right value for metric :gte" do @custom_attribute.metrics = :gte build_test_values(@custom_attribute, '10', 'foo', '15', 'bar', '20', 'baz') lead1 = Fabricate(:lead, data: {"test" => 25}) lead2 = Fabricate(:lead, data: {"test" => 15}) # 25 is greater than 20, so 20 should be matched ('baz') @custom_attribute.get_custom_value_for(lead1).must_equal 'baz' # 15 is equal to 15, so 15 should be matched ('baz') @custom_attribute.get_custom_value_for(lead2).must_equal 'bar' end it "should return right value for metric :lte" do @custom_attribute.metrics = :lte build_test_values(@custom_attribute, '10', 'foo', '15', 'bar', '20', 'baz') lead1 = Fabricate(:lead, data: {"test" => 5}) lead2 = Fabricate(:lead, data: {"test" => 15}) # 5 is lower than 10, so 10 should be matched ('foo') @custom_attribute.get_custom_value_for(lead1).must_equal 'foo' # 15 is equal to 15, so 15 should be matched ('bar') @custom_attribute.get_custom_value_for(lead2).must_equal 'bar' end def build_test_values(custom_attribute, one, one_css, two, two_css, three, three_css) Fabricate.build(:custom_value, value: one, css: one_css, custom_attribute: custom_attribute) Fabricate.build(:custom_value, value: two, css: two_css, custom_attribute: custom_attribute) Fabricate.build(:custom_value, value: three, css: three_css, custom_attribute: custom_attribute) end end
true
d183830fddac0404fc1145c79186570d28fd7974
Ruby
ehayne00/ruby-enumerables-generalized-map-and-reduce-lab-london-web-102819
/lib/my_code.rb
UTF-8
291
3.34375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def map(array) new_array = [] i = 0 while i < array.length new_array.push(yield(array[i])) i+=1 end return new_array end def reduce(array, sv=nil) if sv sum = sv i=0 else sum= array[0] i=1 end while i<array.length sum = yield(sum, array[i]) i+=1 end sum end
true
59dfed1bb63671b08d43122ce45a4a710b3bc112
Ruby
afeld/facial
/lib/facial.rb
UTF-8
524
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'rubygems' require 'opencv' include OpenCV module Facial class << self def detect image_path # initialize the detector, if it wasn't already @detector ||= CvHaarClassifierCascade::load(File.expand_path(File.dirname(__FILE__) + '/../data/haarcascade_frontalface_alt.xml')) image = IplImage::load image_path @detector.detect_objects(image).map do |rect| { top_left: rect.top_left, bottom_right: rect.bottom_right } end end end end
true
1efe23ce59ab2e5cd74ba724496f560bfda832c8
Ruby
mserino/Email-predictor
/lib/analyzer.rb
UTF-8
1,141
3.15625
3
[]
no_license
require_relative 'error' require_relative 'constants' class Analyzer attr_accessor :pattern def initialize @pattern = {} end def get(name) name.split('@')[0] end def find(string) @name, @lastname = string.split('.') [name_pattern, lastname_pattern].join('_dot_').to_sym end def convert(pattern) string = get(pattern) find(string) end def match(company) emails = DATA.values pattern[company] ||= [] emails.map do |email| name = get(email) pattern[company] << convert(name) if email.include? company end pattern[company].uniq! end def to_email(name, pattern) @first_part, @last_part = name.split(' ') @pattern_first, @pattern_last = pattern.to_s.split('_dot_') [first_part, last_part].join('.') end private def name_pattern @name.length == 1 ? 'first_initial' : 'first_name' end def lastname_pattern @lastname.length == 1 ? 'last_initial' : 'last_name' end def first_part @pattern_first.to_sym == :first_name ? @first_part.downcase : @first_part[0].downcase end def last_part @pattern_last.to_sym == :last_name ? @last_part.downcase : @last_part[0].downcase end end
true
a1948eb780f245713cb88cf84f890031f6420dc6
Ruby
ibanzajoe/m3fasdf
/volumes/bundler/gems/neatjson-0.7.1/test/test_neatjson.rb
UTF-8
787
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require_relative '../lib/neatjson' require_relative './tests' start = Time.now pass = 0 count = 0 TESTS.each do |value_tests| val, tests = value_tests[:value], value_tests[:tests] tests.each do |test| cmd = test[:opts] ? "JSON.neat_generate(#{val.inspect},#{test[:opts].inspect})" : "JSON.neat_generate(#{val.inspect})" begin json = test[:opts] ? JSON.neat_generate(val,test[:opts].dup) : JSON.neat_generate(val) raise "EXPECTED:\n#{test[:json]}\nACTUAL:\n#{json}" unless test[:json]===json pass += 1 rescue StandardError => e puts "Error running #{cmd}", e, "" end count += 1 end end elapsed = Time.now-start elapsed = 0.0001 if elapsed==0 puts "%d/%d test#{:s if count!=1} passed in %.2fms (%d tests per second)" % [pass, count, elapsed*1000, count/elapsed]
true
bf644a3eb81b66192b3343f7355f69a70fd9086e
Ruby
havok2905/gitfolio
/lib/classes/repo_sync.rb
UTF-8
695
2.609375
3
[]
no_license
class RepoSync def initialize(user, api) @user = user @api = api end def run @user.update_attributes repos: repo_list end private def language(args) RepoLanguage.where(args).first_or_create(args) end def repo_list @api.repo_data(username: @user.nickname).map do |r| repo = Repo.where(user_id: @user.id, name: r[:name]).first_or_create repo.update_attributes( url: r[:url], description: r[:description], name: r[:name], user_id: @user.id ) r[:languages].each do |key, value| repo.repo_languages << language(name: key, bytes: value, repo_id: repo.id) end repo end end end
true
556e3b5b231da2b37bd1e4d4f1c8f956714dc276
Ruby
wolfemm/email_assessor
/lib/email_assessor.rb
UTF-8
1,181
2.8125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "email_assessor/email_validator" module EmailAssessor DISPOSABLE_DOMAINS_FILE_NAME = File.expand_path("../../vendor/disposable_domains.txt", __FILE__) FASTPASS_DOMAINS_FILE_NAME = File.expand_path("../../vendor/fastpass_domains.txt", __FILE__) EDUCATIONAL_DOMAINS_FILE_NAME = File.expand_path("../../vendor/educational_domains.txt", __FILE__) BLACKLISTED_DOMAINS_FILE_NAME = File.expand_path("vendor/blacklisted_domains.txt") def self.domain_is_disposable?(domain) domain_in_file?(domain, DISPOSABLE_DOMAINS_FILE_NAME) end def self.domain_is_blacklisted?(domain) domain_in_file?(domain, BLACKLISTED_DOMAINS_FILE_NAME) end def self.domain_in_file?(domain, file_name) any_token_in_file?(tokenize_domain(domain), file_name) end def self.any_token_in_file?(domain_tokens, file_name) file_name ||= "" File.foreach(file_name, chomp: true).any? do |line| domain_tokens.key?(line) end end def self.tokenize_domain(domain) parts = domain.downcase.split(".") tokens = {} parts.length.times do tokens[parts.join(".")] = nil parts.shift end tokens end end
true
c75ba2d2d63648975728aa91da88221fd0d49c3c
Ruby
quiettimes03/Kele
/lib/kele.rb
UTF-8
2,080
2.65625
3
[ "MIT" ]
permissive
require 'HTTParty' require 'json' require './lib/roadmap.rb' class Kele include HTTParty include Roadmap base_uri 'https://www.bloc.io/api/v1/' def initialize(email, password) @email, @password = email, password response = self.class.post(api_url("sessions"), body: { "email": email, "password": password }) raise InvalidStudentCode.new() if response.code == 401 @auth_token = response["auth_token"] end def get_me response = self.class.get(api_url("users/me"), user_auth_token) @user_data = JSON.parse(response.body) end def get_mentor_availability(mentor_id) response = self.class.get(api_url("mentor/#{mentor_id}/student_availability"), user_auth_token) @mentor_availability = JSON.parse(response.body) end def get_messages(page_num) if page_num == nil response = self.class.get(api_url("message_threads"), user_auth_token) @list_of_messages = JSON.parse(response.body) else response = self.class.get(api_url("message_threads/#{page_num}"), user_auth_token) @list_of_messages = JSON.parse(response.body) end end def create_messages(sender, recipient_id, token, subject, text) response = self.class.post(api_url("messages"), body: { "sender": sender, "recipient_id": recipient_id, "token": token, "subject": subject, "text": text }, headers: { authorization => @auth_token}) puts response end def create_submission(checkpoint_id, assignment_branch, assignment_commit_link, comment, enrollment_id) response = self.class.post(api_url("checkpoint_submissions"), body: { "checkpoint_id": checkpoint_id, "assignment_branch": assignment_branch, "assignment_commit_link": assignment_commit_link, "comment": comment, "enrollment_id": enrollment_id }, headers: { "authorization" => @auth_token }) puts response end def api_url(endpoint) "https://www.bloc.io/api/v1/#{endpoint}" end def user_auth_token {headers: { authorization: @auth_token}} end end
true
3c452f44f18fd5138e560f228fb2a1baa188aaa2
Ruby
pcahalane/launch_school
/lesson_3/pp_easy_2/010.rb
UTF-8
197
2.890625
3
[]
no_license
# QUESTION 10: # Center the given title across 40 characters #-----------------------------------------------------------------------------# title = "Flintstone Family Members" p title.center(40)
true
210c02357b4408b31b881bbdeb0a078b63d7abd8
Ruby
ireneybean/advent-of-code
/2019/2.rb
UTF-8
2,013
4.15625
4
[]
no_license
# An Intcode program is a list of integers separated by commas (like 1,0,0,3,99). To run one, start by looking at # the first integer (called position 0). Here, you will find an opcode - either 1, 2, or 99. The opcode indicates # what to do; for example, 99 means that the program is finished and should immediately halt. Encountering an # unknown opcode means something went wrong. # Opcode 1 adds together numbers read from two positions and stores the result in a third position. The three # integers immediately after the opcode tell you these three positions - the first two indicate the positions # from which you should read the input values, and the third indicates the position at which the output # should be stored. # Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them. Again, # the three integers after the opcode indicate where the inputs and outputs are, not their values. # Once you're done processing an opcode, move to the next one by stepping forward 4 positions. require './lib/common.rb' require './lib/intcode_program.rb' def test_intcode(input) program = Intcode::Program.new(input) program.run program.memory end AdventOfCode::test([2,0,0,0,99]) { test_intcode([1,0,0,0,99]) } AdventOfCode::test([2,3,0,6,99]) { test_intcode([2,3,0,3,99]) } AdventOfCode::test([2,4,4,5,99,9801]) { test_intcode([2,4,4,5,99,0]) } AdventOfCode::test([30,1,1,4,2,5,6,0,99]) { test_intcode([1,1,1,4,99,5,6,0,99]) } intcode = AdventOfCode::inputs(2).first.split(',').map!(&:to_i) output = 0 noun = -1 while output != 19690720 && noun < 100 noun = noun + 1 intcode[1] = noun verb = -1 while output != 19690720 && verb < 100 do verb = verb + 1 intcode[2] = verb program = Intcode::Program.new(intcode) output = begin program.run program.memory[0] rescue => e puts e program.memory[0] end end end if output == 19690720 puts 100 * noun + verb else puts "didn't find it" end
true
ab390e6e89b945bdf1ca9aff139aedcf246984f5
Ruby
Sheshaw/oxford-comma-onl01-seng-pt-030220
/lib/oxford_comma.rb
UTF-8
312
3.1875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) if array.size == 2 array[-2] << " and " array.join elsif array.size == 1 array.join elsif array.size > 2 array[-1].prepend "and " #the prepend method will add to #the element array.join(", ") end end
true
69b2fad5190b6384fccef36648522f69948db728
Ruby
frogstarr78/sandbox
/ruby/pegt.rb
UTF-8
655
2.828125
3
[]
no_license
require 'rubygems' require 'treetop' require 'colored' Treetop.load "arithmetic" parser = ArithmeticParser.new if parser.parse('1+2') puts 'success' else puts 'failure' end #puts parser.parse('1+1').klass #puts parser.index parsed = parser.parse('1+2') puts parsed.elements.collect(&:inspect), parsed.inspect, '', ' multitive ' << parsed.multitive.inspect, ' additive ' << parsed.additive.inspect, parsed.instance_variables.sort #puts parser.klass puts '-'*10 puts parser.parse('1+2').value puts parser.parse('(1+3)*4') ? 'y'.green : 'n'.red puts parser.parse('(1+3)').value puts parser.parse('(1+3)*4').value #puts parser.parse('(1+3)*4').value
true
359beb991d170eaed80f8f3f5e4f179ab0109ce3
Ruby
kjleitz/brainfuck_ruby
/lib/brainfuck_ruby/errors.rb
UTF-8
2,161
3.03125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module BrainfuckRuby class Error < StandardError; end # Internal interpreter error class InternalError < BrainfuckRuby::Error def initialize(message = "Something went wrong") super(message) end end # Cursor is negative or past the end of the file class CursorOutOfBoundsError < BrainfuckRuby::Error def initialize(message = "Cursor position out of bounds") super(message) end end # Cursor is negative class CursorBeforeBeginningOfFileError < BrainfuckRuby::CursorOutOfBoundsError def initialize(message = "Cursor position cannot go below zero") super(message) end end # Cursor is past the end of the file class CursorAfterEndOfFileError < BrainfuckRuby::CursorOutOfBoundsError def initialize(message = "Cursor position cannot go past the end of the program") super(message) end end # Syntax error in the brainfuck code class SyntaxError < BrainfuckRuby::Error def initialize(message = "Invalid brainfuck syntax") super(message) end end # A bracket doesn't have a corresponding bracket to close the group class UnmatchedBracketError < BrainfuckRuby::SyntaxError def initialize(message = "Bracket has no partner", line: nil, column: nil, snippet: nil) position = "(line: #{line || 'unknown'}, column: #{column || 'unknown'})" snippet_lines = snippet && "\n#{snippet}" super("#{message} #{position}#{snippet_lines}") end end # Open bracket without a matching closing bracket class UnmatchedOpenBracketError < BrainfuckRuby::UnmatchedBracketError def initialize(message = "Opening bracket has no corresponding closing bracket", line: nil, column: nil, snippet: nil) super(message, line: line, column: column, snippet: snippet) end end # Close bracket without a matching opening bracket class UnmatchedClosingBracketError < BrainfuckRuby::UnmatchedBracketError def initialize(message = "Closing bracket has no corresponding opening bracket", line: nil, column: nil, snippet: nil) super(message, line: line, column: column, snippet: snippet) end end end
true
1cf1e96ac82a97bbfffb72f56b713508f7ec7e56
Ruby
davidrajnus/Algorithms-In-Ruby
/spec/anagram_spec.rb
UTF-8
696
2.8125
3
[]
no_license
require './anagram' RSpec.describe '#anagram' do it '"hello" is an anagram of "llohe"' do expect(anagram('hello', 'llohe')).to be_truthy end it '"Whoa! Hi!" is an anagram of "Hi! Whoa!"' do expect(anagram('Whoa! Hi!', 'Hi! Whoa!')).to be_truthy end it '"One One" is not an anagram of "Two two two"' do expect(anagram('One One', 'Two two two')).to be_falsy end it '"One one" is not an anagram of "One one c"' do expect(anagram('One one', 'One one c')).to be_falsy end it '"A tree, a life, a bench" is not an anagram of "A tree, a fence, a yard"' do expect( anagram('A tree, a life, a bench', 'A tree, a fence, a yard') ).to be_falsy end end
true
48b38da115443adb15cb82563a4a98af26f1e787
Ruby
dangerstephen/ruby_method_drills
/starter-code/numbers.rb
UTF-8
1,197
3.59375
4
[]
no_license
############################## #### MANIPULATING NUMBERS #### ############################## def count_to(number) number = number.to_i if number >= 0 (0..number).to_a else 0.downto(number).to_a end end #is_integer? # takes in a number # returns true for Fixnums and Bignums (whole number or 'integer' types) # returns true for Floats (decimals) equal to integers # returns false for non-integer decimals # returns false for Float::NAN # returns false for non-numbers #is_prime? # takes in a number and checks if it's prime # returns false for non-integer decimals # returns false for numbers less than or equal to 1 # returns false for numbers divisible by anything but 1 and themselves # returns true for prime numbers # Hint: google prime numbers! #primes_less_than # takes in a number # returns an empty array if there are no primes below num # does not return the number itself # finds all primes less than the given number ## STRETCH ## #iterative_factorial # takes in a number # returns 1 for 0 and 1 # returns NaN for numbers less than 0 # returns NaN for non-integers # calculates and returns the factorial of the input number
true
9e21aee7cc02695c7bb9db980aceaeff0dc92369
Ruby
abruzzim/RockSolid
/db/seeds.rb
UTF-8
5,797
2.640625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Cargo.delete_all Address.delete_all # Add New Customer with linked (new) Address. class CustomersRow def initialize @cust_street = Faker::Address.street_address @cust_city = Faker::Address.city @cust_state = Faker::Address.state_abbr @cust_zip = Faker::Address.zip @cust_name = Faker::Name.last_name end def populate Address.create({ street: @cust_street, city: @cust_city, state: @cust_state, zip: @cust_zip, customer_id: Customer.create({name: @cust_name}).id }) puts "%SEED-I-CUSTOMERS, attempting row add." # Answers: # Customer.last.addresses[0]["street"] # Customer.find(7).addresses.first.street # Customer.where(name: "Koepp").first.addresses.where(state: "MN").first.street end end Customer.delete_all 10.times {CustomersRow.new.populate} # Add New Order with (linked) new Cargo and (linked) new Rock class OrderRow def initialize @seeds = [ {type: "Igneous", grade: "High", form: "Slab", thickness: 2, price: 50.00, qty: 5, ordnum: "Q00123"}, {type: "Igneous", grade: "Med", form: "Slab", thickness: 2, price: 40.00, qty: 7, ordnum: "Q00456"}, {type: "Igneous", grade: "Low", form: "Slab", thickness: 2, price: 30.00, qty: 9, ordnum: "Q00789"}, {type: "Igneous", grade: "High", form: "Gravel", thickness: nil, price: 99.88, qty: 25, ordnum: "Q06789"}, {type: "Igneous", grade: "Low", form: "Gabion", thickness: 2, price: 13.76, qty: 9, ordnum: "Q08765"}, ] end def populate @seeds.each do |seed| Rock.create({ rtype: seed[:type], rgrade: seed[:grade], rform: seed[:form], rthickness: seed[:thickness], unit_price: seed[:price], cargo_id: Cargo.create({ quantity: seed[:quantity], order_id: Order.create({ order_num: seed[:ordnum], }).id }).id }) puts "%SEED-I-ORDERS, attempting row add." # Answers: # Order.find(2).cargo.quantity.to_f # Order.find(2).cargo.rock.unit_price.to_f end end end Order.delete_all #OrderRow.new.populate # Add New Delivery with (linked) new Customer, Order, Cargo and Rock class DeliveriesRow def initialize @seeds = [ {type: "Igneous", grade: "Med", form: "Slab", thickness: 2, price: 90.00, qty: 4, ordnum: "Q00765", sdate: "2014-01-29"}, {type: "Igneous", grade: "High", form: "Slab", thickness: 2, price: 90.35, qty: 2, ordnum: "Q00799", sdate: "2014-02-15"} ] end def populate @seeds.each do |seed| Rock.create({ rtype: seed[:type], rgrade: seed[:grade], rform: seed[:form], rthickness: seed[:thickness], unit_price: seed[:price], cargo_id: Cargo.create({ quantity: seed[:quantity], order_id: Order.create({ order_num: seed[:ordnum], customer_id: Customer.create({ name: Faker::Name.last_name, }).id, delivery_id: Delivery.create({ ship_date: seed[:sdate] }).id }).id, }).id }) puts "%SEED-I-DELIVERIES, attempting row add." end end end Delivery.delete_all #DeliveriesRow.new.populate # Add Rock class RockRow def initialize @seeds = [ {type: "Sedimentary", grade: "Med", form: "Silt", thickness: nil, price: 23.45, qty: 1, ordnum: "Q98765"}, {type: "Sedimentary", grade: "High", form: "Sand", thickness: nil, price: 13.45, qty: 5, ordnum: "Q48484"}, {type: "Igneous", grade: "Med", form: "Gravel", thickness: nil, price: 123.45, qty: 11, ordnum: "Q10100"}, {type: "Igneous", grade: "High", form: "Gabion", thickness: nil, price: 103.45, qty: 8, ordnum: "Q73737"}, {type: "Igneous", grade: "High", form: "Boulder", thickness: nil, price: 323.45, qty: 3, ordnum: "Q63017"} ] end def populate @seeds.each do |seed| Rock.create({ rtype: seed[:type], rgrade: seed[:grade], rform: seed[:form], rthickness: seed[:thickness], unit_price: seed[:price] }) puts "%SEED-I-ROCKS, attempting row add." end end end Rock.delete_all #RockRow.new.populate # Add New Drivers. class DriversRow def initialize end def populate Driver.create({ name: Faker::Name.first_name }) puts "%SEED-I-DRIVERS, attempting row add." end end Driver.delete_all 3.times {DriversRow.new.populate} # Add New Trucks. class TrucksRow def initialize @seeds = [ {plate: "QRY-123", capacity: 25}, {plate: "QRY-234", capacity: 25}, {plate: "QRY-456", capacity: 25}, {plate: "QRY-678", capacity: 25}, {plate: "QRY-890", capacity: 25} ] end def populate @seeds.each do |seed| Truck.create({ lic_plate: seed[:plate], capacity: seed[:capacity] }) puts "%SEED-I-TRUCKS, attempting row add." end end end Truck.delete_all TrucksRow.new.populate
true
8bb02ab572f6f42cd482b3b5266d79234f57b00b
Ruby
dojomaringa/dojo_20121130
/nome_spec.rb
UTF-8
1,446
3.203125
3
[]
no_license
require_relative "nome" describe "Escolha o nome do seu filho" do context "Calcula a distancia entre duas palavras" do it "A distancia entre A e A deve ser 0" do Nome.calcula_distancia("A", "A").should == 0 end it "A distancia entre A e B deve ser 1" do Nome.calcula_distancia("A", "B").should == 1 end it "A distancia entre C e B deve ser 1" do Nome.calcula_distancia("C", "B").should == 1 end it "A distancia entre a e A deve ser 0" do Nome.calcula_distancia("a", "A").should == 0 end it "A distancia entre Z e a deve ser 25" do Nome.calcula_distancia("Z", "a").should == 25 end it "A distancia entre AA e AA deve ser 0" do Nome.calcula_distancia("AA", "AA").should == 0 end it "A distancia entre AA e AC deve ser 2" do Nome.calcula_distancia("AA", "AC").should == 2 end it "A distancia entre ABC e AB deve ser 13" do Nome.calcula_distancia("ABC", "AB").should == 13 end it "A distancia entre ab e ABC deve ser 13" do Nome.calcula_distancia("ab", "ABC").should == 13 end end context "Calcula nome menos distante" do it "Para [Amanda, Bruna, Camila] com palavra_base Jose deve escolher Bruna" do Nome.calcula_nome("Jose", ["Amanda", "Bruna", "Camila"]).should == "Bruna" end it "Para [Amanda, Bruna, Camila] com palavra_base Camila deve escolher Camila" do Nome.calcula_nome("Camila", ["Amanda", "Bruna", "Camila"]).should == "Camila" end end end
true
01eaff5b7e38bb38e62b801098635f201710480f
Ruby
mellejwz/ruby-opdrachten
/8.3.rb
UTF-8
153
3.75
4
[]
no_license
puts 'Type some words and press enter after each one' array = [] words = ' ' while words != '' words = gets.chomp array.push words end puts array.sort
true
4c57ea4c27de58f5d255ca7e871a63e065658f17
Ruby
Nish8192/Ruby_on_Rails
/TDD/RubyTDD/AppleTree/AppleTree_Spec.rb
UTF-8
1,372
3.1875
3
[]
no_license
require_relative 'AppleTree' RSpec.describe AppleTree do before (:each) do @tree = AppleTree.new end it "should have an age attribute w/ getter and setter methods" do age = @tree.age @tree.age = 10 end it "should have height and age attributes w/ only getter methods" do expect{@tree.height = 5}.to raise_error(NoMethodError) expect{@tree.apple = 5}.to raise_error(NoMethodError) height = @tree.height apple = @tree.apple end it "should have a method called yearGoneBy that adds one year to age, increases the height by %10 and raises the apple count by two" do @tree.yearGoneBy @tree.age.should be 1 @tree.height.should be 11.0 @tree.yearGoneBy.yearGoneBy.yearGoneBy @tree.apple.should be 2 end it "should not grow apples for the first three years of its life" do @tree.yearGoneBy @tree.apple.should_not be > 0 end it "should have a method called pick_apples that takes all of the apples off the tree" do @tree.yearGoneBy.yearGoneBy.yearGoneBy.yearGoneBy.yearGoneBy.yearGoneBy @tree.pick_apples @tree.apple.should be 0 end it "should not grow apples if the tree is older than 10" do @tree.age = 11 @tree.yearGoneBy @tree.apple.should be 0 end end
true
85b4b3cad90300d11b10824430c9223b33082071
Ruby
albowen/FirstRailsTTS
/app/models/home.rb
UTF-8
112
2.546875
3
[]
no_license
class Home def name name = "Ashley" end def birthdate birthdate = Date.new(1985,6,02) end end
true
213f17d33eb5b06648de4ed2732b069cc5187dd2
Ruby
travisofthenorth/euler
/lib.rb
UTF-8
520
3.5
4
[]
no_license
module Euler def factors(n) (Math.sqrt(n)).ceil.downto(1).select { |d| n % d == 0 }.inject([]) do |factors, d| factors << n / d if d != n / d factors << d end end def proper_divisors(n) factors(n) - [n] end def prime?(n) (2..Math.sqrt(n)).each { |d| return false if n % d == 0 } true end def primes(array) array.select { |x| prime?(x) } end def sum_digits(n) n.to_s.chars.map(&:to_i).inject(:+) end def factorial(n) n.downto(2).inject(:*) end end
true
f8ff9f2a866c973589a12e7773a88ee1782bbbd2
Ruby
JuliaFranzoi/HWw2d1
/student.rb
UTF-8
639
3.03125
3
[]
no_license
class Student # attr_reader :account_holder #we use reader because it won't change attr_accessor :favourite_language def initialize(name, cohort, can_talk, favourite_language) @name = name @cohort = cohort @can_talk = can_talk @favourite_language = favourite_language end def name return @name end def cohort return @cohort end def can_talk return @can_talk end def say_favourite_language return "I love #{@favourite_language}" end def change_name(new_name) return @name = new_name end def change_cohort(new_cohort) return @cohort = new_cohort end end
true
bba33c958a187eacc642b6d3613e35bdfe4dd0a0
Ruby
DoriansGrave/collections_practice-v-000
/collections_practice.rb
UTF-8
914
4
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort do | down, up | up <=> down end end def sort_array_char_count(array) array.sort do | down, up | down.length <=> up.length end end def swap_elements(array) array[1], array[2] = array[2], array[1] array end def reverse_array(array) array.reverse end def kesha_maker(array) array.each do |string| string[2] = "$" end end def find_a(array) array.select do |string| string[0] == "a" end end def sum_array(array) sum = 0 array.each do |num| sum+=num end sum end # using reduce method # array.reduce(:+) # using inject method (short) # array.inject(:+) # using inject method (long) # array.inject do |sum,x| # sum + x # end def add_s(array) array.collect do |string| if array[1] == string string else string + "s" end end end
true
7d18f9b10fbcabc9a56bd95b01dcbc9c328b9d51
Ruby
davidpera/prueba
/dividir.rb
UTF-8
152
3.859375
4
[]
no_license
print "Introduce el primer numero: " n1 = gets.chomp.to_i print "Introduce el segundo numero: " n2 = gets.chomp.to_i puts "El resultado es #{n1 / n2}."
true
8264a36e5888b733bc8eb53e8f7310f9e9efc9c3
Ruby
hamjahb/lesson-w07d03-ruby-oop
/test/bird.rb
UTF-8
215
3.03125
3
[]
no_license
require './animal' class Bird < Animal def move super + ' by fly!' end def whats_the_word @the_answer end end big_bird = Bird.new puts big_bird.move puts big_bird.whats_the_word
true
eea8f91b9e60d0b1f21768dd0aa8bee4a6c6c529
Ruby
SWEN30006-Group-31/WeatherPrediction
/app/models/postcode.rb
UTF-8
1,627
2.921875
3
[]
no_license
# vim:sw=2:sts=2:et class Postcode < ActiveRecord::Base has_many :locations has_many :observations, :through => :locations has_many :predictions, :through => :locations #TODO: Put the distance code into a separate module for re-use. def self.get_nearest lat, lon #Sorts Postcode in place according to distance from lat, long, and then #returns the head of that list. (Postcode.all.sort_by { |pcode| #Based on: http://www.movable-type.co.uk/scripts/latlong.html r = 6381000 phi1 = lat * Math::PI / 180 phi2 = pcode.lat * Math::PI / 180 dPhi = (pcode.lat - lat) * Math::PI / 180 dLambda = (pcode.lon - lon) * Math::PI / 180 a = Math.sin(dPhi/2) * Math.sin(dPhi/2) * Math.cos(phi1) * Math.cos(phi2) * Math.sin(dLambda/2) * Math.sin(dLambda/2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) d = r * c }).first end def get_best_location #Gets the location associated with the postcode that is #closest to the postcode's co-ordinates. (self.locations.where(active: true).sort_by { |loc| #Based on: http://www.movable-type.co.uk/scripts/latlong.html r = 6381000 phi1 = self.lat * Math::PI / 180 phi2 = loc.lat * Math::PI / 180 dPhi = (loc.lat - self.lat) * Math::PI / 180 dLambda = (loc.lon - self.lon) * Math::PI / 180 a = Math.sin(dPhi/2) * Math.sin(dPhi/2) * Math.cos(phi1) * Math.cos(phi2) * Math.sin(dLambda/2) * Math.sin(dLambda/2) c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) d = r * c }).first end end
true
f8da39581d0fbf6ba14b134858ba134430ce7fdb
Ruby
ravjohal/comparifier
/app/models/category.rb
UTF-8
3,119
2.765625
3
[]
no_license
require 'rubygems' require 'rexml/document' require 'happymapper' class Category < ActiveRecord::Base has_many :comparifier_attributes has_many :items include REXML #include HappyMapper # #tag 'BrowseNode' #element :vendorCategoryId, String, :tag=>'BrowseNodeId' #element :name, String, :tag=>'Name' #has_one :children, Children # this is being used for the xml way... def from_xml(xml, searchIndex) browse_categories = [] # Will take in each BrowseNode element //BrowseNodeLookupResponse/BrowseNodes/BrowseNode # parentId = xml.elements['BrowseNodeId[1]'].text # parentName = xml.elements['Name[1]'].text parentId = xml.attributes['BrowseNodeId'] parentName = xml.attributes['Name'] p "name: " + parentName + " id: " + parentId + " !!!!!!!" xml.each_element("//Children/BrowseNode"){|element| browseNodeId = element.attributes['BrowseNodeId'] name = element.attributes['Name'] category = Category.new category.name = name category.description = name + " " + browseNodeId category.vendorCategoryId = browseNodeId category.vendor = "Amazon" category.parentCategoryId = parentId category.searchIndex = searchIndex category.parentCategoryName = parentName category.operation = "BrowseNodeLookup" puts "\n NAME: \n" + name + " \n"; #I am not including any general categories that were requested into the array that will be sent off to Flex # if name != "" && !(requestBrowseIds.include?(browseNodeId)) browse_categories.push(category) ## category.save # end } browse_categories end # This method is being used by the Product Advertising Gem: def extract_children(category_response, searchIndex) # log = Logger.new('../log/debug.log') browse_categories = [] category_response.response.browse_nodes.each{|top_browse_nodes| parentId = top_browse_nodes.browse_node_id parentName = top_browse_nodes.name # log.debug "\n Top Browse Node Name: " + top_browse_nodes.name.to_s + "\n" #Since the calls are dynamic, i need to handle the noMethodError because children is not always a method that's part of the top_browse_nodes object begin top_browse_nodes.children.each{|child| puts "\n >>>>>>Child Name: " + child.name.to_s + "\n" browseNodeId = child.browse_node_id name = child.name category = Category.new category.name = name category.description = name + " " + browseNodeId category.vendorCategoryId = browseNodeId category.vendor = "Amazon" category.parentCategoryId = parentId category.searchIndex = searchIndex #puts "\n IN CATEGORY OBJECT SEARCHINDEX: " + category.searchIndex + " \n\n" category.parentCategoryName = parentName category.operation = "BrowseNodeLookup" browse_categories.push(category) } rescue NoMethodError next end } browse_categories end end
true
4cb386b77421befd556cf1670a23829ea26438b3
Ruby
georuiz817/collections_practice-online-web-ft-061019
/collections_practice.rb
UTF-8
710
3.8125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort end def sort_array_desc(array) array.sort.reverse end def sort_array_char_count(array) array.sort_by {|x| x.length} end def swap_elements(array) array[1],array[2] = array[2], array[1] return array end def reverse_array(array) array.reverse end def kesha_maker(array) kesha = [] array.each do |word| word_array = word.split "" word_array[2] = "$" kesha << word_array.join end kesha end def find_a(array) array.select {|i| i.start_with?("a")} end def sum_array(array) array.sum end def add_s(array) array.each_with_index.collect do |string, index| if index == 1 string else string << "s" end end end
true
2957bac3af6413ea031392464e1b940ab4e94583
Ruby
tdooner/tomstats
/models/daily_spreadsheet_entry.rb
UTF-8
1,077
2.640625
3
[]
no_license
class DailySpreadsheetEntry < ActiveRecord::Base LEGACY_ENTRY_TYPES = { 'How was today? [Good]' => :how_good, 'How was today? [Unique]' => :how_unique, 'How was today? [Productive]' => :how_productive, 'Who did you hang out with?' => :hung_out_with, 'How many glasses of alcohol today?' => :glasses_alcohol, } scope :last_365_days, -> { where('date > ?', Date.today - 365) } def self.create_from_row(row) date = if row['Timestamp'].include?(' ') DateTime.strptime(row['Timestamp'], '%m/%d/%Y %T') else DateTime.strptime(row['Timestamp'], '%m/%d/%Y') end if date.hour <= 12 date = date - 1 end row.each do |col, type| next if col == 'Timestamp' entry_name = LEGACY_ENTRY_TYPES.fetch(col) do |entry_type| entry_type.downcase.scan(/\w+/).first(5).join('_') end entry = DailySpreadsheetEntry .where(date: date.to_date, entry_type: entry_name) .first_or_create entry.update_attributes(value: row[col]) end end end
true
9b57b918f9928eb578e95e3d54290839b670691d
Ruby
tfb34/learn_ruby
/02_calculator/calculator.rb
UTF-8
434
3.578125
4
[]
no_license
#write your code here def add(num,num2) return num+num2 end def subtract(num,num2) return num-num2 end def sum(list) i=0 sum=0 while i<list.size do sum=sum+list[i] i+=1 end return sum end def multiply(num) i=0 total=1 while i<num.size do total*=num[i] i+=1 end return total end def power(num,num2) return num**num2 end def factorial(num) total=1 while num>0 do total*=num num-=1 end return total end
true
8a3eff0411ca00a4fd09c1a93964272e5be5c6bf
Ruby
mwagner19446/wdi_work
/w06/d05/Cory/minesweeper/lib/minesweeper.rb
UTF-8
444
3.046875
3
[]
no_license
class Minesweeper def initialize(rows, cols) @rows = rows @cols = cols @board = Array.new(@rows) {Array.new(@cols, 0)} return true end def rows return @rows end def cols return @cols end def board return @board end def has_mines board = [[1, 0, 0], [0, 0, 0], [0, 0, 0]] return board end end class Cell def initialize(value, status) end def value return @value end end
true
cc5c8587c894a2d2699a085cdf148c0e82961fe7
Ruby
alex-handley/cryptopals-ruby
/set_1/crypto_helpers.rb
UTF-8
85
2.546875
3
[]
no_license
class CryptoHelpers def hex_to_base64(hex) [[hex].pack("H*")].pack("m0") end end
true
388552f6b917a1e7fb804a22318b1d03b34399bf
Ruby
michalmuskala/janusze
/app/models/project_location.rb
UTF-8
1,399
2.71875
3
[]
no_license
# == Schema Information # # Table name: project_locations # # id :integer not null, primary key # state :string(255) # city :string(255) # street :string(255) # street_number :string(255) # longitude :float # latitude :float # project_id :integer # created_at :datetime # updated_at :datetime # # Indexes # # index_project_locations_on_project_id (project_id) # class ProjectLocation < ActiveRecord::Base STATES = Carmen::Country.coded('PL').subregions STATE_NAME_TO_CODE = Hash[STATES.map { |state| [state.name, state.code.downcase] }] STATE_NAME_TO_CODE_DOWNCASED = Hash[STATES.map { |state| [state.name.mb_chars.downcase.normalize.to_s, state.code.downcase] }] CODE_TO_STATE = Hash[STATES.map { |state| [state.code.downcase, state] }] belongs_to :project geocoded_by :address after_validation :geocode def address [state, city, "#{street} #{street_number}"].reject(&:blank?).join(', ') end def coords {lat: latitude, lng: longitude} end def self.state_name_to_code(state_name) STATE_NAME_TO_CODE_DOWNCASED[state_name.mb_chars.downcase.normalize.to_s] end def self.code_to_state(state_code) CODE_TO_STATE[state_code.downcase] end def self.code_to_state_name_downcased(state_code) CODE_TO_STATE[state_code.downcase].name.mb_chars.downcase.normalize.to_s end end
true
788329644e1224db7e69234fce78a2b0cbedf18c
Ruby
alexlev1/pick_a_card_game
/pick_a_card.rb
UTF-8
364
3.953125
4
[]
no_license
puts "Pick a Card!" values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] suits = ["\u2660", "\u2661", "\u2663", "\u2662"] cards = [] values.each do |value| suits.each do |suit| cards << "#{value} of #{suit}" end end cards.shuffle! puts "How many cards do you pick?" number = STDIN.gets.to_i number.times do puts cards.pop end
true
00be124864e1bbc70b3083ec00364e680fe5cd89
Ruby
UCLeuvenLimburg/apt-course-material
/samples/ruby/grading/test.rb
UTF-8
520
3.234375
3
[]
no_license
require_relative 'functional.rb' require_relative 'imperative.rb' require_relative '01-find-if.rb' Evaluation = Struct.new :student, :grade, :course N = 20 rnd = Random.new courses = ['bop', 'oop', 'ooo', 'vgo', 'pvm'] evaluations = (1..N).map do id = "r#{rnd.rand(1000).to_s.rjust(3, '0')}" grade = (rnd.rand.then { |x| 1 - x**2 } * 20).round course = courses[rnd.rand(courses.size)] Evaluation.new id, grade, course end p functional(evaluations) p imperative(evaluations) p findif(evaluations)
true
b1b596a4b3d7926a6be3bd0de2a2fb69cf39429a
Ruby
4rlm/SDF2
/lib/tools/csv/serv_csv_import.rb
UTF-8
4,388
2.546875
3
[]
no_license
module ServCsvImport ############## BEST CSV IMPORT METHOD ##################### # RESTORE BACKUP METHODS BELOW - VERY QUICK PROCESS !!! # Re-Imports previously exported, formatted CSVs w/ ids, joins, assoc. # Imports CSV from: db/csv/backups/file_name.csv ########################################################### #CALL: ServCsvTool.new.restore_all_backups def restore_all_backups db_table_list = get_db_table_list db_table_list_hashes = db_table_list.map do |table_name| { model: table_name.classify.constantize, plural_model_name: table_name.pluralize } end db_table_list_hashes.each do |hsh| hsh[:model].delete_all ActiveRecord::Base.connection.reset_pk_sequence!(hsh[:plural_model_name]) end db_table_list_hashes.each do |hsh| restore_backup(hsh[:model], "#{hsh[:plural_model_name]}.csv") end ######### Reset PK Sequence ######### ActiveRecord::Base.connection.tables.each do |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) end end # Call: ServCsvTool.new.restore_backup(User, 'Users.csv') def restore_backup(model, file_name) @file_path = "#{@backups_path}/#{file_name}" parse_csv @headers.map!(&:to_sym) model.import(@headers, @rows, validate: false) completion_msg(model, file_name) end ############# WORST CSV IMPORT METHOD BELOW ############# # IMPORT SEED METHODS BELOW - BIG PROCESS!! # Imports Raw Data files, which runs through extensive validations. # Imports CSV from: db/csv/seeds/file_name.csv ########################################################## #CALL: ServCsvTool.new.import_all_seed_files def import_all_seed_files Mig.new.reset_pk_sequence ServCsvTool.new.import_uni_seeds('uni_act', 'cop_formated.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '1_acts_top_150.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '2_wards_500.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '3_acts_cop.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '4_acts_sfdc.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '5_acts_scraped.csv') # ServCsvTool.new.import_uni_seeds('uni_act', '6_acts_geo_locations.csv') # ########## STANDARD SEED IMPORT BELOW ########## # ServCsvTool.new.import_standard_seeds('who', '8_whos.csv') # ServCsvTool.new.import_standard_seeds('brand', '9_brands.csv') # ServCsvTool.new.import_standard_seeds('term', '10_terms.csv') end ########## UNI SEED IMPORT BELOW ########## # ServCsvTool.new.import_uni_seeds('uni_act', '1_cops.csv') def import_uni_seeds(model_name, file_name) @file_path = "#{@seeds_path}/#{file_name}" model = model_name.classify.constantize plural_model_name = model_name.pluralize custom_migrate_method = "migrate_#{plural_model_name}" parse_csv objs = [] puts @clean_csv_hashes.count @clean_csv_hashes.each do |clean_csv_hsh| clean_csv_hsh = clean_csv_hsh.stringify_keys clean_csv_hsh.delete_if { |key, value| value.blank? } if !clean_csv_hsh.empty? uni_hsh = val_hsh(model.column_names, clean_csv_hsh) objs << model.new(uni_hsh) end model.import(objs) puts "\nSleep(3) - Complete: model.import(objs)\n#{model_name}, #{file_name}" sleep(3) Mig.new.send(custom_migrate_method) ### NEED TO WORK ON THIS!!! puts "\nSleep(3) - Complete: Mig.new.#{custom_migrate_method}\n#{file_name}" sleep(3) completion_msg(model, file_name) end ########## STANDARD SEED IMPORT BELOW ########## def import_standard_seeds(model_name, file_name) @file_path = "#{@seeds_path}/#{file_name}" model = model_name.classify.constantize plural_model_name = model_name.pluralize custom_migrate_method = "migrate_#{plural_model_name}" parse_csv objs = [] @clean_csv_hashes.each do |clean_csv_hsh| clean_csv_hsh = clean_csv_hsh.stringify_keys clean_csv_hsh.delete_if { |key, value| value.blank? } if !clean_csv_hsh.empty? new_hsh = val_hsh(model.column_names, clean_csv_hsh) obj_exists = model.exists?(new_hsh) if new_hsh.present? obj = model.new(new_hsh) if !obj_exists objs << obj if obj end model.import(objs) puts "\nSleep(3) - Complete: model.import(objs)\n#{model_name}, #{file_name}" sleep(3) completion_msg(model, file_name) end end
true