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
33907a8c775fb6573ec2d61f416ac0f59a09007c
Ruby
machinedogs/Authentication
/app/commands/authorize_api_request.rb
UTF-8
949
2.59375
3
[]
no_license
# frozen_string_literal: true # app/commands/authorize_api_request.rb class AuthorizeApiRequest prepend SimpleCommand def initialize(params = {}) @params = params end def call user end private attr_reader :params def user @user ||= Host.find(decoded_auth_token[:host_id]) if decoded_auth_token @user || errors.add(:token, 'Invalid token') && nil rescue ActiveRecord::RecordNotFound => e return nil end def decoded_auth_token decoded_auth_token = JsonWebToken.decode(http_auth_header) #See if it decodes correctly, meaning not expired, then check if it is a refresh token or not if decoded_auth_token && decoded_auth_token[:refresh] return decoded_auth_token else return nil end end def http_auth_header if params['refresh_token'].present? params['refresh_token'].split(' ').last else errors.add :token, 'Missing token' end end end
true
2f719391e376f6c72ef4b2550f0636b38d6609a5
Ruby
KIMJUNGKWON/ProgrammingRuby
/ch3/array.rb
UTF-8
2,731
4.40625
4
[]
no_license
# 루비는 처음이므로 책에 나온 모든 함수들 다 짚고 넘어가기 # 특히 다른 함수를 사용함으로써 array를 stack과 queue로 활용하는 것 숙지 # Array 의 정의와 생성 # class Array < Object # Arrays are ordered, integer-indexed collections of any object. # Array indexing starts at 0, as in C or Java. # A negative index is assumed to be relative to the end of the array arr1 = [] p arr1.class # => Array arr2 = Array.new() p arr2.class # => Array # Array의 내장 함수 test_arr = [1, "hello", 3, 6, "jk", "apple", 10] p test_arr.length() # => 7 p test_arr[1] # => "hello" p test_arr # => [1, "hello", 3, 6, "jk", "apple", 10] p test_arr.inspect # => "[1, \"hello\", 3, 6, \"jk\", \"apple\", 10]" p test_arr[1, 3] # => ["hello", 3, 6] => array[start, count] 은 array[start]부터 count개 원소가 담긴 array를 return p test_arr[3..6] # => [6, "jk", "apple", 10] => array[n..m] 은 array[n]부터 array[m]까지의 값을 경계 포함하여 array를 return p test_arr[3...6] # => [6, "jk", "apple"] => array[n...m] 은 array[n]부터 array[m]까지의 값을 경계 불포함하여 array를 return p test_arr[1, 4] # => ["hello", 3, 6, "jk"] test_arr[1, 4] = [] # => start부터 count개 부분을 [] 처리 p test_arr # => [1, "apple", 10] p "************************************************************************" p "Array 활용 => Stack" # Array 활용 => Stack stack = [] stack.push("1_apple") stack.push("2_orange") stack.push("3_banana") stack.push("4_grape") p stack # => ["1_apple", "2_orange", "3_banana", "4_grape"] # Array # public method #pop(*several_variants) # ary.pop -> obj or nil ary.pop(n) -> new_ary Removes the last element from self and returns it, # or nil if the array is empty. p stack.pop() # => "4_grape" p stack # => ["1_apple", "2_orange", "3_banana"] p stack.pop(2) # => ["2_orange", "3_banana"] p "************************************************************************" p "Array 활용 => queue" # Array 활용 => queue queue = [] queue.push("1_apple") queue.push("2_orange") queue.push("3_banana") queue.push("4_grape") p queue p queue.shift() # => queue p queue # => ["2_orange", "3_banana", "4_grape"] p queue.shift(2) # => ["2_orange", "3_banana"] p queue # => ["4_grape"] p "************************************************************************" p "first, last 활용" # Array를 stack과 queue로 활용할 수 있다는 사실과 push, pop, shift 를 숙지하는 것은 맞지만 # 사실 Array에는 first(count), last(count)함수가 있다. arr_test = [1, 2, 3, 4, 5] p arr_test # => [1, 2, 3, 4, 5] p arr_test.first # => 1 p arr_test.first(3) # => [1, 2, 3] p arr_test.last # => 5 p arr_test.last(3) # => [3, 4, 5]
true
2ec5517aa911e62da4e10dd98cb5b4f0f075ef2b
Ruby
RReiso/ruby-practice
/Leetcode/single-number.rb
UTF-8
886
4.15625
4
[]
no_license
#Given a non-empty array of integers nums, every element appears twice except for one. #Find that single one. def single_number(num) hash = num.tally #Returns a hash with the elements of the collection as keys and the corresponding counts as values. return hash.key(1) end puts single_number([4, 1, 2, 1, 2]) def single_number2(num) num.each { |n| return n if num.count(n) == 1 } end puts single_number2([1, 1, 2, 91, 2]) def single_number3(num) num.sort_by { |el| num.count(el) }[0] end puts single_number3([1, 1, 7, 2, 1, 2]) def single_number4(num) tally = num.each_with_object(Hash.new(0)) { |number, hash| hash[number] += 1 } tally.key(1) end puts single_number3([1, 1, 887, 2, 1, 2]) #bitwise solution works if the number of numbers that repeat are even def single_num5(num) a = 0 num.each { |i| a ^= i } a end puts single_num5([1, 1, 99, 2, 2, 1, 2, 1, 2])
true
865d0f98e6d1ac275eb25d5fbb8a468cd36231b6
Ruby
bradrf/rsql
/lib/rsql.rb
UTF-8
794
2.734375
3
[ "MIT" ]
permissive
# A module encapsulating classes to manage MySQLResults and process # Commands using an EvalContext for handling recipes. # # See the {file:example.rsqlrc.rdoc} file for a simple tutorial and usage # information. # module RSQL VERSION = [0,3,1] def VERSION.to_s self.join('.') end # Set up our version to be comparable to version strings. # VERSION.extend(Comparable) def VERSION.eql?(version) self.<=>(version) == 0 end def VERSION.<=>(version) version = version.split('.').map!{|v|v.to_i} r = self[0] <=> version[0] r = self[1] <=> version[1] if r == 0 r = self[2] <=> version[2] if r == 0 r end require 'rsql/mysql_results' require 'rsql/eval_context' require 'rsql/commands' end
true
039d08998f8743f0c759e38468000029cba9eb67
Ruby
ElaErl/Fundations
/exerc/easy4/2.rb
UTF-8
559
3.828125
4
[]
no_license
def century(a) def almost_all(a) b = a / 100 + 1 if b.digits[0..1] == [3, 1] puts "#{b}th" elsif b.digits[0..1] == [2, 1] puts "#{b}th" elsif b.digits[0..1] == [1, 1] puts "#{b}th" elsif b % 10 == 1 puts "#{b}st" elsif b % 10 == 2 puts "#{b}nd" elsif b % 10 == 3 puts "#{b}rd" else puts "#{b}th" end end if a % 100 != 0 almost_all(a) else almost_all(a - 1) end end century(1) century(1965) century(256) century(5) century(10103) century(1052) century(1127) century(11201)
true
0b424560f4092c49c9745a28867db123100f198d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/word-count/572912c222da48b2b08607d955aff20a.rb
UTF-8
384
3.53125
4
[]
no_license
class Words attr_reader :split_cleaned_input def initialize(raw_input) @split_cleaned_input = spit_and_clean_input(raw_input) end def count split_cleaned_input.each_with_object({}) do |word, hash| hash[word] = split_cleaned_input.count(word) end end def spit_and_clean_input(raw_input) raw_input.downcase.gsub(/\W/, ' ').split(' ') end end
true
1ae6e0990f46fbec8c29c2c7ce619b58ea448c28
Ruby
palakverma/3-Warmups
/my_benchmark.rb
UTF-8
329
4
4
[]
no_license
def my_benchmark(number_of_times, word) start = (Time.now) number_of_times.times do word end finish = (Time.now) - start puts finish end puts "Enter the # of times you want this block to run: " number_of_times = gets.chomp.to_i puts "Enter your word: " word = gets.chomp.to_s my_benchmark(number_of_times, word)
true
fbe4f1553c288c9f4f1f0c56a1ca120c6afa3455
Ruby
ahoward/openobject
/sample/c.rb
UTF-8
186
2.734375
3
[]
no_license
require 'openobject' oo = openobject :foo => 42 oo.bar = 'forty-two' oo.extend do fattr :foobar => 42.0 def barfoo [ foo, bar, foobar ] end end p oo.foobar p oo.barfoo
true
2a491c0f658695cba5c56145eb680f953dffe873
Ruby
sf-bobolinks-2016/DBC-Overflow-Team-Emerald
/app/models/user.rb
UTF-8
740
2.78125
3
[ "MIT" ]
permissive
class User < ActiveRecord::Base has_many :questions has_many :answers has_many :comments validates :email, :hashed_password, presence: true validates :email, uniqueness: true include BCrypt def password @password ||= Password.new(hashed_password) end def password=(pass) @password = Password.create(pass) self.hashed_password = @password end # e.g., User.authenticate('jess@devbootcamp.com', 'apples123') def self.authenticate(input_email, input_password) # if email and password correspond to a valid user, return that user current_user = self.find_by(email: input_email) return current_user if current_user.password == input_password # otherwise, return nil nil end end
true
90c9d086276e067bdb5ba590c7843401bc9223ca
Ruby
MichaelHilton/TDDViz
/lib/UniqueId.rb
UTF-8
626
2.796875
3
[ "MIT" ]
permissive
# mixin module UniqueId def unique_id `uuidgen`.strip.delete('-')[0...10].upcase end end # 10 hex chars gives N possibilities where # N == 16^10 == 1,099,511,627,776 # which is more than enough as long as # uuidgen is reasonably well behaved. # # 6 hex chars are all that need to be entered # to enable id-auto-complete which gives # N == 16^6 == 16,777,216 possibilities. # # Idea: massage the uuidgen into a format of # three letters (A-F) + three digits (0-9) # to make it more user friendly. Eg BEA327.... # Analysis: gives 6^3 * 10^3 == 216,000 possibilities # Outcome: duplication too likely. Idea not used.
true
e6f7e8ae13baef6acc81151d44c07ecbc888168e
Ruby
jichen3000/colin-ruby
/test/module_test/many_modules.rb
UTF-8
714
2.625
3
[]
no_license
require 'testhelper' module ColinA def my_p "ColinA".pt self.class.pt __method__.pt end def my_call_p "ColinA".pt __method__.pt my_p end end module ColinB def my_p "ColinB".pt self.class.pt __method__.pt end # def my_call_p # "ColinB".pt # __method__.pt # my_p # end end class Colin include ColinA include ColinB end if __FILE__ == $0 require 'minitest/autorun' require 'minitest/spec' require 'testhelper' describe "some" do it "function" do c = Colin.new c.my_call_p Colin.ancestors.pt end end end
true
e77e40acfb9066f86dc1a3b169922017903da8f5
Ruby
lfborjas/minimalisp
/norvig/tests.rb
UTF-8
4,528
3.265625
3
[]
no_license
#Tests for the ruby translation of Peter Norvig's Lispy #These are also his: http://norvig.com/lispy2.html require './norvig.rb' require 'test/unit' module Test::Unit class TestCase alias_method :t?, :assert def f?(c) assert c == false end def self.must(name, &block) test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym defined = instance_method(test_name) rescue false raise "#{test_name} is already defined in #{self}" if defined if block_given? define_method(test_name, &block) else define_method(test_name) do flunk "No implementation provided for #{name}" end end end end end class SchemeTest < Test::Unit::TestCase def _!(exp) eval!(exp.to_sexp).to_lisp.to_atom end must "quote expressions" do t? _!("(quote (testing 1 (2.0) -3.14e159))") == :"(testing 1 (2.0) -3.14e+159)" end must "use predefined arithmetic methods" do t? _!("(+ 2 2)") == 4 t? _!("(+ (* 2 100) (* 1 10))") == 210 end must "branch well on conditional expressions" do t? _!("(if (> 6 5) (+ 1 1) (+ 2 2))") == 2 t? _!("(if (< 6 5) (+ 1 1) (+ 2 2))") == 4 end must "add bindings to the current environment" do _! "(define x 3)" t? _!("x") == 3 t? _!("(+ x x)") == 6 end must "evaluate consecutive expressions" do t? _!("(begin (define x 1) (set! x (+ x 1)) (+ x 1))") == 3 end must "apply anonymous functions" do t? _!("((lambda (x) (+ x x)) 5)") == 10 end must "add bindings to functions in the current environment" do _!("(define twice (lambda (x) (* 2 x)))") t? _!("(twice 5)") == 10 end must "handle closures properly" do _!("(define compose (lambda (f g) (lambda (x) (f (g x)))))") t? _!("((compose list twice) 5)") == :"(10)" _!("(define repeat (lambda (f) (compose f f)))") t? _!("((repeat twice) 5)") == 20 t? _!("((repeat (repeat twice)) 5)") == 80 end must "handle recursive functions properly" do _!("(define fact (lambda (n) (if (<= n 1) 1 (* n (fact (- n 1))))))") t? _!("(fact 3)") == 6 t? _!("(fact 50)") == 30414093201713378043612608166064768844377641568960512000000000000 end must "evaluate arguments to a function before applying it" do _!("(define abs (lambda (n) ((if (> n 0) + -) 0 n)))") t? _!("(list (abs -3) (abs 0) (abs 3))") == :"(3 0 3)" end must "handle complex closures" do _! %q|(define combine (lambda (f) (lambda (x y) (if (null? x) (quote ()) (f (list (car x) (car y)) ((combine f) (cdr x) (cdr y)))))))| _! "(define zip (combine cons))" t? _!("(zip (list 1 2 3 4) (list 5 6 7 8))") == :"((1 5) (2 6) (3 7) (4 8))" _! %q|(define riff-shuffle (lambda (deck) (begin (define take (lambda (n seq) (if (<= n 0) (quote ()) (cons (car seq) (take (- n 1) (cdr seq)))))) (define drop (lambda (n seq) (if (<= n 0) seq (drop (- n 1) (cdr seq))))) (define mid (lambda (seq) (/ (length seq) 2))) ((combine append) (take (mid deck) deck) (drop (mid deck) deck)))))| t? _!("(riff-shuffle (list 1 2 3 4 5 6 7 8))") == :"(1 5 2 6 3 7 4 8)" t? _!("((repeat riff-shuffle) (list 1 2 3 4 5 6 7 8))") == :"(1 3 5 7 2 4 6 8)" t? _!("(riff-shuffle (riff-shuffle (riff-shuffle (list 1 2 3 4 5 6 7 8))))") == :"(1 2 3 4 5 6 7 8)" end must "Throw syntax errors" do wrong = lambda do |exp, msg| exc = assert_raise(SyntaxError){_!(exp)} t? exc == msg end wrong.call("()", "(): wrong length") wrong.call("(set! x)", "(set! x): wrong length") wrong.call "(define 3 4)", "(define 3 4): can define only a symbol" wrong.call "(quote 1 2)", "(quote 1 2): wrong length" wrong.call "(if 1 2 3 4)" , "(if 1 2 3 4): wrong length" wrong.call "(lambda 3 3)" , "(lambda 3 3): illegal lambda argument list" wrong.call "(lambda (x))" , "(lambda (x)): wrong length" wrong.call "(if (= 1 2) (define-macro a 'a) ", "(define-macro a (quote a)): define-macro only allowed at top level" end must "check arguments" do _! "(define (twice x) (* 2 x))" t? _!("(twice 2)") == 4 exc = assert_raise(TypeError) {_!("(twice 2 2)")} t? exc == "TypeError expected (x), given (2 2)" end end
true
8983f8d10dfc115ae83f8179d9c6c47193963c18
Ruby
RianaFerreira/ruby-sandbox
/hashes.rb
UTF-8
597
3.96875
4
[]
no_license
# hash is an unordered collection organized into key/value pairs # key is the address # value is the data at that address # => rocket links a key with a value produce = { "apples" => 3, "oranges" => 5, "carrots" => 12 } puts "There are #{produce["oranges"]} oranges in the fridge." produce["grapes"] = 221 puts produce produce["oranges"] = 10 puts produce produce.keys produce.values # symbols can be used as keys of a hash # shorthand syntax to use if all the keys are symbols produce = { apples: 3, oranges: 5, carrots: 10 } puts "There are #{produce[]:oranges]} in the fridge."
true
e0a6a446896aeb7570e9f147337518d038060778
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/series/ca3773fe40d94be49299056283c44d44.rb
UTF-8
428
3.546875
4
[]
no_license
class Series attr_reader :numbers def initialize(string) @numbers = collect_integers_from(string) end def slices(scope) raise ArgumentError if scope > numbers.length result = [] numbers.length.times do |i| slice = numbers[i,scope] result << slice if slice.length == scope end result end private def collect_integers_from(string) string.chars.map{|c| c.to_i} end end
true
c5669cd24a4c0887dec93f40b80ffca28d37d292
Ruby
katietensfeldt/movie-app
/script.rb
UTF-8
575
3.328125
3
[]
no_license
require "http" system "clear" puts "===========================" puts "Welcome to the Movies App!" puts "===========================" puts puts "Here are some of my favorite movies:" puts response = HTTP.get("http://localhost:3000/all_movies") movies = response.parse movies.each { |movie| puts movie["title"] } puts puts "If you would like to learn more about a particular movie, please enter a number 0-3." input = gets.chomp.to_i puts puts "Title: #{movies[input]["title"]}" puts "Release year: #{movies[input]["year"]}" puts "Plot Summary: #{movies[input]["plot"]}"
true
dba33869be408a67d5a369ff3d6bb7c2781fd9ac
Ruby
cjeycjey/LiquidPlanner
/examples/create_task.rb
UTF-8
1,081
2.671875
3
[]
no_license
# Require the LiquidPlanner API. require File.dirname(__FILE__) + '/../lib/liquidplanner' # Require support libraries used by this example. require 'rubygems' require 'highline/import' require File.dirname(__FILE__) + '/support/helper' # Get the user's credentials email, password, space_id = get_credentials! # Connect to LiquidPlanner and get the workspace lp = LiquidPlanner::Base.new(:email=>email, :password=>password) workspace = lp.workspaces(space_id) unless parent = workspace.packages(:first) || workspace.projects(:first) say "There are no packages or projects in this workspace; cannot add a task." exit end # Ask for a task's name and estimate say "Add a new task to '#{workspace.name}'" name = ask("New task name") low = ask("Min effort", Float) high = ask("Max effort", Float){|q| q.above = low} # Submit the task and estimate say "Submitting: '#{name}' [#{low} - #{high}] to LiquidPlanner" task = workspace.create_task(:name=>name, :parent_id => parent.id) task.create_estimate(:low=>low, :high=>high) # All done say "Added task"
true
12b0c4f7aa2b35456321eb210d87fb639d373464
Ruby
oshou/procon
/Paiza/D/d097.rb
UTF-8
133
3.140625
3
[]
no_license
arr = gets.chomp.split.map { |i| i.to_i } cloudy = arr.select { |i| i == 1 }.length if cloudy >= 5 puts "yes" else puts "no" end
true
b699f316ff9a70d14c73a427498d959dcc0610ad
Ruby
siman-man/Ruby
/ryudai_rb/ryudai_rb5/lisp/lib/method_missing.rb
UTF-8
208
3.234375
3
[]
no_license
class Test def method_missing(name, *args) p name p args end def hello(*args) p "hello" end end @t = Test.new def test(&block) @t.instance_eval(&block) end @t.test(:+, (:hello, 3))
true
9df266a68cc5eb82b31e31a1bda59822e93ca612
Ruby
MichaelGofron/TDDRuby
/02_calculator/calculator.rb
UTF-8
205
3.40625
3
[]
no_license
def add(a,b) a + b end def subtract(a,b) a - b end def sum(array) array.inject(0, :+) end def multiply(a,b) a*b end def power(a,b) a**b end def factorial(a) a <= 1 ? 1 : a * factorial(a-1) end
true
dc6764b38535a1283eff921353c56bd162e6e367
Ruby
dmytro/capistrano-recipes
/base.rb
UTF-8
5,779
2.59375
3
[]
no_license
#require 'chef/knife' require 'chef/application/solo' require 'chef/data_bag_item' require 'pathname' require 'securerandom' $LOAD_PATH << "#{File.dirname(__FILE__)}/lib" require "git_tags" def fatal(str) sep = "\n\n#{'*' * 80}\n\n" abort "#{sep}\t#{str}#{sep}" end ## # Read databag on local host, using custom directory if it is defined. # def get_data_bag bag, item=nil Chef::Config[:solo] = true Chef::Config[:data_bag_path] = "#{local_chef_cache_dir}/data_bags" if item Chef::DataBagItem.load(bag, item.to_s).raw_data else Chef::DataBag.load(bag) end end ## # Return relative path to the recipe file. Use in recipe documentation. # def path_to file Pathname.new(file).relative_path_from(Pathname.new(ENV['PWD'])).to_s end ## # Ensure that application code is tagged. Deploy only code from the git tag. # def ensure_release_tagged set :branch do tags = GitTags.new(repository).tags default = tags.last fatal "Cannot find any tags in the repository" if default.nil? puts <<-PUT ******************************************** Found tags: #{tags[-10..-1].join("\n")} ******************************************** PUT tag = Capistrano::CLI.ui.ask "\n\n Choose a tag to deploy (make sure to push the tag first): [Default: #{default}] " tag = default if tag.empty? fatal "Cannot deploy as no tag was found" if tag.nil? tag end end ## # Parse ERB template from tempaltes directory and upload to target server. # # @param [File] __file__ - if not provided then templates are assumed # to be in ../templates directory relative to this file, otherwise # in the same directory relative to the __file__ parameter. # def template(from, to, __file__=__FILE__, options: {}) @template_path = File.dirname(File.expand_path("../templates/#{from}", __file__)) erb = File.read(File.expand_path("../templates/#{from}", __file__ )) remote_user = options.delete :as if remote_user begin temp = "/tmp/template_#{from.gsub("/","_")}.temp" put ERB.new(erb,0,'<>%-').result(binding), temp, options sudo "mv #{temp} #{to}", options sudo "chown #{remote_user} #{to}", options ensure sudo "rm -f #{temp}" end else put ERB.new(erb,0,'<>%-').result(binding), to, options end end ## # Partial parsing for template files. # For nested template inclusion. # Usage: see nginx.conf.erb for erxample def partial file ERB.new(File.read(file),0,'<>%-').result(binding) end def set_default(name, *args, &block) set(name, *args, &block) unless exists?(name) end # Runs +command+ as root invoking the command with su -c # and handling the root password prompt. # # surun "/etc/init.d/apache reload" # # Executes # # su - -c '/etc/init.d/apache reload' # def surun(command) password = Capistrano::CLI.password_prompt("root password: ") options = { shell: :bash, pty: true } options.merge! hosts: only_hosts if exists? :only_hosts run("su - -c '#{command}'", options) do |channel, stream, output| channel.send_data("#{password}\n") if output end end # Try to execute command with sudo, if it fails fallback to surun. # def sudo_or_su(command) begin sudo command rescue puts <<-EMSG ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sudo is not installed (or not configured) following commands will be executed with root password. #{command} Please type root password at the prompt. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EMSG surun(command) end end # Runs command remotely and return 0 or other status code # # @param cmd Shell command to tun # # @return true or false def test_command cmd cmd << " > /dev/null 2>&1 ; echo $?" return(capture(cmd, shell: :bash, pty: true).strip.to_i == 0) end set_default :config_sub_dir, "" # # DSL extensions. Some functions to extend current Capistrano DSL with # ofthen used patterns. # ================================================================== ## # Load additional recipes from file. # # @param name [String,Symbol] name of the recipe file, symbolized, # without .rb extension. # # @param local [Boolean] If `true` try to load recipe from # `site/recipes` subdirectory. Otherwise use subdirectory # `recipes`. Recipes is git submodule with generic recipes, while # `site/recipes` is local subdirectory with collection of the # recipes that are used only in the current project. # def recipe name, local = false load "#{local ? site_capistrano_recipes : capistrano_recipes}/#{name.to_s}.rb" end ## # Tar directory locally and send it to remote location, untarring # # @param local [String] # # @param remote [String] # # @param exclude: [Array] list of local subdirectories, regexp's to # exclude from tar'ing. Arguments to tar's --exclude command. By # default always exclude .git subdirectory. # def upload_dir local, remote, options: {}, exclude: ["./.git"] begin temp = %x{ mktemp /tmp/captemp-tar.XXXX }.chomp remote_temp = "/tmp/captemp.#{SecureRandom.hex}" run_locally "cd #{local} && tar cfz #{temp} #{exclude.map { |e| "--exclude #{e}" }.join(' ')} ." upload temp, remote_temp run "mkdir -p #{remote} && cd #{remote} && tar xfz #{remote_temp}", options ensure run_locally "rm -f #{temp}" run "rm -f #{remote_temp}", options end end ## # Copy directory locally using tar. # # @param src [String] # # @param dst [String] # # @param exclude: [Array] list of local subdirectories, regexp's to # exclude from tar'ing. Arguments to tar's --exclude command. By # default always exclude .git subdirectory. def copy_dir src, dest, exclude: ["./.git"] run_locally "mkdir -p #{dest} && (cd #{src} && tar cf - #{exclude.map { |e| "--exclude #{e}" }.join(' ')} .) | (cd #{dest} && tar xf -)" end
true
2353fd9d5f1251bdb2a5f4dee7be4af42e54aa01
Ruby
caspg/bitmap_editor
/spec/bitmap_editor_spec.rb
UTF-8
3,606
3.078125
3
[]
no_license
require 'spec_helper' require_relative '../app/bitmap_editor' describe BitmapEditor do subject { described_class.new(bitmap) } let(:bitmap) { double(:bitmap) } describe '#run' do it 'outputs initial message with prompt sign' do allow(subject).to receive(:gets).and_return('X') expect { subject.run }.to output(/type \? for help\n>/).to_stdout end it 'calls #execute_command method with proper argument' do allow(subject).to receive(:gets).and_return('ARG1 ARG2 ARG3') allow(subject).to receive(:execute_command) { subject.send(:exit_console) } subject.run expect(subject).to have_received(:execute_command).with(%w(ARG1 ARG2 ARG3)) end end describe '#execute_command' do let(:command) { double(:command) } before do # return different values each time :gets is called # allow(subject).to receive(:gets).and_return(input, 'X') allow(Response).to receive(:new) allow(Command).to receive(:new).and_return(command) allow(command).to receive(:create_new_bitmap) allow(command).to receive(:clear_bitmap) allow(command).to receive(:colour_pixel) allow(command).to receive(:draw_vertical_line) allow(command).to receive(:draw_horizontal_line) allow(command).to receive(:show_bitmap) subject.execute_command(input) end context 'when command is I' do let(:input) { ['I', 2, 2] } it { expect(command).to have_received(:create_new_bitmap).with(input) } end context 'when command is C' do let(:input) { ['C'] } it { expect(command).to have_received(:clear_bitmap).with(bitmap) } end context 'when command is L' do let(:input) { ['L', 2, 3, 'A'] } it { expect(command).to have_received(:colour_pixel).with(bitmap, input) } end context 'when command is V' do let(:input) { ['V', 2, 3, 6, 'W'] } it { expect(command).to have_received(:draw_vertical_line).with(bitmap, input) } end context 'when command is H' do let(:input) { ['H', 3, 5, 2, 'Z'] } it { expect(command).to have_received(:draw_horizontal_line).with(bitmap, input) } end context 'when command is S' do let(:input) { ['S'] } it { expect(command).to have_received(:show_bitmap).with(bitmap) } end context 'when command is ?' do let(:input) { ['?'] } it { expect(Response).to have_received(:new).with(bitmap, expected_help_message) } end context 'when command is X' do let(:input) { 'X' } it { expect(Response).to have_received(:new).with(bitmap, 'goodbye!') } end context 'when there is no input' do let(:input) { '' } it { expect(Response).to have_received(:new).with(bitmap, "type \? for help") } end context 'when there is unrecognised command' do let(:input) { 'stranger things' } it { expect(Response).to have_received(:new).with(bitmap, 'unrecognised command :(') } end end def expected_help_message <<~HEREDOC ? - Help I M N - Create a new M x N image with all pixels coloured white (O). C - Clears the table, setting all pixels to white (O). L X Y C - Colours the pixel (X,Y) with colour C. V X Y1 Y2 C - Draw a vertical segment of colour C in column X between rows Y1 and Y2 (inclusive). H X1 X2 Y C - Draw a horizontal segment of colour C in row Y between columns X1 and X2 (inclusive). S - Show the contents of the current image X - Terminate the session HEREDOC end end
true
ee27bfeacbab645f133f0b21ce007ce3aa9b0cd7
Ruby
johnofsydney/eulers
/ex4/main.rb
UTF-8
536
3.984375
4
[]
no_license
puts "ruby" # # A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. # # Find the largest palindrome made from the product of two 3-digit numbers. def palin candidates = [] (100..999).to_a.reverse.each do |x| (100..999).to_a.reverse.each do |y| p = (x * y).to_s if ((p[0] == p[5]) && (p[1] == p[4]) && (p[2] == p[3]) ) candidates.push(p.to_i) end end end return candidates.sort.reverse[0] end print( palin )
true
b98ab95198d0728f396a181b6ebe51ad8a8bc972
Ruby
djdarkbeat/yard-junk
/lib/yard-junk/janitor/resolver.rb
UTF-8
3,303
2.625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module YardJunk class Janitor class Resolver include YARD::Templates::Helpers::HtmlHelper include YARD::Templates::Helpers::MarkupHelper # This one is copied from real YARD output OBJECT_MESSAGE_PATTERN = "In file `%{file}':%{line}: " \ 'Cannot resolve link to %{name} from text: %{link}' # ...while this one is totally invented, YARD doesn't check file existance at all FILE_MESSAGE_PATTERN = "In file `%{file}':%{line}: File '%{name}' does not exist: %{link}" def self.resolve_all(yard_options) YARD::Registry.all.map(&:base_docstring).each { |ds| new(ds, yard_options).resolve } yard_options.files.each { |file| new(file, yard_options).resolve } end def initialize(object, yard_options) @options = yard_options case object when YARD::CodeObjects::ExtraFileObject init_file(object) when YARD::Docstring init_docstring(object) else fail "Unknown object to resolve #{object.class}" end end def resolve markup_meth = "html_markup_#{markup}" return unless respond_to?(markup_meth) send(markup_meth, @string) .gsub(%r{<(code|tt|pre)[^>]*>(.*?)</\1>}im, '') .scan(/{[^}]+}/).flatten .map(&CGI.method(:unescapeHTML)) .each(&method(:try_resolve)) end private def init_file(file) @string = file.contents @file = file.filename @line = 1 @markup = markup_for_file(file.contents, file.filename) end def init_docstring(docstring) @string = docstring @root_object = docstring.object @file = @root_object.file @line = @root_object.line @markup = options.markup end attr_reader :options, :file, :line, :markup def try_resolve(link) name, _comment = link.tr('{}', '').split(/\s+/, 2) # See YARD::Templates::Helpers::BaseHelper#linkify for the source of patterns # TODO: there is also {include:}, {include:file:} and {render:} syntaxes, but I've never seen # a project using them. /shrug case name when %r{://}, /^mailto:/ # that's pattern YARD uses # do nothing, assume it is correct when /^file:(\S+?)(?:#(\S+))?$/ resolve_file(Regexp.last_match[1], link) else resolve_code_object(name, link) end end def resolve_file(name, link) return if options.files.any? { |f| f.name == name || f.filename == name } Logger.instance.register( FILE_MESSAGE_PATTERN % {file: file, line: line, name: name, link: link} ) end def resolve_code_object(name, link) resolved = YARD::Registry.resolve(@root_object, name, true, true) return unless resolved.is_a?(YARD::CodeObjects::Proxy) Logger.instance.register( OBJECT_MESSAGE_PATTERN % {file: file, line: line, name: name, link: link} ) end # Used by HtmlHelper for RDoc def object @string.object if @string.is_a?(YARD::Docstring) end # Used by HtmlHelper def serializer nil end end end end
true
3d009ff199163850001932d50574949bb11c6294
Ruby
corinnawiesner/knowledge_base
/spec/forms/articles/new_form_spec.rb
UTF-8
2,432
2.515625
3
[]
no_license
require 'rails_helper' RSpec.describe Articles::NewForm, type: :form do context "validations" do it { is_expected.to validate_presence_of(:title) } it { is_expected.to validate_length_of(:title).is_at_least(5) } it { is_expected.to validate_presence_of(:abstract) } it { is_expected.to validate_presence_of(:question_title) } it { is_expected.to validate_length_of(:question_title).is_at_least(5) } it { is_expected.to validate_presence_of(:question_abstract) } it { is_expected.to validate_presence_of(:question_answer) } end context "instance methods" do subject(:empty_form) { described_class.new } subject(:form) do described_class.new( title: "How to become a programmer", abstract: "This is a quick tutorial on how to become a programmer.", question_title: "How to get started?", question_abstract: "Learn the basic elements to get started.", question_answer: "To get started in programming you need to...", ) end describe "#save" do context "when object is valid" do it "creates a new article" do expect{ form.save }.to change { Article.count }.by(1) end it "creates a new question" do expect{ form.save }.to change { Question.count }.by(1) end it "creates an article with a question" do form.save article = form.article question = article.questions.first expect(article.title).to eq(form.title) expect(article.abstract).to eq(form.abstract) expect(question.title).to eq(form.question_title) expect(question.abstract).to eq(form.question_abstract) expect(question.answer).to eq(form.question_answer) end it "returns true" do expect(form.save).to be_truthy end it "creates a QuestionTranslationJob" do form.save expect { QuestionTranslationJob.perform_later(id: form.article.id) }.to have_enqueued_job end it "creates a ArticleTranslationJob" do form.save expect { ArticleTranslationJob.perform_later(id: form.article.questions.first.id) }.to have_enqueued_job end end context "when object is invalid" do it "returns false" do expect(empty_form.save).to be_falsey end end end end end
true
36bda30bc7cdee65ab982447684cb23778ac1db1
Ruby
theironyard-rails-atl/AndrewHouse
/8-06/widget.rb
UTF-8
907
3.078125
3
[]
no_license
require 'yaml' WIDGET_INFO = YAML.load_file('widgets.yml') class Widget include Enumerable attr_reader :widgets def initialize widgets @widgets = widgets end def each @widgets.each { |widget| yield widget } end def max_price @widgets.max_by { |widget| widget[:price] } end def min_price @widgets.min_by { |widget| widget[:price] } end def total_revenue @widgets.inject(0) { |sum, widget| sum += (widget[:price]*widget[:sold])} end def total_cost costs = @widgets.inject(0) { |sum, widget| sum += (widget[:sold] * widget[:cost_to_make])} end def total_profit total_revenue - total_cost end def ten_best_sellers @widgets.sort_by { |widget| widget[:sold]}.last(10).reverse end def sold_by_department @widgets.inject(Hash.new(0)) do |hash, widget| hash[widget[:department]] += widget[:sold] hash end end end
true
5662ed8b9b6a27957ee2e9fea3f6825fd7904ccf
Ruby
CiaraAnderson/image_blur
/imageblurtwo.rb
UTF-8
1,672
3.84375
4
[]
no_license
class Image def initialize(array) @image = array end def output_image @image.each do |row| puts row.join end end def blur_coords! coords_to_blur = [] @image.each_with_index do |row, row_index| # [0, 0, 0, 0, 0, 0] row.each_with_index do |column, column_index| # 0 if column == 1 # above # unless row_index == 0 # coords_to_blur << [row_index - 1, column_index] # end coords_to_blur << [row_index - 1, column_index] unless row_index == 0 # below unless row_index >= @image.length - 1 coords_to_blur << [row_index + 1, column_index] end # left unless column_index == 0 coords_to_blur << [row_index, column_index - 1] end # right unless column_index >= row.length - 1 coords_to_blur << [row_index, column_index + 1] end end end end # convert 0s to 1s # [[0, 1], [2, 1], [1, 0], [1, 2]] puts coords_to_blur.to_s coords_to_blur.each do |coord_to_blur| # @image[0][2] = 1 # coord_to_blur == [0, 1] [row_index, column_index] row_index = coord_to_blur[0] column_index = coord_to_blur[1] @image[row_index][column_index] = 1 end #puts @image.to_s end end image = Image.new([ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0] ]) image.output_image puts "--------" image.blur_coords! image.output_image
true
d60e454592176b51634cb4ab11f9791a4d09faa3
Ruby
DumboCL/TL-Course1-Object-Oriented-Programming-Book
/inheritance.rb
UTF-8
1,898
4.0625
4
[]
no_license
# inheritance.rb # my_car module Towable def can_tow?(pounds) pounds < 2000 ? true : false end end class Vehicle @@number_of_vehicles = 0 attr_accessor :color, :model, :current_speed attr_reader :year def initialize(year, color, model) @year = year @color = color @model = model @current_speed = 0 @@number_of_vehicles += 1 end def speed_up(number) puts "Speed up #{number}" self.current_speed += number puts "The speed now is #{self.current_speed}" end def brake(number) puts "Brake #{number}" self.current_speed -= number puts "The speed now is #{self.current_speed}" end def shut_off puts "Shut off!!" self.current_speed = 0 puts "The speed now is #{self.current_speed}" end def spray_paint(color) self.color = color puts "The color change to #{self.color}" end def self.cal_gas(gallons, miles) puts "#{miles / gallons} miles per gallon of gas" end def self.number_of_vehicles puts "This program has created #{@@number_of_vehicles} vehicles" end def age "your #{self.model} is #{years_old} years old." end private def years_old Time.now.year - self.year end end class MyCar < Vehicle NUMBER_OF_DOORS = 4 def to_s "My car is a #{self.color}, #{self.year}, #{@model}!" end end class MyTruck < Vehicle include Towable NUMBER_OF_DOORS = 2 def to_s "My truck is a #{self.color}, #{self.year}, #{@model}!" end end MyCar.cal_gas(13, 351) one_car = MyCar.new(1994,"red","car model") one_truck = MyTruck.new(2009,"black","truck model") puts one_car puts one_truck puts Vehicle.number_of_vehicles #puts one_car.can_tow?(2400) puts one_truck.can_tow?(2400) puts "-----" puts Vehicle.ancestors puts "-----" puts MyCar.ancestors puts "-----" puts MyTruck.ancestors puts one_car.age puts one_truck.age
true
a4a4c112c317a49c5ef87d07e20cd2634f24073c
Ruby
masahino/mruby-mrbmacs-base
/mrblib/project.rb
UTF-8
1,099
2.515625
3
[ "MIT" ]
permissive
module Mrbmacs # Project class Project attr_accessor :root_directory, :build_command, :last_build_command def initialize(root_directory) @root_directory = root_directory @build_command = guess_build_command @last_build_command = nil end def guess_build_command build_types = { 'Rakefile' => 'rake', 'Makefile' => 'make', 'makefile' => 'make', 'build.sh' => './build.sh' } build_types.each do |k, v| return v if File.exist?("#{@root_directory}/#{k}") end nil end def update(root_directory) @root_directory = root_directory Dir.chdir(@root_directory) @build_command = guess_build_command @last_build_command = nil end end # Command module Command def open_project(root_directory = nil) if root_directory.nil? root_directory = read_dir_name('Project directory: ', @current_buffer.directory) end if root_directory != nil && Dir.exist?(root_directory) @project.update(root_directory) end end end end
true
4f27388bc3c8368a842027d7a63403a19f4431fc
Ruby
brucedickey/poly-app
/test/controllers/categories_controller_test.rb
UTF-8
2,232
2.71875
3
[]
no_license
# frozen_string_literal: true # SQLite3 DB may become busy locked. Fix is Andrew's answer here: # https://www.udemy.com/course/the-complete-ruby-on-rails-developer-course/learn/lecture/3852574#questions/9537992 # which is to comment out the parallelize line in test/test_helper.rb. require "test_helper" class CategoriesControllerTest < ActionController::TestCase def setup # "Create" instead of "new" so that it hits the test DB. # Creating an object so that we can use it to pass the required id for the show method. @category = Category.create(name: "sports") @user = User.create(username: "john", email: "john@example.com", password: "password", admin: true,) end test "Should get categories index" do get :index # HTML GET assert_response :success end test "Should get new" do # TODO: How is `session` in scope? session[:user_id] = @user.id # Simulate admin login get :new assert_response :success end test "Should get show" do get(:show, params: { "id" => @category.id }) assert_response :success end test "Should redirect the create action when an admin is not logged in" do # The setup() method does not log in a user, so the redirect should happen. assert_no_difference "Category.count", "assert_no_difference \"Category.count\"" do # In create_categories_test.rb, the line below is used w/ current Rails 6 version, # but does not work here. This is the line from the "Text Directions and code" # for Rails 5 as well. # TODO: Why does it work in create_categories_test.rb, but not here? # post blog_categories_path, params: {category: {name: "sports"}} # Rails 5 # This is from the video. Error: "catetory is undefined" # TODO: Assuming no errors, how does this specify a route, the correct route? # post :create, category: {name: "sports"} # This works, and initially returns 200 success instead of 3xx redirect, because # the category new page is not limited to admin users yet. post :create, params: { category: { name: "sports" } } end assert_redirected_to blog_categories_path, "assert_redirected_to blog_categories_path" end end
true
955ad36814bf2433c4f72edeafdb2341818ab393
Ruby
hboulter/silicon-valley-code-challenge-austin-web-102819
/app/models/startup.rb
UTF-8
1,481
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Startup attr_accessor :name, :investors attr_reader :founder, :domain @@all = [] @@all_domains = [] def initialize(name, founder, domain) @name = name @founder = founder @domain = domain @@all << self @@all_domains << domain end def pivot(name, domain) @name = name @domain = domain end def self.all @@all end def self.find_by_founder(founder) @@all.detect {|x| x.founder == founder} end def self.domains @@all_domains.uniq end def sign_contract(venture_capitalist, type_of_investment, amount_invested) FundingRound.new(self, venture_capitalist, type_of_investment, amount_invested) end def num_funding_rounds FundingRound.all.select { |round| round.startup == self }.count end def total_funds startups_array = FundingRound.all.select { |x| x.startup == self } startups_array.reduce(0) { |sum, round| sum + round.investment } end def investors xyz = FundingRound.all.select { |x| x.startup == self } xyz.map { |y| y.venture_capitalist }.uniq end def big_investors investors = self.investors # startups_array = FundingRound.all.select { |x| x.startup == self } # investors = startups_array.map { | round | round.venture_capitalist }.uniq investors.select { |y| y.total_worth > 1000000000 } end end
true
0a2a10410dde86af05094b15c07a1be710dd9bea
Ruby
Geovo/codeeval
/easy/intersect/intersect.rb
UTF-8
298
2.6875
3
[]
no_license
File.open(ARGV[0]).each_line do |line| string = [] matches = line.chomp.match(";") a = matches.pre_match.split(',') b = matches.post_match.split(',') a.map{|x| string << x if b.include?(x)} puts string.join(',') end # l = (string.length * (-1)) # p string #puts string
true
4cc4f62f0a259f57f67cdc1f81154dfead9e1bca
Ruby
masao/nextl-util-mailer
/lib/next_l/mailer/logger.rb
UTF-8
822
2.640625
3
[]
no_license
# -*- coding:utf-8 -*- # ja: 転送したメールのログを記録・出力するモジュール module NextL::Mailer::Logger def setup_logger @logger ||= ::NextL::Mailer::Logger::Logger.new end def log setup_logger @logger.log end def latest_log setup_logger @logger.latest_log end def add_log(mail) setup_logger @logger << mail end class Logger def initialize @log = Redis::List.new("next_l:mailer:log", :marshal=>true) end # ja: ログの記録 def << (mail) record = Array.new record[0] = Time.now record[1] = mail.to_hash @log << record self end # ja: ログの表示 def log @log.values end # ja: 最新のログを表示する def latest_log log.last end end end
true
e5d588345339353c7bd7ff34fb051a5402438999
Ruby
rikniitt/wadror_beer
/spec/models/user_spec.rb
UTF-8
3,867
2.578125
3
[]
no_license
require 'spec_helper' describe User do it "has the username set correctly" do user = User.new :username => "Pekka" user.username.should == "Pekka" end it "is not saved without a proper password" do user = User.create :username => "Pekka69" expect(user.valid?).to be(false) expect(User.count).to eq(0) end it "is not saved with too short username" do user = User.create :username => "P1", :password => "mysecret1", :password_confirmation=> "mysecret1" expect(user.valid?).to be(false) expect(User.count).to eq(0) end it "is not saved with password containing only character" do user = User.create :username => "Pekka69", :password => "mysecret", :password_confirmation=> "mysecret" expect(user.valid?).to be(false) expect(User.count).to eq(0) end it "is not saved with too short password" do user = User.create :username => "Pekka69", :password => "mys", :password_confirmation=> "mys" expect(user.valid?).to be(false) expect(User.count).to eq(0) end describe "with a proper password" do let(:user) { FactoryGirl.create :user } it "is saved" do expect(user.valid?).to eq(true) expect(User.count).to eq(1) end it "and with two ratings, has the correct average rating" do rating1 = FactoryGirl.create :rating1 rating2 = FactoryGirl.create :rating2 user.ratings << rating1 user.ratings << rating2 expect(user.ratings.count).to eq(2) expect(user.average_rating).to eq(15.0) end end describe "favorite" do let(:user) { FactoryGirl.create :user } describe "beer" do it "has method for determining one" do user.should respond_to :favorite_beer end it "without ratings does not have one" do expect(user.favorite_beer).to eq(nil) end it "is the only rated if only one rating" do beer = create_beer_with_rating 10, user expect(user.favorite_beer).to eq(beer) end it "is the one with highest rating if several rated" do create_beers_with_ratings 10, 20, 15, 7, 9, user best = create_beer_with_rating 25, user expect(user.favorite_beer).to eq(best) end end describe "style" do it "has method for determining one" do user.should respond_to :favorite_style end it "without ratings does not have one" do expect(user.favorite_style).to eq(nil) end it "is style of the only rated beer if only one rating" do beer = create_beer_with_rating 10, user expect(user.favorite_style).to eq(beer.style) end it "is the one with highest rating if several rated" do create_beers_with_ratings 10, 20, 15, 7, 9, user best = FactoryGirl.create(:kill_darlings) FactoryGirl.create(:rating, :score => 25, :beer => best, :user => user) expect(user.favorite_style).to eq(best.style) end end describe "brewery" do it "has method for determining one" do user.should respond_to :favorite_brewery end it "without ratings does not have one" do expect(user.favorite_brewery).to eq(nil) end it "is brewery of the only rated beer if only one rating" do beer = create_beer_with_rating 10, user expect(user.favorite_brewery).to eq(beer.brewery) end it "is the brewery of the beer with highest rating if several rated" do create_beers_with_ratings 10, 20, 15, 7, 9, user best = FactoryGirl.create(:gpa) FactoryGirl.create(:rating, :score => 50, :beer => best, :user => user) expect(user.favorite_brewery).to eq(best.brewery) end end def create_beers_with_ratings(*scores, user) scores.each do |score| create_beer_with_rating score, user end end def create_beer_with_rating(score, user) beer = FactoryGirl.create(:jaipur) FactoryGirl.create(:rating, :score => score, :beer => beer, :user => user) beer end end end
true
24ea5ecea327b50ae7a36150b6be1707c7b88e1c
Ruby
lassiter/sep-assignments
/01-data-structures/05-hashes-part-2/open_addressing/open_addressing.rb
UTF-8
2,328
3.484375
3
[]
no_license
require_relative 'node' class OpenAddressing def initialize(size) @items = Array.new(size) @size = size end # Places Key Value pair at an index. def []=(key, value) inital_index = index(key,@size) node = Node.new(key, value) # Immediate Placement of Key Pair if @items[inital_index].nil? @items[inital_index] = node elsif @items[next_open_index(inital_index)].nil? open_index = next_open_index(inital_index) return @items[open_index] = node else resize if @items[inital_index].nil? return @items[inital_index] = node elsif @items[next_open_index(inital_index)].nil? open_index = next_open_index(inital_index) return @items[open_index] = node else while @items[index(key,@size)] != nil resize return @items[index(key,@size)] = node if @items[index(key,@size)].nil? return @items[next_open_index(index(key,@size))] = node if @items[next_open_index(index(key,@size))].nil? end end end end # Returns value that matches key. def [](key) expected_index = index(key,@size) # Expected Index Matches Key if @items[expected_index].key == key return @items[expected_index].value # Loop Starting at expected_index elsif @items[expected_index].nil? || @items[expected_index].key != key i = expected_index while i < @size if !@items[i].nil? && key == @items[i].key return @items[i].value end i += 1 end end return "Not Found" end # Returns a unique, deterministically reproducible index into an array # We are hashing based on strings, let's use the ascii value of each string as # a starting point. def index(key, size) key.sum % size end # Given an index, find the next open index in @items def next_open_index(index) return -1 if @items.all? {|item| !item.nil?} (index..@size-1).each do |i| return i if @items[i].nil? end end # Simple method to return the number of items in the hash def size @size end # Resize the hash def resize @size *= 2 rehashed = Array.new(@size) @items.each do |item| unless item.nil? rehashed[index(item.key,@size)] = item end end @items = rehashed end end
true
a70f1606e3b5544231ac5cbd47df8d40f8645133
Ruby
joshtkim/ruby-oo-relationships-practice-gym-membership-exercise-nyc01-seng-ft-042020
/tools/console.rb
UTF-8
767
2.828125
3
[]
no_license
# You don't need to require any of the files in lib or pry. # We've done it for you here. require_relative '../config/environment.rb' # test code goes here gym1 = Gym.new("24 hr fitness") gym2 = Gym.new("Retro") gym3 = Gym.new("Planet Fitness") gym4 = Gym.new("Equinox") lifter1 = Lifter.new("Josh", 150) lifter2 = Lifter.new("Jessica", 175) lifter3 = Lifter.new("Sonia", 200) lifter4 = Lifter.new("Mom", 400) lifter5 = Lifter.new("Dad", 350) mem1 = Membership.new(lifter1, gym1, 150) mem2 = Membership.new(lifter2, gym2, 150) mem3 = Membership.new(lifter3, gym3, 150) mem4 = Membership.new(lifter4, gym4, 150) mem5 = Membership.new(lifter5, gym2, 150) mem6 = Membership.new(lifter4, gym3, 150) mem7 = Membership.new(lifter2, gym1, 150) binding.pry puts "Gains!"
true
eeb460be3f67952fbfe337634f87ff81da7884af
Ruby
ed5j4prog-winter/iotex-esp32-mrubyc
/mrblib/models/i2c.rb
UTF-8
1,093
2.796875
3
[]
no_license
class I2C # 定数 MASTER = 0 SLAVE = 1 # 初期化 def initialize(port, scl, sda, freq = 400000) @port = port @scl = scl @sda = sda @freq = freq self.driver_install end # コンストラクタ外からの再初期化 def init(port, scl, sda, freq = 400000) @port = port @scl = scl @sda = sda @freq = freq self.driver_install end # IC2ドライバーの削除 def deinit self.driver_delete end def write(i2c_adrs_7, *data) if(data[0].kind_of?(String)) s = data[0] data = Array.new s.length.times do |n| data.push(s[n].ord) end elsif(data[0].kind_of?(Array)) data = data[0] end self.__write(i2c_adrs_7, data) end def read(i2c_adrs_7, len, *params) write(i2c_adrs_7, params) unless params.empty? a = self.__read(i2c_adrs_7, len) s = "" a.length.times do |n| s << a[n].chr end s end def read_integer(i2c_adrs_7, len, *params) write(i2c_adrs_7, params) unless params.empty? self.__read(i2c_adrs_7, len) end end
true
0a9c88d5c51c23fb4b78a14647b4b132b6355b4f
Ruby
arvicco/win_gui
/book_code/guessing/spec_helper.rb
UTF-8
1,642
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#--- # Excerpted from "Scripted GUI Testing With Ruby", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/idgtr for more book information. #--- require 'rubygems' require 'hpricot' require 'open-uri' module RandomHelper def random_paragraph doc = Hpricot open('http://www.lipsum.com/feed/html?amount=1') (doc/"div#lipsum p").inner_html.strip #(1) end end describe 'a new document', :shared => true do before do @note = Note.open end after do @note.exit! if @note.running? end end describe 'a saved document', :shared => true do before do Note.fixture 'SavedNote' end end describe 'a reopened document', :shared => true do before do @note = Note.open 'SavedNote' end after do @note.exit! if @note.running? end end describe 'a searchable document', :shared => true do include RandomHelper #(2) before do @example = random_paragraph #(3) words = @example.split /[^A-Za-z]+/ last_cap = words.select {|w| w =~ /^[A-Z]/}.last @term = last_cap[0..1] #(4) @first_match = @example.index(/#{@term}/i) @second_match = @first_match ? @example.index(/#{@term}/i, @first_match + 1) : nil @reverse_match = @example.rindex(/#{@term}/i) @word_match = @example.index(/#{@term}\b/i) @case_match = @example.index(/#{@term}/) @note.text = @example end end
true
f9c2e49c9de6ac98ff6361e79bb1f1b32d36ba96
Ruby
Eli017/romanconvertor
/romanconvertor.rb
UTF-8
1,911
4.1875
4
[]
no_license
def fromRoman(romanNumber) valid = ["M","D","C","L","X","V","I"] for c in romanNumber.chars if !valid.include? c raise TypeError end end number = 0 number += romanNumber.count("M") * 1000 number += romanNumber.count("D") * 500 number += romanNumber.count("C") * 100 number += romanNumber.count("L") * 50 number += romanNumber.count("X") * 10 number += romanNumber.count("V") * 5 number += romanNumber.count("I") * 1 sub = addArabicNumber(romanNumber) number-sub end def addArabicNumber(romanNumber) number = 0 if romanNumber.include? "IV" number += 2 end if romanNumber.include? "XC" number += 20 end if romanNumber.include? "CD" number += 200 end number end def toRoman(arabicNumber) result = "" if arabicNumber < 1 || arabicNumber > 3999 raise RangeError end result += "M" * (arabicNumber / 1000).floor arabicNumber-=(arabicNumber/1000).floor * 1000 result += "D" * (arabicNumber / 500).floor arabicNumber-=(arabicNumber/500).floor * 500 result += "CD" * (arabicNumber / 400).floor arabicNumber-=(arabicNumber/400).floor * 400 result += "C" * (arabicNumber / 100).floor arabicNumber-=(arabicNumber/100).floor * 100 result += "XC" * (arabicNumber / 90).floor arabicNumber-=(arabicNumber/90).floor * 90 result += "L" * (arabicNumber / 50).floor arabicNumber-=(arabicNumber/50).floor * 50 result += "XL" * (arabicNumber / 40).floor arabicNumber-=(arabicNumber/40).floor * 40 result += "X" * (arabicNumber / 10).floor arabicNumber-=(arabicNumber/10).floor * 10 result += "V" * (arabicNumber / 5).floor arabicNumber-=(arabicNumber/5).floor * 5 result += "IV" * (arabicNumber / 4).floor arabicNumber-=(arabicNumber/4).floor * 4 result += "I" * (arabicNumber / 1).floor end
true
665c16f9f9c900b4c9662bc2542259809b436708
Ruby
milenoss/OO-Animal-Zoo-london-web-082619
/lib/Zoo.rb
UTF-8
1,080
3.796875
4
[]
no_license
class Zoo attr_reader :name, :location @@all = [] def initialize(name,location) @name = name @location = location @@all << self end def self.all @@all end # we iterate over animals class to find out all the animals in the zoo. def animals #instance method soo zoo1.animal will give you all the animals Animal.all.select{|animal| animal.zoo == self} end # will return an array of species in the zoo def animal_species(species) animals.map{|animal| animal.species }.uniq end #species what are we iterating over ?? return an array of particular species def find_by_species(species) animals.select{|animal|animal.species == species} end #return an array of nicknames use map def animal_nicknames self.all.map{|names|names.nicknames} end # class method #returns location of zoos in that location use map and do compare to location. def self.find_by_location(location) self.all.map{|location|location.zoo == location} end end
true
0170baad78112161f12f923aaba6389af2a36aa1
Ruby
bpieck/rubyx
/lib/risc/builtin/word.rb
UTF-8
2,788
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Risc module Builtin module Word module ClassMethods include CompileHelper # wrapper for the syscall # io/file currently hardcoded to stdout # set up registers for syscall, ie # - pointer in r1 # - length in r2 # - emit_syscall (which does the return of an integer, see there) def putstring( context) compiler = compiler_for(:Word , :putstring ,{}) builder = compiler.builder(compiler.source) builder.prepare_int_return # makes integer_tmp variable as return builder.build do word! << message[:receiver] integer! << word[Parfait::Word.get_length_index] end Risc::Builtin::Object.emit_syscall( builder , :putstring ) compiler.add_mom( Mom::ReturnSequence.new) compiler end # self[index] basically. Index is the first arg > 0 # return a word sized new int, in return_value # # Note: no index (or type) checking. Method should be internal and check before. # Which means the returned integer could be passed in, instead of allocated. def get_internal_byte( context) compiler = compiler_for(:Word , :get_internal_byte , {at: :Integer}) builder = compiler.builder(compiler.source) integer_tmp = builder.allocate_int builder.build do object! << message[:receiver] integer! << message[:arguments] integer << integer[Parfait::NamedList.type_length + 0] #"at" is at index 0 integer.reduce_int object <= object[integer] integer_tmp[Parfait::Integer.integer_index] << object message[:return_value] << integer_tmp end compiler.add_mom( Mom::ReturnSequence.new) return compiler end # self[index] = val basically. Index is the first arg ( >0 , unchecked), # value the second, which is also returned def set_internal_byte( context ) compiler = compiler_for(:Word, :set_internal_byte , {at: :Integer , value: :Integer} ) compiler.builder(compiler.source).build do word! << message[:receiver] integer! << message[:arguments] integer_reg! << integer[Parfait::NamedList.type_length + 1] #"value" is at index 1 message[:return_value] << integer_reg integer << integer[Parfait::NamedList.type_length + 0] #"at" is at index 0 integer.reduce_int integer_reg.reduce_int word[integer] <= integer_reg end compiler.add_mom( Mom::ReturnSequence.new) return compiler end end extend ClassMethods end end end
true
56447067eb185318b90af2dec01d6e1fbceca47a
Ruby
smallfryy/RaiseYourHand
/app/models/tag.rb
UTF-8
1,230
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# == Schema Information # # Table name: tags # # id :integer not null, primary key # name :string # created_at :datetime not null # updated_at :datetime not null # class Tag < ActiveRecord::Base has_many :question_tags has_many :questions, through: :question_tags validates_presence_of :name def self.most_popular_by_questions Tag.joins(:questions).group("tags.id").order("COUNT(questions.id) desc").first end def self.most_answered Tag.joins(questions: :answers).group("tags.id").order("COUNT(answers.id) desc").first end def self.least_answered Tag.joins(questions: :answers).group("tags.id").order("COUNT(DISTINCT(answers.id)) asc").first end def self.most_popular_by_users Tag.joins(questions: :user).group("tags.id").order("COUNT(DISTINCT(users.id)) desc").first end def self.trending_tag #most popular tag within last week by question Tag.joins(:questions).where("questions.created_at > ?", DateTime.now - 7).group("tags.id").order("COUNT(questions.id) desc").first end def most_active_user User.joins(questions: :tags).where("tags.id = ?", self.id).group("users.id").order("COUNT(questions.id) desc").first end end
true
fbe8ed5947543bda59d26d7d5463860ad2b69a59
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz68_sols/solutions/Patrick Chanezon/current_temp.rb
UTF-8
319
2.796875
3
[ "MIT" ]
permissive
require 'net/http' puts ((ARGV.length != 1) ? "Usage: #$0 <zip code>" : (["The temperature in"] + (/Weather<\/b> for <b>(.*)<\/b>.*\D(\d+)&deg;F/.match(Net::HTTP.get( URI.parse("http://www.google.com/search?hl=en&q=temperature+#{ARGV[0]}")))[1,2].collect! {|x| " is " + x})).to_s.gsub!(/in is /, "in ") + " degree F")
true
63f0201d81b38affde1da4413184a4313c24e420
Ruby
kaleflatbread/cartoon-collections-nyc-web-051418
/cartoon_collections.rb
UTF-8
515
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def roll_call_dwarves(dwarf_names) index = 1 dwarf_names.each do |name| puts "#{index}. #{name}" index +=1 end end def summon_captain_planet(list_of_foods) list_of_foods.collect do |food| food.split.map(&:capitalize).join('') + "!" end end def long_planeteer_calls(array_of_calls) array_of_calls.any? do |call| call.length > 4 end end def find_the_cheese(cheeses) cheese_types = ["cheddar", "gouda", "camembert"] cheeses.find do |cheese| cheese_types.include?(cheese) end end
true
424c7dc3779b02f12230ba69b165d1ebc213f022
Ruby
thesilentc/square_array-v-000
/square_array.rb
UTF-8
233
3.875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# example elements for array [1, 2, 3] def square_array(array) squared = [] # create new empty array array.each { |element| squared << element ** 2 } # 1**1, 2**2, 3**3 squared # reurns new array of squared array [1, 4, 9] end
true
c5ec792b5aede0557f66680ae904f0317a90b891
Ruby
OthmanAmoudi/cartoon-collections-cb-gh-000
/cartoon_collections.rb
UTF-8
635
3.453125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def roll_call_dwarves array# code an argument here # Your code here array.each_with_index do |name,index| puts "#{index+1} #{name}" end end def summon_captain_planet array# code an argument here # Your code here array.collect do |item| "#{item.capitalize}!" end end def long_planeteer_calls array# code an argument here # Your code here array.any? do |item| item.size > 4 end end def find_the_cheese array# code an argument here # the array below is here to help cheese_types = ["cheddar", "gouda", "camembert"] array.each do |item| return item if cheese_types.include?(item) end nil end
true
856305f06450471374c29241d221dc6adcd23c3d
Ruby
EdwinHongCheng/aAHomework
/W4D5/02 Octopus Problems/My Answer/octopus_problems.rb
UTF-8
2,956
4.15625
4
[]
no_license
# Octopus Problems (W4D5 HW) # Finished: the day before W4D5 # array of fishes of different string lengths fishes = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] # 1. Sluggish Octopus # uses Bubble Sort - O(n^2) time def sluggish_octopus(arr) bubble_sort(arr)[-1] end # Helper Method: Bubble Sort # Time Complexity: O(n^2) time def bubble_sort(arr) arr_copy = arr.dup sorted = false while !sorted sorted = true (0...arr.length - 1).each do |i| if arr_copy[i].length > arr_copy[i + 1].length arr_copy[i], arr_copy[i + 1] = arr_copy[i + 1], arr_copy[i] sorted = false end end end arr_copy end # Test # p sluggish_octopus(fishes) #=> "fiiiissshhhhhh" # 2. Dominant Octopus # Self-Note: using Merge Sort over Quick Sort # Quick Sort's Time Complexity: worst case scenario: O(n^2), average case: O(n log n) def dominant_octopus(arr) merge_sort(arr)[-1] end # Merge Sort - Time Complexity: O(n log n) def merge_sort(arr) return arr if arr.length <= 1 middle_idx = (arr.length / 2) - 1 left = arr[0..middle_idx] right = arr[middle_idx + 1..-1] sorted_left = merge_sort(left) sorted_right = merge_sort(right) merge(sorted_left, sorted_right) end # Helper Method def merge(arr1, arr2) answer = [] while !arr1.empty? && !arr2.empty? if arr1[0].length < arr2[0].length answer << arr1.shift elsif arr2[0].length < arr1[0].length answer << arr2.shift else answer << arr1.shift answer << arr2.shift end end answer + arr1 + arr2 end # Test # p dominant_octopus(fishes) #=> "fiiiissshhhhhh" # 3. Clever Octopus # Time Complexity: O(n) time def clever_octopus(arr) longest_str = "" arr.each do |word| if word.length > longest_str.length longest_str = word end end longest_str end # Test # p clever_octopus(fishes) #=> "fiiiissshhhhhh" # 4. Dancing Octopus (Both Parts) # 4a. Slow Dance tiles_array = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up" ] # Time Complexity: O(n) time def slow_dance(target_tile, tiles_arr) tile_idx = nil tiles_arr.each_with_index do |tile, idx| tile_idx = idx if tile == target_tile end tile_idx end # Tests # p slow_dance("up", tiles_array) #=> 0 # p slow_dance("right-down", tiles_array) #=> 3 # 4b. Constant Dance! # Time Complexity: O(1) time # from Solution: # use a hash for constant lookup tiles_hash = { "up" => 0, "right-up" => 1, "right"=> 2, "right-down" => 3, "down" => 4, "left-down" => 5, "left" => 6, "left-up" => 7 } def fast_dance(direction, hash) hash[direction] end # Tests # p fast_dance("up", tiles_hash) #=> 0 # p fast_dance("right-down", tiles_hash) #=> 3
true
04763767aa736298de9829603953e68179748020
Ruby
Bestra/cso-chorus-page
/app/models/user.rb
UTF-8
260
2.609375
3
[]
no_license
class User def self.from_session_token(token) type = Authenticator.authenticate_type(token) return unless type User.new(type == :admin ? true : false) end def initialize(admin) @admin = admin end def is_admin? @admin end end
true
7e9e176e7c6512af5e6259894e47233f3557bda4
Ruby
miguelmota/twitter-purge
/purge.rb
UTF-8
1,745
2.625
3
[ "MIT" ]
permissive
require 'dotenv/load' require 'twitter' @client = Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] config.access_token = ENV['TWITTER_ACCESS_TOKEN_KEY'] config.access_token_secret = ENV['TWITTER_ACCESS_TOKEN_SECRET'] end def check(friend_id) puts "checking user: #{friend_id}" timeline = @client.user_timeline(friend_id, { :include_rts => false, :count => 1 }) if timeline.count == 0 return unfollow(friend_id) end status = @client.status(timeline[0].id) date = status.created_at.to_date now = Date.today thirty_days_ago = (now - 30) if date < thirty_days_ago unfollow(friend_id) end end def following(username) @client.friend_ids(username).to_a rescue Twitter::Error::TooManyRequests => error p error sleep error.rate_limit.reset_in retry end def unfollow(friend_id) @client.unfollow(friend_id) puts "unfollowed user: #{friend_id}" rescue Twitter::Error::TooManyRequests => error p error sleep error.rate_limit.reset_in retry end if ARGV.empty? puts "username argument is required" Process.exit(1) end username = ARGV[0] puts "Twitter account: #{username}" filename = "#{username}.cache" f = open(filename, "a") checked_list = [] if File.exists?(filename) checked_list = File.readlines(filename) end following_ids = following(username) puts "following count: #{following_ids.count}" following_ids.each do |friend_id| skip = false checked_list.each do |line| if line.strip.include? friend_id.to_s skip = true puts "skipping check: #{friend_id}" next end end if skip next end check(friend_id) f << "#{friend_id}\n" end puts "done"
true
bebb270eeae9da0968223a7aeed0b9f139377e16
Ruby
BlaneCordes/99bottles
/lib/bottles.rb
UTF-8
1,226
3.8125
4
[]
no_license
class Bottles def verse(number_of_bottles) verse_response(number_of_bottles) end def verses(start_of_range, end_of_range) [*end_of_range..start_of_range].reverse.map do |number_of_bottles| verse(number_of_bottles) end.join("\n") end def song [*0..99].reverse.map do |bottles| verse(bottles) end.join("\n") end def verse_response(number_of_bottles) if number_of_bottles.zero? <<~VERSE No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. VERSE else <<~VERSE #{number_of_bottles} #{bottles_pluralization(number_of_bottles)} of beer on the wall, #{number_of_bottles} #{bottles_pluralization(number_of_bottles)} of beer. #{closing_line(number_of_bottles - 1)} VERSE end end def closing_line(bottles) return "Take it down and pass it around, no more bottles of beer on the wall." if bottles.zero? "Take one down and pass it around, #{bottles} #{bottles_pluralization(bottles)} of beer on the wall." end private def bottles_pluralization(number_of_bottles) number_of_bottles == 1 ? "bottle" : "bottles" end end
true
4fc45938ce88387a8889b4806995f06697f9596c
Ruby
somethinrother/bitmaker_lessons
/roll-of-the-die/james_dice/permutations.rb
UTF-8
209
3.078125
3
[]
no_license
roll1 = 1 roll2 = 1 until roll1 == 7 if roll2 == 7 roll2 = 1 end if roll2 < 6 puts "#{roll1} #{roll2}" roll2 += 1 else puts "#{roll1} #{roll2}" roll1 += 1 roll2 += 1 end end
true
88b43cb35b1ccfe27e26c701efd3d9cd849fef1b
Ruby
danthompson/seesaw-rb
/lib/seesaw/client/timelines.rb
UTF-8
409
2.578125
3
[ "MIT" ]
permissive
module Seesaw class Client # Client methods for working with timelines module Timelines # Get recent decisions from the global timeline. # # @param limit [Fixnum] Number of decisions to return. # @return [Array] # @example # Seesaw.recent_decisions def global_timeline(limit = 10) get "timelines/global?limit=#{limit}" end end end end
true
85057ded5d2bf4ffc2b307b5f4daf0842abb68e0
Ruby
VadimVadimVadim1337/ruby4
/1lab/lib/main2.rb
UTF-8
493
3.515625
4
[]
no_license
class FK def otvet(number) (number - 32) / 1.8 + 273 end end class KC def otvet(number) number - 273 end end class KF def otvet(number) (number - 273) * 1.8 + 32 end end class CF def otvet(number) (number * 9 / 5) + 32 end end class CK def otvet(number) number + 273 end end class FC def otvet(number) (number - 32) * 5 / 9 end end class SS def self.class_build(inp, out) str = "#{inp}#{out}" Object.const_get(str).new end end
true
d19b65c07af035aafc73a353090381e82247de16
Ruby
szareey/ministryDocs
/lib/ministry_docs/math_2007_doc/doc_parser.rb
UTF-8
804
2.6875
3
[]
no_license
module MinistryDocs module Math2007Doc class DocParser < MinistryDocs::BaseDoc::DocParser PDF_URL = 'https://www.edu.gov.on.ca/eng/curriculum/secondary/math1112currb.pdf' TXT_URL = 'https://www.edu.gov.on.ca/eng/curriculum/secondary/math1112currb.txt' protected def info(courses) { courses: courses, subject: 'math', province: 'Ontario', pdf_url: PDF_URL, txt_url: TXT_URL, title: 'The Ontario Curriculum, Grades 11 and 12: Mathematics', grades: [11, 12], year: '2007' } end def course_parser @course_parser ||= CourseParser.new end def get_courses_section(text) normlize(text).split('COURSES ')[1] end end end end
true
02500a3a6075754175a98fafd1d77f9c6f77636c
Ruby
willmoeller/launch-school
/exercises/101-109_small_problems/easy_1/stringy_strings.rb
UTF-8
793
4.96875
5
[]
no_license
# Write a method that takes one argument, a positive integer, and returns a # string of alternating 1s and 0s, always starting with 1. The length of the # string should match the given integer. def stringy(integer) binary = [] (1..integer).each do |num| binary << 0 if num.even? binary << 1 if num.odd? end binary.join end # def stringy(size) # numbers = [] # size.times do |index| # number = index.even? ? 1 : 0 # numbers << number # end # numbers.join # end puts stringy(6) # => '101010' puts stringy(9) # => '101010101' puts stringy(4) # => '1010' puts stringy(7) # => '1010101' # note that times method starts counting from 0: # 5.times { |index| puts index } => 0, 1, 2, 3, 4 # so the first index in the stringy method is 0, which is even, so it's a 1.
true
529409ce535d52df17a9e9581b9610692b739eac
Ruby
dkubb/axiom-do-adapter
/lib/axiom/adapter/data_objects/statement.rb
UTF-8
2,657
2.671875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# encoding: utf-8 module Axiom module Adapter class DataObjects # Executes generated SQL statements class Statement include Enumerable, Adamantium::Flat # Initialize a statement # # @param [::DataObjects::Connection] connection # the database connection # @param [Relation] relation # the relation to generate the SQL from # @param [#visit] visitor # optional object to visit the relation and generate SQL with # # @return [undefined] # # @api private def initialize(connection, relation, visitor = SQL::Generator::Relation) @connection = connection @relation = relation @visitor = visitor end # Iterate over each row in the results # # @example # statement = Statement.new(connection, relation, visitor) # statement.each { |row| ... } # # @yield [row] # # @yieldparam [Array] row # each row in the results # # @return [self] # # @api public def each return to_enum unless block_given? each_row { |row| yield row } self end # Return the SQL query # # @example # statement.to_s # => SQL representation of the relation # # @return [String] # # @api public def to_s @visitor.visit(@relation).to_sql.freeze end private # Yield each row in the result # # @yield [row] # # @yieldparam [Array] row # each row in the results # # @return [undefined] # # @api private def each_row reader = command.execute_reader yield reader.values while reader.next! ensure reader.close if reader end # Return the command for the SQL query and column types # # @return [::DataObjects::Command] # # @api private def command command = @connection.create_command(to_s) command.set_types(column_types) command end # Return the list of types for each column # # @return [Array<Class>] # # @api private def column_types @relation.header.map { |attribute| attribute.type.primitive } end memoize :to_s memoize :command, freezer: :flat end # class Statement end # class DataObjects end # module Adapter end # module Axiom
true
5ec62c114e2e3589608486fcaa5d38272ee0805f
Ruby
JKCodes/ttt-with-ai-project-v-000
/bin/tictactoe
UTF-8
3,205
3.609375
4
[]
no_license
#!/usr/bin/env ruby require_relative '../config/environment' flag = false until flag puts "\e[H\e[2J" puts "Welcome to Tic Tac Toe!\n" puts "How many human players for this game? (0, 1, or 2)" puts " Enter -1 to simulate 10000 computer player games" num_human_players = gets.strip until num_human_players == "0" || num_human_players == "1" || num_human_players == "2" || num_human_players == "-1" puts "ERROR: #{num_human_players} is not a valid option. Please enter 0, 1, 2, or -1" num_human_players = gets.strip end computer_first = "n" if num_human_players == "1" puts "Let computer go first? (y/N)" puts " Just hit enter for 'n" computer_first = gets.strip.downcase if computer_first == "" computer_first = "n" puts "No input was provided. Human will go first by default" end until computer_first == "y" || computer_first == "n" puts "ERROR: #{computer_first} is not a valid option. Please enter y or n" computer_first = gets.strip end end # The hardest computer level will not lose any games. if num_human_players == "0" || num_human_players == "1" || num_human_players == "-1" puts "\nComputer's skill level? (1, 2, 3)" puts " No input or invalid entries will default to level of 1 (easy)" computer1_level = gets.strip computer1_level = "1" if computer1_level != "1" && computer1_level != "2" && computer1_level != "3" end if num_human_players == "0" || num_human_players == "-1" puts "\nComputer 2's skill level? (1, 2, 3)" puts " No input or invalid entries will default to level of 1 (easy)" computer2_level = gets.strip computer2_level = "1" if computer2_level != "1" && computer2_level != "2" && computer2_level != "3" end if num_human_players == "0" || num_human_players == "-1" player_1 = Players::Computer.new('X', computer1_level) player_2 = Players::Computer.new('O', computer2_level) elsif num_human_players == "1" player_1 = computer_first == "n" ? Players::Human.new('X') : Players::Computer.new('X', computer1_level) player_2 = computer_first == "n" ? Players::Computer.new('O', computer1_level) : Players::Human.new('O') else player_1 = Players::Human.new('X') player_2 = Players::Human.new('O') end run_count = 1 if num_human_players == "-1" comp1win = 0 draw_count = 0 comp2win = 0 run_count = 10000 end run_count.times do game = Game.new(player_1, player_2) game.play if num_human_players == "-1" winner = game.winner comp1win += 1 if winner == 'X' comp2win += 1 if winner == 'O' draw_count += 1 if winner == nil end end if num_human_players == "-1" puts "\nAfter 10000 iterations:" puts "Computer 1 (level: #{computer1_level}) wins: #{comp1win}" puts "Computer 2 (level: #{computer2_level}) wins: #{comp2win}" puts "Computer draws: #{draw_count}" end puts "\nPlay again? (y/n)" choice = gets.strip.downcase until choice == "y" || choice == "n" puts "ERROR: #{choice} is not a valid option. Please enter y or n" choice = gets.strip end flag = true if choice == 'n' end puts "\nThank you for playing!"
true
bf925cd1cfe59347ff3eb336ed4fd890101e9a02
Ruby
yamshim/StockPortal
/lib/clawler/models/credit_deal.rb
UTF-8
3,714
2.53125
3
[]
no_license
# coding: utf-8 module Clawler module Models class CreditDeal < Clawler::Base extend AllUtils # include Clawler::Sources # Initializeは一番最初にスクリプトとして実行する csv化するか、分割化するかなどはまた後で # sleepを入れる # エラーバンドリング # 強化 # 重複データの保存を避ける # break, next def self.patrol credit_deal_patroller = self.new(:credit_deal, :patrol) credit_deal_patroller.scrape credit_deal_patroller.import credit_deal_patroller.finish end def self.build credit_deal_builder = self.new(:credit_deal, :build) credit_deal_builder.build credit_deal_builder.finish end def set_latest_object(company_code) @latest_object = ::Company.find_by_company_code(company_code).try(:credit_deals).try(:pluck, :date).try(:sort).try(:last) end def each_scrape(company_code, page) credit_deal_lines = [] credit_deals_info = Clawler::Sources::Yahoo.get_credit_deals_info(company_code, page) return {type: :break, lines: nil} if credit_deals_info.blank? credit_deals_info.each do |credit_deal_info| credit_deal_line = Clawler::Sources::Yahoo.get_credit_deal_line(credit_deal_info, company_code) if @status == :patrol && @latest_object.present? return {type: :all, lines: credit_deal_lines} if @latest_object >= credit_deal_line[1] end credit_deal_lines << credit_deal_line end return {type: :part, lines: credit_deal_lines} end def line_import companies = ::Company.all @lines.group_by{|random_line| random_line[0]}.each do |company_code, lines| ::Company.transaction do credit_deals_info = [] company = companies.select{|c| c.company_code == company_code}[0] last_date = company.try(:credit_deals).try(:pluck, :date).try(:sort).try(:last) lines.sort_by{|line| line[1]}.reverse.each do |line| if last_date.present? break if last_date >= line[1] end credit_deal_info = {} credit_deal_info[:date] = line[1] credit_deal_info[:selling_balance] = line[2] credit_deal_info[:debt_balance] = line[3] credit_deal_info[:margin_ratio] = line[6] credit_deals_info << credit_deal_info end company.credit_deals.build(credit_deals_info).each(&:save!) end end true end def csv_import companies = ::Company.all companies.each do |company| ::Company.transaction do last_date = company.try(:credit_deals).try(:pluck, :date).try(:sort).try(:last) credit_deals_info = [] csv_text = get_csv_text(company.company_code) lines = CSV.parse(csv_text).sort_by{|line| trim_to_date(line[1])}.reverse.uniq lines.each do |line| if last_date.present? break if last_date >= trim_to_date(line[1]) end credit_deal_info = {} credit_deal_info[:date] = trim_to_date(line[1]) credit_deal_info[:selling_balance] = line[2].to_i credit_deal_info[:debt_balance] = line[3].to_i credit_deal_info[:margin_ratio] = line[6].to_f credit_deals_info << credit_deal_info end company.credit_deals.build(credit_deals_info).each(&:save!) end end true end end end end
true
5be843b5a9b7aa203b8864cbcab5fe6754ef9b21
Ruby
fanjieqi/LeetCodeRuby
/101-200/128. Longest Consecutive Sequence.rb
UTF-8
298
3.203125
3
[ "MIT" ]
permissive
# @param {Integer[]} nums # @return {Integer} def longest_consecutive(nums) hash = nums.zip(nums).to_h max = 0 nums.each_with_index do |num, index| next if hash[num - 1] count = 0 while hash[num] count += 1 num += 1 end max = [max, count].max end max end
true
afc863de5252e9b17c2b772ac97f406747871731
Ruby
ReinaldoAguilar/AT03_API_test
/DanielCabero/practice5/exercise2.rb
UTF-8
948
3.5625
4
[]
no_license
class Exercise2 def initialize maps @users= hash @users = maps end def getValuesNumbers @users.each_key {|key | key=~/1(.*)/ puts "#{key}" } end def numbersGroups @users.each_key {|key| result = case key when 0..25 then puts "Use belong Group 1" when 26..50 then puts "Use belong Group 2" when 51..75 then puts "Use belong Group 3" when 76..100 then puts "Use belong Group 4" else puts "the Id no between in the range " end } end def getList @users.each_key {|key | puts "#{key}" } end end list = hash list={1=>"a",12=>"b",52=>"c",82=>"d",26=>"e",25=>"f",36=>"g",99=>"h",50=>"i",72=>"j"} test = Exercise2.new list test.getValuesNumbers test.getList test.numbersGroups
true
9a4eec2fb8912780bf97ec48a6e5e5216c69b2e7
Ruby
rparkerson/launch-school
/RB100/intro_to_ruby/7_hashes/8.rb
UTF-8
1,523
3.765625
4
[]
no_license
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] # print out groups of words that are anagrams # print out seperate lines as arrays # go through each index assign each word to alphabetical compare with # all other words. next words # make hash with key value pair of sorted words # go through array and add all words from array and print out new array. # permanently take out words from array # go through hash compare word values make array # words_hash = {} # words_sorted = [] # combined_arr = [] # words_sorted = words.map { |word| word.split('').sort.join } # words.each_with_index do |word, index| # words_hash[word] = words_sorted[index] # end # words_hash.each do |word, value| # p combined_arr.push word # if value # end # end # p words_sorted # p words_hash words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live', 'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide', 'flow', 'neon'] hash = {} words.each do |value| sorted_word = value.split('').sort.join if hash.keys.include? sorted_word hash[sorted_word] = hash[sorted_word] << value else hash[sorted_word] = [value] end end hash.each {|k, v| p v} #book solution result = {} words.each do |word| key = word.split('').sort.join if result.has_key?(key) result[key].push(word) else result[key] = [word] end end result.each_value do |v| puts "------" p v end
true
386b2d48cc7f1532f69b556d6cd32145bd351d66
Ruby
ltello/checkout
/spec/lib/promotional_rules/promotion_spec.rb
UTF-8
1,998
3.09375
3
[]
no_license
# frozen_string_literal: true describe Promotion do class MyPromotion < Promotion DISCOUNT_PER_UNIT = 5 private def applicable? item_names.include?("A") end def computed_discount item_names.count("A") * DISCOUNT_PER_UNIT end end class WrongPromotion < Promotion end describe "instance methods" do subject { MyPromotion.new(price_before_discount, *items) } let(:price_before_discount) { 60 } let(:items) { [ Item.new(name: "A", price: 20), Item.new(name: "B", price: 30), Item.new(name: "A", price: 20) ] } describe "private methods" do subject { WrongPromotion.new(price_before_discount, *items) } describe ".applicable?" do it "raises an Exception to warn the developer to overide the method in a subclass" do expect { subject.send(:applicable?) }.to raise_error(Exception) end end describe ".computed_discount" do it "raises an Exception to warn the developer to overide the method in a subclass" do expect { subject.send(:computed_discount) }.to raise_error(Exception) end end end describe ".items" do it "return the list of items to which apply the discount" do expect(subject.items).to eq(items) end end describe ".price_before_discount" do it "return the list of items to which apply the discount" do expect(subject.price_before_discount).to eq(price_before_discount) end end describe ".amount" do describe "when the discount is not applicable" do let(:items) { [ Item.new(name: "B", price: 30) ] } it "return 0" do expect(subject.amount).to eq(0) end end describe "when the discount is applicable" do it "return the computed discount amount" do expect(subject.amount).to eq(10) end end end end end
true
156e91af148f4c34f0156847ab284210c784a27f
Ruby
evantravers/euler
/ruby/40.rb
UTF-8
341
2.84375
3
[]
no_license
counter = 0 num = 0 targets = [1, 10, 100, 1000, 10000, 100000, 1000000] solutions = [] until targets.empty? num.to_s.chars.each do |char| if targets.include?(counter) targets.delete(counter) puts "found a char! #{char}" solutions << char.to_i end counter += 1 end num += 1 end puts solutions.inject(:*)
true
e6235ee6242b62cb7d837ffc989ae69a17695942
Ruby
heysaturday/samples
/walker-realty-locomotive-engine-2/lib/rets/syncer.rb
UTF-8
1,910
2.609375
3
[]
no_license
require_relative '../../app/models/singlefamily' require_relative '../../app/models/rets_update' require_relative '../../app/models/mls' require 'logger' require 'mongoid' require 'pathname' dump = false ingest = false dump = true if ARGV.include?("dump") ingest = true if ARGV.include?("ingest") if !(dump || ingest) dump = true ingest = true end path = Pathname.new(File.dirname(__FILE__) + "/../../config/mongoid.yml").realpath.to_s Mongoid.load!(path, :production) # Setup a log file to rotate every 100M logfile = Pathname.new(File.dirname(__FILE__) + "/mls_sync.log").realpath.to_s $LOG = Logger.new(logfile, 0, 100 * 1024 * 1024) $LOG.formatter = Logger::Formatter.new $LOG.level = Logger::INFO lookup_cache = {} # Loop over all othe lookup tables and cache the values so that we save the value rather than the keys, which are useless $LOG.debug "Caching Lookup Tables for Single Family Homes" lookup_tables = SingleFamilyHome.lookup_tables() lookup_tables.each do |attribute, info| lookup_cache[attribute] = MLS.get_lookup_values(SingleFamilyHome.resource, SingleFamilyHome.klass, attribute) end if dump begin last_update = RetsUpdate.desc(:created_at).first.created_at $LOG.info "Grabbing all Single Family Home updates since #{last_update}" count = MLS.dump_all_properties(SingleFamilyHome, lookup_cache, last_update) rescue $LOG.info "Grabbing all Single Family Homes in the database. A full backup has not been perfomed on this machine before" count = MLS.dump_all_properties(SingleFamilyHome, lookup_cache) end RetsUpdate.create( property_class: SingleFamilyHome.name, record_count: count ) $LOG.info "Downloaded #{count} listings to harddisk" end if ingest begin $LOG.info "Ingesting all updates downloaded from last sync" MLS.load_properties(SingleFamilyHome, lookup_cache) rescue Exception => e $LOG.info "Load failed somehow: #{e.message}" end end
true
38ca0a86f1c4040dc5c7c7482479ac83bd2f529b
Ruby
skryl/restforce-db
/lib/restforce/db/tracker.rb
UTF-8
1,266
2.90625
3
[ "MIT" ]
permissive
module Restforce module DB # Restforce::DB::Tracker encapsulates a minimal API to track and configure # synchronization runtimes. It allows Restforce::DB to persist a "last # successful sync" timestamp. class Tracker attr_reader :last_run # Public: Initialize a Restforce::DB::Tracker. Sets a last_run timestamp # on Restforce::DB if the supplied tracking file already contains a stamp. # # file_path - The Path to the tracking file. def initialize(file_path) @file = File.open(file_path, "a+") timestamp = @file.read return if timestamp.empty? @last_run = Time.parse(timestamp) Restforce::DB.last_run = @last_run end # Public: Persist the passed time in the tracker file. # # time - A Time object. # # Returns nothing. def track(time) @last_run = time @file.truncate(0) @file.print(time.utc.iso8601) @file.flush @file.rewind end end class SimpleTracker attr_reader :last_run def initialize(time) @last_run = time Restforce::DB.last_run = @last_run end def track(time) @last_run = time end end end end
true
5046bef5900a4b0095c6bc949023cee60b10f76d
Ruby
ichylinux/banbanlive
/app/models/band_member.rb
UTF-8
535
2.53125
3
[]
no_license
# coding: UTF-8 module BandMemberConst INSTRUMENTS = { VOCAL = 1 => 'ボーカル', GUITAR = 2 => 'ギター', BASE = 3 => 'ベース', KEYBOARD = 4 => 'キーボード', DRUM = 5 => 'ドラム', } end class BandMember < ActiveRecord::Base include BandMemberConst belongs_to :band belongs_to :member attr_accessible :deleted, :instrument_id, :member_id def instrument_name INSTRUMENTS[instrument_id] end def member_name return nil unless member_id member.full_name end end
true
a9b6f1545c0274fbca1b0bf0cc2b141f39291a6a
Ruby
mose/icallect
/lib/icallect/config.rb
UTF-8
829
2.65625
3
[ "MIT" ]
permissive
require "yaml" module Icallect class Config CONFIG_DEFAULTFILE = File.expand_path("../../../config.yml.defaults",__FILE__) attr_reader :feeds def initialize @__configfile = nil @feeds = [] @values = {} setup end def setup FileUtils.mkdir_p(File.dirname(configfile)) unless File.directory?(File.dirname(configfile)) FileUtils.cp(CONFIG_DEFAULTFILE, configfile) unless File.file?(configfile) @values = YAML.load_file(configfile) @feeds = @values['feeds'] end def configfile @__configfile ||= ENV["CONFIG_FILE"] || File.expand_path("~/.config/icallect/config.yml") end def add(feed) @values['feeds'] << feed save end def save File.open(configfile, 'w+') {|f| f.write(@values.to_yaml) } end end end
true
ba7a4c053abab8cd5a66421b837cd12dc44b422e
Ruby
kinsomicrote/gofish-game-api
/app/services/v1/deck_service.rb
UTF-8
2,929
2.96875
3
[]
no_license
# frozen_string_literal: true module V1 class DeckService RANK = { "2" => "two", "3" => "three", "4" => "four", "5" => "five", "6" => "six", "7" => "seven", "8" => "eight", "9" => "nine", "10" => "ten", "KING" => "king", "ACE" => "ace", "JACK" => "jack", "QUEEN" => "queen" }.freeze def new_game(params) game = HTTParty.get('https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1').parsed_response params[:players].each do |player| build_player_pile({ game_id: game['deck_id'], player: player, count: 7 }) end { game_id: game['deck_id'], players: params[:players] } end def build_player_pile(params) response = draw_card_from_deck({ game_id: params[:game_id], count: params[:count] }) add_to_pile({ game_id: params[:game_id], player: params[:player], cards: response }) end def draw_card_from_deck(params) response = HTTParty.get("https://deckofcardsapi.com/api/deck/#{params[:game_id]}/draw/?count=#{params[:count]}") response['cards'] if response['success'] end def add_to_pile(params) url = "https://deckofcardsapi.com/api/deck/#{params[:game_id]}/pile/#{params[:player]}/add/?cards=" params[:cards].each do |card| url = "#{url},#{card['code']}" end HTTParty.get(url) end def get_cards(params) response = HTTParty.get("https://deckofcardsapi.com/api/deck/#{params[:game_id]}/pile/#{params[:playerName]}/list") response['piles'][params[:playerName]]['cards'] if response['success'] end def player_cards(params) response = get_cards(params) data = {} data[:cards] = response.map do |card| { rank: RANK[card['value']], suit: card['suit'].downcase } end data end def draw_from_player(params) response = HTTParty.get("https://deckofcardsapi.com/api/deck/#{params[:game_id]}/pile/#{params[:playerName]}/draw/?cards=#{params[:card]['code']}") response['cards'] if response['success'] end def sort_card(params) response = get_cards(params) response.each do |card| next unless card['value'] == RANK.invert[params[:rank]] card = draw_from_player({ game_id: params[:game_id], playerName: params[:playerName], card: card }) return card end nil end def fish(params) sorted_card = sort_card( { game_id: params[:game_id], playerName: params[:player], rank: params[:rank] }) card = sorted_card.nil? ? draw_card_from_deck({ game_id: params[:game_id], count: 1 }) : sorted_card response = add_to_pile({ player: params[:playerName], game_id: params[:game_id], cards: card }) return unless response['success'] { catch: true, cards: [ { suit: card[0]['suit'], rank: RANK[card[0]['value']] } ] } end end end
true
accf7b79bc1249fcade3e654d71ac55e82ceb33e
Ruby
yatinsns/testing-playground
/learn-ruby/mixing-code-data/second.rb
UTF-8
162
2.625
3
[]
no_license
def print_second_data puts "Second file\n--------" puts DATA.read # Won't output anything, since first.rb read the entire file end __END__ Second end clause
true
6e3679ef3895d7e3f3e3e1af0c02aa4db5851e67
Ruby
mnain/learn-ruby
/Massmail/mailtest.rb
UTF-8
1,710
2.515625
3
[]
no_license
require 'net/smtp' require 'rubygems' require 'mailfactory' filename = 'emaillist.csv' mail = MailFactory.new() mail.to = "mnain@yahoo.com" mail.from = "madan@mnain.org" mail.subject = "DLF Jasola for Lease" mail.text = <<EOF1 DLF Commercial office Space for Lease in tower A.ready for possession in Jan 09. These are 3 adjacent units: JA 318 1706 sq feet JA 319 1072 sq feet JA 320 1072 sq feet Total Area 3850 sq feet Can be leased together or separate. All 3 above units have individual parking space. These are on the 3rd floor facing the main road. Contact information: Sanjeev Kassal 9810367063 Email: Sanjeev.kassal@gmail.com Geeta Kassal (USA) cell is 001-240-602-5555 Email: GeetaNain@gmail.com EOF1 mail.html = <<EOF2 <pre> <b>DLF Commercial office Space for Lease</b> in tower A.ready for possession in Jan 09. These are 3 adjacent units: JA 318 1706 sq feet JA 319 1072 sq feet JA 320 1072 sq feet Total Area 3850 sq feet Can be leased together or separate. All 3 above units have individual parking space. These are on the 3rd floor facing the main road. Contact information: <font color='blue'>Sanjeev Kassal 9810367063 <a href='mailto:Sanjeev.kassal@gmail.com'>Email</a> Geeta Kassal (USA) cell is 001-240-602-5555 <a href='mailto:GeetaNain@gmail.com'>Email</a> </font> </pre> EOF2 #print mail.to_s #Net::SMTP.start(('mnain.org','madan@mnain.org','wak89giv') { |smtp| #mail.to = 'mnain@yahoo.com' #smtp.send_message(mail.to_s(), fromaddress, toaddress) #} smtp = Net::SMTP.new('mail.mnain.org') #p smtp smtp.start('mnain.org','madan@mnain.org','wak89giv') msg = mail.to_s #p smtp smtp.sendmail(msg, 'madan@mnain.org', 'mnain@yahoo.com') smtp.sendmail(msg, 'madan@mnain.org', 'madan.nain@gmail.com') smtp.finish()
true
f988b0cfeccd4c3ec74dc6397978d5894696261d
Ruby
c80609a/improved-adventure
/lib/css_pictures.rb
UTF-8
1,392
2.671875
3
[]
no_license
require 'base64' require 'css_parser' require 'securerandom' require 'uri_helper' class CSSPictures include UriHelper URL_REGEX = /url\(["']?(?<img>[^"'\)]+)/ BASE64_REGEX = /data:(?<type>[^\/]+)\/(?<ext>[^;]+);base64,(?<base64>.+)/ attr_reader :source, :parser, :download_manager def initialize(source:, parser: CssParser::Parser.new, download_manager:) @source = source @parser = parser @download_manager = download_manager parser.load_uri!(source) end def process images.each do |url| process_one(url) end end private def process_one(url) match = BASE64_REGEX.match(url) if match dump_base64(match) else uri = normalize_url(source, url) download_manager.enqueue(uri) end end def dump_base64(match) file_name = "#{data_dir}/base64_pic-#{SecureRandom.hex(4)}.#{match[:ext]}" data = Base64.decode64(match[:base64]) File.binwrite(file_name, data) end def images result = [] parser.each_rule_set(:all) do |rule_set, _media_types| rule_set.each_declaration do |property, value, _is_important| if property =~ /^background(?:-image)?$/ && value.start_with?('url') md = URL_REGEX.match(value) img = md[:img] result << img if img end end end result end def data_dir download_manager.data_dir end end
true
e9505eeedf8fd935d7e3638992aa0fd2084d9563
Ruby
yndajas/ttt-with-ai-project-online-web-sp-000
/lib/game.rb
UTF-8
1,780
3.96875
4
[]
no_license
require 'pry' class Game attr_accessor :board, :player_1, :player_2 WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def initialize(player_1 = Players::Human.new("X"), player_2 = Players::Human.new("O"), board = Board.new) self.player_1 = player_1 self.player_2 = player_2 self.board = board end def current_player self.board.turn_count.even? ? self.player_1 : self.player_2 end def won? WIN_COMBINATIONS.find do |combination| combination.all? {|index|self.board.cells[index] == "X"} || combination.all? {|index|self.board.cells[index] == "O"} end end def draw? self.board.full? && !self.won? end def over? self.won? || self.draw? end def winner if self.won? self.board.cells[self.won?[0]] end end def turn puts "\nPlease enter 1-9 (top row = 123):" cell = self.current_player.move(self.board) if self.board.valid_move?(cell) self.board.update(cell, self.current_player) puts "\n" self.board.display else puts "\nInvalid move" turn end end def play puts "\nLet's play!\n\n" self.board.display until self.over? self.turn end if self.won? # could add logic here so that the message is "You win!" or "You lose!" for one-player games if self.player_1.class == self.player_2.class puts "\nCongratulations #{self.winner}!" else player = self.player_1.token == self.winner ? self.player_1 : self.player_2 if player.class == Players::Human puts "\nYou win!" else puts "\nYou lose!" end end else puts "\nIt's a draw!" end end end
true
df4de5023f8ee40be278f6b902dfd9f4aac5515c
Ruby
Heybluguy/black_thursday
/test/item_repository_test.rb
UTF-8
1,918
2.84375
3
[]
no_license
require_relative 'test_helper' require './lib/item_repository' class ItemRepositoryTest < MiniTest::Test attr_reader :ir def setup @ir = ItemRepository.new end def test_it_exists assert_instance_of ItemRepository, ir end def test_all_returns_all_items_in_array ir.populate('test/fixtures/items_fixture.csv') assert_instance_of Array, ir.all assert_instance_of Item, ir.all.first assert_equal 5, ir.all.count end def test_it_can_find_item_by_id ir.populate('test/fixtures/items_fixture.csv') assert_instance_of Item, ir.find_by_id(4) assert_nil ir.find_by_id(1000) end def test_IR_can_find_item_by_name ir.populate('test/fixtures/items_fixture.csv') assert_instance_of Item, ir.find_by_name(" Zoom super FLukE ") assert_nil ir.find_by_name("HELLO WorlD!!") end def test_IR_can_find_items_with_some_text_in_description ir.populate('test/fixtures/items_fixture.csv') assert_instance_of Array, ir.find_all_with_description("fish ") assert_instance_of Item, ir.find_all_with_description("fish").first assert_equal 3, ir.find_all_with_description("fish").count assert_equal [], ir.find_all_with_description("Hello World") end def test_IR_can_find_all_items_with_price ir.populate('test/fixtures/items_fixture.csv') assert_equal 1, ir.find_all_by_price(0.15e0).count assert_equal [], ir.find_all_by_price(100000) end def test_IR_can_find_items_within_price_range ir.populate('test/fixtures/items_fixture.csv') assert_equal [], ir.find_all_by_price_in_range((10000..20000)) assert_equal 5, ir.find_all_by_price_in_range((0.3e-1..0.25e0)).count end def test_IR_can_find_all_items_by_merchant_ID ir.populate('test/fixtures/items_fixture.csv') assert_equal [], ir.find_all_by_merchant_id(100008) assert_equal 1, ir.find_all_by_merchant_id(12334105).count end end
true
8f70093ac744c117f70a57a5f953fca7e8e28a52
Ruby
jpe442/W2D3
/poker/spec/player_spec.rb
UTF-8
423
2.734375
3
[]
no_license
require 'player' describe Player do subject(:player) { Player.new } let(:dealer) { double("dealer") } let(:card) { double("King of Spades") } describe "#initialize" do it "initializes with an empty hand" do expect(player.hand).to eq([]) end end describe "#receive_card" do it "receives card from the dealer" do expect(player.receive_card(card)).to eq(player.hand) end end end
true
6a2a8cbf652f1ad0e2739d25d2a07c1e4439b01f
Ruby
eoliveiramg/viva_challenge
/app/factory/province_factory.rb
UTF-8
476
2.625
3
[]
no_license
class ProvinceFactory def self.build(province_params) province_params.to_h.map do |key, value| Province.new( name: key, upper_left_x: value.fetch(:boundaries).fetch(:upperLeft).fetch(:x), upper_left_y: value.fetch(:boundaries).fetch(:upperLeft).fetch(:y), bottom_right_x: value.fetch(:boundaries).fetch(:bottomRight).fetch(:x), bottom_right_y: value.fetch(:boundaries).fetch(:bottomRight).fetch(:y) ) end end end
true
26ee076d914152a19b4b785e6b6f4348ad6acbf8
Ruby
JEG2/icfp_2014
/lib/lambda_lang/lexer.rb
UTF-8
633
3.234375
3
[]
no_license
require "strscan" module LambdaLang class Lexer TOKEN_REGEX = /(?:==|>=|<=|\w+|[-+*\/(){},&<>#'"])/ def initialize(code) @code = StringScanner.new(code) consume_whitespace end attr_reader :code private :code def next code.scan(TOKEN_REGEX).tap do consume_whitespace end end def next? !code.eos? end def peek code.check(TOKEN_REGEX) end def unshift(token) code.string = "#{token} #{code.rest}" end def rest code.rest end private def consume_whitespace code.scan(/\s+/) end end end
true
902b2330f134529d428900b7315dbc4b2c649673
Ruby
AndreiMotinga/ctci
/arrays_and_strings/urlify.rb
UTF-8
113
3.046875
3
[]
no_license
# write a method to replace all spaces in a stirng with '%20'. def urlify(str) str.strip.gsub(" ", "%20") end
true
c6da8751aee2250118a522eda32f2d570f25e82d
Ruby
myokoym/poker
/poker.rb
UTF-8
2,924
3.34375
3
[]
no_license
class Poker # TODO パラメータを柔軟に def initialize(hand) @hands = hand.gsub(/A/, "Z").gsub(/T/, "B").gsub(/K/, "Y").split(/ /) end def rank nums = @hands.map {|v| v[0] } base = nums.sort.reverse if royal? "J#{base.join}" elsif straight_flush? "I#{base.join}" elsif four? hit = nums.select {|v| nums.count(v) == 4 }.first "H#{hit * 4}#{base.reject {|v| v == hit}.join}" elsif full_house? hit1 = nums.select {|v| nums.count(v) == 3 }.first hit2 = nums.select {|v| nums.count(v) == 2 }.first "G#{hit1 * 3}#{hit2 * 2}" elsif flush? "F#{base.join}" elsif straight? "E#{base.join}" elsif three? hit = nums.select {|v| nums.count(v) == 3 }.first "D#{hit * 3}#{base.reject {|v| v == hit}.join}" elsif two_pair? hit1 = nums.select {|v| nums.count(v) == 2 }.max hit2 = nums.select {|v| nums.count(v) == 2 }.min "C#{hit1 * 2}#{hit2 * 2}#{base.reject {|v| v == hit1 or v == hit2}.join}" elsif one_pair? hit = nums.select {|v| nums.count(v) == 2 }.first "B#{hit * 2}#{base.reject {|v| v == hit}.join}" else "A#{base.join}" end end def one_pair? nums = @hands.map {|x| x[0] } if nums.group_by {|e| nums.count(e) }.keys.max == 2 and nums.group_by {|e| nums.count(e) }[2].uniq.size == 1 return true end false end def two_pair? nums = @hands.map {|x| x[0] } if nums.group_by {|e| nums.count(e) }.keys.max == 2 and nums.group_by {|e| nums.count(e) }[2].uniq.size == 2 return true end false end def three? nums = @hands.map {|x| x[0] } if nums.group_by {|e| nums.count(e) }.keys.max == 3 return true end false end def straight? nums = @hands.map {|x| x[0] } if nums.include?("2") nums.map! {|v| v.gsub("Z", "1") } else nums.map! {|v| v.gsub("Z", "14") } end nums.map! {|v| v.gsub("B", "10") } nums.map! {|v| v.gsub("J", "11") } nums.map! {|v| v.gsub("Q", "12") } nums.map! {|v| v.gsub("Y", "13") } if nums.uniq.size == 5 and nums.map {|v| v.to_i }.max - nums.map {|v| v.to_i }.min == 4 return true end false end def flush? if @hands.map {|x| x[1] }.uniq.size == 1 return true end false end def full_house? nums = @hands.map {|x| x[0] } if nums.uniq.size == 2 and nums.group_by {|e| nums.count(e) }.keys.max == 3 return true end false end def four? nums = @hands.map {|x| x[0] } if nums.group_by {|e| nums.count(e) }.keys.max == 4 return true end false end def straight_flush? if straight? and flush? return true end false end def royal? if @hands.map {|x| x[1] }.uniq.size == 1 and @hands.map {|x| x[0] }.sort == %w[B J Q Y Z] return true end false end end
true
e4b04f8c8f1173be28d8e16e6bdce842e6026eae
Ruby
mdo5004/oo-student-scraper-v-000
/lib/scraper.rb
UTF-8
1,478
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'open-uri' require 'nokogiri' require 'pry' class Scraper def self.scrape_index_page(index_url) doc = Nokogiri::HTML(open(index_url)) page_url = index_url.chomp("index.html") pages = doc.css("div.student-card") parsed_hashes = [] pages.each { |page| name = page.css("h4.student-name").text location = page.css("p.student-location").text profile_url = page.css("a").attribute("href").value parsed_hashes << {name: name, location: location, profile_url: page_url + profile_url} } parsed_hashes end def self.scrape_profile_page(profile_url) doc = Nokogiri::HTML(open(profile_url)) links = doc.css("div.social-icon-container").css("a") profile = Hash.new('none') links.each { |link| url = link.attribute("href").value if url.match(/twitter/) profile[:twitter] = url elsif url.match(/linkedin/) profile[:linkedin] = url elsif url.match(/github/) profile[:github] = url elsif link.css("img").attribute("src").value.match(/rss-icon/) profile[:blog] = url end } profile[:profile_quote] = doc.css("div.profile-quote").text profile[:bio] = doc.css("div.bio-content div.description-holder p").text profile end end
true
b0cac53e5e510f1b62b9fe12a2b946aeba8cb0cf
Ruby
ParthaviDobariya/Ruby
/Basics/polymorphism.rb
UTF-8
367
3.390625
3
[]
no_license
class Language def print puts "This is Language Class" end end class C < Language def print puts "This is C Language Class" end end class Ruby < Language def print puts "This is Ruby Language Class" end end C.new.print Ruby.new.print puts "\n....C class ancestors...." puts C.ancestors puts "\n....Ruby class ancestors...." puts Ruby.ancestors
true
fcc7f6d8812d1141745fd695bddaf271e5448dcd
Ruby
davidcelis/geocodio
/lib/geocodio/school_district.rb
UTF-8
353
2.609375
3
[ "MIT" ]
permissive
module Geocodio class SchoolDistrict attr_reader :name attr_reader :lea_code attr_reader :grade_low attr_reader :grade_high def initialize(payload = {}) @name = payload['name'] @lea_code = payload['lea_code'] @grade_low = payload['grade_low'] @grade_high = payload['grade_high'] end end end
true
80c11c84873a4adf8c8fd7a0102e16489f91d2d6
Ruby
SultanBS/hw-w10d02-ruby101
/app.rb
UTF-8
832
3.3125
3
[]
no_license
i = 1 while i <= 100 if i % 3 ===0 puts "Fizz" elsif i % 5 === 0 puts "Buzz" elsif i % 3 ===0 && i % 5 ===0 puts "FizzBuzz" else puts i end i += 1 end # planeteers = ["Earth", "Wind", "Captain Planet", "Fire", "Water"] # puts planeteers[1] # planeteers << "Heart" # puts planeteers # rangers = ["Red", "Blue", "Pink", "Yellow", "Black"] # heroes = planeteers + rangers # puts heroes.sort.inspect # puts heroes.rand # ninja_turtle = { # name: "Michelangelo", # weapon: "Nunchuks", # radical: true # } # ninja_turtle = {:age => 15} # ninja_turtle.without(:radical) # ninja_turtle.store(:pizza_toppings, ["cheese", "pepperoni", "peppers"]) # ninja_turtle.pizza_toppings[0] # ninja_turtle.to_a
true
b06a22e9c8d24572fb09317bf456be1e3fbc5690
Ruby
lukaszgryglicki/my_flatten
/array_spec.rb
UTF-8
865
2.796875
3
[]
no_license
require_relative 'my_flatten' RSpec.describe Array do context '.my_flatten' do # Here we are testing various cases # We expect that `my_flatten` will transform input into expected output let(:examples) do [ { input: [1, [2], 3, [], [[], [4, [5]]]], output: [1, 2, 3, 4, 5] }, { input: [], output: [] }, { input: [[[]]], output: [] }, { input: [[], [[]]], output: [] }, { input: [nil], output: [nil] }, { input: ['a', Array, [1, 2, 3]], output: ['a', Array, 1, 2, 3] }, { input: [1, [2, [3]], 'a', [], [[], 'b', ['c', [], []]]], output: [1, [2, [3]], 'a', [], [[], 'b', ['c', [], []]]].flatten } ] end it 'passes' do examples.each do |example| expect(example[:input].my_flatten).to eq(example[:output]) end end end end
true
6f201b59980c47d6819d77a022d491df42d4f19a
Ruby
PaddyDwyer/ProjectEuler
/ruby/p27/p27.rb
UTF-8
1,063
3.25
3
[]
no_license
#!/usr/bin/env ruby -wKU -I ../lib require "util.rb" #ablist = generatePrimes(1000) alist = (0..500).map { |n| (n * 2) + 1 } blist = generatePrimes(1000) $deflist = generatePrimes(1000000) def getQuadraticLambda(a,b) return lambda { |n| n ** 2 + (a * n) + b } end def testLambda(a, b) quad = getQuadraticLambda(a, b) i = 0 begin prm = quad.call(i) i += 1 end until $deflist.index(prm).nil? #puts "testLambda(#{a}, #{b}) is #{i}" return i end m = 0 ansa = 0 ansb = 0 blist.each do |a| blist.select { |t| t > ansb }.each do |b| if (x = testLambda(a, b)) > m ansa = a ansb = b m = x puts "found #{x} with a #{ansa}, b #{ansb}" end if (x = testLambda(-a, -b)) > m ansa = a ansb = b m = x puts "found #{x} with -#{a}, -#{b}" end if (x = testLambda(a, -b)) > m ansa = a ansb = b m = x puts "found #{x} with #{a}, -#{b}" end if (x = testLambda(-a, b)) > m ansa = a ansb = b m = x puts "found #{x} with -#{a}, #{b}" end end end puts "result is a: #{ansa}, b: #{ansb}, prod #{ansa * ansb}"
true
b540268f597589a7cf09cd966b2a3774125cce1d
Ruby
Rebeliosman/RubyProjectRep
/mail_app/mail_app.rb
UTF-8
947
2.75
3
[]
no_license
require "pony" require 'io/console' my_mail = 'rebeliosman@gmail.com' puts "Enter password #{my_mail} for sending e-mail:" password = noecho(&:gets).chomp puts "Reciever e-mail:" send_to = STDIN.gets.chomp puts "Enter subject" sub = STDIN.gets.chomp puts "Message test:" body = STDIN.gets.chomp success = false begin Pony.mail({ :subject => sub, :body => body, :to => send_to, :from => my_mail, via: :smtp, via_options: { address: 'smtp.gmail.com', port: '587', enable_starttls_auto: true, user_name: my_mail, password: password, authentication: :plain, } }) success = true rescue SocketError puts "Cant connect to server. " rescue Net::SMTPFatalError => error puts "Inccorect e-mail address. " + error.message rescue Net::SMTPAuthenticationError => error puts "Incorrect password. " + error.message ensure puts "We try." end if success == true puts 'E-mail sent!' else puts 'E-mail not sent!' end
true
08dab67c8bda76deb58d80e76088266d1233e46c
Ruby
dannyevega/discover
/app/models/user.rb
UTF-8
531
2.609375
3
[]
no_license
require 'bcrypt' class User < ActiveRecord::Base validates_presence_of :name, :email, :password, presence: { message: "%{value} cannot be left blank." } validates_format_of :email, :with=> /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, :on => :create, message: "Email address invalid. Please enter a valid Email address." include BCrypt def password @password ||= Password.new(password_hash) end def password=(new_password) @password = Password.create(new_password) self.password_hash = @password end end
true
93c61a56a73333a626273269f54da7c5d5d615d6
Ruby
kkburr/homework_assignments
/Warmups/01/warmup_01.rb
UTF-8
293
3.546875
4
[]
no_license
#!/usr/bin/env ruby letters = ('a'..'z').to_a letters = letters.rotate(-7) print letters[13] print letters[21] print letters[21] print letters[10] print letters[16] print letters[21] print letters[8] print letters[9] print letters[21] print letters[10] print letters[11] print letters[24]
true
d866694341473f097bdd4571fb4cd17e961dae6c
Ruby
Aissac/radiant-extensions-extension
/lib/tag_binding_extensions.rb
UTF-8
743
2.5625
3
[]
no_license
module TagBindingExtensions def self.included(base) base.send(:include, InstanceMethods) # base.send(:alias_method, :orig_attr, :attr) # base.send(:alias_method, :attr, :parsed_attributes) base.send(:alias_method_chain, :attr, :parsed_attributes) end module InstanceMethods def attr_with_parsed_attributes if PageContext === context parsed_attributes else attr_without_parsed_attributes end end def parsed_attributes @parsed_attributes ||= parse_attributes end private def parse_attributes new_attr = {} @attributes.each do |k, v| new_attr[k] = context.parser.parse(v) end new_attr end end end
true
f543628158818d3b24652e118f9806e37190a517
Ruby
hopkinschris/nightowl
/app/services/bot.rb
UTF-8
2,091
2.8125
3
[ "MIT" ]
permissive
class Bot MAX_ATTEMPTS = 3 def initialize(user) if @user = user establish_client end end def scour_twitter num_attempts = 0 begin num_attempts += 1 @user.keywords.each do |k| @client.search(k.name, result_type: k.result_type, count: 10).take(k.rate).each do |tweet| begin if sentiment_analysis(k, tweet) && mention_extraction(k, tweet) if @client.favorite(tweet) k.impression_count += 1 k.save end end rescue => e puts "#{ e.message }" end end end rescue Twitter::Error::TooManyRequests => error if num_attempts <= MAX_ATTEMPTS sleep (error.rate_limit.reset_in.nil? ? 15.minutes : error.rate_limit.reset_in) puts "Waiting..." retry else raise end end end private def mention_extraction(keyword, tweet) mention_extractor = MentionExtractor.new keyword, tweet mention_extractor.perform case mention_extractor.instance_variable_get(:@forward) when true return true when false return false end end def sentiment_analysis(keyword, tweet) sentiment = SentimentBot.new tweet.text results = sentiment.analyze if results.include?(':)') # POSITIVE if keyword.sentiment.include?('positive') return true else return false end elsif results.include?(':|') # NEUTRAL if keyword.sentiment.include?('neutral') return true else return false end else # NEGATIVE if keyword.sentiment.include?('negative') return true else return false end end end def establish_client @client = Twitter::REST::Client.new do |config| config.consumer_key = ENV['TWITTER_CONSUMER_KEY'] config.consumer_secret = ENV['TWITTER_CONSUMER_SECRET'] config.access_token = @user.token config.access_token_secret = @user.secret end end end
true
c36d3396a611a2d7494c9bbc63ff806fbadcfeca
Ruby
LFDM/gem_polish
/lib/gem_polish/cli.rb
UTF-8
3,127
2.59375
3
[ "MIT" ]
permissive
require 'thor' require 'yaml' module GemPolish class CLI < Thor require 'gem_polish/cli/aliases' require 'gem_polish/gem' require 'gem_polish/cli/polisher' require 'gem_polish/cli/versioner' include Thor::Actions register(Gem, 'gem', 'gem <action>', 'Manipulates your Gemfile. Call "gem_polish gem" to learn about your options') desc "polish", "Polishes your gem skeleton" method_option :badges, type: :array, aliases: '-b', desc: 'Adds badges to your README. Takes one or more of: badge_fury, gemnasium, travis, coveralls and code_climate' method_option :git_user, type: :string, aliases: '-g', desc: 'Git user to be used for badge links. Defaults to your .gitconfig information' method_option :description, aliases: '-d', desc: 'Adds a descriptopn to the gemspec and the README' method_option :coverage, aliases: '-c', desc: 'Adds coveralls coverage' method_option :rspec_conf, aliases: '-r', desc: 'Adds additional rspec configuration' method_option :travis, type: :array, aliases: '-t', desc: 'Adds ruby versions to travis' method_option :no_default, type: :boolean, aliases: '-n', desc: 'Bypasses ~/.gem_polish.yml. Defaults to false' def polish(name = '.') inside name do p = Polisher.new(options, self) p.insert_description p.insert_badges p.insert_coveralls p.insert_rspec_conf p.insert_travis end end desc 'version OPTION', 'Reads and writes the version file of your gem' method_option :read, type: :boolean, aliases: '-r', desc: 'Print current version number' method_option :bump, aliases: '-b', lazy_default: 'revision', desc: 'Bumps the version number (revision [default], minor or major)' method_option :version, aliases: '-v', desc: 'Specify the new version number directly' method_option :commit, aliases: '-c', lazy_default: 'Bump version', desc: 'Creates a git commit of a bump, takes a message, defaults to "Bump version"' method_option :release, type: :boolean, aliases: '-R', desc: 'Releases a gem trough rake install. Can only be used in combination with -c' def version(name = '.') inside name do return help(:version) if options.empty? v = Versioner.new(self) if specified_version = options[:version] v.substitute_version(specified_version) elsif options[:read] puts v.to_version elsif bump = options[:bump] updated = v.update_version(bump) v.substitute_version(updated) if message = options[:commit] v.commit_version_bump(message) v.release if options[:release] end end end end desc 'aliases', 'Creates aliases for gem_polish' method_option :prefix, aliases: '-p', desc: 'Prefix to use for the aliases, e.g. gem_polish version becomes GPv when the prefix GP is requested. Defaults to gp' def aliases(destination) Aliases.new(self).create(options.merge(destination: destination)) end end end
true
f26783174566dc198d680bd417f1241ba5ddcf46
Ruby
AAMani5/learn-to-program
/chap13/ex4.rb
UTF-8
2,588
4.46875
4
[]
no_license
#!/usr/bin/env ruby #Baby dragon - we can feed it, put it to bed, talk it on walks. We can name it(parameter) #internally Dragon will keep track of if its hungry, needs to go. class Dragon def initialize name @name = name @asleep = false @stuffInBelly = 10 #its full @stuffInIntestine = 0 #it doesn't need to go puts @name + ' is born.' dispatch # calls dispatch method when a new dragon is created end def dispatch while true puts "Would you like to feed, walk, toss, rock, make_him_sleep or exit?" @cmd = gets.chomp.downcase if @cmd == 'feed' #instead of checking each input string feed #we can use respond_to method to see if dragon class elsif @cmd == 'walk' # responds to that method walk elsif @cmd == "make_him_sleep" putToBed elsif @cmd == "toss" toss elsif @cmd == "rock" rock elsif @cmd == "exit" exit else puts 'Sorry, what did you say?' end end end def feed puts 'You feed '+ @name + '.' @stuffInBelly = 10 passageOfTime end def walk puts 'You walk ' + @name + '.' @stuffInIntestine = 0 passageOfTime end def putToBed puts 'You put ' + @name + ' to bed.' @asleep = true 3.times do if @asleep passageOfTime end if @sleep puts @name + ' snores, filling the room with smoke.' end end if @asleep @asleep = false puts @name + ' wakes up slowly.' end end def rock puts 'You rock ' + @name + ' gently.' @asleep = true puts 'He briefly dozes off...' passageOfTime if @asleep @asleep = false puts '... but wakes when you stop.' end end def toss puts 'You toss ' + @name + ' up in the air.' puts 'He giggles, which singes your eyebrows.' passageOfTime end private def hungry? @stuffInBelly <= 2 end def poopy? @stuffInIntestine >= 8 end def passageOfTime if @stuffInBelly >0 @stuffInBelly -= 1 @stuffInIntestine += 1 else if @asleep puts 'It wakes up suddenly!' end puts @name + ' is starving! In desperation, it ate YOU!' exit end if @stuffInIntestine >= 10 @stuffInIntestine = 0 puts 'Whoops! ' + @name + ' had an accident...' end if hungry? if @sleep @sleep = false puts 'It wakes up suddenly!' end puts @name + "'s stomach grumbles" end if poopy? if @asleep @sleep = false puts 'It wakes up suddenly!' end puts @name + ' does the poopy dance...' end end end pet = Dragon.new 'Norbert' pet.feed pet.toss pet.walk pet.putToBed pet.rock pet.putToBed pet.putToBed pet.putToBed pet.putToBed
true
c5c4994e2b48e74ea54ad26d97ccc8911eb7e4d4
Ruby
kkeppel/shelter_importer
/app/models/organization.rb
UTF-8
2,014
2.53125
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'digest' class Organization include Mongoid::Document field :name, type: String field :shelter_id, type: String field :created_at, type: Date field :address1, type: String field :address2, type: String field :city, type: String field :state, type: String field :zip, type: String field :country, type: String field :latitude, type: String field :longitude, type: String field :phone, type: String field :fax, type: String field :email, type: String has_many :pets, inverse_of: :organization accepts_nested_attributes_for :pets, :allow_destroy => true validates_presence_of :shelter_id validates_uniqueness_of :shelter_id validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, on: :create KEY = "4c998baa8bbb5498a272063861be77e9" def self.get_shelter_info(org_id, zip) uri = URI.parse "http://api.petfinder.com/shelter.get?key=#{KEY}&id=#{org_id}&location=#{zip}" response = uri.read return Nokogiri::XML(response) end def self.import_shelter(org_id, zip) doc = Organization.get_shelter_info(org_id, zip) shelters = doc.xpath("//shelter") shelter = shelters.select{|s| s.xpath("id").text == org_id}.first db_shelter = Organization.find_or_create_by(shelter_id: org_id) db_shelter.update_attributes( shelter_id: org_id, name: shelter.xpath("name").text.strip, address1: shelter.xpath("address1").text.strip, address2: shelter.xpath("address2").text.strip, city: shelter.xpath("city").text.strip, state: shelter.xpath("state").text.strip, country: shelter.xpath("country").text.strip, zip: shelter.xpath("zip").text.strip, latitude: shelter.xpath("latitude").text.strip, longitude: shelter.xpath("longitude").text.strip, phone: shelter.xpath("phone").text.strip, fax: shelter.xpath("fax").text.strip, email: shelter.xpath("email").text.strip, created_at: Time.now ) db_shelter.save end end
true
45024b2e3243e4b6a4f75a228fd9ffc4630c8a39
Ruby
kavinderd/secret_santa
/bin/secret_santa
UTF-8
624
3.078125
3
[]
no_license
#!/usr/bin/env ruby require 'highline/import' require_relative "../lib/secret_santa" ENTER_NAME = 1 SELECT_SANTAS = 2 begin ss = SecretSanta.new loop do response = ask("1. Enter Name\n2. Select Santas\n3. Quit", Integer) {|r| r.in = [1,2, 3]} if response == ENTER_NAME response = ask('Enter First, Last & Email') #Add Regex to verify parts response = response.split(' ') ss.input_record(first_name: response[0], last_name: response[1], email: response[2]) elsif response == SELECT_SANTAS ss.assign_santas p ss.assignments end break if response == 3 end end
true
06dff95932febf324b3e118fe57de24601333fa8
Ruby
rpl/tiny-slidedown
/tiny-slidedown.rb
UTF-8
6,074
2.84375
3
[]
no_license
#!/bin/env ruby # tiny-slidedown: All-in-one SlideDown Fork # # original slidedown: # http://github.com/nakajima/slidedown # tiny-slidedown fork: # http://github.com/rpl/tiny-slidedown require 'rubygems' require 'open4' require 'bluecloth' require 'nokogiri' require 'optparse' require 'nokogiri' require 'erb' class Albino @@bin = ENV['PYGMENTIZE_BIN'] || '/usr/local/bin/pygmentize' def self.bin=(path) @@bin = path end def self.colorize(*args) new(*args).colorize end def initialize(target, lexer = :ruby, format = :html) @target = File.exists?(target) ? File.read(target) : target rescue target.chomp @options = { :l => lexer, :f => format } end def execute(command) pid, stdin, stdout, stderr = Open4.popen4(command) stdin.puts @target stdin.close stdout.read.strip end def colorize(options = {}) execute @@bin + convert_options(options) end alias_method :to_s, :colorize def convert_options(options = {}) @options.merge(options).inject('') do |string, (flag, value)| string += " -#{flag} #{value}" string end end end $LOAD_PATH << File.dirname(__FILE__) module MakersMark def self.generate(markdown) Generator.new(markdown).to_html end end module MakersMark class Generator def initialize(markdown) @markdown = markdown end def to_html highlight! doc.search('body > *').to_html end private def doc @doc ||= Nokogiri::HTML(markup) end def highlight! doc.search('div.code').each do |div| lexer = div['rel'] || :ruby lexted_text = Albino.new(div.text, lexer).to_s highlighted = Nokogiri::HTML(lexted_text).at('div') klasses = highlighted['class'].split(/\s+/) klasses << lexer klasses << 'code' klasses << 'highlight' highlighted['class'] = klasses.join(' ') div.replace(highlighted) end end def markup @markup ||= begin logger.info "WRITING!" text = @markdown.dup ### NOTE: preserve code snippets text.gsub!(/^(?:<p>)?@@@(?:<\/p>)?$/, '</div>') text.gsub!(/^(?:<p>)?@@@\s*([\w\+]+)(?:<\/p>)?$/, '<div class="code" rel="\1">') ### NOTE: convert to html and return BlueCloth.new(text).to_html end end def logger @logger ||= Class.new { def info(msg) say msg end private def say(msg) $stdout.puts msg if $VERBOSE end }.new end end end class Slide attr_accessor :text, :classes, :notes def initialize(text, *classes) @text = text @classes = classes @notes = nil extract_notes! end def html MakersMark::Generator.new(@text).to_html end private def extract_notes! @text.gsub!(/^!NOTES\s*(.*\n)$/m) do |note| @notes = note.to_s.chomp.gsub('!NOTES', '') '' end end end $SILENT = true class SlideDown USAGE = "The SlideDown command line interface takes a .md (Markdown) file as its only required argument. It will convert the file to HTML in standard out. Options: -t, --template [TEMPLATE] the .erb files in /templates directory. Default is -t default, which prints stylesheets and javascripts inline. The import template uses link and script tags. This can also accept an absolute path for templates outside the /templates directory." attr_accessor :stylesheets, :title attr_reader :classes def self.run!(argv = ARGV) args = argv.dup @@local_template = false @@output_text = "" if args.empty? puts USAGE else source = args[0] if args.length == 1 render(source) else option_parser(source).parse!(args) end end return @@output_text end def self.option_parser(source) OptionParser.new do |opts| opts.on('-h', '--help') { puts USAGE } opts.on('-l', '--local') { @@local_template = true } opts.on('-t', '--template TEMPLATE') do |template| @@output_text = render(source, template) end end end def self.render(source_path, template = "default") if source_path slideshow = new(File.read(source_path)) slideshow.render(template) end end # Ensures that the first slide has proper !SLIDE declaration def initialize(raw, opts = {}) @raw = raw =~ /\A!SLIDE/ ? raw : "!SLIDE\n#{raw}" extract_classes! self.stylesheets = opts[:stylesheets] || local_stylesheets self.title = opts[:title] || "Slides" end def slides @slides ||= lines.map { |text| Slide.new(text, *@classes.shift) } end def read(path) if @@local_template File.read(File.join(Dir.pwd, File.dirname(@local_template_name), path)) else File.read(File.join(File.dirname(__FILE__), '..', "templates", path)) end end def render(name) if is_absolute_path?(name) template = File.read("#{name}.erb") elsif @@local_template @local_template_name = name template = File.read("#{Dir.pwd}/#{name}.erb") else directory = File.join(File.dirname(__FILE__), "..", "templates") path = File.join(directory, "#{name}.erb") template = File.read(path) end ERB.new(template).result(binding) end private def lines @lines ||= @raw.split(/^!SLIDE\s*([a-z\s]*)$/).reject { |line| line.empty? } end def local_stylesheets Dir[Dir.pwd + '/*.stylesheets'] end def javascripts Dir[Dir.pwd + '/*.javascripts'].map { |path| File.read(path) } end def extract_classes! @classes = [] @raw.gsub!(/^!SLIDE\s*([a-z\s]*)$/) do |klass| @classes << klass.to_s.chomp.gsub('!SLIDE', '') "!SLIDE" end @classes end def extract_notes! @raw.gsub!(/^!NOTES\s*(.*)!SLIDE$/m) do |note| '!SLIDE' end @raw.gsub!(/^!NOTES\s*(.*\n)$/m) do |note| '' end end def is_absolute_path?(path) path == File.expand_path(path) end end if __FILE__ == $PROGRAM_NAME puts SlideDown.run! end
true
2310b0035166cddbe8d509ad7fcf9c67bc8dfdd7
Ruby
jeanettepayne/school-domain-online-web-sp-000
/lib/school.rb
UTF-8
471
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class School attr_accessor :school_name, :roster def initialize(school_name) @school_name = school_name @roster = {} end def add_student(name, grade) if roster.has_key?(grade) roster[grade] << name else roster[grade] = [] roster[grade] << name end end def grade(num) roster[num] end def sort sorted = {} roster.each do |grade, name| sorted[grade] = name.sort end sorted end end
true
aa76d624bf852d6b6bf5489485727ab775ab6976
Ruby
haydenlangelier/phase-0-tracks
/ruby/alias_manager.rb
UTF-8
501
3.59375
4
[]
no_license
answer ="" box={} until answer === "no" puts "what is your first name?" first=gets.chomp puts "what is your last name?" last=gets.chomp originalname = first+" "+last newfirst= first.downcase.tr('aeioubcdfghjklmnpqrstvwxyz','eiouacdfghjklmnpqrstvwxyzb') newlast= last.downcase.tr('aeioubcdfghjklmnpqrstvwxyz','eiouacdfghjklmnpqrstvwxyzb') newname = newlast+" "+newfirst box[originalname]= newname puts "Your new name is #{newname}! Want to enter more names? yes or no?" answer=gets.chomp end box.each {|key,value| puts " #{key}'s secret name is #{value}!"}
true
f2150688248fe9bf361db14466716183a46dbdc0
Ruby
MarcosFortuna/ruby
/Ruby/operadores/Inputs.rb
UTF-8
55
3.390625
3
[]
no_license
puts "digite algo:" nome = gets.chomp puts "#{nome}"
true
bbbbd753169ce841d1c1de5bb4038edafa35aab3
Ruby
nupurkapoor/learning-ROR
/ruby-warrior-challenges/beginner-track/level-2.rb
UTF-8
688
3.9375
4
[]
no_license
## # Level 2 challenge # # It is too dark to see anything, but you smell sludge nearby. # Use warrior.feel.empty? to see if there is anything in front of you, and warrior.attack! to fight it. # Remember, you can only do one action (ending in !) per turn. # # Simple if you take the hidden hint, it specifies that "you can only do one action (ending in !) per turn" # that means, there has to be conditionals. Use if-else condition to chose what to do. # If space ahead is empty, move forward, if not (else) fight the slug. # Success in 1st attempt. class Player def play_turn(warrior) if warrior.feel.empty? warrior.walk!() else warrior.attack! end end end
true
6d2a6d592037f09c77f8115108826fb99c040a86
Ruby
puyanwei/Tic-Tac-Toe
/spec/game_spec.rb
UTF-8
1,004
2.8125
3
[]
no_license
RSpec.describe Game do subject(:game) { described_class.new(board) } let(:board) { double :board } let(:win?) { double :win? } let(:tie?) { double :tie? } describe "#win?" do it "sets win to true if there is a win" do allow(game).to receive(:win?) { true } expect(game.win?).to be(true) end end describe "#tie?" do it "sets tie to true if there is a tie" do allow(game).to receive(:tie?) { true } expect(game.tie?).to be(true) end end describe '#display_result' do it 'outputs a message if there is a winner' do allow(game).to receive(:win?) { true } allow(game).to receive(:tie?) { false } expect { game.display_result }.to output("game over, you win\n").to_stdout end it 'outputs a message you if the game is tied' do allow(game).to receive(:win?) { false } allow(game).to receive(:tie?) { true } expect { game.display_result }.to output("game over, its a tie\n").to_stdout end end end
true
b065a5c649aae5d3eb3fde8ebb9b76eff6dd4ebb
Ruby
yelber-ride-and-eat-app/api
/test/models/uber_test.rb
UTF-8
663
2.859375
3
[]
no_license
require 'test_helper' class UberTest < ActiveSupport::TestCase test "retreive UberX price range" do u = Uber.new assert_equal "$6-8", u.xprice end test "retreive UberXL price range" do u = Uber.new assert_equal "$9-12", u.xlprice end test "retreive UberSELECT price range" do u = Uber.new assert_equal "$12-16", u.selectprice end test "retreive trip distance" do u = Uber.new assert_equal 3.42, u.distance end test "retrieve response given latitude and longitude" do u = Uber.new(latitude: "36.0339433397368", longitude: "-78.8919607517747") assert (u.distance > 3 && u.distance < 4) end end
true
a599b3fa950ed9aad2e5fb636bbe52065ac4918b
Ruby
radarscreen/sinatra
/calc.rb
UTF-8
694
2.765625
3
[]
no_license
require 'sinatra' require 'sinatra/reloader' require 'better_errors' configure :development do use BetterErrors::Middleware BetterErrors.application_root = __dir__ end get "/add/:num1/:num2" do sum = params[:num1].to_i + params[:num2].to_i "The sum is #{sum}" end get "/subtr/:num1/:num2" do leftover = params[:num1].to_i - params[:num2].to_i "The leftover is #{leftover}" end get "/mult/:num1/:num2" do prod = params[:num1].to_i * params[:num2].to_i "The product is #{prod}" end get "/div/:num1/:num2" do begin quotient = params[:num1].to_i / params[:num2].to_i "The quotient is #{quotient}" rescue ZeroDivisionError "Don't divide by zero!!" end end
true